问:
Deleting 50 rows in 3 tables using IN () in SQL Server so slow
I'm running a pretty straight forward delete statement query. I have 50 'file' keys and I want to delete them.  Our database schema looks like this:

File - UID (int) column is primary key (with unique, clustered index)

Version - File column is foreign key to File.UID, DataLockerToken column is foreign key to Cache.UID

Cache - UID (uniqueidentifier) column is primary key (with unique, non-clustered index)

Version had to index suggestions from SQL that I applied:

```<code>CREATE NONCLUSTERED INDEX [nc_VersionFile_DataLockerToken]
ON [dbo].[Version] ([File] ASC) INCLUDE([DataLockerToken])

CREATE NONCLUSTERED INDEX [nc_VersionFile_UID]
ON [dbo].[Version] ([File] ASC) INCLUDE([UID])
</code>```

Relationships: File 1:M to Version 1:1 to Cache

Here is the query I try to execute:

```<code>DELETE [Cache]
FROM [Cache] c
INNER JOIN Version v ON c.UID = v.DataLockerToken
WHERE v.[File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE Version
WHERE [File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE [File]
WHERE UID IN ( 241647, ... 50 ids in total ..., 244038 );
</code>```

This takes almost 1 minute and I'd expect it to be practically immediate. The File and Version tables are simply metadata, while the Cache table actually holds the binary info for the file.

Here is a screen shot of the execution plan:

UPDATE: It must be something with the Cache table or the binary info inside, because if I run the query in SQL Server Management Studio, as I said it takes ~1 minute. Then if I run the exact same query (same keys, so obviously they are not there) again in Management Studio or even a C# console app, the query is immediate, so unless there is some sort of 'query caching' which I don't think there is, this points to the fact that the data being deleted is the problem versus a problem with the query?

With that minimal info, anyone see and glaring problems in the execution plan?  I usually rely on SQL to give me an index hint if needed (and I know you can't always trust SQL), but it isn't like this db schema is so complicated.

Let me know if there is a better platform to ask this question on if this is not the correct place.

答: With 50 records I would recommend switching to a temp table, and joining on it instead of using a large IN clause. This will make the execution plan static per run, and perform much more consistently.</p>

Body:
I'm running a pretty straight forward delete statement query. I have 50 'file' keys and I want to delete them.  Our database schema looks like this:

File - UID (int) column is primary key (with unique, clustered index)

Version - File column is foreign key to File.UID, DataLockerToken column is foreign key to Cache.UID

Cache - UID (uniqueidentifier) column is primary key (with unique, non-clustered index)

Version had to index suggestions from SQL that I applied:

CREATE NONCLUSTERED INDEX [nc_VersionFile_DataLockerToken]
ON [dbo].[Version] ([File] ASC) INCLUDE([DataLockerToken])

CREATE NONCLUSTERED INDEX [nc_VersionFile_UID]
ON [dbo].[Version] ([File] ASC) INCLUDE([UID])

Relationships: File 1:M to Version 1:1 to Cache

Here is the query I try to execute:

DELETE [Cache]
FROM [Cache] c
INNER JOIN Version v ON c.UID = v.DataLockerToken
WHERE v.[File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE Version
WHERE [File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE [File]
WHERE UID IN ( 241647, ... 50 ids in total ..., 244038 );

This takes almost 1 minute and I'd expect it to be practically immediate. The File and Version tables are simply metadata, while the Cache table actually holds the binary info for the file.

Here is a screen shot of the execution plan:

UPDATE: It must be something with the Cache table or the binary info inside, because if I run the query in SQL Server Management Studio, as I said it takes ~1 minute. Then if I run the exact same query (same keys, so obviously they are not there) again in Management Studio or even a C# console app, the query is immediate, so unless there is some sort of 'query caching' which I don't think there is, this points to the fact that the data being deleted is the problem versus a problem with the query?

With that minimal info, anyone see and glaring problems in the execution plan?  I usually rely on SQL to give me an index hint if needed (and I know you can't always trust SQL), but it isn't like this db schema is so complicated.

Let me know if there is a better platform to ask this question on if this is not the correct place.


来源: stackexchange

问:
Close Command WPF
I have just started learning WPF.  I currently have the MenuItem File -> EXIT on my main window.

I want to know how i should add functionality to the Exit MenuItem.  As i see it there are 3 main choices

1) Add an Event handler to the Click event of the Exit menuitem. Then code the event handler in the window code behind

2) Add a Close command to to Exit menuitem and add a binding in the main window that handles the command.  Again this involves adding code to the window code behind.

3) Add a command to the Exit menuItem that calls a method in the ViewModel.  This removes code from the views code behind, but means the ViewModel needs to hold a reference to the View.

Which approach would best suit this situation?

I don't want to get to hung up on not putting any code at all into the Views code-behind.  However, since this is action only reaaly involves the view, maybe method 1 or 2 would be best.  Any thoughts?

答:
If it is a basic Exit command, I see no problem in putting it in the code behind.

If you start wanting to execute other code during Exit than I would either put your Exit code in a ViewModel somewhere and bind to it, or use something like MVVM Light's Messenger class or Prism's EventAggregator to raise a CloseApplicationEvent so other objects can handle themselves during shutdown.

ContentLicense: CC BY-SA 3.0

Title: Close Command WPF


问:
Microbial Network Analysis in igraph
I have bacterial OTU table at all taxonomy levels. I want to plot network using igraph (or any other package). I have never created such plot so please if anyone know some tutorial link for beginner? OR If someone guide me with scripts, you time would be really appreciated. Thank you!</p>

答:
A relationship dataset in network analysis is made of, at least, one data.frame (or matrix) which describe the links and contains at least 2 cols, in order to indicate 'from' and 'to' link on the 2 first cols of the data.frame. Others col's of this 'edges list' indicates the caracteristics of each of theselinks. Hereafter, lets call this data.frame edgeslist

You maybe wan't a second dataset, in order to indicate caracteristics for your nodes, aka 'nodes-list'. These are a second data.frame (or matrix) with first col indicate the nodes-names, and others cols indicate caracteristics of each nodes. The nodes-list in Igraph have to indicate each of the single nodes. Each node had to appear only once in the nodes-list, and not a single of the nodes that are in the edgeslist ('from' or 'to' columns) is allowed to be missing in the nodes-list. Hereafter, lets call this data.frame nodeslist.

Then, you have to create an Igraph object with igraph::graph_from_data_frame(edgeslist, directed = F, vertices = nodeslist)

And you can access to this object for compile a bunch of global statistics or obtain some new-data associated with some nodes (e.g., cliques <- igraph::largest_cliques(mygraph) or igraph::edge_density(mygraph, loops=T) )

Or access to a very precise set of nodes or edges (e.g., igraph::E(mygraph)$weight <- 1 or whatever func.

I suggest to play with the edge-list and the tidyverse, in order to made group-statistics.

Try to find some of the existing tutorials like this one.

ContentLicense: CC BY-SA 4.0

Title: Microbial Network Analysis in igraph


问:
Laravel UUID as primary key and ID as foreign key
I've defined a uuid as primary key, and would like to use id (auto increment) as foreign key to define relationships.

Both Posts and Comments have in their migration:

```<code>$table->uuid('uuid')->primary();
$table->bigInteger('id');
</code>```

Their models have:

```<code>protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;
</code>```

And the comments migration has

```<code>$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
</code>```

But if I run the migration I get General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade) of which I'm not sure why it's happening? Before adding the UUID logic it was working fine so I'm sure I've made a mistake there, but I'm not sure what as the error is generic.

答:
Give this a try.</p>

```<code>$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');
</code>```

Body:
I've defined a uuid as primary key, and would like to use id (auto increment) as foreign key to define relationships.

Both Posts and Comments have in their migration:

$table->uuid('uuid')->primary();
$table->bigInteger('id');

Their models have:

protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;

And the comments migration has

$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

But if I run the migration I get General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade) of which I'm not sure why it's happening? Before adding the UUID logic it was working fine so I'm sure I've made a mistake there, but I'm not sure what as the error is generic.

Body:
Give this a try.

$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');


问:
How to create an sql string to count selected rows with group by
I am trying to query a mysql database with columns AUTHOR, TITLE, TEXT to count all instances of texts by a given title, grouped by an author, e.g.
my table look like this

If my parameter is "Great Expectations", there are 2 entries of Great Expectaions by Dickens and 1 entry of Great Expectaions some Kathy Acker.

```<code>[{author=Charles Dickens, title=Great Expectations, count=2}, {author=Kathy Ackers, title=Great Expectations, count=1}]
</code>```

So far I have come up with this string:

```<code> jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote GROUP BY author")
</code>```

It somehow works but returns the counts of all entries by author in the database and all of my attempts to refine the search have failed.

I thought to include ...WHERE title = "Great Expectations"... but it does not work.

答:
Is this what you are looking for ?
It is hard to understand from your question what is in your text field ? What kind of data?
What do you counting ?
My understanding is this:

```<code>SELECT author, title, ROUND ((LENGTH(text) - LENGTH(REPLACE(text,
                            title, "") )) / LENGTH(title))  AS count
FROM Quote
</code>```

Then you can add this to select only the title you need:

```<code>where title = 'The Lost World'
</code>```

So you get this:

```<code>SELECT author, title, ROUND ((LENGTH(text) - LENGTH(REPLACE(text,
                            title, "") )
        ) / LENGTH(title)
    )  AS count
FROM Quote
where title = 'The Lost World'
</code>```

Here is a demo

Reading your question second time I see you maybe need this:

```<code>SELECT author, title, COUNT(*) as count
FROM Quote
where title = 'The Lost World'
GROUP BY author, title
</code>```

or like this:

```<code>jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote
where title = 'The Lost World'
GROUP BY author, title")
</code>```

Body:
I am trying to query a mysql database with columns AUTHOR, TITLE, TEXT to count all instances of texts by a given title, grouped by an author, e.g.
my table look like this

If my parameter is "Great Expectations", there are 2 entries of Great Expectaions by Dickens and 1 entry of Great Expectaions some Kathy Acker.

[{author=Charles Dickens, title=Great Expectations, count=2}, {author=Kathy Ackers, title=Great Expectations, count=1}]

So far I have come up with this string:

 jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote GROUP BY author")

It somehow works but returns the counts of all entries by author in the database and all of my attempts to refine the search have failed.

I thought to include ...WHERE title = "Great Expectations"... but it does not work.

Body:
Is this what you are looking for ?
It is hard to understand from your question what is in your text field ? What kind of data?
What do you counting ?
My understanding is this:

SELECT author, title, ROUND ((LENGTH(text) - LENGTH(REPLACE(text,
                            title, "") )) / LENGTH(title))  AS count
FROM Quote

Then you can add this to select only the title you need:

where title = 'The Lost World'

So you get this:

SELECT author, title, ROUND ((LENGTH(text) - LENGTH(REPLACE(text,
                            title, "") )
        ) / LENGTH(title)
    )  AS count
FROM Quote
where title = 'The Lost World'

Here is a demo

Reading your question second time I see you maybe need this:

SELECT author, title, COUNT(*) as count
FROM Quote
where title = 'The Lost World'
GROUP BY author, title

or like this:

jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote
where title = 'The Lost World'
GROUP BY author, title")


问:
Apache Has Default URL Rewrites
So I just ran across this oddity.  It appears that Ubuntu has a "feature" (or bug) that allows you to access the same file using differing methods.

```<code><domain>/phpinfo.php
<domain>/phpinfo/somthinghere
</code>```

It seems that both of these load the same file.  I would like to turn this off but so far haven't found a way to do so.  Any Debian/Ubuntu folks out there know how to do that?

Thanks

答:
Can you paste the virtual hosts file?

My bet is Content Negotiation, you need to remove the

```<code> Options -MultiViews
</code>```

MultiViews from the option section, or put a - before it.

Title: Apache Has Default URL Rewrites

Body:
So I just ran across this oddity.  It appears that Ubuntu has a "feature" (or bug) that allows you to access the same file using differing methods.

<domain>/phpinfo.php
<domain>/phpinfo/somthinghere

It seems that both of these load the same file.  I would like to turn this off but so far haven't found a way to do so.  Any Debian/Ubuntu folks out there know how to do that?

Thanks

Body:
Can you paste the virtual hosts file?

My bet is Content Negotiation, you need to remove the

 Options -MultiViews

MultiViews from the option section, or put a - before it.


问:
Get X coordinate from SDO_GEOMETRY point
I have a SDO_GEOMETRY point:

```<code> --yields SDO_GEOMETRY type, which contains an SDO_POINT
 select point from tbl

  --yields a vertex_set_tye
 select SDO_UTIL.GETVERTICES(point) from tbl
</code>```

How can I extract the X coordinate value using: SDO_UTIL.GETVERTICES(point)?

答:
This is my table and its contents; column GEOM is SDO_GEOMETRY.

```<code>SQL> desc test
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                                        NOT NULL NUMBER
 GEOM                                               MDSYS.SDO_GEOMETRY

SQL> select id, geom from test where rownum = 1;

        ID GEOM(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES)
---------- ------------------------------------------------------------------------------------------
   1062937 SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE(16,9176067, 46,2172763, NULL), NULL, NULL)

SQL>
</code>```

Extracting X and Y coordinates is quite simple:

```<code>SQL> select a.x,
  2         a.y
  3  from test t cross join table(sdo_util.getvertices(t.geom)) a
  4  where t.id = 1062937;

         X          Y
---------- ----------
16,9176067 46,2172763

SQL>
</code>```

Body:
I have a SDO_GEOMETRY point:

 --yields SDO_GEOMETRY type, which contains an SDO_POINT
 select point from tbl

  --yields a vertex_set_tye
 select SDO_UTIL.GETVERTICES(point) from tbl

How can I extract the X coordinate value using: SDO_UTIL.GETVERTICES(point)?

Body:
This is my table and its contents; column GEOM is SDO_GEOMETRY.

SQL> desc test
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                                        NOT NULL NUMBER
 GEOM                                               MDSYS.SDO_GEOMETRY

SQL> select id, geom from test where rownum = 1;

        ID GEOM(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES)
---------- ------------------------------------------------------------------------------------------
   1062937 SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE(16,9176067, 46,2172763, NULL), NULL, NULL)

SQL>

Extracting X and Y coordinates is quite simple:

SQL> select a.x,
  2         a.y
  3  from test t cross join table(sdo_util.getvertices(t.geom)) a
  4  where t.id = 1062937;

         X          Y
---------- ----------
16,9176067 46,2172763

SQL>


问:
Google sheets add-on, not working properly after publishing
I've created a google sheets add-on for someone else, and they need other people in their Gsuite organization to be able to use the add-on as well. The add on worked as intended during testing and development, but when we published it, it would only work for the account that published it. When other's tried using it, it would not work properly. It had some functionality, but not others, and I'm unable to pinpoint what is happening.

I have been googling, following guides and experimenting for hours now and cannot figure this out. I believe I have added all the scopes needed, and enabled all the apis, but I am new to this so idk?

I'm sorry if this is a really vague and not very thought out question, but I really need help and don't really know where else to go. Any help is appreciated so much

[EDITED WITH CODE]
The Add-on shows up in the marketplace and can be installed. It shows the menu and the sidebar, but no buttons actually work in the sidebar. I think its an issue with the add-on and publication of it, rather than an issue with the code itself, but I guess that's why I'm asking here...
https://codepen.io/garrettarh/pen/abvgmKJ
I get this error in the chrome console:

```<code>Uncaught     (string of numbers)-mae_html_user_bin_i18n_mae_html_user.js:54
</code>```

I know it's not pretty lmao, but I'm new to Gsuite and App Script, just finding something that works. Optimization isn't really the priority atm.

[EDITED WITH SCOPES]

[EDIT WITH WORKAROUND]
I came across this question Uploading a file using an HtmlService form in Google Apps always causes "server error" and a stack trace

and someone suggested using STABLE as the runtime version instead of V8, and so far I believe this has fixed my issue. I'm not savvy enough to know exactly what was wrong.

答:
I'm not sure if this will make any difference at all, but I changed the script in the HTML to:

    <base target="_top">
    <link href="https://ssl.gstatic.com/docs/script/css/add-ons.css" rel="stylesheet">

Course Choice ID Match

Input Sheet

    <select name="Input Sheet" id="inputSheetDD">
       <option value="" disabled selected hidden>Choose an input sheet</option>
       <? var sheets=SpreadsheetApp.getActive().getSheets(); ?>
       <? for (var i=0;i<sheets.length;i++) { ?>
       <option value=<?=sheets[i].getName()?>> <?= sheets[i].getName()?></option>
       <? } ?>
    </select>
    <? var sheets=SpreadsheetApp.getActive(); ?>

Input Columns

Email Columns

       <input type="text" placeholder="type cell range" id="emailRange" size="12"?>

OR...

       <button id="emailButton">Get Selected Range</button>

Classes Columns

       <input type="text" placeholder="type cell range" id="classesRange" size="12"?>

OR...

       <button id="classesButton">Get Selected Range</button>

Output

Output Sheet Name

    <input type="text" placeholder="name output sheet" id="outputName">

Creator ID

    <input type="text" placeholder="type creator ID #" id="creatorID">
    <button id="runScript">Run Script</button>

```

Body:
I've created a google sheets add-on for someone else, and they need other people in their Gsuite organization to be able to use the add-on as well. The add on worked as intended during testing and development, but when we published it, it would only work for the account that published it. When other's tried using it, it would not work properly. It had some functionality, but not others, and I'm unable to pinpoint what is happening.

I have been googling, following guides and experimenting for hours now and cannot figure this out. I believe I have added all the scopes needed, and enabled all the apis, but I am new to this so idk?

I'm sorry if this is a really vague and not very thought out question, but I really need help and don't really know where else to go. Any help is appreciated so much

[EDITED WITH CODE]
The Add-on shows up in the marketplace and can be installed. It shows the menu and the sidebar, but no buttons actually work in the sidebar. I think its an issue with the add-on and publication of it, rather than an issue with the code itself, but I guess that's why I'm asking here...
https://codepen.io/garrettarh/pen/abvgmKJ
I get this error in the chrome console:

Uncaught     (string of numbers)-mae_html_user_bin_i18n_mae_html_user.js:54

I know it's not pretty lmao, but I'm new to Gsuite and App Script, just finding something that works. Optimization isn't really the priority atm.

[EDITED WITH SCOPES]

[EDIT WITH WORKAROUND]
I came across this question Uploading a file using an HtmlService form in Google Apps always causes "server error" and a stack trace

and someone suggested using STABLE as the runtime version instead of V8, and so far I believe this has fixed my issue. I'm not savvy enough to know exactly what was wrong.

Body:
I'm not sure if this will make any difference at all, but I changed the script in the HTML to:

<html>
  <head>
    <base target="_top">
    <link href="https://ssl.gstatic.com/docs/script/css/add-ons.css" rel="stylesheet">
    <style>
    #title {
    color: #54AE54 !important;
    font-size: 18px;
    padding: 6px;
    }
    #runScript {
    background: #54AE54 !important;
    color: #F1FFE7;
    margin: 20px;
    }

    body {
    background: white;
    text-align: center;
    }
    .outline {
    outline-style: double ;
    outline-color: #968E85 ;
    padding: 10px;
    }

    .smallH {
    margin-block-start: 0.8em;
    margin-block-end: 0.8em;
    }
    .range {
    width: 45%;
    display: inline-block;
    padding: 5px;
    }
    #classesRange:disabled {
    color: gray;
    }
    #emailRange:disabled {
    color: gray;
    }
    </style>
  </head>

  <body>
  <div class="outline">
    <h1 id="title">Course Choice ID Match</h1>
    <hr class='solid'>
    <h2>Input Sheet</h2>
    <select name="Input Sheet" id="inputSheetDD">
       <option value="" disabled selected hidden>Choose an input sheet</option>
       <? var sheets=SpreadsheetApp.getActive().getSheets(); ?>
       <? for (var i=0;i<sheets.length;i++) { ?>
       <option value=<?=sheets[i].getName()?>> <?= sheets[i].getName()?></option>
       <? } ?>
    </select>
    <? var sheets=SpreadsheetApp.getActive(); ?>
    <h2>Input Columns</h2>
    <div class="range">
    <h4>Email Columns</h4>
       <input type="text" placeholder="type cell range" id="emailRange" size="12"?>
       <h5 class="smallH">OR...</h5>
       <button id="emailButton">Get Selected Range</button>
    </div>
    <div class="range">
       <h4>Classes Columns</h4>
       <input type="text" placeholder="type cell range" id="classesRange" size="12"?>
       <h5 class="smallH">OR...</h5>
       <button id="classesButton">Get Selected Range</button>
    </div>
    <h2>Output</h2>
    <h5 class="smallH">Output Sheet Name</h5>
    <input type="text" placeholder="name output sheet" id="outputName">
    <h5 class="smallH">Creator ID</h5>
    <input type="text" placeholder="type creator ID #" id="creatorID">
    <button id="runScript">Run Script</button>
   </div>

    <script>
    function onSuccess(activeRange) {
       if (window.buttonClicked == 'classesButton') {
          classesRange.value = activeRange;
          classesRange.disabled = false;
       }
       if (window.buttonClicked == 'emailButton') {
          emailRange.value = activeRange;
          emailRange.disabled = false;
       }
    }

    window.onload = function() {
      var buttons = document.getElementsByTagName("button");

      console.log("buttons.length: " + buttons.length)

      for (var i = 0; i <= buttons.length; i += 1) {
        var thisBtn = buttons[i];

        if (!thisBtn) {
          return;
        }

        console.log('thisBtn.id: ' + thisBtn.id)
        var thisID = thisBtn.id;

        switch(thisID) {

          case 'classesButton':
            console.log('its classesButton')
            thisBtn.addEventListener("click", function() {
              window.buttonClicked = this.id;
              document.getElementById("classesRange").disabled = true;
              document.getElementById("classesRange").value = "working...";
              google.script.run.withSuccessHandler(onSuccess).getSelectedRange();
             })

             break;
            case 'emailButton':
              console.log('its emailButton')

              thisBtn.addEventListener("click", function() {
                window.buttonClicked = this.id;
                document.getElementById("emailRange").disabled = true;
                document.getElementById("emailRange").value = "working...";
                google.script.run.withSuccessHandler(onSuccess).getSelectedRange();
               })
              break;
            case 'runScript':
              console.log('its runScript')

              thisBtn.addEventListener("click", function() {
                window.buttonClicked = this.id;
                var inputSheet = document.getElementById('inputSheetDD').value;
                var emailRange = document.getElementById('emailRange').value;
                var classesRange = document.getElementById('classesRange').value;
                var outputName = document.getElementById('outputName').value;
                var creatorID = document.getElementById('creatorID').value
                google.script.run.interpret(inputSheet, emailRange, classesRange, outputName, creatorID);
                })
                break;
            }
         }

        };

    </script>
  </body>
</html>


问:
:hover seems to not work and i have no idea why
I don't know why, but hover won't change the opacity of the image. I've even tried to make a separate HTML page and it has the same problem.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

OPACITY 0.2

OPACITY 0.5

OPACITY 1

```

