问:
How do I insert an uploaded image into an  tag/placeholder?
How do I insert an uploaded image into an html  tag?
Is it possible to create an  tag as placeholder for uploaded images?

I can select an image with "< input type="file" name="fileToUpload" id="fileToUpload" >" and after this i want to send that image to an img placeholder.

And is it possible to delete the uploaded image from the placeholder after the user closed the website?

Thanks a lot!

答:
Try using canvas to crop the image</p>

```<code>const updateImageDisplay = () => {
  const input = document.querySelector('input');
  const previewContainer = document.querySelector('.previewContainer');
  [...input.files].forEach(file => {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();
      imageObj.onload = function() {
        var sourceX = 150;
        var sourceY = 0;
        var sourceWidth = 150;
        var sourceHeight = 150;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = canvas.width / 2 - destWidth / 2;
        var destY = canvas.height / 2 - destHeight / 2;

        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
      };
      imageObj.src = URL.createObjectURL(file);
      previewContainer.appendChild(canvas);
  })
}
</code>```

Title: How do I insert an uploaded image into an <IMG> tag/placeholder?

Body:
Try using canvas to crop the image

const updateImageDisplay = () => {
  const input = document.querySelector('input');
  const previewContainer = document.querySelector('.previewContainer');
  [...input.files].forEach(file => {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();
      imageObj.onload = function() {
        var sourceX = 150;
        var sourceY = 0;
        var sourceWidth = 150;
        var sourceHeight = 150;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = canvas.width / 2 - destWidth / 2;
        var destY = canvas.height / 2 - destHeight / 2;

        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
      };
      imageObj.src = URL.createObjectURL(file);
      previewContainer.appendChild(canvas);
  })
}


来源: stackexchange

问:
Failed Deployment in App Engine Google Cloud
I am deploying my nodejs application in google cloud app engine but it is giving error
This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time.
This request may thus take longer and use more CPU than a typical request for your application. -- when making request.

I had also saw some stackoverflow answers, but they didn't worked for me.

my app.yaml have this config

runtime: nodejs10

Can anyone help me out

答:
The "request caused a new process to be started" notification usually occurred when there is no warm up request present in your application.

Can you try to implement a health check handler that only returns a ready status when the application is warmed up. This will allow your service to not receive traffic until it is ready.

Warning: Legacy health checks using the /_ah/health path are now
  deprecated, and you should migrate to use split health checks.

Here you can find Split health checks for Nodejs

Liveness checks

Liveness checks confirm that the VM and the Docker container are
  running. Instances that are deemed unhealthy are restarted.

```<code>  path: "/liveness_check"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2

</code>```

Readiness checks

Readiness checks confirm that an instance can accept incoming
  requests. Instances that don't pass the readiness check are not added
  to the pool of available instances.

```<code>  path: "/readiness_check"
  check_interval_sec: 5
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2
  app_start_timeout_sec: 300
</code>```

Edit

For App Engine Standard, which doesn't afford you that flexibility, hardware and software failures that cause early termination or frequent restarts can occur without prior warning. link

App Engine attempts to keep manual and basic scaling instances running
  indefinitely. However, at this time there is no guaranteed uptime for
  manual and basic scaling instances. Hardware and software failures
  that cause early termination or frequent restarts can occur without
  prior warning and can take considerable time to resolve; thus, you
  should construct your application in a way that tolerates these
  failures.

Here are some good strategies for avoiding downtime due to instance
  restarts:

Reduce the amount of time it takes for your instances restart or for
  new ones to start.

For long-running computations, periodically create
  checkpoints so that you can resume from that state.

Your app should be "stateless" so that nothing is stored on the instance.

Use queues for performing asynchronous task execution.

If you configure your instances to manual scaling: Use load balancing across > multiple instances. Configure more instances than required to handle normal
  traffic. Write fall-back logic that uses cached results when a manual
  scaling instance is unavailable.

Instance Uptime

ContentLicense: CC BY-SA 4.0

Body:
The "request caused a new process to be started" notification usually occurred when there is no warm up request present in your application.

Can you try to implement a health check handler that only returns a ready status when the application is warmed up. This will allow your service to not receive traffic until it is ready.

Warning: Legacy health checks using the /_ah/health path are now
  deprecated, and you should migrate to use split health checks.

Here you can find Split health checks for Nodejs

Liveness checks

Liveness checks confirm that the VM and the Docker container are
  running. Instances that are deemed unhealthy are restarted.

  path: "/liveness_check"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2

Readiness checks

Readiness checks confirm that an instance can accept incoming
  requests. Instances that don't pass the readiness check are not added
  to the pool of available instances.

  path: "/readiness_check"
  check_interval_sec: 5
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2
  app_start_timeout_sec: 300

Edit

For App Engine Standard, which doesn't afford you that flexibility, hardware and software failures that cause early termination or frequent restarts can occur without prior warning. link

App Engine attempts to keep manual and basic scaling instances running
  indefinitely. However, at this time there is no guaranteed uptime for
  manual and basic scaling instances. Hardware and software failures
  that cause early termination or frequent restarts can occur without
  prior warning and can take considerable time to resolve; thus, you
  should construct your application in a way that tolerates these
  failures.

Here are some good strategies for avoiding downtime due to instance
  restarts:

Reduce the amount of time it takes for your instances restart or for
  new ones to start.

For long-running computations, periodically create
  checkpoints so that you can resume from that state.

Your app should be "stateless" so that nothing is stored on the instance.

Use queues for performing asynchronous task execution.

If you configure your instances to manual scaling: Use load balancing across > multiple instances. Configure more instances than required to handle normal
  traffic. Write fall-back logic that uses cached results when a manual
  scaling instance is unavailable.

Instance Uptime


问:
2D conditional calculation
I have a spreadsheet with list of Products sold over time, with each product having it's class (I'd prefer if classes would be unlimited, but I can also live with predefined classes) and status active/inactive.
I need an arrayformula for H5 to fill the yellow area (only active products). I've tried with combination of MMULT and Arrayformula, but no luck, maybe someone can help me out.</p>

答:
Class A:

```<code>=ARRAYFORMULA(MMULT(IF(($C2:$F2="Class A")*($C3:$F3=TRUE);
 INDIRECT("C5:F"&COUNTA($A5:$A)+4)*1; 0); TRANSPOSE(SIGN($C5:$F5))))
</code>```

Class B:

```<code>=ARRAYFORMULA(MMULT(IF(($C2:$F2="Class B")*($C3:$F3=TRUE);
 INDIRECT("C5:F"&COUNTA($A5:$A)+4)*1; 0); TRANSPOSE(SIGN($C5:$F5))))
</code>```

to turn it unlimited, remove F:

Title: 2D conditional calculation

Body:
Class A:

=ARRAYFORMULA(MMULT(IF(($C2:$F2="Class A")*($C3:$F3=TRUE);
 INDIRECT("C5:F"&COUNTA($A5:$A)+4)*1; 0); TRANSPOSE(SIGN($C5:$F5))))

Class B:

=ARRAYFORMULA(MMULT(IF(($C2:$F2="Class B")*($C3:$F3=TRUE);
 INDIRECT("C5:F"&COUNTA($A5:$A)+4)*1; 0); TRANSPOSE(SIGN($C5:$F5))))

to turn it unlimited, remove F:


问:
Getting exception jQuery must be included before Bootstrap's JavaScript
I am getting below exception

bootstrap.js:240 Uncaught TypeError:  Bootstrap's JavaScript requires
  jQuery. jQuery must be included before Bootstrap's JavaScript

at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 at
  bootstrap.js:9 at bootstrap.js:10

This is my code in Angular.json

```<code>"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]
</code>```

How can I fix this issue?

答:
Surely "node_modules/jquery/dist/jquery.min.js" should come under "scripts"?

```<code>"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]
</code>```

And the now duplicated jQuery file ""node_modules/jquery/dist/jquery.js" should be removed.

Body:
I am getting below exception

bootstrap.js:240 Uncaught TypeError:  Bootstrap's JavaScript requires
  jQuery. jQuery must be included before Bootstrap's JavaScript

at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 at
  bootstrap.js:9 at bootstrap.js:10

This is my code in Angular.json

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]

How can I fix this issue?

Body:
Surely "node_modules/jquery/dist/jquery.min.js" should come under "scripts"?

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]

And the now duplicated jQuery file ""node_modules/jquery/dist/jquery.js" should be removed.


问:
Not finding the right syntax to use near '1' at line 1 [mysqli]
I got

"You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '1' at line 1"

message when I run this

```<code>private function saveBookingData(){
        global $mysqli;
        $sql = $mysqli->query("INSERT INTO bsi_bookings
                    (booking_id, booking_time, start_date, end_date, client_id,
                     total_cost, payment_amount, payment_type, special_requests)
                values(".$this->bookingId.", NOW(),
                        '".$this->mysqlCheckInDate."',
                        '".$this->mysqlCheckOutDate."',
                        ".$this->clientId.",
                        ".$this->grandTotalAmount.",
                        ".$this->totalPaymentAmount.",
                        '".$this->paymentGatewayCode."',
                        '".$this->clientdata['message']."')");

        foreach($this->reservationdata as $revdata){
            foreach($revdata['availablerooms'] as $rooms){
                $sql = $mysqli->query("INSERT INTO bsi_reservation
                              (bookings_id, room_id, room_type_id)
                          values(".$this->bookingId.",  ".$rooms['roomid'].",
                              ".$revdata['roomtypeid'].")");
            }
        }
        if (mysqli_connect_errno()) {
              printf("Connect failed: %s\n", mysqli_connect_error());
              exit();
        }

        $result = $mysqli->query($sql);
        if (!$result) {
             printf("%s\n", $mysqli->error);
             exit();
        }
    }
</code>```