答:
As is mentioned your inline style is overriding any attempt to affect opacity:

Here is a better way to do it:

```<code><h3>OPACITY 0.2</h3>
<img class="changeme" src="https://i.ytimg.com/vi/Ep3jK1bZrB8/maxresdefault.jpg" alt="1">

.changeme {
  opacity: 0.2;
}
.changeme:hover {
  opacity: 1;
}
</code>```

https://jsfiddle.net/7mo8ygxn/

Body:
As is mentioned your inline style is overriding any attempt to affect opacity:

Here is a better way to do it:

<h3>OPACITY 0.2</h3>
<img class="changeme" src="https://i.ytimg.com/vi/Ep3jK1bZrB8/maxresdefault.jpg" alt="1">

.changeme {
  opacity: 0.2;
}
.changeme:hover {
  opacity: 1;
}

https://jsfiddle.net/7mo8ygxn/


问:
Jmeter Mobile App testing - Unable to proxy
Installed Jmeter 5.3 on my Mac. I had set the HTTP(s) proxy to 8089. Installed Jmeter certificate on my pixel 2xl device. Configured the proxy with port. After proxy setup, unable to surf internet on my mobile. As a result unable to record Jmeter script.</p>

答:
Make sure that both devices are on the same subnet and you can i.e. ping mobile from laptop and vice versa

Make sure that JMeter is listening to IPv4 interface and if this is not the case - add java.net.preferIPv4Stack=true line to system.properties file (lives in "bin" folder of your JMeter installation)

Make sure that incoming connections to port 8089 are not blocked by your operating system firewall or other antivirus software

If your device is running Android 7.0 or higher you need to take some extra steps to be able to record HTTPS traffic, in particular:

Add the next line to the application section of your Android application  manifest file:

```<code>android:networkSecurityConfig="@xml/network_security_config"
</code>```

Create network_security_config.xml file under your application resources folder and put the following code inside:

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <!-- Trust user added CAs while debuggable only -->
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>
</code>```

Compile and install your application in debug mode:

```<code>gradlew installDebug
</code>```

More information: Recording Using Android Devices

If you don't have access to application sources you will have to root your device in order to be able to record traffic using JMeter by placing its certificate into Android OS  trusted authorities storage

Body:
Make sure that both devices are on the same subnet and you can i.e. ping mobile from laptop and vice versa

Make sure that JMeter is listening to IPv4 interface and if this is not the case - add java.net.preferIPv4Stack=true line to system.properties file (lives in "bin" folder of your JMeter installation)

Make sure that incoming connections to port 8089 are not blocked by your operating system firewall or other antivirus software

If your device is running Android 7.0 or higher you need to take some extra steps to be able to record HTTPS traffic, in particular:

Add the next line to the application section of your Android application  manifest file:

android:networkSecurityConfig="@xml/network_security_config"

Create network_security_config.xml file under your application resources folder and put the following code inside:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <!-- Trust user added CAs while debuggable only -->
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>

Compile and install your application in debug mode:

gradlew installDebug

More information: Recording Using Android Devices

If you don't have access to application sources you will have to root your device in order to be able to record traffic using JMeter by placing its certificate into Android OS  trusted authorities storage


问:
enter special characters (accents) in a windows form application
I am working on a MS Paint like application and we allow the user to enter text as well. Now a requirement is to allow the user to enter accents and other special characters.

I understand that we can show the charmap.exe from within the application and allow the user to copy the character and the paste it in the text box used to enter the text. However, we would like the ability where user selects the character and it is entered in the text box.

So is implementing a dialog with the character set the only option ? And if it is the only option, is there a standard way to implement this.

Thanks,
Gaurav

答: You don't need to do anything. Typically the user will have a keyboard that lets them enter the characters that they need for their language. For some languages they will use a system provided IME but again you need to do nothing special to support this.</p>


问:
What is the best way to programmatically choose the best GPU in OpenCL?
On my laptop I have two graphic cards - Intel Iris and Nvidia GeForce GT 750M. I am trying to do a simple vector add using OpenCL. I know, that Nvidia card is much faster and can do the job better. In principle, I can put an if statement in the code that will look for NVIDIA in the VENDOR attribute. But I'd like to have something elegant. What is the best way to choose a better (faster) GPU programmatically in OpenCL C/C++?

答:
Take a look at this code for GPU discrimination:

```<code>#include <iostream>

#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#pragma comment (lib, "x86_64/opencl.lib")
#endif

//OpenCL saxpy kernel used for benchmarking
const char* saxpy_kernel =
"__kernel                                    \n"
"void saxpy_kernel(float alpha,              \n"
"                  __global float *A,        \n"
"                  __global float *B,        \n"
"                  __global float *C)        \n"
"{                                           \n"
"    int idx = get_global_id(0);             \n"
"    C[idx] = alpha * A[idx] + B[idx];       \n"
"}                                           ";

const char* clErrName[] = {
    "CL_SUCCESS",                                   //0
    "CL_DEVICE_NOT_FOUND",                          //-1
    "CL_DEVICE_NOT_AVAILABLE",                      //-2
    "CL_COMPILER_NOT_AVAILABLE",                    //-3
    "CL_MEM_OBJECT_ALLOCATION_FAILURE",             //-4
    "CL_OUT_OF_RESOURCES",                          //-5
    "CL_OUT_OF_HOST_MEMORY",                        //-6
    "CL_PROFILING_INFO_NOT_AVAILABLE",              //-7
    "CL_MEM_COPY_OVERLAP",                          //-8
    "CL_IMAGE_FORMAT_MISMATCH",                     //-9
    "CL_IMAGE_FORMAT_NOT_SUPPORTED",                //-10
    "CL_BUILD_PROGRAM_FAILURE",                     //-11
    "CL_MAP_FAILURE",                               //-12
    "CL_MISALIGNED_SUB_BUFFER_OFFSET",              //-13
    "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST", //-14
    "CL_COMPILE_PROGRAM_FAILURE",                   //-15
    "CL_LINKER_NOT_AVAILABLE",                      //-16
    "CL_LINK_PROGRAM_FAILURE",                      //-17
    "CL_DEVICE_PARTITION_FAILED",                   //-18
    "CL_KERNEL_ARG_INFO_NOT_AVAILABLE",             //-19

    "CL_UNDEFINED_ERROR_20",                        //-20
    "CL_UNDEFINED_ERROR_21",                        //-21
    "CL_UNDEFINED_ERROR_22",                        //-22
    "CL_UNDEFINED_ERROR_23",                        //-23
    "CL_UNDEFINED_ERROR_24",                        //-24
    "CL_UNDEFINED_ERROR_25",                        //-25
    "CL_UNDEFINED_ERROR_26",                        //-26
    "CL_UNDEFINED_ERROR_27",                        //-27
    "CL_UNDEFINED_ERROR_28",                        //-28
    "CL_UNDEFINED_ERROR_29",                        //-29

    "CL_INVALID_VALUE",                             //-30
    "CL_INVALID_DEVICE_TYPE",                       //-31
    "CL_INVALID_PLATFORM",                          //-32
    "CL_INVALID_DEVICE",                            //-33
    "CL_INVALID_CONTEXT",                           //-34
    "CL_INVALID_QUEUE_PROPERTIES",                  //-35
    "CL_INVALID_COMMAND_QUEUE",                     //-36
    "CL_INVALID_HOST_PTR",                          //-37
    "CL_INVALID_MEM_OBJECT",                        //-38
    "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",           //-39
    "CL_INVALID_IMAGE_SIZE",                        //-40
    "CL_INVALID_SAMPLER",                           //-41
    "CL_INVALID_BINARY",                            //-42
    "CL_INVALID_BUILD_OPTIONS",                     //-43
    "CL_INVALID_PROGRAM",                           //-44
    "CL_INVALID_PROGRAM_EXECUTABLE",                //-45
    "CL_INVALID_KERNEL_NAME",                       //-46
    "CL_INVALID_KERNEL_DEFINITION",                 //-47
    "CL_INVALID_KERNEL",                            //-48
    "CL_INVALID_ARG_INDEX",                         //-49
    "CL_INVALID_ARG_VALUE",                         //-50
    "CL_INVALID_ARG_SIZE",                          //-51
    "CL_INVALID_KERNEL_ARGS",                       //-52
    "CL_INVALID_WORK_DIMENSION",                    //-53
    "CL_INVALID_WORK_GROUP_SIZE",                   //-54
    "CL_INVALID_WORK_ITEM_SIZE",                    //-55
    "CL_INVALID_GLOBAL_OFFSET",                     //-56
    "CL_INVALID_EVENT_WAIT_LIST",                   //-57
    "CL_INVALID_EVENT",                             //-58
    "CL_INVALID_OPERATION",                         //-59
    "CL_INVALID_GL_OBJECT",                         //-60
    "CL_INVALID_BUFFER_SIZE",                       //-61
    "CL_INVALID_MIP_LEVEL",                         //-62
    "CL_INVALID_GLOBAL_WORK_SIZE",                  //-63
    "CL_INVALID_PROPERTY",                          //-64
    "CL_INVALID_IMAGE_DESCRIPTOR",                  //-65
    "CL_INVALID_COMPILER_OPTIONS",                  //-66
    "CL_INVALID_LINKER_OPTIONS",                    //-67
    "CL_INVALID_DEVICE_PARTITION_COUNT",            //-68
    "CL_INVALID_PIPE_SIZE",                         //-69
    "CL_INVALID_DEVICE_QUEUE",                      //-70
};
 const int MAX_ERR_CODE = 70;