Other info

table 1

```<code>CREATE TABLE `bsi_bookings` (
        `booking_id` int(10) UNSIGNED NOT NULL,
        `booking_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
        `start_date` date NOT NULL DEFAULT '0000-00-00',
        `end_date` date NOT NULL DEFAULT '0000-00-00',
        `client_id` int(10) UNSIGNED DEFAULT NULL,
        `child_count` int(2) NOT NULL DEFAULT '0',
        `extra_guest_count` int(2) NOT NULL DEFAULT '0',
        `discount_coupon` varchar(50) DEFAULT NULL,
        `total_cost` decimal(10,2) UNSIGNED NOT NULL DEFAULT '0.00',
        `payment_amount` decimal(10,2) NOT NULL DEFAULT '0.00',
        `payment_type` varchar(255) NOT NULL,
        `payment_success` tinyint(1) NOT NULL DEFAULT '0',
        `payment_txnid` varchar(100) DEFAULT NULL,
        `paypal_email` varchar(500) DEFAULT NULL,
        `special_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
        `special_requests` text,
        `is_block` tinyint(4) NOT NULL DEFAULT '0',
        `is_deleted` tinyint(4) NOT NULL DEFAULT '0',
        `block_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

table 2

```<code>CREATE TABLE `bsi_reservation` (
        `id` int(11) NOT NULL,
        `bookings_id` int(11) NOT NULL,
        `room_id` int(11) NOT NULL,
        `room_type_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

答:
You may use PHP MySQLi Prepared Statements to Prevent SQL Injection

Expl :

```<code>$stmt = $mysqli->prepare("INSERT INTO bsi_bookings (booking_id, booking_time, start_date, end_date, client_id, total_cost, payment_amount, payment_type, special_requests) VALUES (?, ?, ?, ...)");
$stmt->bind_param("si", $this->bookingId, $var2, ....);
$stmt->execute();
$stmt->close();
</code>```

Read more

Body:
I got

"You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '1' at line 1"

message when I run this