inline bool __clCallSuccess(cl_int err_code, const char* source_file, const int source_line)
{
    if (err_code == CL_SUCCESS)
        return true;

    if ((err_code > 0) || (err_code < -MAX_ERR_CODE))
        std::clog << "\t - unknown CL error: " << err_code;
    else
        std::clog << "\t - CL call error: " << clErrName[-err_code];

    std::clog << " [" << source_file << " : " << source_line << "]" << std::endl;

    return false;
}

#define clCallSuccess(err_code) __clCallSuccess(err_code, __FILE__, __LINE__)

float cl_BenchmarkDevice(cl_context context, cl_command_queue command_queue, cl_device_id device_id)
{
    float microSeconds = -1.;
    int i;
    cl_int clStatus;

    const int VECTOR_SIZE = 512 * 1024;
    // Allocate space for vectors A, B and C
    float* A = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(A) {
    float* B = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(B) {
    float* C = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(C) {
    for (i = 0; i < VECTOR_SIZE; i++)
    {
        A[i] = (float)i;
        B[i] = (float)(VECTOR_SIZE - i);
        C[i] = 0;
    }

    // Create memory buffers on the device for each vector
    cl_mem A_clmem = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);   if (clCallSuccess(clStatus)) {
    cl_mem B_clmem = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);   if (clCallSuccess(clStatus)) {
    cl_mem C_clmem = clCreateBuffer(context, CL_MEM_WRITE_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);  if (clCallSuccess(clStatus)) {

    // Copy the Buffer A and B to the device
    clStatus = clEnqueueWriteBuffer(command_queue, A_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), A, 0, NULL, NULL); if (clCallSuccess(clStatus)) {
    clStatus = clEnqueueWriteBuffer(command_queue, B_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), B, 0, NULL, NULL); if (clCallSuccess(clStatus)) {

    // Create a program from the kernel source and build it
    cl_program program = clCreateProgramWithSource(context, 1, (const char**)&saxpy_kernel, NULL, &clStatus);   if (clCallSuccess(clStatus) && program) {
    clStatus = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);                                        if (clCallSuccess(clStatus)) {

    // Create the OpenCL kernel
    cl_kernel kernel = clCreateKernel(program, "saxpy_kernel", &clStatus);                  if (clCallSuccess(clStatus) && kernel) {

    float alpha = 2.5;
    // Set the arguments of the kernel
    clStatus = clSetKernelArg(kernel, 0, sizeof(float), (void*)&alpha);                     if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&A_clmem);                  if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&B_clmem);                  if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*)&C_clmem);                  if (clCallSuccess(clStatus)) {

    // Execute the OpenCL kernel on the list
    cl_event event;
    size_t global_size = VECTOR_SIZE; // Process the entire lists
    size_t local_size = 512;           // Process one item at a time
    //clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, &event);
    clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, NULL, 0, NULL, &event);                 if (clCallSuccess(clStatus)) {
    clStatus = clWaitForEvents(1, &event);                                                                                if (clCallSuccess(clStatus)) {
    //measure duration
    cl_ulong time_start;
    cl_ulong time_end;
    clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL);
    clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL);
    microSeconds = (float)(time_end - time_start) / 1000.0f;
    std::clog << "\nOpenCl benchmarking time: " << microSeconds << " microseconds \n";

    std::clog << "\n\t*****************************\n\n";
    }
    // Read the cl memory C_clmem on device to the host variable C
    clCallSuccess(clEnqueueReadBuffer(command_queue, C_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), C, 0, NULL, NULL));

    // Clean up and wait for all the comands to complete.
    clCallSuccess(clFlush(command_queue));
    clCallSuccess(clFinish(command_queue));

    } //Kernel

    }}}} //SetKErnelArg

    // Finally release all OpenCL allocated objects and host buffers.

    clCallSuccess(clReleaseKernel(kernel)); }

    } //BuildProgram

    clCallSuccess(clReleaseProgram(program)); }

    } } //EnqueueWriteBuffer

    clCallSuccess(clReleaseMemObject(C_clmem)); }
    clCallSuccess(clReleaseMemObject(B_clmem)); }
    clCallSuccess(clReleaseMemObject(A_clmem)); }

    free(C); }
    free(B); }
    free(A); }

    return microSeconds;
}