private function saveBookingData(){
        global $mysqli;
        $sql = $mysqli->query("INSERT INTO bsi_bookings
                    (booking_id, booking_time, start_date, end_date, client_id,
                     total_cost, payment_amount, payment_type, special_requests)
                values(".$this->bookingId.", NOW(),
                        '".$this->mysqlCheckInDate."',
                        '".$this->mysqlCheckOutDate."',
                        ".$this->clientId.",
                        ".$this->grandTotalAmount.",
                        ".$this->totalPaymentAmount.",
                        '".$this->paymentGatewayCode."',
                        '".$this->clientdata['message']."')");

        foreach($this->reservationdata as $revdata){
            foreach($revdata['availablerooms'] as $rooms){
                $sql = $mysqli->query("INSERT INTO bsi_reservation
                              (bookings_id, room_id, room_type_id)
                          values(".$this->bookingId.",  ".$rooms['roomid'].",
                              ".$revdata['roomtypeid'].")");
            }
        }
        if (mysqli_connect_errno()) {
              printf("Connect failed: %s\n", mysqli_connect_error());
              exit();
        }

        $result = $mysqli->query($sql);
        if (!$result) {
             printf("%s\n", $mysqli->error);
             exit();
        }
    }

Other info

table 1

CREATE TABLE `bsi_bookings` (
        `booking_id` int(10) UNSIGNED NOT NULL,
        `booking_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
        `start_date` date NOT NULL DEFAULT '0000-00-00',
        `end_date` date NOT NULL DEFAULT '0000-00-00',
        `client_id` int(10) UNSIGNED DEFAULT NULL,
        `child_count` int(2) NOT NULL DEFAULT '0',
        `extra_guest_count` int(2) NOT NULL DEFAULT '0',
        `discount_coupon` varchar(50) DEFAULT NULL,
        `total_cost` decimal(10,2) UNSIGNED NOT NULL DEFAULT '0.00',
        `payment_amount` decimal(10,2) NOT NULL DEFAULT '0.00',
        `payment_type` varchar(255) NOT NULL,
        `payment_success` tinyint(1) NOT NULL DEFAULT '0',
        `payment_txnid` varchar(100) DEFAULT NULL,
        `paypal_email` varchar(500) DEFAULT NULL,
        `special_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
        `special_requests` text,
        `is_block` tinyint(4) NOT NULL DEFAULT '0',
        `is_deleted` tinyint(4) NOT NULL DEFAULT '0',
        `block_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

table 2

CREATE TABLE `bsi_reservation` (
        `id` int(11) NOT NULL,
        `bookings_id` int(11) NOT NULL,
        `room_id` int(11) NOT NULL,
        `room_type_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Body:
You may use PHP MySQLi Prepared Statements to Prevent SQL Injection

Expl :

$stmt = $mysqli->prepare("INSERT INTO bsi_bookings (booking_id, booking_time, start_date, end_date, client_id, total_cost, payment_amount, payment_type, special_requests) VALUES (?, ?, ?, ...)");
$stmt->bind_param("si", $this->bookingId, $var2, ....);
$stmt->execute();
$stmt->close();

Read more


问:
Copy pasting tables from Excel to word including a line break, but use only Excel VBA
I am working on a file where i have populated a lot of tables in excel using VBA. Following this i want to paste the tables one by one into word. Once i paste a table for some reason, the cursor is stuck at Cell 1 of the first table and when i paste the second table it gets paste into the first cell.

I want to know if there is way to introduce line break or page break following pasting the first table or if i can even move the active cursor to outside of the table.

All the options ive found so far are on word but i dont want to use word. I want to introduce a line break in word after the table using excel VBA.

Can someone help me with this? Is there a way to move the cursor or introduce line break after pasting the table?

The code is as follows:

```<code>WSout.Cells(2, 5).Copy
With myDoc.ActiveWindow.Selection
 .EndOf Unit:=wdStory, Extend:=wdMove
 .TypeParagraph
 '.TypeText (str)
 .TypeParagraph
End With
myDoc.Paragraphs(ba).Range.PasteSpecial xlPasteValues

'For Table 1
ba = 1 + ba

WSout.Range("N1:O22").Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

myDoc.Application.Selection.MoveDown Unit:=wdLine, Count:=23

'WordApp.Selection.MoveDown Unit:=wdLine, Count:=23

'For Table 2

ba = 1 + ba

lastrow = "0"
lastcol = "22"

For bb = 2 To WSout.Range("Q" & Rows.Count).End(xlUp).Row

lastrow = 1 + lastrow

Next bb

WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting
</code>```

答:
The problem is that 'ba = 1 + ba' with 'myDoc.Paragraphs(ba).Range' only points to the second logical paragraph in your original selection - you haven't updated 'ba' to match the 'Selection.MoveDown Unit:=wdLine, Count:=23'. In any event, working with Selection objects is inefficient; you should use Range objects instead. Try something along the lines of:</p>

```<code>With myDoc.Range
  .InsertAfter vbCr & WSout.Cells(2, 5).Text & vbCr
  WSout.Range("N1:O22").Copy
  .Characters.Last.PasteAndFormat wdFormatOriginalFormatting
  .InsertAfter vbCr
  With WSout
    .Range("Q1:V" & .Range("Q" & Rows.Count).End(xlUp).Row).Copy
  End With
  .Characters.Last.PasteAndFormat wdFormatOriginalFormatting
End With
</code>```

Body:
I am working on a file where i have populated a lot of tables in excel using VBA. Following this i want to paste the tables one by one into word. Once i paste a table for some reason, the cursor is stuck at Cell 1 of the first table and when i paste the second table it gets paste into the first cell.

I want to know if there is way to introduce line break or page break following pasting the first table or if i can even move the active cursor to outside of the table.

All the options ive found so far are on word but i dont want to use word. I want to introduce a line break in word after the table using excel VBA.

Can someone help me with this? Is there a way to move the cursor or introduce line break after pasting the table?

The code is as follows:

WSout.Cells(2, 5).Copy
With myDoc.ActiveWindow.Selection
 .EndOf Unit:=wdStory, Extend:=wdMove
 .TypeParagraph
 '.TypeText (str)
 .TypeParagraph
End With
myDoc.Paragraphs(ba).Range.PasteSpecial xlPasteValues

'For Table 1
ba = 1 + ba

WSout.Range("N1:O22").Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

myDoc.Application.Selection.MoveDown Unit:=wdLine, Count:=23

'WordApp.Selection.MoveDown Unit:=wdLine, Count:=23

'For Table 2

ba = 1 + ba

lastrow = "0"
lastcol = "22"

For bb = 2 To WSout.Range("Q" & Rows.Count).End(xlUp).Row

lastrow = 1 + lastrow

Next bb

WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

Body:
The problem is that 'ba = 1 + ba' with 'myDoc.Paragraphs(ba).Range' only points to the second logical paragraph in your original selection - you haven't updated 'ba' to match the 'Selection.MoveDown Unit:=wdLine, Count:=23'. In any event, working with Selection objects is inefficient; you should use Range objects instead. Try something along the lines of:

With myDoc.Range
  .InsertAfter vbCr & WSout.Cells(2, 5).Text & vbCr
  WSout.Range("N1:O22").Copy
  .Characters.Last.PasteAndFormat wdFormatOriginalFormatting
  .InsertAfter vbCr
  With WSout
    .Range("Q1:V" & .Range("Q" & Rows.Count).End(xlUp).Row).Copy
  End With
  .Characters.Last.PasteAndFormat wdFormatOriginalFormatting
End With


问:
Javascript: How do I use React component globally?
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

```<code>import Progress from 'package-name'

// jsx
<Progress /> //working fine
</code>```

It's working fine.

But if I use it from CDN like unpkg, it's not working.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

// Package Script
<script src="https://unpkg.com/@delowar/react-circle-progressbar@0.0.9/lib/Progress.js"></script>

<script>
    ...react code...
    <Progress />
    ...react code...
</script>
</code>```

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

```<code>var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}
</code>```

Original Repo: https://github.com/delowardev/react-circle-progressbar

答:
Change the value of library to the name of your component library: 'Progress' and add libraryExport: 'default' to assign the default export to the library target:

```<code>output: {
  path: path.resolve('lib'),
  filename: 'Progress.js',
  library: 'Progress',
  libraryTarget: 'umd',
  libraryExport: 'default',
  umdNamedDefine: true,
  globalObject: `(typeof self !== 'undefined' ? self : this)`
},
</code>```

Working example:

function App() {
  return (
    <Progress />
  )
}

ReactDOM.render( <App /> , document.getElementById('root'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

<script src="https://rawcdn.githack.com/fraction01/react-circle-progressbar/0957fed54db16a3f7b9d625711ed3961f3b34371/lib/Progress.js"></script>
<div id="root"></div></code>```

Body:
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

import Progress from 'package-name'

// jsx
<Progress /> //working fine

It's working fine.

But if I use it from CDN like unpkg, it's not working.

// Package Script

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}

Original Repo: https://github.com/delowardev/react-circle-progressbar

Body:
Change the value of library to the name of your component library: 'Progress' and add libraryExport: 'default' to assign the default export to the library target:

output: {
  path: path.resolve('lib'),
  filename: 'Progress.js',
  library: 'Progress',
  libraryTarget: 'umd',
  libraryExport: 'default',
  umdNamedDefine: true,
  globalObject: `(typeof self !== 'undefined' ? self : this)`
},

Working example:

function App() {
  return (
    <Progress />
  )
}

ReactDOM.render( <App /> , document.getElementById('root'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

<script src="https://rawcdn.githack.com/fraction01/react-circle-progressbar/0957fed54db16a3f7b9d625711ed3961f3b34371/lib/Progress.js"></script>
<div id="root"></div>


问:
Prevent from changing the values in array
In my program I am creating an array which contains values of year-month-date. I assign them the values 2019, 6 and 17. As of now, the program allows me to change the value (see the comment in main). But i do not want this to be possible, how can i prevent this?</p>

```<code>    public static void main (String[] args)
    {
        Date date = new Date (2019, 6, 17);
        date.printDate ();

        int[] dateValue = date.getDate ();
        dateValue[2] = 35; //Changes the value from 17 to 35. Is not suppose to happen.

        date.printDate ();
    }
</code>```

```<code>public class Date
{
    private int[] ymd = new int[3];
    public Date (int year, int month, int day)
    {
        ymd[0] = year;
        ymd[1] = month;
        ymd[2] = day;
    }

    public int[] getDate ()
    {
      return ymd;
    }

    public void printDate ()
    {
        System.out.println (ymd[0] + "-" + ymd[1] + "-" + ymd[2]);
    }
}
</code>```

答:
Change getDate() to return a copy of the private array instance variable:

```<code>public int[] getDate ()
{
  return Arrays.copyOf(ymd,ymd.length);
}
</code>```

This way callers of the method cannot mutate the state of the Date instance by modifying the returned array.

Body:
In my program I am creating an array which contains values of year-month-date. I assign them the values 2019, 6 and 17. As of now, the program allows me to change the value (see the comment in main). But i do not want this to be possible, how can i prevent this?

    public static void main (String[] args)
    {
        Date date = new Date (2019, 6, 17);
        date.printDate ();

        int[] dateValue = date.getDate ();
        dateValue[2] = 35; //Changes the value from 17 to 35. Is not suppose to happen.

        date.printDate ();
    }

public class Date
{
    private int[] ymd = new int[3];
    public Date (int year, int month, int day)
    {
        ymd[0] = year;
        ymd[1] = month;
        ymd[2] = day;
    }

    public int[] getDate ()
    {
      return ymd;
    }

    public void printDate ()
    {
        System.out.println (ymd[0] + "-" + ymd[1] + "-" + ymd[2]);
    }
}

Body:
Change getDate() to return a copy of the private array instance variable:

public int[] getDate ()
{
  return Arrays.copyOf(ymd,ymd.length);
}

This way callers of the method cannot mutate the state of the Date instance by modifying the returned array.


问:
How to finish Loading View only when inner Iframes are done loading MVC
I have a DotNet CORE MVC project.
The project has a controller which receives an array of strings, each string represents an Iframe source that needs to be placed in the View.

The model takes the array of string and do some manipulation on them, which means that eventually when the model is done and passed to the view it has a list of strings ready to be used as an iframe SRC.

The list in the model is this -

```<code>        public List<string> IFramePixels { get; set; };
</code>```

And this is my View -

```<code><body>
    @foreach (string iframe in Model.IFramePixels)
    {
        <iframe width='1' height='1' frameborder='0' src='@iframe'></iframe>
    }
</body>
</code>```

Everything works fine, the question is how can I delay the view loading finish time to when all those inner Iframes are done loading.

The reason I want that is that some outside website gonna place my website as an Iframe, and they need to know when all the inner Iframes are done (so I can't use a simple JS listener), I wanted to tell them to do some sort of a listener on when my webpage is done loading which means that the inner Iframes are done as well.

Thanks!

Edit ->
Well.. still couldn't find any answer, maybe thats simply not possible?
Does anyone have some different approach that might get me what I need? thanks!

答:
need to know when all the inner Iframes are done...

Your sentence reminded me of Promise.All in Javascript.

So, if I got you right, jQuery.when() can serve your intention.
In addition, to make sure the page load is not made until all iframes are loaded, you can use $.holdReady

A sample code to get you on the way:

```<code><div>
    <iframe id="if1" src="./let.html" height="200" width="300"></iframe>
    <iframe id="if2" src="./let.html" height="200" width="300"></iframe>
    <iframe id="if3" src="./let.html" height="200" width="300"></iframe>
</div>

<script src="./jquery-3.4.1.min.js"></script>
<script>
    // call this at the top of your script to delay jQuery's ready event.
    $.holdReady(true);

    var d1 = $.Deferred();
    var d2 = $.Deferred();
    var d3 = $.Deferred();

    $('#if1').on('load', function() {
        alert('iframe 1 Loaded');
        d1.resolve();
    });
    $('#if2').on('load', function() {
        alert('iframe 2 Loaded');
        d2.resolve();
    });
    $('#if3').on('load', function() {
        alert('iframe 3 Loaded');
        d3.resolve();
    });

    $.when(d1, d2, d3).done(function(v1, v2, v3) {
        alert(' All iframes loaded');
        $.holdReady(false); // this allows document.ready to begin

        // your logic here ...
        // At this moment, all iframes are loaded ...
    });

    $(document).ready(function() {
        alert('This page just now finished Loading');
    });
</script>
</code>```

The sequence of alerts clearly shows what happens. As you can see, jQuery.when() provides a way to execute callback functions based on objects that represent asynchronous events. Please check the Docs if needed.

Finally, since you're inserting the  tags dynamically, consider the following code:

```<code>        $.holdReady(true); // delay page load until all iframes get loaded

        var defer_Array = [];
        $.each($('iframe'), (index, tag) => {

            let temp = $.Deferred();
            defer_Array.push(temp);

            $(tag).on('load', function() {
                alert('iframe loaded #' + index);
                (defer_Array[index]).resolve();
            });
        })

        $.when(...defer_Array).done(function(v1, v2, v3) {
            alert(' All iframes loaded');
            $.holdReady(false);
            // your logic here ...
        });
</code>```

Feel free to grab the code and tweak it as you wish ... :)

Body:
I have a DotNet CORE MVC project.
The project has a controller which receives an array of strings, each string represents an Iframe source that needs to be placed in the View.

The model takes the array of string and do some manipulation on them, which means that eventually when the model is done and passed to the view it has a list of strings ready to be used as an iframe SRC.

The list in the model is this -

        public List<string> IFramePixels { get; set; };

And this is my View -

    @foreach (string iframe in Model.IFramePixels)
    {

    }

Everything works fine, the question is how can I delay the view loading finish time to when all those inner Iframes are done loading.

The reason I want that is that some outside website gonna place my website as an Iframe, and they need to know when all the inner Iframes are done (so I can't use a simple JS listener), I wanted to tell them to do some sort of a listener on when my webpage is done loading which means that the inner Iframes are done as well.

Thanks!

Edit ->
Well.. still couldn't find any answer, maybe thats simply not possible?
Does anyone have some different approach that might get me what I need? thanks!

Body:
need to know when all the inner Iframes are done...

Your sentence reminded me of Promise.All in Javascript.

So, if I got you right, jQuery.when() can serve your intention.
In addition, to make sure the page load is not made until all iframes are loaded, you can use $.holdReady

A sample code to get you on the way:

<div>
    <iframe id="if1" src="./let.html" height="200" width="300"></iframe>
    <iframe id="if2" src="./let.html" height="200" width="300"></iframe>
    <iframe id="if3" src="./let.html" height="200" width="300"></iframe>
</div>

<script src="./jquery-3.4.1.min.js"></script>
<script>
    // call this at the top of your script to delay jQuery's ready event.
    $.holdReady(true);

    var d1 = $.Deferred();
    var d2 = $.Deferred();
    var d3 = $.Deferred();

    $('#if1').on('load', function() {
        alert('iframe 1 Loaded');
        d1.resolve();
    });
    $('#if2').on('load', function() {
        alert('iframe 2 Loaded');
        d2.resolve();
    });
    $('#if3').on('load', function() {
        alert('iframe 3 Loaded');
        d3.resolve();
    });

    $.when(d1, d2, d3).done(function(v1, v2, v3) {
        alert(' All iframes loaded');
        $.holdReady(false); // this allows document.ready to begin

        // your logic here ...
        // At this moment, all iframes are loaded ...
    });

    $(document).ready(function() {
        alert('This page just now finished Loading');
    });
</script>

The sequence of alerts clearly shows what happens. As you can see, jQuery.when() provides a way to execute callback functions based on objects that represent asynchronous events. Please check the Docs if needed.

Finally, since you're inserting the <iframe> tags dynamically, consider the following code:

        $.holdReady(true); // delay page load until all iframes get loaded

        var defer_Array = [];
        $.each($('iframe'), (index, tag) => {

            let temp = $.Deferred();
            defer_Array.push(temp);

            $(tag).on('load', function() {
                alert('iframe loaded #' + index);
                (defer_Array[index]).resolve();
            });
        })

        $.when(...defer_Array).done(function(v1, v2, v3) {
            alert(' All iframes loaded');
            $.holdReady(false);
            // your logic here ...
        });

Feel free to grab the code and tweak it as you wish ... :)


问:
OpenVPN user certificates
I have problem with understanding of combination of OpenVPN with EasyRsa.

I have read this instructions

I am not understanding how client keys signing and revoking.

When I sign on CA server for user certificate and keys, openVPN server determines that user had signed his certificates and keys by same CA server and allows user to connect?

Similar to https with trusted certification server(example LetsEncrypt)

Right?

If i want to block user from access to openVPN, i need to revoke certificate on CA server.

But how openVPN server will understand that this user has no more rights to access openVPN?
Only with help of extra certificate revoke list?

That is generated with easyrsa gen-crl and synced/copied from CA server to openVPN server?

However if user certificate is expired, so openVPN server will simply not accept connection?

Am i right?

答:
To revoke certificates, you create a list of them and tell your OpenVPN server that when clients enter, they need to be verified using this list.

Using the "./revoke-full client_name" command, you add forbidden clients to the crl.pem file. Then, copy this file to the server configuration directory.
In order for the server to check this file when clients enter, it needs to enter the line "crl-verify crl.pem" in the configuration file.
Attention! If this string appears in the configuration file, but this file does not exist, the server will stop letting all clients!

Title: OpenVPN user certificates


问:
How can I add Laravel Crinsane cart data as an order?
In order to create an order from Crinsane based cart and associate it to the (authenticated) user, I created Order model and tried the following in order controller.

```<code><?php

namespace App\Http\Controllers;

use Cart;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
    /**
     * store cart to authenticated user as order.
     *
     */
    public function store(Request $request)
    {
        $order = new Order;

        $cartcontent = Cart::content();
        $user = auth('api')->user();
        $serializedcontent = $cartcontent->toJson(); //Returns []
        //$serializedcontent = $cartcontent->toArray(); //error
        //$serializedcontent = str_replace("\0", "~~NULL_BYTE~~", serialize($cartcontent)); //returns 0:29:"Illuminate....

        $order->user_id= $user->id;
        $order->cart_content= $serializedcontent;
        $order->save();

    }
}
</code>```

Edit:

I tried with column type as TEXT (without serialization) as well as JSON. I'm using Json API for front end (Vue) and JWT for authentication.

The column results in an empty set [] when I serialize to JSON. If I don't serialize, it returns O:29:"Illuminate\Support\Collection":1:{s:8:"~~NULL_BYTE~~*~~NULL_BYTE~~items";a:0:{}}

Order Model:

```<code>    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
        protected $fillable = [
        'user_id','user_id','cart_content'
    ];
        public function User(){
        return $this->belongsTo('App\User');
    }
}
</code>```

Link to source: https://github.com/riyaz7us/Laraman/tree/master/app/Http/Controllers

答:
From the docs

Cart::content() Of course you also want to get the carts content. This
  is where you'll use the content method. This method will return a
  Collection of CartItems which you can iterate over and show the
  content to your customers.

You are trying to insert a collection inside the database. You need to fetch the data from the current instance of the Crinsane based card then insert the data in the database as
json or whatever fits your needs.

Body:
In order to create an order from Crinsane based cart and associate it to the (authenticated) user, I created Order model and tried the following in order controller.

<?php

namespace App\Http\Controllers;

use Cart;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
    /**
     * store cart to authenticated user as order.
     *
     */
    public function store(Request $request)
    {
        $order = new Order;

        $cartcontent = Cart::content();
        $user = auth('api')->user();
        $serializedcontent = $cartcontent->toJson(); //Returns []
        //$serializedcontent = $cartcontent->toArray(); //error
        //$serializedcontent = str_replace("\0", "~~NULL_BYTE~~", serialize($cartcontent)); //returns 0:29:"Illuminate....

        $order->user_id= $user->id;
        $order->cart_content= $serializedcontent;
        $order->save();

    }
}

Edit:

I tried with column type as TEXT (without serialization) as well as JSON. I'm using Json API for front end (Vue) and JWT for authentication.

The column results in an empty set [] when I serialize to JSON. If I don't serialize, it returns O:29:"Illuminate\Support\Collection":1:{s:8:"~~NULL_BYTE~~*~~NULL_BYTE~~items";a:0:{}}

Order Model:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
        protected $fillable = [
        'user_id','user_id','cart_content'
    ];
        public function User(){
        return $this->belongsTo('App\User');
    }
}

Link to source: https://github.com/riyaz7us/Laraman/tree/master/app/Http/Controllers


问:
Correctly return boolean variable from python module
I'm sure this is absurdly simple but I have been unable to get it working.

I want to convert a boolean variable to True in a module and return it to my main.

file: test

```<code>import module as mo

value = False
mo.x(value)
print(value)
</code>```

2. file: module

```<code>def x(value):
    value = True
    return value
</code>```

But this code is not working. When I print out the value it gives me a False.
Does anybody know how to return the value so it's True?
Or is it even possible to change a boolean value in another module and return it afterwards?

答:
The problem is, that primitive types, like integers are passed by value and not by reference. So what happens is, you don't pass the variable "value" to function x(), but the value inside "value" gets copied.

A workaround would be using any object, as they are always passed by reference. E.g.: A list:

```<code>value[0] = False
mo.x(value)

def x(value: list):
    value[0] = True
    return value
</code>```

Body:
I'm sure this is absurdly simple but I have been unable to get it working.

I want to convert a boolean variable to True in a module and return it to my main.

file: test

import module as mo

value = False
mo.x(value)
print(value)

2. file: module

def x(value):
    value = True
    return value

But this code is not working. When I print out the value it gives me a False.
Does anybody know how to return the value so it's True?
Or is it even possible to change a boolean value in another module and return it afterwards?

Body:
The problem is, that primitive types, like integers are passed by value and not by reference. So what happens is, you don't pass the variable "value" to function x(), but the value inside "value" gets copied.

A workaround would be using any object, as they are always passed by reference. E.g.: A list:

value[0] = False
mo.x(value)

def x(value: list):
    value[0] = True
    return value


问:
async await in switch case statement does not work
can we wait for the resolution of a promise within switch case statement, using the keyword await? in my angular component I have the following code which crashes my application.

```<code>switch (this.status) {
                case 'opened':
                  break;
                case 'payed':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.localStorageService.storePaymentIsMade(true);
                  await this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()).toPromise();
                  this.router.navigate(['welcome/paying/paying_accepted']);
                  break;
                case 'closed':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.paymentSessionIsClosed = true;
                 await this.dbService.addOrderPaymentResult(ProcessResult.error, this.printerVMService.getSessionId()).toPromise();
                  this.router.navigate(['welcome']);
                  break;
                case 'used':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.router.navigate(['welcome']);
                  break;
                default:
                  console.error('status don\'t exist');
                  this.utils.displayAlertError(this.device.getIntervalStatus);
                  this.router.navigate(['welcome']);
              }
</code>```

After several tests, the error seems to me to come from lines starting with await.
Can you tell me what's wrong please. I would like this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()) which returns an observable is executed synchronously before going to
this.router.navigate(['welcome/paying/paying_accepted']); that's why i chose to use toPromise() and await

答:
Yes, you can:

async function trySwitch(status) {
    switch(status) {
        case 'opened':
            console.log('1');
            break;
        case 'closed':
            console.log('2');
            await new Promise(r => setTimeout(r, 1000));
            console.log('3');
            break;
    }
}

trySwitch('opened');
trySwitch('closed');```

Body:
can we wait for the resolution of a promise within switch case statement, using the keyword await? in my angular component I have the following code which crashes my application.

switch (this.status) {
                case 'opened':
                  break;
                case 'payed':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.localStorageService.storePaymentIsMade(true);
                  await this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()).toPromise();
                  this.router.navigate(['welcome/paying/paying_accepted']);
                  break;
                case 'closed':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.paymentSessionIsClosed = true;
                 await this.dbService.addOrderPaymentResult(ProcessResult.error, this.printerVMService.getSessionId()).toPromise();
                  this.router.navigate(['welcome']);
                  break;
                case 'used':
                  this.getIntervalStatusSubscription.unsubscribe();
                  this.router.navigate(['welcome']);
                  break;
                default:
                  console.error('status don\'t exist');
                  this.utils.displayAlertError(this.device.getIntervalStatus);
                  this.router.navigate(['welcome']);
              }

After several tests, the error seems to me to come from lines starting with await.
Can you tell me what's wrong please. I would like this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()) which returns an observable is executed synchronously before going to
this.router.navigate(['welcome/paying/paying_accepted']); that's why i chose to use toPromise() and await


问:
react material-table won't render icon when clicked
I have searched for a few days. Until now I cannot figured it out.
I want my visibility icon change to hide, when clicked. But I don't know why it not automatically rendering. I must to type something on search bar to get the visibility_off icon.

I read documentation but, it not works
https://material-table.com/#/docs/features/actions
and this https://material-table.com/#/docs/features/component-overriding

this my code

```<code>(rowData) => (
            rowData.isActive === 1 ?
                {
                    icon: "visibility_off",
                    tooltip: "Hide Row",
                    onClick: () => {

                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);

                        /*// console.log(row.tableData.id);
                        //find index
                        console.log(data[row.tableData.id]);
                        //change the data value
                        data[row.tableData.id].isActive = 0;

                        //set data with new data
                        setData(data);*/
                    },
                } :
                {
                    icon: "visibility",
                    tooltip: "Show Row",
                    onClick: () => {
                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);
                    },
                }
</code>```

And this is the full code.

```<code>const [tableConfig, setTableConfig] = useState({
    columns:[
        { title: "ID", field: "processID" },
        { title: "Config Name", field: "configName" },
        { title: "Status", field: "processStatus" },
        { title: "Progress", field: "progressPercentage", type: "numeric" },
        { title: "Start Time", field: "lastStartDateTime", type: "datetime" },
        { title: "End Time", field: "lastEndDateTime", type: "datetime" },
        { title: "Total Input Records", field: "lastInputRecords", type: "numeric" },
        { title: "Total Output Records", field: "masterRecords", type: "numeric" },
    ],
    data:[
        {
            processID: "191030070911880",
            configName: "Test2333",
            configDesc: "191030070911880 Test2333",
            userID: "1",
            createdDateTime: "2019-10-30 03:10:06.844",
            lastModifiedDateTime: "2020-01-18 02:24:59.051",
            isActive: 0,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:32:45.976",
            lastEndDateTime: "2020-01-18 02:32:56.197",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191030072229070",
            configName: "Testimony2",
            configDesc: "191030072229070 Testimony2",
            userID: "1",
            createdDateTime: "2019-10-30 03:22:34.732",
            lastModifiedDateTime: "2019-10-30 03:22:34.732",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "error",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:32:36.533",
            lastEndDateTime: "2020-01-18 02:32:36.566",
            lastInputRecords: 15,
            masterRecords: 0,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191030084112873",
            configName: "Testimony3",
            configDesc: "191030084112873 Testimony3",
            userID: "1",
            createdDateTime: "2019-10-30 04:41:19.856",
            lastModifiedDateTime: "2019-10-30 04:41:19.856",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "error",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:33:59.231",
            lastEndDateTime: "2020-01-18 02:33:59.256",
            lastInputRecords: 15,
            masterRecords: 0,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191104084001318",
            configName: "TestA",
            configDesc: "191104084001318 TestA",
            userID: "1",
            createdDateTime: "2019-11-04 03:40:44.697",
            lastModifiedDateTime: "2019-11-04 05:45:45.388",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2019-11-04 05:43:56.451",
            lastEndDateTime: "2019-11-04 05:44:06.846",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "adv191104084317062",
            configName: "TestA1",
            configDesc: "adv191104084317062 TestA1",
            userID: "1",
            createdDateTime: "2019-11-04 03:43:29.58",
            lastModifiedDateTime: "2019-11-04 05:45:45.732",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2019-11-04 05:43:49.78",
            lastEndDateTime: "2019-11-04 05:44:01.566",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "adv191128105553518",
            configName: "TestAAA",
            configDesc: "adv191128105553518 TestAAA",
            userID: "1",
            createdDateTime: "2019-11-28 05:56:00.845",
            lastModifiedDateTime: "2019-11-28 06:21:04.551",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:34:04.565",
            lastEndDateTime: "2020-01-18 02:34:15.933",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        }
    ],
    actions:[
        {
            icon: "play_arrow",
            tooltip: "Run",
            onClick: () => {
                console.log("run button is clicked");
            }
        },
        {
            icon: "description",
            tooltip: "Summary",
            onClick: () => {
                console.log("summary button is clicked");
            }
        },
        {
            icon: "edit",
            tooltip: "Edit",
            onClick: (event, row) => {
                // console.log(row.tableData.id);
                //cari indeks
                /*console.log(data[row.tableData.id]);
                //ganti data yang mau diganti
                data[row.tableData.id].configName = "ase";

                //mengembalikan data dengan isi yang sama persis seperti sebelumnya
                setData(data);*/
            }
        },
        {
            icon: "file_copy",
            tooltip: "Clone",
            onClick: () => {
                console.log("clone button is clicked");
            }
        },
        {
            icon: "delete",
            tooltip: "Delete",
            onClick: () => {
                console.log("Delete button is clicked");
            }
        },
        (rowData) => (
            rowData.isActive === 1 ?
                {
                    icon: "visibility_off",
                    tooltip: "Hide Row",
                    onClick: () => {

                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);

                        /*// console.log(row.tableData.id);
                        //cari indeks
                        console.log(data[row.tableData.id]);
                        //ganti data yang mau diganti
                        data[row.tableData.id].isActive = 0;

                        //mengembalikan data dengan isi yang sama persis seperti sebelumnya
                        setData(data);*/
                    },
                } :
                {
                    icon: "visibility",
                    tooltip: "Show Row",
                    onClick: () => {
                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);
                    },
                }
        )
    ]
});
</code>```

and this is the result. Please help me. Thank you.

NB: because of my reputation. I cannot post image here. Sorry

答:
First of all you can separate your actions array.

```<code>  const actions = [
        {
            icon: "description",
            tooltip: "Run",
            onClick: () => {
                console.log("run button is clicked");
            }
        },
        {
            icon: "description",
            tooltip: "Summary",
            onClick: () => {
                console.log("summary button is clicked");
            }
        },
        {
            icon: "edit",
            tooltip: "Edit",
            onClick: (event, row) => { }
        }, {
            icon: "visibility_off",
            tooltip: "Hide Row",
            onClick: () => { },
        },
        (rowData) => {
            return {
                icon: rowData.isActive === 1 ? 'visibility_off' : 'visibility',
                tooltip: "Hide Row",
                onClick: (event, row) => {
                    clickHandler(row)
                }
            }
        }
    ];
    const [tableConfig, setTableConfig] = React.useState({
        columns: [
            { title: "ID", field: "processID" },
            { title: "Config Name", field: "configName" },
            { title: "Status", field: "processStatus" },
            { title: "Progress", field: "progressPercentage", type: "numeric" },
            { title: "Start Time", field: "lastStartDateTime", type: "datetime" },
            { title: "End Time", field: "lastEndDateTime", type: "datetime" },
            { title: "Total Input Records", field: "lastInputRecords", type: "numeric" },
            { title: "Total Output Records", field: "masterRecords", type: "numeric" },
        ],
        data: [
            {
                processID: "191030070911880",
                configName: "Test2333",
                configDesc: "191030070911880 Test2333",
                userID: "1",
                createdDateTime: "2019-10-30 03:10:06.844",
                lastModifiedDateTime: "2020-01-18 02:24:59.051",
                isActive: 0,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:32:45.976",
                lastEndDateTime: "2020-01-18 02:32:56.197",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191030072229070",
                configName: "Testimony2",
                configDesc: "191030072229070 Testimony2",
                userID: "1",
                createdDateTime: "2019-10-30 03:22:34.732",
                lastModifiedDateTime: "2019-10-30 03:22:34.732",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "error",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:32:36.533",
                lastEndDateTime: "2020-01-18 02:32:36.566",
                lastInputRecords: 15,
                masterRecords: 0,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191030084112873",
                configName: "Testimony3",
                configDesc: "191030084112873 Testimony3",
                userID: "1",
                createdDateTime: "2019-10-30 04:41:19.856",
                lastModifiedDateTime: "2019-10-30 04:41:19.856",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "error",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:33:59.231",
                lastEndDateTime: "2020-01-18 02:33:59.256",
                lastInputRecords: 15,
                masterRecords: 0,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191104084001318",
                configName: "TestA",
                configDesc: "191104084001318 TestA",
                userID: "1",
                createdDateTime: "2019-11-04 03:40:44.697",
                lastModifiedDateTime: "2019-11-04 05:45:45.388",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2019-11-04 05:43:56.451",
                lastEndDateTime: "2019-11-04 05:44:06.846",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "adv191104084317062",
                configName: "TestA1",
                configDesc: "adv191104084317062 TestA1",
                userID: "1",
                createdDateTime: "2019-11-04 03:43:29.58",
                lastModifiedDateTime: "2019-11-04 05:45:45.732",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2019-11-04 05:43:49.78",
                lastEndDateTime: "2019-11-04 05:44:01.566",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "adv191128105553518",
                configName: "TestAAA",
                configDesc: "adv191128105553518 TestAAA",
                userID: "1",
                createdDateTime: "2019-11-28 05:56:00.845",
                lastModifiedDateTime: "2019-11-28 06:21:04.551",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:34:04.565",
                lastEndDateTime: "2020-01-18 02:34:15.933",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            }
        ],

    });