/*
struct _dev_info {
    cl_platform_id platfID;
    cl_device_id devID;
};
typedef struct _dev_info dev_info;
*/
cl_device_id cl_GetBestDevice(void)
{
    cl_int err;
    cl_uint numPlatforms, numDevices;
    cl_platform_id platfIDs[10];
    cl_device_id devIDsAll[10];
    int countGPUs = 0;
    cl_device_id best_device = NULL;
    float best_perf = 100000000.;

    if (clCallSuccess(clGetPlatformIDs(10, platfIDs, &numPlatforms)))
    {
        std::clog << "OpenCL platforms detected: " << numPlatforms << std::endl;

        for (unsigned int i = 0; i < numPlatforms; i++)
        {
            std::clog << "PlatformInfo for platform no." << (i + 1) << std::endl;

            const int SZ_INFO = 1024;
            char info[SZ_INFO];
            size_t sz;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_NAME, SZ_INFO, info, &sz)))
                std::clog << " - - Name: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_VENDOR, SZ_INFO, info, &sz)))
                std::clog << " - - Vendor: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_PROFILE, SZ_INFO, info, &sz)))
                std::clog << " - - Profile: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_VERSION, SZ_INFO, info, &sz)))
                std::clog << " - - Version: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_EXTENSIONS, SZ_INFO, info, &sz)))
                std::clog << " - - Extensions: " << info << std::endl;

            if (clCallSuccess(clGetDeviceIDs(platfIDs[i], CL_DEVICE_TYPE_ALL, 10, devIDsAll, &numDevices)))
            {
                cl_context_properties cProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platfIDs[i]), 0 };
                cl_command_queue_properties qProperties[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 };

                for (unsigned int ii = 0; ii < numDevices; ii++)
                {
                    cl_uint val;
                    cl_ulong memsz;
                    cl_device_type dt;
                    size_t mws;

                    std::clog << " >> DeviceInfo for device no." << (ii + 1) << std::endl;

                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_NAME, SZ_INFO, info, &sz)))
                        std::clog << "\t - Name: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_VENDOR, SZ_INFO, info, &sz)))
                        std::clog << "\t - Vendor: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_VERSION, SZ_INFO, info, &sz)))
                        std::clog << "\t - Version: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_TYPE, sizeof(dt), &dt, &sz)))
                    {
                        std::clog << "\t - Type: ";
                        switch (dt)
                        {
                            case CL_DEVICE_TYPE_CPU: std::clog << "CPU"; break;
                            case CL_DEVICE_TYPE_GPU: std::clog << "GPU"; break;
                            case CL_DEVICE_TYPE_ACCELERATOR: std::clog << "Accelerator"; break;
                            case CL_DEVICE_TYPE_DEFAULT: std::clog << "Default"; break;
                            default: std::clog << "ERROR";
                        }
                        std::clog << std::endl;
                    }
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memsz), &memsz, &sz)))
                        std::clog << "\t - Memory: " << (memsz / 1024 / 1024) << " MB" << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, &sz)))
                        std::clog << "\t - Max Frequency: " << val << " MHz" << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, &sz)))
                        std::clog << "\t - Compute units: " << val << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(mws), &mws, &sz)))
                        std::clog << "\t - Max workgroup size: " << mws << std::endl;

                    // Create an OpenCL context
                    cl_context context = clCreateContext(NULL, 1, devIDsAll+ii, NULL, NULL, &err);
                    if (clCallSuccess(err) && context)
                    {
                        // Create a command queue
                        cl_command_queue command_queue = clCreateCommandQueueWithProperties(context, devIDsAll[ii], qProperties, &err);
                        if (clCallSuccess(err) && command_queue)
                        {
                            float perf = cl_BenchmarkDevice(context, command_queue, devIDsAll[ii]);
                            if ((perf > 0) && (perf < best_perf))
                            {
                                best_perf = perf;
                                best_device = devIDsAll[ii];
                            }

                            clCallSuccess(clReleaseCommandQueue(command_queue));
                        }
                        clCallSuccess(clReleaseContext(context));
                    }
                }
            }
        }
    }
    return best_device;
}
</code>```

here is the output on my PC

Body:
Take a look at this code for GPU discrimination:

#include <iostream>

#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#pragma comment (lib, "x86_64/opencl.lib")
#endif

//OpenCL saxpy kernel used for benchmarking
const char* saxpy_kernel =
"__kernel                                    \n"
"void saxpy_kernel(float alpha,              \n"
"                  __global float *A,        \n"
"                  __global float *B,        \n"
"                  __global float *C)        \n"
"{                                           \n"
"    int idx = get_global_id(0);             \n"
"    C[idx] = alpha * A[idx] + B[idx];       \n"
"}                                           ";

const char* clErrName[] = {
    "CL_SUCCESS",                                   //0
    "CL_DEVICE_NOT_FOUND",                          //-1
    "CL_DEVICE_NOT_AVAILABLE",                      //-2
    "CL_COMPILER_NOT_AVAILABLE",                    //-3
    "CL_MEM_OBJECT_ALLOCATION_FAILURE",             //-4
    "CL_OUT_OF_RESOURCES",                          //-5
    "CL_OUT_OF_HOST_MEMORY",                        //-6
    "CL_PROFILING_INFO_NOT_AVAILABLE",              //-7
    "CL_MEM_COPY_OVERLAP",                          //-8
    "CL_IMAGE_FORMAT_MISMATCH",                     //-9
    "CL_IMAGE_FORMAT_NOT_SUPPORTED",                //-10
    "CL_BUILD_PROGRAM_FAILURE",                     //-11
    "CL_MAP_FAILURE",                               //-12
    "CL_MISALIGNED_SUB_BUFFER_OFFSET",              //-13
    "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST", //-14
    "CL_COMPILE_PROGRAM_FAILURE",                   //-15
    "CL_LINKER_NOT_AVAILABLE",                      //-16
    "CL_LINK_PROGRAM_FAILURE",                      //-17
    "CL_DEVICE_PARTITION_FAILED",                   //-18
    "CL_KERNEL_ARG_INFO_NOT_AVAILABLE",             //-19

    "CL_UNDEFINED_ERROR_20",                        //-20
    "CL_UNDEFINED_ERROR_21",                        //-21
    "CL_UNDEFINED_ERROR_22",                        //-22
    "CL_UNDEFINED_ERROR_23",                        //-23
    "CL_UNDEFINED_ERROR_24",                        //-24
    "CL_UNDEFINED_ERROR_25",                        //-25
    "CL_UNDEFINED_ERROR_26",                        //-26
    "CL_UNDEFINED_ERROR_27",                        //-27
    "CL_UNDEFINED_ERROR_28",                        //-28
    "CL_UNDEFINED_ERROR_29",                        //-29

    "CL_INVALID_VALUE",                             //-30
    "CL_INVALID_DEVICE_TYPE",                       //-31
    "CL_INVALID_PLATFORM",                          //-32
    "CL_INVALID_DEVICE",                            //-33
    "CL_INVALID_CONTEXT",                           //-34
    "CL_INVALID_QUEUE_PROPERTIES",                  //-35
    "CL_INVALID_COMMAND_QUEUE",                     //-36
    "CL_INVALID_HOST_PTR",                          //-37
    "CL_INVALID_MEM_OBJECT",                        //-38
    "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",           //-39
    "CL_INVALID_IMAGE_SIZE",                        //-40
    "CL_INVALID_SAMPLER",                           //-41
    "CL_INVALID_BINARY",                            //-42
    "CL_INVALID_BUILD_OPTIONS",                     //-43
    "CL_INVALID_PROGRAM",                           //-44
    "CL_INVALID_PROGRAM_EXECUTABLE",                //-45
    "CL_INVALID_KERNEL_NAME",                       //-46
    "CL_INVALID_KERNEL_DEFINITION",                 //-47
    "CL_INVALID_KERNEL",                            //-48
    "CL_INVALID_ARG_INDEX",                         //-49
    "CL_INVALID_ARG_VALUE",                         //-50
    "CL_INVALID_ARG_SIZE",                          //-51
    "CL_INVALID_KERNEL_ARGS",                       //-52
    "CL_INVALID_WORK_DIMENSION",                    //-53
    "CL_INVALID_WORK_GROUP_SIZE",                   //-54
    "CL_INVALID_WORK_ITEM_SIZE",                    //-55
    "CL_INVALID_GLOBAL_OFFSET",                     //-56
    "CL_INVALID_EVENT_WAIT_LIST",                   //-57
    "CL_INVALID_EVENT",                             //-58
    "CL_INVALID_OPERATION",                         //-59
    "CL_INVALID_GL_OBJECT",                         //-60
    "CL_INVALID_BUFFER_SIZE",                       //-61
    "CL_INVALID_MIP_LEVEL",                         //-62
    "CL_INVALID_GLOBAL_WORK_SIZE",                  //-63
    "CL_INVALID_PROPERTY",                          //-64
    "CL_INVALID_IMAGE_DESCRIPTOR",                  //-65
    "CL_INVALID_COMPILER_OPTIONS",                  //-66
    "CL_INVALID_LINKER_OPTIONS",                    //-67
    "CL_INVALID_DEVICE_PARTITION_COUNT",            //-68
    "CL_INVALID_PIPE_SIZE",                         //-69
    "CL_INVALID_DEVICE_QUEUE",                      //-70
};
 const int MAX_ERR_CODE = 70;

inline bool __clCallSuccess(cl_int err_code, const char* source_file, const int source_line)
{
    if (err_code == CL_SUCCESS)
        return true;

    if ((err_code > 0) || (err_code < -MAX_ERR_CODE))
        std::clog << "\t - unknown CL error: " << err_code;
    else
        std::clog << "\t - CL call error: " << clErrName[-err_code];

    std::clog << " [" << source_file << " : " << source_line << "]" << std::endl;

    return false;
}

#define clCallSuccess(err_code) __clCallSuccess(err_code, __FILE__, __LINE__)

float cl_BenchmarkDevice(cl_context context, cl_command_queue command_queue, cl_device_id device_id)
{
    float microSeconds = -1.;
    int i;
    cl_int clStatus;

    const int VECTOR_SIZE = 512 * 1024;
    // Allocate space for vectors A, B and C
    float* A = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(A) {
    float* B = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(B) {
    float* C = (float*)malloc(sizeof(float) * VECTOR_SIZE);         if(C) {
    for (i = 0; i < VECTOR_SIZE; i++)
    {
        A[i] = (float)i;
        B[i] = (float)(VECTOR_SIZE - i);
        C[i] = 0;
    }

    // Create memory buffers on the device for each vector
    cl_mem A_clmem = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);   if (clCallSuccess(clStatus)) {
    cl_mem B_clmem = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);   if (clCallSuccess(clStatus)) {
    cl_mem C_clmem = clCreateBuffer(context, CL_MEM_WRITE_ONLY, VECTOR_SIZE * sizeof(float), NULL, &clStatus);  if (clCallSuccess(clStatus)) {

    // Copy the Buffer A and B to the device
    clStatus = clEnqueueWriteBuffer(command_queue, A_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), A, 0, NULL, NULL); if (clCallSuccess(clStatus)) {
    clStatus = clEnqueueWriteBuffer(command_queue, B_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), B, 0, NULL, NULL); if (clCallSuccess(clStatus)) {

    // Create a program from the kernel source and build it
    cl_program program = clCreateProgramWithSource(context, 1, (const char**)&saxpy_kernel, NULL, &clStatus);   if (clCallSuccess(clStatus) && program) {
    clStatus = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);                                        if (clCallSuccess(clStatus)) {

    // Create the OpenCL kernel
    cl_kernel kernel = clCreateKernel(program, "saxpy_kernel", &clStatus);                  if (clCallSuccess(clStatus) && kernel) {

    float alpha = 2.5;
    // Set the arguments of the kernel
    clStatus = clSetKernelArg(kernel, 0, sizeof(float), (void*)&alpha);                     if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&A_clmem);                  if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&B_clmem);                  if (clCallSuccess(clStatus)) {
    clStatus = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*)&C_clmem);                  if (clCallSuccess(clStatus)) {

    // Execute the OpenCL kernel on the list
    cl_event event;
    size_t global_size = VECTOR_SIZE; // Process the entire lists
    size_t local_size = 512;           // Process one item at a time
    //clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, &event);
    clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, NULL, 0, NULL, &event);                 if (clCallSuccess(clStatus)) {
    clStatus = clWaitForEvents(1, &event);                                                                                if (clCallSuccess(clStatus)) {
    //measure duration
    cl_ulong time_start;
    cl_ulong time_end;
    clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL);
    clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL);
    microSeconds = (float)(time_end - time_start) / 1000.0f;
    std::clog << "\nOpenCl benchmarking time: " << microSeconds << " microseconds \n";

    std::clog << "\n\t*****************************\n\n";
    }
    // Read the cl memory C_clmem on device to the host variable C
    clCallSuccess(clEnqueueReadBuffer(command_queue, C_clmem, CL_TRUE, 0, VECTOR_SIZE * sizeof(float), C, 0, NULL, NULL));

    // Clean up and wait for all the comands to complete.
    clCallSuccess(clFlush(command_queue));
    clCallSuccess(clFinish(command_queue));

    } //Kernel

    }}}} //SetKErnelArg

    // Finally release all OpenCL allocated objects and host buffers.

    clCallSuccess(clReleaseKernel(kernel)); }

    } //BuildProgram

    clCallSuccess(clReleaseProgram(program)); }

    } } //EnqueueWriteBuffer

    clCallSuccess(clReleaseMemObject(C_clmem)); }
    clCallSuccess(clReleaseMemObject(B_clmem)); }
    clCallSuccess(clReleaseMemObject(A_clmem)); }

    free(C); }
    free(B); }
    free(A); }

    return microSeconds;
}

/*
struct _dev_info {
    cl_platform_id platfID;
    cl_device_id devID;
};
typedef struct _dev_info dev_info;
*/
cl_device_id cl_GetBestDevice(void)
{
    cl_int err;
    cl_uint numPlatforms, numDevices;
    cl_platform_id platfIDs[10];
    cl_device_id devIDsAll[10];
    int countGPUs = 0;
    cl_device_id best_device = NULL;
    float best_perf = 100000000.;

    if (clCallSuccess(clGetPlatformIDs(10, platfIDs, &numPlatforms)))
    {
        std::clog << "OpenCL platforms detected: " << numPlatforms << std::endl;

        for (unsigned int i = 0; i < numPlatforms; i++)
        {
            std::clog << "PlatformInfo for platform no." << (i + 1) << std::endl;

            const int SZ_INFO = 1024;
            char info[SZ_INFO];
            size_t sz;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_NAME, SZ_INFO, info, &sz)))
                std::clog << " - - Name: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_VENDOR, SZ_INFO, info, &sz)))
                std::clog << " - - Vendor: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_PROFILE, SZ_INFO, info, &sz)))
                std::clog << " - - Profile: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_VERSION, SZ_INFO, info, &sz)))
                std::clog << " - - Version: " << info << std::endl;
            if (clCallSuccess(clGetPlatformInfo(platfIDs[i], CL_PLATFORM_EXTENSIONS, SZ_INFO, info, &sz)))
                std::clog << " - - Extensions: " << info << std::endl;

            if (clCallSuccess(clGetDeviceIDs(platfIDs[i], CL_DEVICE_TYPE_ALL, 10, devIDsAll, &numDevices)))
            {
                cl_context_properties cProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platfIDs[i]), 0 };
                cl_command_queue_properties qProperties[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 };

                for (unsigned int ii = 0; ii < numDevices; ii++)
                {
                    cl_uint val;
                    cl_ulong memsz;
                    cl_device_type dt;
                    size_t mws;

                    std::clog << " >> DeviceInfo for device no." << (ii + 1) << std::endl;

                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_NAME, SZ_INFO, info, &sz)))
                        std::clog << "\t - Name: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_VENDOR, SZ_INFO, info, &sz)))
                        std::clog << "\t - Vendor: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_VERSION, SZ_INFO, info, &sz)))
                        std::clog << "\t - Version: " << info << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_TYPE, sizeof(dt), &dt, &sz)))
                    {
                        std::clog << "\t - Type: ";
                        switch (dt)
                        {
                            case CL_DEVICE_TYPE_CPU: std::clog << "CPU"; break;
                            case CL_DEVICE_TYPE_GPU: std::clog << "GPU"; break;
                            case CL_DEVICE_TYPE_ACCELERATOR: std::clog << "Accelerator"; break;
                            case CL_DEVICE_TYPE_DEFAULT: std::clog << "Default"; break;
                            default: std::clog << "ERROR";
                        }
                        std::clog << std::endl;
                    }
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memsz), &memsz, &sz)))
                        std::clog << "\t - Memory: " << (memsz / 1024 / 1024) << " MB" << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, &sz)))
                        std::clog << "\t - Max Frequency: " << val << " MHz" << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, &sz)))
                        std::clog << "\t - Compute units: " << val << std::endl;
                    if (clCallSuccess(clGetDeviceInfo(devIDsAll[ii], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(mws), &mws, &sz)))
                        std::clog << "\t - Max workgroup size: " << mws << std::endl;

                    // Create an OpenCL context
                    cl_context context = clCreateContext(NULL, 1, devIDsAll+ii, NULL, NULL, &err);
                    if (clCallSuccess(err) && context)
                    {
                        // Create a command queue
                        cl_command_queue command_queue = clCreateCommandQueueWithProperties(context, devIDsAll[ii], qProperties, &err);
                        if (clCallSuccess(err) && command_queue)
                        {
                            float perf = cl_BenchmarkDevice(context, command_queue, devIDsAll[ii]);
                            if ((perf > 0) && (perf < best_perf))
                            {
                                best_perf = perf;
                                best_device = devIDsAll[ii];
                            }

                            clCallSuccess(clReleaseCommandQueue(command_queue));
                        }
                        clCallSuccess(clReleaseContext(context));
                    }
                }
            }
        }
    }
    return best_device;
}

here is the output on my PC


答:
you are giving inline css, and the priority is more of that compared to on page style block

you should do it in this way

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
#div24 img {
  opacity: 0.2;
}
#div24 img:hover {
  opacity: 1.0;
}
</style>
</head>
<body>
<div id="div24">
  <h3>OPACITY 0.2</h3>
  <img src="img01.jpg" alt="1">
  <h3>OPACITY 0.5</h3>
  <img src="img01.jpg" alt="2">
  <h3>OPACITY 1</h3>
  <img src="img01.jpg" alt="1">
</div>
</body>
</html>
</code>```