</code>```

As you can see I added clikHandler() function in your action array. This is for setting your tableconfig. You set tableConfig in a wrong way. You can check how to set immutable way your state.

```<code>const clickHandler = (rowData) => {
        setTableConfig({
            columns: [...tableConfig.columns],
            data: tableConfig.data.map((item, index) => {
                if (index !== rowData.tableData.id) {
                    return { ...item }
                }
                return {
                    ...item,
                    isActive: item.isActive === 1 ? 0 : 1
                }
            })
        });
    }
</code>```

btw you should change your action in your jsx part as actions={actions}
You can see the working example

Note

In functional component setState does not pretend to merge entire states. You have to merge yourselves.

Body:
I have searched for a few days. Until now I cannot figured it out.
I want my visibility icon change to hide, when clicked. But I don't know why it not automatically rendering. I must to type something on search bar to get the visibility_off icon.

I read documentation but, it not works
https://material-table.com/#/docs/features/actions
and this https://material-table.com/#/docs/features/component-overriding

this my code

(rowData) => (
            rowData.isActive === 1 ?
                {
                    icon: "visibility_off",
                    tooltip: "Hide Row",
                    onClick: () => {

                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);

                        /*// console.log(row.tableData.id);
                        //find index
                        console.log(data[row.tableData.id]);
                        //change the data value
                        data[row.tableData.id].isActive = 0;

                        //set data with new data
                        setData(data);*/
                    },
                } :
                {
                    icon: "visibility",
                    tooltip: "Show Row",
                    onClick: () => {
                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);
                    },
                }

And this is the full code.

const [tableConfig, setTableConfig] = useState({
    columns:[
        { title: "ID", field: "processID" },
        { title: "Config Name", field: "configName" },
        { title: "Status", field: "processStatus" },
        { title: "Progress", field: "progressPercentage", type: "numeric" },
        { title: "Start Time", field: "lastStartDateTime", type: "datetime" },
        { title: "End Time", field: "lastEndDateTime", type: "datetime" },
        { title: "Total Input Records", field: "lastInputRecords", type: "numeric" },
        { title: "Total Output Records", field: "masterRecords", type: "numeric" },
    ],
    data:[
        {
            processID: "191030070911880",
            configName: "Test2333",
            configDesc: "191030070911880 Test2333",
            userID: "1",
            createdDateTime: "2019-10-30 03:10:06.844",
            lastModifiedDateTime: "2020-01-18 02:24:59.051",
            isActive: 0,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:32:45.976",
            lastEndDateTime: "2020-01-18 02:32:56.197",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191030072229070",
            configName: "Testimony2",
            configDesc: "191030072229070 Testimony2",
            userID: "1",
            createdDateTime: "2019-10-30 03:22:34.732",
            lastModifiedDateTime: "2019-10-30 03:22:34.732",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "error",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:32:36.533",
            lastEndDateTime: "2020-01-18 02:32:36.566",
            lastInputRecords: 15,
            masterRecords: 0,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191030084112873",
            configName: "Testimony3",
            configDesc: "191030084112873 Testimony3",
            userID: "1",
            createdDateTime: "2019-10-30 04:41:19.856",
            lastModifiedDateTime: "2019-10-30 04:41:19.856",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "error",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:33:59.231",
            lastEndDateTime: "2020-01-18 02:33:59.256",
            lastInputRecords: 15,
            masterRecords: 0,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "191104084001318",
            configName: "TestA",
            configDesc: "191104084001318 TestA",
            userID: "1",
            createdDateTime: "2019-11-04 03:40:44.697",
            lastModifiedDateTime: "2019-11-04 05:45:45.388",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2019-11-04 05:43:56.451",
            lastEndDateTime: "2019-11-04 05:44:06.846",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "adv191104084317062",
            configName: "TestA1",
            configDesc: "adv191104084317062 TestA1",
            userID: "1",
            createdDateTime: "2019-11-04 03:43:29.58",
            lastModifiedDateTime: "2019-11-04 05:45:45.732",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2019-11-04 05:43:49.78",
            lastEndDateTime: "2019-11-04 05:44:01.566",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        },
        {
            processID: "adv191128105553518",
            configName: "TestAAA",
            configDesc: "adv191128105553518 TestAAA",
            userID: "1",
            createdDateTime: "2019-11-28 05:56:00.845",
            lastModifiedDateTime: "2019-11-28 06:21:04.551",
            isActive: 1,
            lastEditUserID: "1",
            processStatus: "success",
            progressPercentage: 0,
            lastStartDateTime: "2020-01-18 02:34:04.565",
            lastEndDateTime: "2020-01-18 02:34:15.933",
            lastInputRecords: 15,
            masterRecords: 15,
            systemConfig: null,
            dedupConfig: null
        }
    ],
    actions:[
        {
            icon: "play_arrow",
            tooltip: "Run",
            onClick: () => {
                console.log("run button is clicked");
            }
        },
        {
            icon: "description",
            tooltip: "Summary",
            onClick: () => {
                console.log("summary button is clicked");
            }
        },
        {
            icon: "edit",
            tooltip: "Edit",
            onClick: (event, row) => {
                // console.log(row.tableData.id);
                //cari indeks
                /*console.log(data[row.tableData.id]);
                //ganti data yang mau diganti
                data[row.tableData.id].configName = "ase";

                //mengembalikan data dengan isi yang sama persis seperti sebelumnya
                setData(data);*/
            }
        },
        {
            icon: "file_copy",
            tooltip: "Clone",
            onClick: () => {
                console.log("clone button is clicked");
            }
        },
        {
            icon: "delete",
            tooltip: "Delete",
            onClick: () => {
                console.log("Delete button is clicked");
            }
        },
        (rowData) => (
            rowData.isActive === 1 ?
                {
                    icon: "visibility_off",
                    tooltip: "Hide Row",
                    onClick: () => {

                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);

                        /*// console.log(row.tableData.id);
                        //cari indeks
                        console.log(data[row.tableData.id]);
                        //ganti data yang mau diganti
                        data[row.tableData.id].isActive = 0;

                        //mengembalikan data dengan isi yang sama persis seperti sebelumnya
                        setData(data);*/
                    },
                } :
                {
                    icon: "visibility",
                    tooltip: "Show Row",
                    onClick: () => {
                        console.log(rowData);
                        // console.log(event);
                        // console.log(row.isActive);
                        console.log(tableConfig.data[rowData.tableData.id].isActive);
                        console.log(rowData.tableData.id);
                        tableConfig.data[rowData.tableData.id].isActive = !tableConfig.data[rowData.tableData.id].isActive;
                        setTableConfig(tableConfig);
                        // console.log(row.isActive);
                    },
                }
        )
    ]
});

and this is the result. Please help me. Thank you.

NB: because of my reputation. I cannot post image here. Sorry

Body:
First of all you can separate your actions array.

  const actions = [
        {
            icon: "description",
            tooltip: "Run",
            onClick: () => {
                console.log("run button is clicked");
            }
        },
        {
            icon: "description",
            tooltip: "Summary",
            onClick: () => {
                console.log("summary button is clicked");
            }
        },
        {
            icon: "edit",
            tooltip: "Edit",
            onClick: (event, row) => { }
        }, {
            icon: "visibility_off",
            tooltip: "Hide Row",
            onClick: () => { },
        },
        (rowData) => {
            return {
                icon: rowData.isActive === 1 ? 'visibility_off' : 'visibility',
                tooltip: "Hide Row",
                onClick: (event, row) => {
                    clickHandler(row)
                }
            }
        }
    ];
    const [tableConfig, setTableConfig] = React.useState({
        columns: [
            { title: "ID", field: "processID" },
            { title: "Config Name", field: "configName" },
            { title: "Status", field: "processStatus" },
            { title: "Progress", field: "progressPercentage", type: "numeric" },
            { title: "Start Time", field: "lastStartDateTime", type: "datetime" },
            { title: "End Time", field: "lastEndDateTime", type: "datetime" },
            { title: "Total Input Records", field: "lastInputRecords", type: "numeric" },
            { title: "Total Output Records", field: "masterRecords", type: "numeric" },
        ],
        data: [
            {
                processID: "191030070911880",
                configName: "Test2333",
                configDesc: "191030070911880 Test2333",
                userID: "1",
                createdDateTime: "2019-10-30 03:10:06.844",
                lastModifiedDateTime: "2020-01-18 02:24:59.051",
                isActive: 0,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:32:45.976",
                lastEndDateTime: "2020-01-18 02:32:56.197",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191030072229070",
                configName: "Testimony2",
                configDesc: "191030072229070 Testimony2",
                userID: "1",
                createdDateTime: "2019-10-30 03:22:34.732",
                lastModifiedDateTime: "2019-10-30 03:22:34.732",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "error",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:32:36.533",
                lastEndDateTime: "2020-01-18 02:32:36.566",
                lastInputRecords: 15,
                masterRecords: 0,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191030084112873",
                configName: "Testimony3",
                configDesc: "191030084112873 Testimony3",
                userID: "1",
                createdDateTime: "2019-10-30 04:41:19.856",
                lastModifiedDateTime: "2019-10-30 04:41:19.856",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "error",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:33:59.231",
                lastEndDateTime: "2020-01-18 02:33:59.256",
                lastInputRecords: 15,
                masterRecords: 0,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "191104084001318",
                configName: "TestA",
                configDesc: "191104084001318 TestA",
                userID: "1",
                createdDateTime: "2019-11-04 03:40:44.697",
                lastModifiedDateTime: "2019-11-04 05:45:45.388",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2019-11-04 05:43:56.451",
                lastEndDateTime: "2019-11-04 05:44:06.846",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "adv191104084317062",
                configName: "TestA1",
                configDesc: "adv191104084317062 TestA1",
                userID: "1",
                createdDateTime: "2019-11-04 03:43:29.58",
                lastModifiedDateTime: "2019-11-04 05:45:45.732",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2019-11-04 05:43:49.78",
                lastEndDateTime: "2019-11-04 05:44:01.566",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            },
            {
                processID: "adv191128105553518",
                configName: "TestAAA",
                configDesc: "adv191128105553518 TestAAA",
                userID: "1",
                createdDateTime: "2019-11-28 05:56:00.845",
                lastModifiedDateTime: "2019-11-28 06:21:04.551",
                isActive: 1,
                lastEditUserID: "1",
                processStatus: "success",
                progressPercentage: 0,
                lastStartDateTime: "2020-01-18 02:34:04.565",
                lastEndDateTime: "2020-01-18 02:34:15.933",
                lastInputRecords: 15,
                masterRecords: 15,
                systemConfig: null,
                dedupConfig: null
            }
        ],

    });

As you can see I added clikHandler() function in your action array. This is for setting your tableconfig. You set tableConfig in a wrong way. You can check how to set immutable way your state.

const clickHandler = (rowData) => {
        setTableConfig({
            columns: [...tableConfig.columns],
            data: tableConfig.data.map((item, index) => {
                if (index !== rowData.tableData.id) {
                    return { ...item }
                }
                return {
                    ...item,
                    isActive: item.isActive === 1 ? 0 : 1
                }
            })
        });
    }

btw you should change your action in your jsx part as actions={actions}
You can see the working example

Note

In functional component setState does not pretend to merge entire states. You have to merge yourselves.


问:
QTreeView: some cells editable
I created a QTreeview(+QStandardItemModel(+QStandardItems)). On some cells I inserted a checkBox with by using setItemDelegate(). Now I want to set editable property, but all I try, nothing happens. I am wondering if setting flags hasn't any effect?

Is there any method to set the both lower right items not editable and the both upper right items editable. At the moment I am also able to write to the both checkbox-items (next to the checkboxes) (when it loose focus, it will disappear and when making a screenshot i looses focus so I cant show you)

答: Solution is to return true for indicating that event is handled in QAbstractItemDelegate::editorEvent

Title: QTreeView: some cells editable


问:
UWP Datagrid Get Row
How do I get a row in UWP? I have found solutions in WPF but UWP doesn't seem to have those options.

And I am not asking about the SelectedItem.

For example, I have a datagrid displaying a music library. I want to highlight a row whose music is being played. How can I do that in c# or using xaml?

I have tried using Style and a converter but I don't know what to bind.

The item source of the DataGrid is a public static List<Music> object.

```<code>    <controls:DataGrid
        x:Name="MusicLibraryDataGrid"
        Grid.Row="1"
        Margin="10"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        AlternatingRowBackground="WhiteSmoke"
        AlternatingRowForeground="Gray"
        AreRowDetailsFrozen="False"
        AreRowGroupHeadersFrozen="True"
        AutoGenerateColumns="False"
        CanUserReorderColumns="True"
        CanUserResizeColumns="True"
        CanUserSortColumns="True"
        ColumnHeaderHeight="32"
        DoubleTapped="MusicLibraryDataGrid_DoubleTapped"
        Foreground="Black"
        FrozenColumnCount="0"
        GridLinesVisibility="None"
        HeadersVisibility="Column"
        HorizontalScrollBarVisibility="Visible"
        IsDoubleTapEnabled="True"
        IsReadOnly="False"
        ItemsSource="{Binding AllSongs}"
        MinColumnWidth="100"
        SelectionMode="Extended"
        Sorting="MusicLibraryDataGrid_Sorting"
        VerticalScrollBarVisibility="Visible">
        <controls:DataGrid.Columns>
            // Some code
        </controls:DataGrid.Columns>
        <controls:DataGrid.RowStyle>
            <Style TargetType="controls:DataGridRow">
                <Setter Property="Foreground" Value="{Binding Music, Converter={StaticResource DataGridRowColorConverter}}" />
            </Style>
        </controls:DataGrid.RowStyle>
    </controls:DataGrid>
</code>```

答:
Sorry for the late anwser but maybe it can help future people.

I was also with this problem. I wanted to highlight some rows whose the data was changed or was with some error.

I found out that using DataGrid.LoadingRow event you can access the row before it get instanciated and change some atributes:

```<code>dataGrid.LoadingRow += DataGrid_LoadingRow;
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    if ((e.Row.DataContext as string).Length == 0)
            e.Row.Background = new SolidColorBrush(Colors.Blue);
}
</code>```

If the rows are already instanciated and you cant reload them, then this solution is not that useful. I hope it helps someone

Title: UWP Datagrid Get Row

Body:
How do I get a row in UWP? I have found solutions in WPF but UWP doesn't seem to have those options.

And I am not asking about the SelectedItem.

For example, I have a datagrid displaying a music library. I want to highlight a row whose music is being played. How can I do that in c# or using xaml?

I have tried using Style and a converter but I don't know what to bind.

The item source of the DataGrid is a public static List<Music> object.

    <controls:DataGrid
        x:Name="MusicLibraryDataGrid"
        Grid.Row="1"
        Margin="10"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        AlternatingRowBackground="WhiteSmoke"
        AlternatingRowForeground="Gray"
        AreRowDetailsFrozen="False"
        AreRowGroupHeadersFrozen="True"
        AutoGenerateColumns="False"
        CanUserReorderColumns="True"
        CanUserResizeColumns="True"
        CanUserSortColumns="True"
        ColumnHeaderHeight="32"
        DoubleTapped="MusicLibraryDataGrid_DoubleTapped"
        Foreground="Black"
        FrozenColumnCount="0"
        GridLinesVisibility="None"
        HeadersVisibility="Column"
        HorizontalScrollBarVisibility="Visible"
        IsDoubleTapEnabled="True"
        IsReadOnly="False"
        ItemsSource="{Binding AllSongs}"
        MinColumnWidth="100"
        SelectionMode="Extended"
        Sorting="MusicLibraryDataGrid_Sorting"
        VerticalScrollBarVisibility="Visible">
        <controls:DataGrid.Columns>
            // Some code
        </controls:DataGrid.Columns>
        <controls:DataGrid.RowStyle>

        </controls:DataGrid.RowStyle>
    </controls:DataGrid>

Body:
Sorry for the late anwser but maybe it can help future people.

I was also with this problem. I wanted to highlight some rows whose the data was changed or was with some error.

I found out that using DataGrid.LoadingRow event you can access the row before it get instanciated and change some atributes:

dataGrid.LoadingRow += DataGrid_LoadingRow;
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    if ((e.Row.DataContext as string).Length == 0)
            e.Row.Background = new SolidColorBrush(Colors.Blue);
}

If the rows are already instanciated and you cant reload them, then this solution is not that useful. I hope it helps someone


问:
Navigate to a specific component (React)
I have a page 1 and a page 2. On page 1 is a specific component. On page 2 I have a button. After clicking on that button I want to navigate to the position of the specific component on page 1.

Is there a legit way to handle this?

By the way I am using GatsbyJS.

答:
If you are using Gatsby, there is a plugin made for that :)
https://www.gatsbyjs.org/packages/gatsby-plugin-anchor-links/

Else you can just set an id on the component on page 2 and link with /page2#yourid


问:
A better way to submit a form for Django
This is what I am doing at the moment:

views.py

```<code>def activation_signupcount(request):

    if request.method == 'POST':

        return render_to_response('activation_signupcount.html',
                                {   'datestart': request.POST['datestart'],
                                    'dateend': request.POST['dateend'],
                                    'usersegment': request.POST['usersegment'],
                                    'segment_form': SegmentForm(request.POST),
                                    'date_form': DateSelectForm(request.POST)    })
    else:

        return render_to_response('activation_signupcount.html',
                                {'segment_form': SegmentForm(), 'date_form': DateSelectForm()})