Title: :hover seems to not work and i have no idea why

Body:
I don't know why, but hover won't change the opacity of the image. I've even tried to make a separate HTML page and it has the same problem.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

OPACITY 0.2

OPACITY 0.5

OPACITY 1

Body:
you are giving inline css, and the priority is more of that compared to on page style block

you should do it in this way

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
#div24 img {
  opacity: 0.2;
}
#div24 img:hover {
  opacity: 1.0;
}
</style>
</head>
<body>
<div id="div24">
  <h3>OPACITY 0.2</h3>
  <img src="img01.jpg" alt="1">
  <h3>OPACITY 0.5</h3>
  <img src="img01.jpg" alt="2">
  <h3>OPACITY 1</h3>
  <img src="img01.jpg" alt="1">
</div>
</body>
</html>


问:
Median and mode in excel using multiple columns
I am working on a spreadsheet for my statistics class. It contains a column filled with a quantity and a column filled with a frequency for each quantity. Using these two columns and several formulas, the mean, mode, median, coefficient variation, quartiles, interquartile range, minimum and maximum values and standard deviation can be found.

The issue is that to shorten the list of quantities, the use of the frequencies column comes in. Take the quantity list of : 10, 12, 14, 15, 18, 18, 10.

Notice that 18 and 10 have been repeated. Instead of repeating those quantities in my quantities column, I increment the frequency of that quantity from 1 to 2. The reason for doing it this way is due to very large lists of quantity data. Meaning I might have 5000 quantities that could potentially be reduced to 20 quantities where each quantity will have a larger frequency.

The issue is that the built-in Median and Mode function use only 1 column or row and do not account for the frequency of each quantity.

My question is this: Is there a way to use both columns to calculate the median and mode? Below is an example of what I was explaining. Additionally, my column containing quantities and frequencies may not be filled from start to end, meaning there maybe empty entries.

```<code>Quantity  |  Frequency
  10      |     4
  12      |     6
  11      |     3
  15      |     1
  18      |     10

VS.

Quantity
10
10
10
10
12
12
12
12
12
12
11
11
11
15
18
18
18
18
18
18
18
18
18
18
</code>```

答:
If one has Office 365 with the dynamic array formula use:

```<code>=MEDIAN(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))
</code>```

and

```<code>=MODE.SNGL(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))
</code>```

If not then this array formula:

```<code>=MEDIAN(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))
</code>```

and

```<code>=MODE.SNGL(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))
</code>```

Being array formula, then need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
I am working on a spreadsheet for my statistics class. It contains a column filled with a quantity and a column filled with a frequency for each quantity. Using these two columns and several formulas, the mean, mode, median, coefficient variation, quartiles, interquartile range, minimum and maximum values and standard deviation can be found.

The issue is that to shorten the list of quantities, the use of the frequencies column comes in. Take the quantity list of : 10, 12, 14, 15, 18, 18, 10.

Notice that 18 and 10 have been repeated. Instead of repeating those quantities in my quantities column, I increment the frequency of that quantity from 1 to 2. The reason for doing it this way is due to very large lists of quantity data. Meaning I might have 5000 quantities that could potentially be reduced to 20 quantities where each quantity will have a larger frequency.

The issue is that the built-in Median and Mode function use only 1 column or row and do not account for the frequency of each quantity.

My question is this: Is there a way to use both columns to calculate the median and mode? Below is an example of what I was explaining. Additionally, my column containing quantities and frequencies may not be filled from start to end, meaning there maybe empty entries.

Quantity  |  Frequency
  10      |     4
  12      |     6
  11      |     3
  15      |     1
  18      |     10

VS.

Quantity
10
10
10
10
12
12
12
12
12
12
11
11
11
15
18
18
18
18
18
18
18
18
18
18

Body:
If one has Office 365 with the dynamic array formula use:

=MEDIAN(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

and

=MODE.SNGL(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

If not then this array formula:

=MEDIAN(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

and

=MODE.SNGL(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

Being array formula, then need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
How to fix limax.zdb.XError: dbhome "zdb" not exist?
here is the error:

```<code>`limax.zdb.XError: dbhome "zdb" not exist
at limax.zdb.Zdb.testMeta(Zdb.java:130)
at limax.zdb.Zdb.start(Zdb.java:144)
at limax.provider.XmlConfig$StartZdb.lambda$0(XmlConfig.java:410)
at limax.xmlconfig.Service$Loader$TaskList.run(Service.java:108)
at limax.xmlconfig.Service$Loader.runTaskBeforeEngineStart(Service.java:257)
at limax.xmlconfig.Service$Loader.startNetEngine(Service.java:298)
at limax.xmlconfig.Service.startNetEngine(Service.java:350)
at limax.xmlconfig.Service.run(Service.java:372)
at forview.server.Main.main(Main.java:8)`
</code>```

here is what's in my service-server.xml:

```<code>`<Zdb autoKeyInitValue="0" autoKeyStep="4096"
    checkpointPeriod="60000" corePoolSize="30" dbhome="zdb"
    deadlockDetectPeriod="1000"
    defaultTableCache="limax.zdb.TTableCacheLRU"
    edbCacheSize="65536" edbLoggerPages="16384" jdbcPoolSize="5"
    marshalN="1" marshalPeriod="-1" procPoolSize="10"
    schedPoolSize="5" snapshotFatalTime="200" zdbVerify="true">
    <Procedure maxExecutionTime="0" retryDelay="100" retryTimes="3" trace="WARN"/>
</Zdb>`
</code>```

Probably I was trying to build a provider using limax in eclipse, but when I run it something goes wrong.Can someone please help me? Thanks very much.

答: ok,I create a new folder named "zdb" in my project and everything is ok now. orz</p>

Body:
here is the error:

`limax.zdb.XError: dbhome "zdb" not exist
at limax.zdb.Zdb.testMeta(Zdb.java:130)
at limax.zdb.Zdb.start(Zdb.java:144)
at limax.provider.XmlConfig$StartZdb.lambda$0(XmlConfig.java:410)
at limax.xmlconfig.Service$Loader$TaskList.run(Service.java:108)
at limax.xmlconfig.Service$Loader.runTaskBeforeEngineStart(Service.java:257)
at limax.xmlconfig.Service$Loader.startNetEngine(Service.java:298)
at limax.xmlconfig.Service.startNetEngine(Service.java:350)
at limax.xmlconfig.Service.run(Service.java:372)
at forview.server.Main.main(Main.java:8)`

here is what's in my service-server.xml:

`<Zdb autoKeyInitValue="0" autoKeyStep="4096"
    checkpointPeriod="60000" corePoolSize="30" dbhome="zdb"
    deadlockDetectPeriod="1000"
    defaultTableCache="limax.zdb.TTableCacheLRU"
    edbCacheSize="65536" edbLoggerPages="16384" jdbcPoolSize="5"
    marshalN="1" marshalPeriod="-1" procPoolSize="10"
    schedPoolSize="5" snapshotFatalTime="200" zdbVerify="true">
    <Procedure maxExecutionTime="0" retryDelay="100" retryTimes="3" trace="WARN"/>
</Zdb>`

Probably I was trying to build a provider using limax in eclipse, but when I run it something goes wrong.Can someone please help me? Thanks very much.


问:
How to pass default for named parameters in javascript
I have a method in typescript as below using named parameters

```<code>public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}
</code>```

parameters m and n will be provided from another object like

```<code>const default = { m : 'M', n :10, o:6 }
</code>```

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

```<code>  foo({x:'x', y: 5, z: 0})
</code>```

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}
</code>```

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}
</code>```

or

```<code>foo({...default, x:'x', y: 5, z: 0 });
</code>```

答:
For merge, u need to use merge using de-structure. default assignment will not work here. The default assignment is for work only if the object is undefined while passing value. So you need to merge the default value with passed value.

Please check comment in code.

```<code>interface Foo {
  x: string;
  y: number;
  z: number;
  m?: string;
  n?: number;
  o?: number;
}
const defaultValue = { m: "M", n: 10, o: 6 } as Foo;
class A {
  public foo(props: Foo) {
    const { x, y, z, m, n } = { ...defaultValue, ...props };
    console.log(x, y, z, m, n);
  }
  public foo2({ x, y, z, m = defaultValue.m, n = defaultValue.n }: Foo) {
    // this will work, but verbose
    console.log(x, y, z, m, n);
  }
  public foo1({ x, y, z, m, n }: Foo = defaultValue) {
    // this will work only if foo1 called without argument
    console.log(x, y, z, m, n);
  }
  public print() {
    this.foo({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
    this.foo1(); // undefined undefined undefined 'M' 10
    this.foo1({ x: "x", y: 5, z: 0 }); // x 5 0 undefined undefined
    this.foo2({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
  }
}
const a = new A();
a.print();
</code>```

foo and foo2 function will work. However, foo2 is very verbose if more then few arguments. Use Object.assign() or {...} to merge value.

Body:
I have a method in typescript as below using named parameters

public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}

parameters m and n will be provided from another object like

const default = { m : 'M', n :10, o:6 }

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

  foo({x:'x', y: 5, z: 0})

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}

or

foo({...default, x:'x', y: 5, z: 0 });

Body:
For merge, u need to use merge using de-structure. default assignment will not work here. The default assignment is for work only if the object is undefined while passing value. So you need to merge the default value with passed value.

Please check comment in code.

interface Foo {
  x: string;
  y: number;
  z: number;
  m?: string;
  n?: number;
  o?: number;
}
const defaultValue = { m: "M", n: 10, o: 6 } as Foo;
class A {
  public foo(props: Foo) {
    const { x, y, z, m, n } = { ...defaultValue, ...props };
    console.log(x, y, z, m, n);
  }
  public foo2({ x, y, z, m = defaultValue.m, n = defaultValue.n }: Foo) {
    // this will work, but verbose
    console.log(x, y, z, m, n);
  }
  public foo1({ x, y, z, m, n }: Foo = defaultValue) {
    // this will work only if foo1 called without argument
    console.log(x, y, z, m, n);
  }
  public print() {
    this.foo({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
    this.foo1(); // undefined undefined undefined 'M' 10
    this.foo1({ x: "x", y: 5, z: 0 }); // x 5 0 undefined undefined
    this.foo2({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
  }
}
const a = new A();
a.print();

foo and foo2 function will work. However, foo2 is very verbose if more then few arguments. Use Object.assign() or {...} to merge value.


问:
Windows C++ stack trace from a running app
All,

I saw an app, an SVN Visual Studio plugin, that displayed a beautiful readable stack trace, when it crashed.

I would love to add that to my application.
How do I provide that? No emailing of the information, just a visual display is enough.

答:
The core of the necessary code is StackWalk64. To get much from that, you'll also want/need to get symbol names with SymGetSymFromAddr64 (which requires SymLoadModule64) and (probably) SymGetLineFromAddr64 and GetThreadContext. If the target was written in C++, you'll probably also want to use UnDecorateSymbolName. Along with those you'll need a few ancillaries like SymInitialize, SymCleanup, and probably SymSetOptions.

Here's a fairly minimal demo. The stack dump it produces is more utilitarian than beautiful, but presumably with the basics of doing the stack trace, you can display the results as you see fit:

```<code>#include <windows.h>
#include <winnt.h>

#include <string>
#include <vector>
#include <Psapi.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <iterator>

#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "dbghelp.lib")

// Some versions of imagehlp.dll lack the proper packing directives themselves
// so we need to do it.
#pragma pack( push, before_imagehlp, 8 )
#include <imagehlp.h>
#pragma pack( pop, before_imagehlp )

struct module_data {
    std::string image_name;
    std::string module_name;
    void *base_address;
    DWORD load_size;
};
typedef std::vector<module_data> ModuleList;

HANDLE thread_ready;

bool show_stack(std::ostream &, HANDLE hThread, CONTEXT& c);
DWORD __stdcall TargetThread( void *arg );
void ThreadFunc1();
void ThreadFunc2();
DWORD Filter( EXCEPTION_POINTERS *ep );
void *load_modules_symbols( HANDLE hProcess, DWORD pid );

int main( void ) {
    DWORD thread_id;

    thread_ready = CreateEvent( NULL, false, false, NULL );

    HANDLE thread = CreateThread( NULL, 0, TargetThread, NULL, 0, &thread_id );

    WaitForSingleObject( thread_ready, INFINITE );
    CloseHandle(thread_ready);
    return 0;
}

// if you use C++ exception handling: install a translator function
// with set_se_translator(). In the context of that function (but *not*
// afterwards), you can either do your stack dump, or save the CONTEXT
// record as a local copy. Note that you must do the stack dump at the
// earliest opportunity, to avoid the interesting stack-frames being gone
// by the time you do the dump.
DWORD Filter(EXCEPTION_POINTERS *ep) {
    HANDLE thread;

    DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
        GetCurrentProcess(), &thread, 0, false, DUPLICATE_SAME_ACCESS);
    std::cout << "Walking stack.";
    show_stack(std::cout, thread, *(ep->ContextRecord));
    std::cout << "\nEnd of stack walk.\n";
    CloseHandle(thread);

    return EXCEPTION_EXECUTE_HANDLER;
}

void ThreadFunc2() {
    __try { DebugBreak(); }
    __except (Filter(GetExceptionInformation())) {  }
    SetEvent(thread_ready);
}

void ThreadFunc1(void (*f)()) {
    f();
}

// We'll do a few levels of calls from our thread function so
//     there's something on the stack to walk...
//
DWORD __stdcall TargetThread(void *) {
    ThreadFunc1(ThreadFunc2);
    return 0;
}

class SymHandler {
    HANDLE p;
public:
    SymHandler(HANDLE process, char const *path=NULL, bool intrude = false) : p(process) {
        if (!SymInitialize(p, path, intrude))
            throw(std::logic_error("Unable to initialize symbol handler"));
    }
    ~SymHandler() { SymCleanup(p); }
};

#ifdef _M_X64
STACKFRAME64 init_stack_frame(CONTEXT c) {
    STACKFRAME64 s;
    s.AddrPC.Offset = c.Rip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Rsp;
    s.AddrStack.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Rbp;
    s.AddrFrame.Mode = AddrModeFlat;
    return s;
}
#else
STACKFRAME64 init_stack_frame(CONTEXT c) {
    STACKFRAME64 s;
    s.AddrPC.Offset = c.Eip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Esp;
    s.AddrStack.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Ebp;
    s.AddrFrame.Mode = AddrModeFlat;
    return s;
}
#endif

void sym_options(DWORD add, DWORD remove=0) {
    DWORD symOptions = SymGetOptions();
    symOptions |= add;
    symOptions &= ~remove;
    SymSetOptions(symOptions);
}

class symbol {
    typedef IMAGEHLP_SYMBOL64 sym_type;
    sym_type *sym;
    static const int max_name_len = 1024;
public:
    symbol(HANDLE process, DWORD64 address) : sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {
        memset(sym, '\0', sizeof(*sym) + max_name_len);
        sym->SizeOfStruct = sizeof(*sym);
        sym->MaxNameLength = max_name_len;
        DWORD64 displacement;

        if (!SymGetSymFromAddr64(process, address, &displacement, sym))
            throw(std::logic_error("Bad symbol"));
    }

    std::string name() { return std::string(sym->Name); }
    std::string undecorated_name() {
        std::vector<char> und_name(max_name_len);
        UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);
        return std::string(&und_name[0], strlen(&und_name[0]));
    }
};

bool show_stack(std::ostream &os, HANDLE hThread, CONTEXT& c) {
    HANDLE process = GetCurrentProcess();
    int frame_number=0;
    DWORD offset_from_symbol=0;
    IMAGEHLP_LINE64 line = {0};

    SymHandler handler(process);

    sym_options(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);

    void *base = load_modules_symbols(process, GetCurrentProcessId());

    STACKFRAME64 s = init_stack_frame(c);

    line.SizeOfStruct = sizeof line;

    IMAGE_NT_HEADERS *h = ImageNtHeader(base);
    DWORD image_type = h->FileHeader.Machine;

    do {
        if (!StackWalk64(image_type, process, hThread, &s, &c, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
            return false;

        os << std::setw(3) << "\n" << frame_number << "\t";
        if ( s.AddrPC.Offset != 0 ) {
            std::cout << symbol(process, s.AddrPC.Offset).undecorated_name();

            if (SymGetLineFromAddr64( process, s.AddrPC.Offset, &offset_from_symbol, &line ) )
                    os << "\t" << line.FileName << "(" << line.LineNumber << ")";
        }
        else
            os << "(No Symbols: PC == 0)";
        ++frame_number;
    } while (s.AddrReturn.Offset != 0);
    return true;
}

class get_mod_info {
    HANDLE process;
    static const int buffer_length = 4096;
public:
    get_mod_info(HANDLE h) : process(h) {}

    module_data operator()(HMODULE module) {
        module_data ret;
        char temp[buffer_length];
        MODULEINFO mi;

        GetModuleInformation(process, module, &mi, sizeof(mi));
        ret.base_address = mi.lpBaseOfDll;
        ret.load_size = mi.SizeOfImage;

        GetModuleFileNameEx(process, module, temp, sizeof(temp));
        ret.image_name = temp;
        GetModuleBaseName(process, module, temp, sizeof(temp));
        ret.module_name = temp;
        std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
        std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
        SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);
        return ret;
    }
};

void *load_modules_symbols(HANDLE process, DWORD pid) {
    ModuleList modules;

    DWORD cbNeeded;
    std::vector<HMODULE> module_handles(1);

    EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
    module_handles.resize(cbNeeded/sizeof(HMODULE));
    EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);

    std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));
    return modules[0].base_address;
}
</code>```

Body:
The core of the necessary code is StackWalk64. To get much from that, you'll also want/need to get symbol names with SymGetSymFromAddr64 (which requires SymLoadModule64) and (probably) SymGetLineFromAddr64 and GetThreadContext. If the target was written in C++, you'll probably also want to use UnDecorateSymbolName. Along with those you'll need a few ancillaries like SymInitialize, SymCleanup, and probably SymSetOptions.

Here's a fairly minimal demo. The stack dump it produces is more utilitarian than beautiful, but presumably with the basics of doing the stack trace, you can display the results as you see fit:

#include <windows.h>
#include <winnt.h>

#include <string>
#include <vector>
#include <Psapi.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <iterator>

#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "dbghelp.lib")

// Some versions of imagehlp.dll lack the proper packing directives themselves
// so we need to do it.
#pragma pack( push, before_imagehlp, 8 )
#include <imagehlp.h>
#pragma pack( pop, before_imagehlp )

struct module_data {
    std::string image_name;
    std::string module_name;
    void *base_address;
    DWORD load_size;
};
typedef std::vector<module_data> ModuleList;

HANDLE thread_ready;

bool show_stack(std::ostream &, HANDLE hThread, CONTEXT& c);
DWORD __stdcall TargetThread( void *arg );
void ThreadFunc1();
void ThreadFunc2();
DWORD Filter( EXCEPTION_POINTERS *ep );
void *load_modules_symbols( HANDLE hProcess, DWORD pid );

int main( void ) {
    DWORD thread_id;

    thread_ready = CreateEvent( NULL, false, false, NULL );

    HANDLE thread = CreateThread( NULL, 0, TargetThread, NULL, 0, &thread_id );

    WaitForSingleObject( thread_ready, INFINITE );
    CloseHandle(thread_ready);
    return 0;
}

// if you use C++ exception handling: install a translator function
// with set_se_translator(). In the context of that function (but *not*
// afterwards), you can either do your stack dump, or save the CONTEXT
// record as a local copy. Note that you must do the stack dump at the
// earliest opportunity, to avoid the interesting stack-frames being gone
// by the time you do the dump.
DWORD Filter(EXCEPTION_POINTERS *ep) {
    HANDLE thread;

    DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
        GetCurrentProcess(), &thread, 0, false, DUPLICATE_SAME_ACCESS);
    std::cout << "Walking stack.";
    show_stack(std::cout, thread, *(ep->ContextRecord));
    std::cout << "\nEnd of stack walk.\n";
    CloseHandle(thread);

    return EXCEPTION_EXECUTE_HANDLER;
}

void ThreadFunc2() {
    __try { DebugBreak(); }
    __except (Filter(GetExceptionInformation())) {  }
    SetEvent(thread_ready);
}

void ThreadFunc1(void (*f)()) {
    f();
}

// We'll do a few levels of calls from our thread function so
//     there's something on the stack to walk...
//
DWORD __stdcall TargetThread(void *) {
    ThreadFunc1(ThreadFunc2);
    return 0;
}

class SymHandler {
    HANDLE p;
public:
    SymHandler(HANDLE process, char const *path=NULL, bool intrude = false) : p(process) {
        if (!SymInitialize(p, path, intrude))
            throw(std::logic_error("Unable to initialize symbol handler"));
    }
    ~SymHandler() { SymCleanup(p); }
};

#ifdef _M_X64
STACKFRAME64 init_stack_frame(CONTEXT c) {
    STACKFRAME64 s;
    s.AddrPC.Offset = c.Rip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Rsp;
    s.AddrStack.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Rbp;
    s.AddrFrame.Mode = AddrModeFlat;
    return s;
}
#else
STACKFRAME64 init_stack_frame(CONTEXT c) {
    STACKFRAME64 s;
    s.AddrPC.Offset = c.Eip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Esp;
    s.AddrStack.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Ebp;
    s.AddrFrame.Mode = AddrModeFlat;
    return s;
}
#endif

void sym_options(DWORD add, DWORD remove=0) {
    DWORD symOptions = SymGetOptions();
    symOptions |= add;
    symOptions &= ~remove;
    SymSetOptions(symOptions);
}

class symbol {
    typedef IMAGEHLP_SYMBOL64 sym_type;
    sym_type *sym;
    static const int max_name_len = 1024;
public:
    symbol(HANDLE process, DWORD64 address) : sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {
        memset(sym, '\0', sizeof(*sym) + max_name_len);
        sym->SizeOfStruct = sizeof(*sym);
        sym->MaxNameLength = max_name_len;
        DWORD64 displacement;

        if (!SymGetSymFromAddr64(process, address, &displacement, sym))
            throw(std::logic_error("Bad symbol"));
    }

    std::string name() { return std::string(sym->Name); }
    std::string undecorated_name() {
        std::vector<char> und_name(max_name_len);
        UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);
        return std::string(&und_name[0], strlen(&und_name[0]));
    }
};

bool show_stack(std::ostream &os, HANDLE hThread, CONTEXT& c) {
    HANDLE process = GetCurrentProcess();
    int frame_number=0;
    DWORD offset_from_symbol=0;
    IMAGEHLP_LINE64 line = {0};

    SymHandler handler(process);

    sym_options(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);

    void *base = load_modules_symbols(process, GetCurrentProcessId());

    STACKFRAME64 s = init_stack_frame(c);

    line.SizeOfStruct = sizeof line;

    IMAGE_NT_HEADERS *h = ImageNtHeader(base);
    DWORD image_type = h->FileHeader.Machine;

    do {
        if (!StackWalk64(image_type, process, hThread, &s, &c, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
            return false;

        os << std::setw(3) << "\n" << frame_number << "\t";
        if ( s.AddrPC.Offset != 0 ) {
            std::cout << symbol(process, s.AddrPC.Offset).undecorated_name();

            if (SymGetLineFromAddr64( process, s.AddrPC.Offset, &offset_from_symbol, &line ) )
                    os << "\t" << line.FileName << "(" << line.LineNumber << ")";
        }
        else
            os << "(No Symbols: PC == 0)";
        ++frame_number;
    } while (s.AddrReturn.Offset != 0);
    return true;
}

class get_mod_info {
    HANDLE process;
    static const int buffer_length = 4096;
public:
    get_mod_info(HANDLE h) : process(h) {}

    module_data operator()(HMODULE module) {
        module_data ret;
        char temp[buffer_length];
        MODULEINFO mi;

        GetModuleInformation(process, module, &mi, sizeof(mi));
        ret.base_address = mi.lpBaseOfDll;
        ret.load_size = mi.SizeOfImage;

        GetModuleFileNameEx(process, module, temp, sizeof(temp));
        ret.image_name = temp;
        GetModuleBaseName(process, module, temp, sizeof(temp));
        ret.module_name = temp;
        std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
        std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
        SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);
        return ret;
    }
};

void *load_modules_symbols(HANDLE process, DWORD pid) {
    ModuleList modules;

    DWORD cbNeeded;
    std::vector<HMODULE> module_handles(1);

    EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
    module_handles.resize(cbNeeded/sizeof(HMODULE));
    EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);

    std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));
    return modules[0].base_address;
}


问:
Extract excel column values based on other column values using script
I am having following excel sheet below:

I need to segregate the data based on comment Column. If the Comment column value is same then I need to retrieve only name, port values as shown below:

```<code>###LSB Team
super_bot0,DstSdp00_Prb
super_tot0,DstSd_PrbAddr

###ESB Team
supe_bot0,IOHC_Vld
subot0_3,IOHC_DVMSyncComplete
</code>```

Can anyone please help me to automate this.

答:
Can you run this on your excel file?

import pandas as pd

df = pd.read_excel('book1.xlsx')

comment_to_teams = {}
for comment, rows in df.groupby('Comment'):
    comment_to_teams[comment] = rows[['Name', 'Port']]

for comment, teams in comment_to_teams.items():
    print(comment)
    print(teams)
```

Body:
I am having following excel sheet below:

I need to segregate the data based on comment Column. If the Comment column value is same then I need to retrieve only name, port values as shown below:

###LSB Team
super_bot0,DstSdp00_Prb
super_tot0,DstSd_PrbAddr

###ESB Team
supe_bot0,IOHC_Vld
subot0_3,IOHC_DVMSyncComplete

Can anyone please help me to automate this.


问:
Using sentry with a custom error handler in Express
I have an Express server running for the backend of a website with Sentry (v5.15.5) successfully implemented. I'm now trying to improve the error handling on the backend, as at the moment if something goes wrong with the request, the request is not ended and the client sits there waiting for a response, which it never gets.
To tell the client if the request has failed I'm using the custom error handler in the documentation:

```<code>app.use(function onError(err, req, res, next) {
  // The error id is attached to `res.sentry` to be returned
  // and optionally displayed to the user for support.
  res.statusCode = 500;
  res.end(res.sentry + "\n");
});
</code>```

However, when I use this on my server, only the custom error handler runs - Sentry never creates an event for the error, but if I just use another custom error function, they both get called fine, which makes me think this is a Sentry issue. Here's the relevant parts of the server code:

```<code>...
const Sentry = require('@sentry/node');
...

const app = express()

Sentry.init({ dsn: process.env.SENTRY });

...

// Middlewares
app.use(Sentry.Handlers.requestHandler());

app.use(express.json())
app.use(helmet())
app.use(cors())
app.use(morgan('tiny'))

const controllers = require('./controllers')

const wrap = fn => (...args) => Promise
    .resolve(fn(...args))
    .catch(args[2])

// Routes
...
app.post('/test', authUser, wrap(controllers.testController))
...

app.use(Sentry.Handlers.errorHandler());
app.use(function onError(err, req, res, next) {
    res.statusCode = 500
    res.end(res.sentry + "\n")
  })

app.listen(PORT, () => console.log(`APP RUNNING ON PORT ${PORT}`))
</code>```

The controllers on the server make database requests, etc. so they are async functions - that's why I use the wrap function to catch promise rejections and pass them to the error handler. If I unwrap the controller then Sentry works fine, but then the server never sends the error to the client.

I expect I'm probably going about this wrong as it should be pretty simple to do, but no matter what I do I cannot get Sentry + async controllers + custom error handler to work. Any help would be appreciated.

(This may be an Express issue, if so let me know and I'll take it over there)

Thanks

答: For some reason Sentry's 'Filter out localhost' option (which was turned off but somehow got toggled on) doesn't actually filter out all local errors. When I removed the custom error handler and wrap function, the errors managed to get past the localhost filter. After I turned it back off all the errors came through on Sentry fine.</p>

Body:
I have an Express server running for the backend of a website with Sentry (v5.15.5) successfully implemented. I'm now trying to improve the error handling on the backend, as at the moment if something goes wrong with the request, the request is not ended and the client sits there waiting for a response, which it never gets.
To tell the client if the request has failed I'm using the custom error handler in the documentation:

app.use(function onError(err, req, res, next) {
  // The error id is attached to `res.sentry` to be returned
  // and optionally displayed to the user for support.
  res.statusCode = 500;
  res.end(res.sentry + "\n");
});

However, when I use this on my server, only the custom error handler runs - Sentry never creates an event for the error, but if I just use another custom error function, they both get called fine, which makes me think this is a Sentry issue. Here's the relevant parts of the server code:

...
const Sentry = require('@sentry/node');
...

const app = express()

Sentry.init({ dsn: process.env.SENTRY });

...

// Middlewares
app.use(Sentry.Handlers.requestHandler());

app.use(express.json())
app.use(helmet())
app.use(cors())
app.use(morgan('tiny'))

const controllers = require('./controllers')

const wrap = fn => (...args) => Promise
    .resolve(fn(...args))
    .catch(args[2])

// Routes
...
app.post('/test', authUser, wrap(controllers.testController))
...

app.use(Sentry.Handlers.errorHandler());
app.use(function onError(err, req, res, next) {
    res.statusCode = 500
    res.end(res.sentry + "\n")
  })

app.listen(PORT, () => console.log(`APP RUNNING ON PORT ${PORT}`))

The controllers on the server make database requests, etc. so they are async functions - that's why I use the wrap function to catch promise rejections and pass them to the error handler. If I unwrap the controller then Sentry works fine, but then the server never sends the error to the client.

I expect I'm probably going about this wrong as it should be pretty simple to do, but no matter what I do I cannot get Sentry + async controllers + custom error handler to work. Any help would be appreciated.

(This may be an Express issue, if so let me know and I'll take it over there)

Thanks


问:
Boolean dynamic memory allocation cannot be delete
```<code>include <iostream>
int main()
{
    bool a=new bool;
    delete a;
    return 0;
}
</code>```

I try to delete the boolean malloc, but so far it keeps giving me the error that bool type expression cant be deleted

答:
new bool returns a boolean pointer (bool *ptr), therefore you
can't atribute new bool to a, which is a bool date type.

And also, one can only delete pointers

So you must declare a as a boolean pointer: bool *a = new bool

Body:
include <iostream>
int main()
{
    bool a=new bool;
    delete a;
    return 0;
}

I try to delete the boolean malloc, but so far it keeps giving me the error that bool type expression cant be deleted