</code>```

template

```<code>{% extends "base_activation.html" %}

{% block content %}
    <h2>Sign ups</h2>
    <p>Number of users who have registered to the site between the dates entered</p>
{% endblock %}

{% block graph %}
    {% if datestart %}
    <p>This counts the number of <strong>{{ usersegment }}</strong> users who have successfully registered to the site (verified their email)
    who joined between <strong>{{ datestart }}</strong> and <strong>{{ dateend }}</strong></p>
    <img src="./activation_signupcount.png?usersegment={{ usersegment }}&datestart={{ datestart }}&dateend={{ dateend }}" />
    {% endif %}
{% endblock %}
</code>```

So I am returning the same page when a user submits the SegmentForm and DateSelectForms. To check if I should return the output (a graph), I am checking for the existence of datestart as seen in my template {% if datestart %} if it was submitted.

Is this a Djangoic way of doing it? I feel I ought to be checking for response == 'POST' rather than forcing the check variable to datestart.

Thanks

答:
First, a few pointers to save you headaches when debugging the code. Instead of testing for request.method == 'POST', check whether the value you have attached to the submit button on your form(s) (in the template) is in the request.POST dictionary. I'm not sure whether you are submitting 2 forms with one "submit"-button, but if you do, why not write one form for it?

Also, always check whether your form is valid. This saves you a lot of headaches when rendering your graph, as the code for the graph can then safely make certain assumptions about the quality of the data it receives. Also, the user will know why the graph doesn't render (he'll get error messages in his form).

You could make the validation check in the template or in the view (the latter is recommended - program logic should reside in your views). If your forms are valid, they will get the "cleaned_data" properties, containing the validated data.

Off the top of my head, here's what more Django-ic code would look like:

```<code>def render_view(request):
    if "submit" in request.POST: # Supposing both forms are submitted with one "submit" button
        segment_form = SegmentForm(request.POST)
        dateselect_form = DateSelectForm(request.POST)
    else:
        segment_form = SegmentForm()
        dateselect_form = DateSelectForm()

    return render_to_response('activation_signupcount.html',{'segment_form': segment_form, 'date_form': date_form, 'display_graph': (segment_form.is_valid() and dateselect_form.is_valid())})
</code>```

Then, in your template, first check if the forms are valid (the 'display_graph' variable is True if both forms are valid), and then access their cleaned_data properties to get the values you want. For instance:

```<code>{% block graph %}
{% if display_graph %}
    <p>This counts the number of <strong>{{ segment_form.cleaned_data.usersegment }}</strong> users who have successfully registered to the site (verified their email)who joined between <strong>{{ date_form.cleaned_data.datestart }}</strong> and <strong>{{ date_form.cleaned_data.dateend }}</strong></p>
<img src="./activation_signupcount.png?usersegment={{ segment_form.cleaned_data.usersegment }}&datestart={{ date_form.cleaned_data.datestart }}&dateend={{ date_form.cleaned_data.dateend  }}" />
{% endif %}
{% endblock %}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is what I am doing at the moment:

views.py

def activation_signupcount(request):

    if request.method == 'POST':

        return render_to_response('activation_signupcount.html',
                                {   'datestart': request.POST['datestart'],
                                    'dateend': request.POST['dateend'],
                                    'usersegment': request.POST['usersegment'],
                                    'segment_form': SegmentForm(request.POST),
                                    'date_form': DateSelectForm(request.POST)    })
    else:

        return render_to_response('activation_signupcount.html',
                                {'segment_form': SegmentForm(), 'date_form': DateSelectForm()})

template

{% extends "base_activation.html" %}

{% block content %}

Sign ups

Number of users who have registered to the site between the dates entered

{% endblock %}

{% block graph %}
    {% if datestart %}

This counts the number of {{ usersegment }} users who have successfully registered to the site (verified their email)
    who joined between {{ datestart }} and {{ dateend }}

    {% endif %}
{% endblock %}

So I am returning the same page when a user submits the SegmentForm and DateSelectForms. To check if I should return the output (a graph), I am checking for the existence of datestart as seen in my template {% if datestart %} if it was submitted.

Is this a Djangoic way of doing it? I feel I ought to be checking for response == 'POST' rather than forcing the check variable to datestart.

Thanks

Body:
First, a few pointers to save you headaches when debugging the code. Instead of testing for request.method == 'POST', check whether the value you have attached to the submit button on your form(s) (in the template) is in the request.POST dictionary. I'm not sure whether you are submitting 2 forms with one "submit"-button, but if you do, why not write one form for it?

Also, always check whether your form is valid. This saves you a lot of headaches when rendering your graph, as the code for the graph can then safely make certain assumptions about the quality of the data it receives. Also, the user will know why the graph doesn't render (he'll get error messages in his form).

You could make the validation check in the template or in the view (the latter is recommended - program logic should reside in your views). If your forms are valid, they will get the "cleaned_data" properties, containing the validated data.

Off the top of my head, here's what more Django-ic code would look like:

def render_view(request):
    if "submit" in request.POST: # Supposing both forms are submitted with one "submit" button
        segment_form = SegmentForm(request.POST)
        dateselect_form = DateSelectForm(request.POST)
    else:
        segment_form = SegmentForm()
        dateselect_form = DateSelectForm()

    return render_to_response('activation_signupcount.html',{'segment_form': segment_form, 'date_form': date_form, 'display_graph': (segment_form.is_valid() and dateselect_form.is_valid())})

Then, in your template, first check if the forms are valid (the 'display_graph' variable is True if both forms are valid), and then access their cleaned_data properties to get the values you want. For instance:

{% block graph %}
{% if display_graph %}
    <p>This counts the number of <strong>{{ segment_form.cleaned_data.usersegment }}</strong> users who have successfully registered to the site (verified their email)who joined between <strong>{{ date_form.cleaned_data.datestart }}</strong> and <strong>{{ date_form.cleaned_data.dateend }}</strong></p>
<img src="./activation_signupcount.png?usersegment={{ segment_form.cleaned_data.usersegment }}&datestart={{ date_form.cleaned_data.datestart }}&dateend={{ date_form.cleaned_data.dateend  }}" />
{% endif %}
{% endblock %}


问:
Scripted Jenkinsfile - Multi choice in middle of run
I have a scripted pipeline, that look like this:

```<code>node(){
  stage("test"){
    echo "test"
  }
  stage("two"){
      deployOptions = "one\ntwo\nthree\nfour\nfive"

      def userInput = input(
        id: 'userInput', message: 'pick option', parameters: [
          [$class: 'ChoiceParameterDefinition', choices: deployOptions, description: 'Select deployment', name: 'deploy-pick']
      ])
    echo "you selected: ${userInput}"
  }
  stage("deploy"){
    echo "deploy"
  }
}
</code>```

What happens is that the first stage print "test", the second stage wait for user pick of list([one,two,three,four,five]), and after the user pick option, the pipeline run the "deploy" stage.

But what I want now, is instead of picking one option from the deployOptions list, I want to be able to pick multiple options (like extendedChoice in the pre-build parameters).

答:
Nevermind, I solved it.

I used the "com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition" Class.

Body:
I have a scripted pipeline, that look like this:

node(){
  stage("test"){
    echo "test"
  }
  stage("two"){
      deployOptions = "one\ntwo\nthree\nfour\nfive"

      def userInput = input(
        id: 'userInput', message: 'pick option', parameters: [
          [$class: 'ChoiceParameterDefinition', choices: deployOptions, description: 'Select deployment', name: 'deploy-pick']
      ])
    echo "you selected: ${userInput}"
  }
  stage("deploy"){
    echo "deploy"
  }
}

What happens is that the first stage print "test", the second stage wait for user pick of list([one,two,three,four,five]), and after the user pick option, the pipeline run the "deploy" stage.

But what I want now, is instead of picking one option from the deployOptions list, I want to be able to pick multiple options (like extendedChoice in the pre-build parameters).