问:
Y-Axis with different colors
I have tried to add different colors to the Y-axis but without success.
Is it possible to achive something like attached image shows?

In the chartjs-plugin-annotation plugin you can set the background but not scale colors.

Describing image

        var config = {
            type: 'line',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{
                    label: 'Dataset',
                    data: [1,2,3,4,5,6,7],
                    fill: false,
                }]
            },
            options: {
                responsive: true,
                scales: {
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Colored scale'
                        },
                        gridLines: { color: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)']  }
                    }]
                }
            }
        };

        window.onload = function () {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, config);
        };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
</head>
<body>
    <div style="width:75%;"><canvas id="canvas"></canvas></div>
</body></code>```

答:
You can draw individual boxes directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the beforeDraw hook to draw the rectangles of different background color each.

new Chart(document.getElementById('canvas'), {
  type: 'line',
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];

      ctx.save();

      ctx.fillStyle  = 'green';
      ctx.beginPath();
      var yGreen = yAxis.getPixelForValue(3.5);
      ctx.fillRect(xAxis.left - 6, yGreen, 6, yAxis.bottom - yGreen);
      ctx.stroke();

      ctx.fillStyle  = 'orange';
      ctx.beginPath();
      var yOrange = yAxis.getPixelForValue(4.5);
      ctx.fillRect(xAxis.left - 6, yOrange, 6, yGreen - yOrange);
      ctx.stroke();

      ctx.fillStyle  = 'red';
      ctx.beginPath();
      var yRed = yAxis.getPixelForValue(7);
      ctx.fillRect(xAxis.left - 6, yRed, 6, yOrange- yRed);
      ctx.stroke();

      ctx.restore();
    }
  }],
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'Dataset',
      data: [1, 2, 3, 4, 5, 6, 7],
      fill: false
    }]
  },
  options: {
    responsive: true,
    scales: {
      yAxes: [{
        gridLines: {
           tickMarkLength: 15
        },
        ticks: {
           padding: 6
        },
        scaleLabel: {
          display: true,
          labelString: 'Colored scale'
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="canvas" height="90"></code>```

Title: Y-Axis with different colors

Body:
I have tried to add different colors to the Y-axis but without success.
Is it possible to achive something like attached image shows?

In the chartjs-plugin-annotation plugin you can set the background but not scale colors.

Describing image

        var config = {
            type: 'line',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{
                    label: 'Dataset',
                    data: [1,2,3,4,5,6,7],
                    fill: false,
                }]
            },
            options: {
                responsive: true,
                scales: {
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Colored scale'
                        },
                        gridLines: { color: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)']  }
                    }]
                }
            }
        };

        window.onload = function () {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, config);
        };

<!DOCTYPE html>

<canvas id="canvas"></canvas>

Body:
You can draw individual boxes directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the beforeDraw hook to draw the rectangles of different background color each.

new Chart(document.getElementById('canvas'), {
  type: 'line',
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];

      ctx.save();

      ctx.fillStyle  = 'green';
      ctx.beginPath();
      var yGreen = yAxis.getPixelForValue(3.5);
      ctx.fillRect(xAxis.left - 6, yGreen, 6, yAxis.bottom - yGreen);
      ctx.stroke();

      ctx.fillStyle  = 'orange';
      ctx.beginPath();
      var yOrange = yAxis.getPixelForValue(4.5);
      ctx.fillRect(xAxis.left - 6, yOrange, 6, yGreen - yOrange);
      ctx.stroke();

      ctx.fillStyle  = 'red';
      ctx.beginPath();
      var yRed = yAxis.getPixelForValue(7);
      ctx.fillRect(xAxis.left - 6, yRed, 6, yOrange- yRed);
      ctx.stroke();

      ctx.restore();
    }
  }],
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'Dataset',
      data: [1, 2, 3, 4, 5, 6, 7],
      fill: false
    }]
  },
  options: {
    responsive: true,
    scales: {
      yAxes: [{
        gridLines: {
           tickMarkLength: 15
        },
        ticks: {
           padding: 6
        },
        scaleLabel: {
          display: true,
          labelString: 'Colored scale'
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="canvas" height="90">


来源: stackexchange

问:
JOIN DQL SYMFONY
i want to count how many baby for a parent

```<code> class abonnementRepository extends \Doctrine\ORM\EntityRepository
{
    public function SumEnfantDQL($id)
    {
        $entityManager = $this->getEntityManager();
        $query = $entityManager->createQueryBuilder();
        $query->select('sum(o.id) AS somme');
        $query->from('AppBundle:enfant', 'o');
        $query->join('AppBundle:User','p')->where('p.id = :id');
        $rez = $query->getQuery()->getResult();
        return $rez;
    }
}
</code>```

the entity enfant had matricul_prt and entity user had enfant_id and $id parameter is the parent id
i don't know how it work with join or innerJoin .So what i want to do is

```<code>SELECT SUM(*)
FROM enfant e
WHERE e.matricul_prt = $id;
</code>```

Thank you so much

答:
First of all, you should create a Repository class for AppBundle:enfant, this repo does not look like created fot 'enfant'.
Next the method should look like below, but only if there is valid association between 'enfant' and 'User'.

```<code>public function SumEnfant(int $id): int
{
    return $this->createQueryBuilder('e') <- alias for 'enfant'
        ->select('sum(e.id)')
        ->join('e.user', 'u') <- join by entity property
        ->where('u.id = :id') <- condition for associated entity
        ->setParameter('id' , $id) <- parameter
        ->getQuery()
        ->getSingleScalarResult();
}
</code>```

Try this, read doc once again and modify for your case.

ContentLicense: CC BY-SA 4.0

Title: JOIN DQL SYMFONY

Body:
i want to count how many baby for a parent

 class abonnementRepository extends \Doctrine\ORM\EntityRepository
{
    public function SumEnfantDQL($id)
    {
        $entityManager = $this->getEntityManager();
        $query = $entityManager->createQueryBuilder();
        $query->select('sum(o.id) AS somme');
        $query->from('AppBundle:enfant', 'o');
        $query->join('AppBundle:User','p')->where('p.id = :id');
        $rez = $query->getQuery()->getResult();
        return $rez;
    }
}

the entity enfant had matricul_prt and entity user had enfant_id and $id parameter is the parent id
i don't know how it work with join or innerJoin .So what i want to do is

SELECT SUM(*)
FROM enfant e
WHERE e.matricul_prt = $id;

Thank you so much

Body:
First of all, you should create a Repository class for AppBundle:enfant, this repo does not look like created fot 'enfant'.
Next the method should look like below, but only if there is valid association between 'enfant' and 'User'.

public function SumEnfant(int $id): int
{
    return $this->createQueryBuilder('e') <- alias for 'enfant'
        ->select('sum(e.id)')
        ->join('e.user', 'u') <- join by entity property
        ->where('u.id = :id') <- condition for associated entity
        ->setParameter('id' , $id) <- parameter
        ->getQuery()
        ->getSingleScalarResult();
}

Try this, read doc once again and modify for your case.


问:
Bluetooth background scan in Xamarin.iOS
I found the Objective-C examples

```<code>[manager scanForPeripheralsWithServices:nil
                                options:@{
    CBCentralManagerScanOptionSolicitedServiceUUIDsKey:@[
        [CBUUID UUIDWithString:@"7905F431-B5CE-4E99-A40F-4B1E122D00D0"]]}];
</code>```

And try to convert Xamarin.iOS code

```<code>PeripheralScanningOptions option = new PeripheralScanningOptions(NSDictionary.FromObjectAndKey(CBCentralManager.ScanOptionSolicitedServiceUUIDsKey, CBUUID.FromString("84C80001-4A61-60B9-3A2B-1300855E588C")));

CBCM.ScanForPeripherals(new []{ CBUUID.FromString("84C80001-4A61-60B9-3A2B-1300855E588C") }, option);
</code>```

but is not working,

how to use CBCentralManager.ScanOptionSolicitedServiceUUIDsKey in Xamarin.iOS?

答:
There is a solution below that you can try for you:

using Plugin.BLE (https://www.nuget.org/packages/Plugin.BLE/) I can get the service uuid of a beacon/device using advertisement records like so

foreach (AdvertisementRecord record in e.Device.AdvertisementRecords)

```<code>        {
            if (record.Type == AdvertisementRecordType.UuidsComplete128Bit || record.Type == AdvertisementRecordType.UuidsComplete16Bit)
            {
                b.ServiceUUID = record.Data;
                break;
            }
        }
</code>```

I then pass in a list of CBUUID with the ServiceUUID values added to them:

```<code> foreach (Beacon beacon in beaconList)
        {
            cbuuidList.Add(CBUUID.FromBytes(beacon.ServiceUUID));
        }

        CBUUID[] uuid = cbuuidList.ToArray();
        BLEManager.ScanForPeripherals(uuid);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found the Objective-C examples

[manager scanForPeripheralsWithServices:nil
                                options:@{
    CBCentralManagerScanOptionSolicitedServiceUUIDsKey:@[
        [CBUUID UUIDWithString:@"7905F431-B5CE-4E99-A40F-4B1E122D00D0"]]}];

And try to convert Xamarin.iOS code

PeripheralScanningOptions option = new PeripheralScanningOptions(NSDictionary.FromObjectAndKey(CBCentralManager.ScanOptionSolicitedServiceUUIDsKey, CBUUID.FromString("84C80001-4A61-60B9-3A2B-1300855E588C")));

CBCM.ScanForPeripherals(new []{ CBUUID.FromString("84C80001-4A61-60B9-3A2B-1300855E588C") }, option);

but is not working,

how to use CBCentralManager.ScanOptionSolicitedServiceUUIDsKey in Xamarin.iOS?

Body:
There is a solution below that you can try for you:

using Plugin.BLE (https://www.nuget.org/packages/Plugin.BLE/) I can get the service uuid of a beacon/device using advertisement records like so

foreach (AdvertisementRecord record in e.Device.AdvertisementRecords)

        {
            if (record.Type == AdvertisementRecordType.UuidsComplete128Bit || record.Type == AdvertisementRecordType.UuidsComplete16Bit)
            {
                b.ServiceUUID = record.Data;
                break;
            }
        }

I then pass in a list of CBUUID with the ServiceUUID values added to them:

 foreach (Beacon beacon in beaconList)
        {
            cbuuidList.Add(CBUUID.FromBytes(beacon.ServiceUUID));
        }

        CBUUID[] uuid = cbuuidList.ToArray();
        BLEManager.ScanForPeripherals(uuid);


问:
Print elegantly in scientific notation python
I wanna print a number and its uncertainty in the following way:

x = (4.23 ± 0.01) e3

where the value and its uncertainty are two different variables.

```<code>mean = 4230
uncertainty = 10
print("x is %.2e \u00B1 %.2e" % (mean, uncertainty))
</code>```

I want them to be formatted with the same power of the exponential in the scientific notation. what I get is

```<code>x is 4.23e+03 ± 1.00e+01
</code>```

答:
Assuming mean integer, a way to do it might be</p>

```<code>>>> mean = 4230
>>> uncertainty = 10
>>> pos_to_first = len(str(mean)) - 1
>>> f"({mean/10**pos_to_first} ± {uncertainty/10**pos_to_first}) E{pos_to_first}"
'(4.23 ± 0.01) E3'
</code>```

Body:
I wanna print a number and its uncertainty in the following way:

x = (4.23 ± 0.01) e3

where the value and its uncertainty are two different variables.

mean = 4230
uncertainty = 10
print("x is %.2e \u00B1 %.2e" % (mean, uncertainty))

I want them to be formatted with the same power of the exponential in the scientific notation. what I get is

x is 4.23e+03 ± 1.00e+01

Body:
Assuming mean integer, a way to do it might be

>>> mean = 4230
>>> uncertainty = 10
>>> pos_to_first = len(str(mean)) - 1
>>> f"({mean/10**pos_to_first} ± {uncertainty/10**pos_to_first}) E{pos_to_first}"
'(4.23 ± 0.01) E3'


问:
BlackBerry - Thread not responding
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

```<code> invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });
</code>```

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

```<code>   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }
</code>```

答:
You're exactly right:

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Calling InvokeLater returns immediately, and queues work for the UI thread to execute.  The problem is that if that queue gets too big, the OS will kill your app, assuming that the UI has bogged down to the point where it is not servicing the queue.

The solution I've used to get around this in the past is to chunk the work being sent to the UI thread.  Make some sort of accumulator object, and boolean flag, and a lock.   The worker thread then grabs the lock and adds work to the accumulator.   The boolean flag indicates whether the UI worker code is scheduled to empty the accumulator in the future.  If not, schedule your UI update code.

In the UI update code, you grab the lock and move the data out of the accumulator as quickly as possible, and mark the boolean as false, to show that there is no longer a UI worker scheduled to empty the accumulator.

Title: BlackBerry - Thread not responding

Body:
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

 invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }


问:
Angular material dialog component hides all my website components
I'm using angular 5 and angular material (latest version) and I'm trying to open a dialog from a page. When I click the button that triggers the opening, the entire website is put in blank background like if the dialog were overlaping it contents and hiding it all.

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
    moduleId: module.id,
    selector: 'app-dialog',
    templateUrl: 'dialog.component.html',
    styleUrls: ['dialog.component.scss']
})
export class DialogComponent implements OnInit {

    constructor(public dialogRef: MatDialogRef<DialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any) { }

    onNoClick(): void {
        this.dialogRef.close();
    }

    ngOnInit() {
    }

}
</code>```

And this is the method that opens the Dialog.

```<code>onSubmit() {

        const dialogRef = this.dialog.open(DialogComponent, {
            width: '250px',
            data: { name: 'Juan Manuel', animal: 'Perro' }
        });

        dialogRef.afterClosed().subscribe(result => {
            console.log('The dialog was closed');
            console.log(result);
        });
    }
</code>```

UPDATE:
I've seen that after the dialog is rendered a class is added to my html tag. .cdk-global-scrollblock I don't know why is that class added to my html tag.

```<code>.cdk-global-scrollblock {
    position: fixed;
    width: 100%;
    overflow-y: scroll;
}
</code>```

That what's causing my error. Does someone knows why is that class on my html tag?

答:
Easiest fix would be setting the dialog scroll strategy to new NoopScrollStrategy object:

```<code>const dialogRef = this.dialog.open(DialogComponent, {
        width: '250px',
        data: { name: 'Juan Manuel', animal: 'Perro' },
        scrollStrategy: new NoopScrollStrategy()
    });
</code>```

this will only require an extra import:

```<code>import { NoopScrollStrategy } from '@angular/cdk/overlay';
</code>```

Body:
I'm using angular 5 and angular material (latest version) and I'm trying to open a dialog from a page. When I click the button that triggers the opening, the entire website is put in blank background like if the dialog were overlaping it contents and hiding it all.

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
    moduleId: module.id,
    selector: 'app-dialog',
    templateUrl: 'dialog.component.html',
    styleUrls: ['dialog.component.scss']
})
export class DialogComponent implements OnInit {

    constructor(public dialogRef: MatDialogRef<DialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any) { }

    onNoClick(): void {
        this.dialogRef.close();
    }

    ngOnInit() {
    }

}

And this is the method that opens the Dialog.

onSubmit() {

        const dialogRef = this.dialog.open(DialogComponent, {
            width: '250px',
            data: { name: 'Juan Manuel', animal: 'Perro' }
        });

        dialogRef.afterClosed().subscribe(result => {
            console.log('The dialog was closed');
            console.log(result);
        });
    }

UPDATE:
I've seen that after the dialog is rendered a class is added to my html tag. .cdk-global-scrollblock I don't know why is that class added to my html tag.

.cdk-global-scrollblock {
    position: fixed;
    width: 100%;
    overflow-y: scroll;
}

That what's causing my error. Does someone knows why is that class on my html tag?

Body:
Easiest fix would be setting the dialog scroll strategy to new NoopScrollStrategy object:

const dialogRef = this.dialog.open(DialogComponent, {
        width: '250px',
        data: { name: 'Juan Manuel', animal: 'Perro' },
        scrollStrategy: new NoopScrollStrategy()
    });

this will only require an extra import:

import { NoopScrollStrategy } from '@angular/cdk/overlay';


问:
Trouble updating MongoDB using Python/PyMongo with REST api
Hello I am having trouble updating a MongoDB document while using a Python REST API.
Here is the Python code:

```<code>import json
import bottle
from bson import json_util
from bson.json_util import dumps
from pymongo import MongoClient
from bottle import route, run, request, abort

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']

#Create
@route('/create', method='POST')
def post_create():

    data=json.load(request.body)
    id=data["id"]
    certificate_number=data["certificate_number"]
    business_name=data["business_name"]
    date=data["date"]
    result=data["result"]
    sector=data["sector"]
    result=collection.insert_one({'id': id, 'certificate_number': certificate_number, 'business_name' : business_name, 'date' : date, 'result' : result, 'sector' : sector}).inserted_id
    return json.loads(json.dumps(result, indent=4, default=json_util.default))

#Update
@route('/update', method='GET')
def update():

    id=request.query.id
    result=request.query.result
    myquery = {"id": "10011-2017-TEST" }
    newvalues = { "$set": { "result" : result } }
    collection.update(myquery, newvalues)
</code>```

After I start the above Python code, these are the two queries I am running in my terminal:

```<code>#Create
curl -H "Content-Type: application/json" -X POST -d '{"id" : "10011-2017-TEST","certificate_number" : 9278833,"business_name" : "ACME TEST INC.","date" : "Feb 20 2017","result" : "No Violation Issued","sector" : "Test Retail Dealer - 101"}' http://localhost:8080/create

#Update
curl http://localhost:8080/update?id="10011-2017-TEST"&result="Violation Issued"
</code>```

The first curl command works perfectly.
However, when I run the second curl update command, I receive an empty "result".

```<code>{
        "_id" : ObjectId("5e48b39618882a084aa35b86"),
        "sector" : "Test Retail Dealer - 101",
        "certificate_number" : 9278833,
        "result" : "",
        "date" : "Feb 20 2017",
        "business_name" : "ACME TEST INC.",
        "id" : "10011-2017-TEST"
}
</code>```

I need the "result" to change from "No Violation Issued" to "Violation Issued". I think I am close, because I know the second update curl command is referencing the correct document, however, it is not updating the "result" properly. I am suspecting the python function can not see the second part of the query, resulting in a blank update.

答:
axme100 is correct, the whitespace is your problem. There's few ways to work around it different shell quotes /escapes etc. but the easiest is probably:

```<code>curl 'http://localhost:8080/update?id=10011-2017-TEST&result=Violation%20Issued'
</code>```

Put the whole thing in single quotes whenever you have an & in the query string to prevent the shell running it in the background.

Body:
Hello I am having trouble updating a MongoDB document while using a Python REST API.
Here is the Python code:

import json
import bottle
from bson import json_util
from bson.json_util import dumps
from pymongo import MongoClient
from bottle import route, run, request, abort

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']

#Create
@route('/create', method='POST')
def post_create():

    data=json.load(request.body)
    id=data["id"]
    certificate_number=data["certificate_number"]
    business_name=data["business_name"]
    date=data["date"]
    result=data["result"]
    sector=data["sector"]
    result=collection.insert_one({'id': id, 'certificate_number': certificate_number, 'business_name' : business_name, 'date' : date, 'result' : result, 'sector' : sector}).inserted_id
    return json.loads(json.dumps(result, indent=4, default=json_util.default))

#Update
@route('/update', method='GET')
def update():

    id=request.query.id
    result=request.query.result
    myquery = {"id": "10011-2017-TEST" }
    newvalues = { "$set": { "result" : result } }
    collection.update(myquery, newvalues)

After I start the above Python code, these are the two queries I am running in my terminal:

#Create
curl -H "Content-Type: application/json" -X POST -d '{"id" : "10011-2017-TEST","certificate_number" : 9278833,"business_name" : "ACME TEST INC.","date" : "Feb 20 2017","result" : "No Violation Issued","sector" : "Test Retail Dealer - 101"}' http://localhost:8080/create

#Update
curl http://localhost:8080/update?id="10011-2017-TEST"&result="Violation Issued"

The first curl command works perfectly.
However, when I run the second curl update command, I receive an empty "result".

{
        "_id" : ObjectId("5e48b39618882a084aa35b86"),
        "sector" : "Test Retail Dealer - 101",
        "certificate_number" : 9278833,
        "result" : "",
        "date" : "Feb 20 2017",
        "business_name" : "ACME TEST INC.",
        "id" : "10011-2017-TEST"
}

I need the "result" to change from "No Violation Issued" to "Violation Issued". I think I am close, because I know the second update curl command is referencing the correct document, however, it is not updating the "result" properly. I am suspecting the python function can not see the second part of the query, resulting in a blank update.

Body:
axme100 is correct, the whitespace is your problem. There's few ways to work around it different shell quotes /escapes etc. but the easiest is probably:

curl 'http://localhost:8080/update?id=10011-2017-TEST&result=Violation%20Issued'

Put the whole thing in single quotes whenever you have an & in the query string to prevent the shell running it in the background.


问:
How to delete a field from UI by clicking its respective delete icon - Angular
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

```<code><div  [formGroup]="parentForm">
  <mat-form-field >
    <div class="delete-icon" *ngIf="showDeleteIcon" (click)="removeIncomeField($event, i)">
      <img src="/assets/icons/delete_income.png"></div>

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>
</div>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>
</code>```

答:
I can think of at least two angular ways to do this:

Remove with *ngIf

```<code>export class EmployeeDetailsComponent {
  public showBusinessIncome = true;
  public showRealEstate = true;

  removeIncomeField(input: number) {
    if(input === 1) {
       this.showBusinessIncome = false;
    }
    else if (input === 2) {
       this.showRealEstate = false;
    }
  }
}
</code>```

And in html

```<code>  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true" *ngIf="showBusinessIncome"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField(1)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" *ngIf="showRealEstate" (deleteIncomeField)="deleteSelectedField(2)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>
</code>```

Make the IncomeFieldComponent custom control and handle with reactive forms

This is a bit more complicated to get into, but I would propose to followi this material guide

Then you will be able to remove the control properly from the FormGroup

Angular form group guide

```<code>const myForm = new FormGroup({
  businessIncome: new FormControl('businessIncome'),
  realEaste: new FormControl('realEstate')
});
</code>```

```<code>this.myForm.removeControl('businessIncome', null);
</code>```

Body:
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

  <mat-form-field >

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>

Body:
I can think of at least two angular ways to do this:

Remove with *ngIf

export class EmployeeDetailsComponent {
  public showBusinessIncome = true;
  public showRealEstate = true;

  removeIncomeField(input: number) {
    if(input === 1) {
       this.showBusinessIncome = false;
    }
    else if (input === 2) {
       this.showRealEstate = false;
    }
  }
}

And in html

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true" *ngIf="showBusinessIncome"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField(1)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" *ngIf="showRealEstate" (deleteIncomeField)="deleteSelectedField(2)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>

Make the IncomeFieldComponent custom control and handle with reactive forms

This is a bit more complicated to get into, but I would propose to followi this material guide

Then you will be able to remove the control properly from the FormGroup

Angular form group guide

const myForm = new FormGroup({
  businessIncome: new FormControl('businessIncome'),
  realEaste: new FormControl('realEstate')
});

this.myForm.removeControl('businessIncome', null);


问:
Vscode git shortcut "ctrl+enter to commit on master" not working on Linux mint
enter image description here

None of the given shortcuts for GitHub is not working. I am unable to use the git feature in the Source Control section using Mouse or Keyboard. I am using Linux Mint 19.3 Tricia.

答:
Problem has been solved by merging this code

```<code>"git.suggestSmartCommit": true,
</code>```

in settings.json file

Body:
Problem has been solved by merging this code

"git.suggestSmartCommit": true,

in settings.json file


问:
Calling a function by adding an onclick event through innerHTML inside react class
How to call a function by add an onclick event in react class through innerHTML

```<code>document.getElementById('activeEmployeesTableContent').innerHTML = `
                                    <tr>
                                      <td>${res.data.empId}</td>
                                      <td><button onclick = ${this.fun}>CLICK</button></td>
                                    </tr>
                                  `;
</code>```

The above code is not working but i must use innerHTML to add the code dynamically into the table body

```<code>  componentDidMount(){
     axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {
          document.getElementById('activeEmployeesTableContent').innerHTML = `
                                  <tr>
                                    <td>${res.data.empId}</td>
                                    <td><button onclick = ${this.fun(res.data.empid)}>CLICK</button></td>
                                  </tr>`;
      }).catch( err => {
        console.log(err);
      });
  }
</code>```

答:
This seems tangential to React, however, you would typically add the onclick function separately from defining the innerHTML. I would recommend leaning into the DOM api if this is the route you're trying to go down.

```<code>const t = document.getElementById('table');
const row = document.createElement('tr');
const id = document.createElement('td');

// Set up the first element in the table
id.innerHTML = ele.empId;
row.appendChild(id);

// Set up the button
const btn = document.createElement('button');
btn.innerHTML = 'CLICK';
btn.addEventListener('click', func);
row.appendChild(btn);

// Add the row to the table.
table.appendChild(row);
</code>```

This approach is overly imperative and generally lacking a framework so I wouldn't recommend doing something like this. Frameworks like React exist to help manage the complexity. React handles interactions with the DOM for you so you can focus on the business logic of your application.

Body:
How to call a function by add an onclick event in react class through innerHTML

document.getElementById('activeEmployeesTableContent').innerHTML = `

                                      ${res.data.empId}
                                      <button onclick = ${this.fun}>CLICK</button>

                                  `;

The above code is not working but i must use innerHTML to add the code dynamically into the table body

  componentDidMount(){
     axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {
          document.getElementById('activeEmployeesTableContent').innerHTML = `

                                    ${res.data.empId}
                                    <button onclick = ${this.fun(res.data.empid)}>CLICK</button>

`;
      }).catch( err => {
        console.log(err);
      });
  }

Body:
This seems tangential to React, however, you would typically add the onclick function separately from defining the innerHTML. I would recommend leaning into the DOM api if this is the route you're trying to go down.

const t = document.getElementById('table');
const row = document.createElement('tr');
const id = document.createElement('td');

// Set up the first element in the table
id.innerHTML = ele.empId;
row.appendChild(id);

// Set up the button
const btn = document.createElement('button');
btn.innerHTML = 'CLICK';
btn.addEventListener('click', func);
row.appendChild(btn);

// Add the row to the table.
table.appendChild(row);

This approach is overly imperative and generally lacking a framework so I wouldn't recommend doing something like this. Frameworks like React exist to help manage the complexity. React handles interactions with the DOM for you so you can focus on the business logic of your application.


问:
Reading JSON Content
I'm using jsoup to scrape some HTML data and it's working out great.  Now I need to pull some JSON content (only JSON, not HTML).  Can I do this easily with jsoup or do I have to do it using another method?  The parsing that jsoup performs is encoding the JSON data so it's not parsing properly with Gson.</p>

答:
An old question but struggled a bit to figure this out. Jsoup can fetch the JSON data if you set ignoreContentType to true. However, it still wraps the JSON content in HTML tags like this.

```<code><html>
 <head></head>
 <body>
{ JSON DATA }
 </body>
</html>
</code>```

In order to remove this, we can simply get the body content as given below.

```<code>Connection connection = Jsoup.connect("URL").ignoreContentType(true);
connection.execute();

String strJsonData = connection.get().body().text();
</code>```

Title: Reading JSON Content

Body:
An old question but struggled a bit to figure this out. Jsoup can fetch the JSON data if you set ignoreContentType to true. However, it still wraps the JSON content in HTML tags like this.

<html>
 <head></head>
 <body>
{ JSON DATA }
 </body>
</html>

In order to remove this, we can simply get the body content as given below.

Connection connection = Jsoup.connect("URL").ignoreContentType(true);
connection.execute();

String strJsonData = connection.get().body().text();


问:
What am I doing wrong when trying to set a cookie using Express
I'm currently trying to send a cookie back to my react app after logging in,
In my server I have a test response:

```<code>res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();
</code>```

and in the app I have

```<code>Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})
</code>```

The response is recieved by call,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url":"http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

But no cookie ends up being set, could somebody tell me what the issue here is?
Thanks-

I also have

```<code>app.use(cookieParser());
</code>```

as the first app use, as that was recommended, but this did not help

答:
The react app is not able to set cookie because the backend application is running on different port so it's cross domain cookie issue.

You have to set the below header in backend and in the Axios request set the withCredentials: true.

credentials:
The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided. Starting with Chrome 50.

In Axios

withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials Default: withCredentials: false.

```<code>1. "Access-Control-Allow-Origin: http://localhost:3000";
2. "Access-Control-Allow-Credentials: true";
3. "Access-Control-Allow-Methods: GET, POST";
4. "Access-Control-Allow-Headers: Content-Type, *";
</code>```

Example:

```<code>res
  .set("Access-Control-Allow-Origin", "http://localhost:3000")
  .set("Access-Control-Allow-Credentials", "true")
  .set("Access-Control-Allow-Methods", "GET, POST")
  .set("Access-Control-Allow-Headers", "Content-Type, *")
  .status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000 * 60 * 60 }).end();
</code>```

Body:
I'm currently trying to send a cookie back to my react app after logging in,
In my server I have a test response:

res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();

and in the app I have

Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})

The response is recieved by call,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url":"http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

But no cookie ends up being set, could somebody tell me what the issue here is?
Thanks-

I also have

app.use(cookieParser());

as the first app use, as that was recommended, but this did not help

Body:
The react app is not able to set cookie because the backend application is running on different port so it's cross domain cookie issue.

You have to set the below header in backend and in the Axios request set the withCredentials: true.

credentials:
The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided. Starting with Chrome 50.

In Axios

withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials Default: withCredentials: false.

1. "Access-Control-Allow-Origin: http://localhost:3000";
2. "Access-Control-Allow-Credentials: true";
3. "Access-Control-Allow-Methods: GET, POST";
4. "Access-Control-Allow-Headers: Content-Type, *";

Example:

res
  .set("Access-Control-Allow-Origin", "http://localhost:3000")
  .set("Access-Control-Allow-Credentials", "true")
  .set("Access-Control-Allow-Methods", "GET, POST")
  .set("Access-Control-Allow-Headers", "Content-Type, *")
  .status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000 * 60 * 60 }).end();


问:
How can i set "Serialize Default Values" to Yes in when deserializing?
I have the following , but the json string has some empty array that are no returned as empty. How can i set that options value to return regardless ?</p>

```<code>vat det =   JsonConvert.DeserializeObject<RootObject>(json, "does option setting go here")
</code>```

答:
There is something called a JsonSerializerSettings class where these kind of settings can be set. These settings can then be passed to with the DeserializeObject all after the json string. The setting you are looking for is called DefaultValueHandling this will be a enumerator in the settings with multiple settings. To see what is posible with these settings see their documentatie.

Your code will be looking something like this:

```<code>        var result = JsonConvert.DeserializeObject<RootObject>("json string", new JsonSerializerSettings
        {
            DefaultValueHandling = DefaultValueHandling.Ignore
        });
</code>```

Body:
I have the following , but the json string has some empty array that are no returned as empty. How can i set that options value to return regardless ?

vat det =   JsonConvert.DeserializeObject<RootObject>(json, "does option setting go here")

Body:
There is something called a JsonSerializerSettings class where these kind of settings can be set. These settings can then be passed to with the DeserializeObject all after the json string. The setting you are looking for is called DefaultValueHandling this will be a enumerator in the settings with multiple settings. To see what is posible with these settings see their documentatie.

Your code will be looking something like this:

        var result = JsonConvert.DeserializeObject<RootObject>("json string", new JsonSerializerSettings
        {
            DefaultValueHandling = DefaultValueHandling.Ignore
        });


问:
UWP ScrollViewer.TopHeader with SkiaSharp does not drawing
The I want to use the SkiaSharp Canvas in ScrollViewer, but not only in Main content, but in TopHeader and LeftHeader as well.  The paint events are called, the skia is drawing, but the result does not displayed on the screen, just in a main content.

here is the example:

```<code><ScrollViewer
    HorizontalScrollBarVisibility="Visible"
    HorizontalScrollMode="Enabled"
    VerticalScrollBarVisibility="Visible"
    VerticalScrollMode="Enabled">
    <ScrollViewer.TopHeader>
        <Grid
            Width="{Binding ElementName=Canvas, Path=ActualWidth}"
            Height="30"
            Background="LightGray">
            <TextBlock Text="Hello" />
            <skia:SKXamlCanvas
                x:Name="TopHeaderCanvas"
                Margin="0"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch"
                PaintSurface="OnPaintTopHeader" />
        </Grid>
    </ScrollViewer.TopHeader>
    <ScrollViewer.LeftHeader>
        <skia:SKXamlCanvas
            Width="60"
            Height="{Binding ElementName=Canvas, Path=ActualHeight}"
            Background="Gray"
            PaintSurface="OnPaintLeftHeader" />
    </ScrollViewer.LeftHeader>
    <ScrollViewer.Content>
        <skia:SKXamlCanvas
            x:Name="Canvas"
            Width="4000"
            Height="3500"
            Margin="0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            PaintSurface="OnPaintMainContent" />
    </ScrollViewer.Content>
</ScrollViewer>
</code>```

As You can see, I tried the skia sharp canvas in wrapped in grid, directly under the ScrollViewer. Unfortunately it does not help.

Here is the result.

The left is totally empty, but is should be filled with HotPink, and the TopHeader just displays the Grid with "hello" , but it should be covered by canvas, and filled with Green color.

Anybody has an idea, why the skia is not working in ScrollView TopHeader and Left Header?

The SkiaSharp nuget which contains the canvas:
https://www.nuget.org/packages/SkiaSharp.Views/1.68.2-preview.21

And here are some SkiaSharp example:
https://github.com/mono/SkiaSharp/tree/master/samples/Basic/UWP/SkiaSharpSample

答:
It was a bug In SkiaSharp.
It is fixed: https://github.com/mono/SkiaSharp/pull/1133

Thank you: mattleibow

Body:
The I want to use the SkiaSharp Canvas in ScrollViewer, but not only in Main content, but in TopHeader and LeftHeader as well.  The paint events are called, the skia is drawing, but the result does not displayed on the screen, just in a main content.

here is the example:

<ScrollViewer
    HorizontalScrollBarVisibility="Visible"
    HorizontalScrollMode="Enabled"
    VerticalScrollBarVisibility="Visible"
    VerticalScrollMode="Enabled">
    <ScrollViewer.TopHeader>
        <Grid
            Width="{Binding ElementName=Canvas, Path=ActualWidth}"
            Height="30"
            Background="LightGray">
            <TextBlock Text="Hello" />
            <skia:SKXamlCanvas
                x:Name="TopHeaderCanvas"
                Margin="0"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch"
                PaintSurface="OnPaintTopHeader" />
        </Grid>
    </ScrollViewer.TopHeader>
    <ScrollViewer.LeftHeader>
        <skia:SKXamlCanvas
            Width="60"
            Height="{Binding ElementName=Canvas, Path=ActualHeight}"
            Background="Gray"
            PaintSurface="OnPaintLeftHeader" />
    </ScrollViewer.LeftHeader>
    <ScrollViewer.Content>
        <skia:SKXamlCanvas
            x:Name="Canvas"
            Width="4000"
            Height="3500"
            Margin="0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            PaintSurface="OnPaintMainContent" />
    </ScrollViewer.Content>
</ScrollViewer>

As You can see, I tried the skia sharp canvas in wrapped in grid, directly under the ScrollViewer. Unfortunately it does not help.

Here is the result.

The left is totally empty, but is should be filled with HotPink, and the TopHeader just displays the Grid with "hello" , but it should be covered by canvas, and filled with Green color.

Anybody has an idea, why the skia is not working in ScrollView TopHeader and Left Header?

The SkiaSharp nuget which contains the canvas:
https://www.nuget.org/packages/SkiaSharp.Views/1.68.2-preview.21

And here are some SkiaSharp example:
https://github.com/mono/SkiaSharp/tree/master/samples/Basic/UWP/SkiaSharpSample


问:
Are the await / async keywords needed under Task.Run?
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

```<code>t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

vs

```<code>var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

答:
Your code is the same as

```<code>t1 = DoSomethingExpensiveAsync();
t2 = DoSomethingExpensiveAsync();
await Task.WhenAll( t1, t2 );
</code>```

because Task.Run( Func< function ) will return a proxy of the task generated by function. There is no other Task created, and so you are awaiting the original tasks.

When you already have an async method then there is no need to use Task.Run at all.

Body:
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

vs

var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

Body:
Your code is the same as

t1 = DoSomethingExpensiveAsync();
t2 = DoSomethingExpensiveAsync();
await Task.WhenAll( t1, t2 );

because Task.Run( Func< function ) will return a proxy of the task generated by function. There is no other Task created, and so you are awaiting the original tasks.

When you already have an async method then there is no need to use Task.Run at all.


问:
How do you handle checks to see if a user changed something in a dialog
Talking .NET WinForms here:

If you have an application where someone can change items using some properties dialog for example, how do you determine if a user has changed something when he clicks on cancel (to decide whether to display a cancel confirmation message box, or not).

I can think of 2 methods:

Defining a dirty bit and handling all "changed" events to set this bit to true.

Clone the original object and write some comparison code to determine if the modified object really was modified compared with the original

Is there any more elegant and/or more generic way to do that?

答: My DAL does what you mention in 2. so I can blindly assign all values back to my DAO that it will take care of submitting only the values that were actually changed.</p>

OwnerDisplayName: Stefan Koell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes


问:
How to use BOOST_FOREACH with a boost::ptr_map?
How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map?

Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an iterator:

```<code>typedef boost::ptr_container_detail::ref_pair<int, int* const> IntPair;
BOOST_FOREACH(IntPair p, mymap) {
    int i = p.first;
}

// vs.

boost::ptr_map<int, T>::iterator it;
for (it = mymap.begin(); it != mymap.end(); ++it) {
    // doSomething()
}
</code>```

The following code is somewhere along the lines what I wish for. It follows the standard way on how to use BOOST_FOREACH with a std::map.  Unfortunately this does not compile:

```<code>boost::ptr_map<int, T> mymap;
// insert something into mymap
// ...

typedef pair<int, T> IntTpair;
BOOST_FOREACH (IntTpair &p, mymap) {
    int i = p.first;
}
</code>```

答:
I use this homebrew template which adds an iteration type which can be handled by BOOST_FOREACH

```<code>namspace homebrew
{
  template
  <
    class Key,
    class T,
    class Compare        = std::less<Key>,
    class CloneAllocator = boost::heap_clone_allocator,
    class Allocator      = std::allocator< std::pair<const Key,void*> >
  >
  class ptr_map :
    public boost::ptr_map<Key,T,Compare,CloneAllocator,Allocator>
  {
  public:
    typedef boost::ptr_container_detail::ref_pair<Key,const T* const> const_ref;
    typedef boost::ptr_container_detail::ref_pair<Key,T* const> ref;
  };
}
</code>```

Let's assume that foo and bar are two of your favorite types ;)

```<code>typedef homebrew::ptr_map<foo,bar> Map;
int f( const Map& m )
{
  BOOST_FOREACH(Map::const_ref v, m)
  {
    v.first;  // foo
    v.second; // const bar* const
  }
}
</code>```

or

```<code>int f( Map& m )
{
  BOOST_FOREACH(Map::ref v, m)
  {
    v.first;  // foo
    v.second; // bar* const
  }
}
</code>```

Which one you have to use doesn't seem to depend on the way you use it in the loop (const or non-const) but on the map's constness!! So the following will end up in an error...

```<code>int f( Map& m )
{
  BOOST_FOREACH(Map::const_ref v, m)  // can't use const_ref because m isn't const
  {
    ...
  }
}
</code>```

Weird! isn't it?

The greatest thing to me is that of all this solutions which were suggested here, this is the first one which is handled correctly by the Eclipse CDT syntax coloring (when using the 'Code/Problem' syntax coloring attribute).

Body:
How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map?

Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an iterator:

typedef boost::ptr_container_detail::ref_pair<int, int* const> IntPair;
BOOST_FOREACH(IntPair p, mymap) {
    int i = p.first;
}

// vs.

boost::ptr_map<int, T>::iterator it;
for (it = mymap.begin(); it != mymap.end(); ++it) {
    // doSomething()
}

The following code is somewhere along the lines what I wish for. It follows the standard way on how to use BOOST_FOREACH with a std::map.  Unfortunately this does not compile:

boost::ptr_map<int, T> mymap;
// insert something into mymap
// ...

typedef pair<int, T> IntTpair;
BOOST_FOREACH (IntTpair &p, mymap) {
    int i = p.first;
}

LastEditorDisplayName: Martin

Body:
I use this homebrew template which adds an iteration type which can be handled by BOOST_FOREACH

namspace homebrew
{
  template
  <
    class Key,
    class T,
    class Compare        = std::less<Key>,
    class CloneAllocator = boost::heap_clone_allocator,
    class Allocator      = std::allocator< std::pair<const Key,void*> >
  >
  class ptr_map :
    public boost::ptr_map<Key,T,Compare,CloneAllocator,Allocator>
  {
  public:
    typedef boost::ptr_container_detail::ref_pair<Key,const T* const> const_ref;
    typedef boost::ptr_container_detail::ref_pair<Key,T* const> ref;
  };
}

Let's assume that foo and bar are two of your favorite types ;)

typedef homebrew::ptr_map<foo,bar> Map;
int f( const Map& m )
{
  BOOST_FOREACH(Map::const_ref v, m)
  {
    v.first;  // foo
    v.second; // const bar* const
  }
}

or

int f( Map& m )
{
  BOOST_FOREACH(Map::ref v, m)
  {
    v.first;  // foo
    v.second; // bar* const
  }
}

Which one you have to use doesn't seem to depend on the way you use it in the loop (const or non-const) but on the map's constness!! So the following will end up in an error...

int f( Map& m )
{
  BOOST_FOREACH(Map::const_ref v, m)  // can't use const_ref because m isn't const
  {
    ...
  }
}

Weird! isn't it?

The greatest thing to me is that of all this solutions which were suggested here, this is the first one which is handled correctly by the Eclipse CDT syntax coloring (when using the 'Code/Problem' syntax coloring attribute).


问:
Monitoring short lived python Batch Job Processes using Prometheus
How can I monitor my python processes (say some script that gets triggered periodically by Cron daemon) using Prometheus?

Note that this is not a web application but a short-lived process that gets launched periodically by the Cron daemon. This script comes up, does its job, and terminates. The same python script gets launched multiple times a day (approximately 100k times) by cron daemon. I want to capture multiple stats from various runs of this script (for example, the time it takes to run a particular function, how much CPU and memory it consumes, etc.)

答:
you can use pushgateway and prometheus_client:

```<code>from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='job_a', registry=registry)
</code>```

Body:
you can use pushgateway and prometheus_client:

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='job_a', registry=registry)


问:
powershell: remove characters in string
I have a list of files in this format NameSerie.S0E1.randomcharacters.mkv where i want to remove the randomcharacters to get NameSerie.S0E1.mkv

I have the following but for this i need to know the randomcharacters which sadly are random.

```<code>#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace("[480p]","") }
</code>```

Does someone have an idea?

答:
Try this:</p>

```<code>#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Split(".")[0..1] -join ".$($_.Name.Split(".")[3])" }
</code>```

Title: powershell: remove characters in string

Body:
I have a list of files in this format NameSerie.S0E1.randomcharacters.mkv where i want to remove the randomcharacters to get NameSerie.S0E1.mkv

I have the following but for this i need to know the randomcharacters which sadly are random.

#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace("[480p]","") }

Does someone have an idea?

Body:
Try this:

#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Split(".")[0..1] -join ".$($_.Name.Split(".")[3])" }


问:
How to redirect page depends on condition in angular 8
I am trying to redirect the page from login page.I have one flag that is for checking the cart is empty or not. I can set that flag true or false. I want to redirect the pages after logged depends on the flag and logged or not.I have tried but not working.Please help anyone to find the solution.

login.commponent.ts:

```<code>onSubmit() {
    this.submitted = true;
    if (this.loginForm.invalid) {
        return;
    }
    this.loading = true;
    this.authenticationService.login(this.f.username.value, this.f.password.value)
        .pipe(first())
        .subscribe(
            data => {
              //if cart is not empty
              // if(this.flag==true){
              //   this.router.navigate(['./billing']);
              // }
               //if cart is empty
              //else{
              //   this.router.navigate(['./cartempty']);
              // }
              //this.router.navigate([this.returnUrl]);

            },
            error => {
                this.alertService.error(error);
                this.loading = false;
            });
}
</code>```

order.component.ts:

```<code>goTOloginbilling(){

                  //if Not logged
                  // if(????){
                  //   this.router.navigate(['./login']);
                  // }
                  //if cart is not empty
                  // else if(this.flag==true){
                  //   this.router.navigate(['./billing']);
                  // }
                   //if cart is empty
                  //else if(this.flag==false){
                  //   this.router.navigate(['./cartempty']);
                  // }

  }
</code>```

Demo: https://stackblitz.com/edit/angular-8-registration-login-example-gnjckr?file=app/order/order.component.ts

答:
Looking your code I saw some problems.

In login.component.ts  the variable flag is declared like this:

```<code>flag: true
</code>```

I suppose you wanted write flag: boolean= true;

In the same file, in onSumbit function when you call the login function, after you
have the response you had wrote:

```<code>this.router.navigate(['./billing']);
</code>```

But In app.routing.module.ts the route is:

```<code>{ path: '', component: BillingComponent, canActivate: [AuthGuard] },
</code>```

So you had to write:

```<code>this.router.navigate(['']);
</code>```

So in conclusion:

```<code>onSubmit() {
    this.submitted = true;
    if (this.loginForm.invalid) {
      return;
    }
    this.loading = true;
    this.authenticationService
      .login(this.f.username.value, this.f.password.value)
      .subscribe(
        data => {
          //if cart is not empty
          if (this.flag == true) this.router.navigate([""]);
          else {
            this.router.navigate(["cartempty"]);
          }
        },
        error => {
          this.alertService.error(error);
          this.loading = false;
        }
      );
  }
</code>```

Obviously you can define a route for cartEmpty in app.routing.ts:

```<code>{ path: 'cartempty', component: CartemptyComponent },
</code>```

Body:
I am trying to redirect the page from login page.I have one flag that is for checking the cart is empty or not. I can set that flag true or false. I want to redirect the pages after logged depends on the flag and logged or not.I have tried but not working.Please help anyone to find the solution.

login.commponent.ts:

onSubmit() {
    this.submitted = true;
    if (this.loginForm.invalid) {
        return;
    }
    this.loading = true;
    this.authenticationService.login(this.f.username.value, this.f.password.value)
        .pipe(first())
        .subscribe(
            data => {
              //if cart is not empty
              // if(this.flag==true){
              //   this.router.navigate(['./billing']);
              // }
               //if cart is empty
              //else{
              //   this.router.navigate(['./cartempty']);
              // }
              //this.router.navigate([this.returnUrl]);

            },
            error => {
                this.alertService.error(error);
                this.loading = false;
            });
}

order.component.ts:

goTOloginbilling(){

                  //if Not logged
                  // if(????){
                  //   this.router.navigate(['./login']);
                  // }
                  //if cart is not empty
                  // else if(this.flag==true){
                  //   this.router.navigate(['./billing']);
                  // }
                   //if cart is empty
                  //else if(this.flag==false){
                  //   this.router.navigate(['./cartempty']);
                  // }

  }

Demo: https://stackblitz.com/edit/angular-8-registration-login-example-gnjckr?file=app/order/order.component.ts

Body:
Looking your code I saw some problems.

In login.component.ts  the variable flag is declared like this:

flag: true

I suppose you wanted write flag: boolean= true;

In the same file, in onSumbit function when you call the login function, after you
have the response you had wrote:

this.router.navigate(['./billing']);

But In app.routing.module.ts the route is:

{ path: '', component: BillingComponent, canActivate: [AuthGuard] },

So you had to write:

this.router.navigate(['']);

So in conclusion:

onSubmit() {
    this.submitted = true;
    if (this.loginForm.invalid) {
      return;
    }
    this.loading = true;
    this.authenticationService
      .login(this.f.username.value, this.f.password.value)
      .subscribe(
        data => {
          //if cart is not empty
          if (this.flag == true) this.router.navigate([""]);
          else {
            this.router.navigate(["cartempty"]);
          }
        },
        error => {
          this.alertService.error(error);
          this.loading = false;
        }
      );
  }

Obviously you can define a route for cartEmpty in app.routing.ts:

{ path: 'cartempty', component: CartemptyComponent },


问:
How to include an iframe(without scroll) within masterpage (with scroll)
enter image description hereI've tried

```<code>scrolling="no" height=100%, overflow:hidden
</code>```

it's not worked out.When i'm trying to add height in pixel like

```<code>style="height:4000px;"
</code>```

iframe's background-image pixel get damaged.Looking for a solution without setting height. Please help me to solve this.

current Code
HTML  code

```<code><div class="header_bar">
<div class="tab_active"   onclick="location.href='...'">Tab1</div>
<div class="tab_inactive" onclick="location.href='...'">Tab2</div>
<div class="tab_inactive" onclick="location.href='...'">Tab3</div>
</div>
<div class="iframe_container">
<iframe id="main_iframe" class="main_iframe" frameborder="0" src="http://en.wikipedia.org/wiki/Special:Random">
</iframe>
</div>
<div class="header_bar">
<div class="tab_active"   onclick="location.href='...'">Tab1</div>
<div class="tab_inactive" onclick="location.href='...'">Tab2</div>
<div class="tab_inactive" onclick="location.href='...'">Tab3</div>
</div>
</code>```

CSS

```<code>html { height:100% }
body { height:100%; width:100%; margin:0; display:table;}
.header_bar {display:table-row; }
.iframe_container {height:100%; display:table-cell; }
iframe { height:100%; width:100%; display:block; }
</code>```

I don't want the iframes scroll.

答:
Add scrolling="no" to ifram tag like this :

```<code><iframe id="main_iframe" class="main_iframe" scrolling="no" frameborder="0" src="http://en.wikipedia.org/wiki/Special:Random"></ifram>
</code>```

Body:
enter image description hereI've tried

scrolling="no" height=100%, overflow:hidden

it's not worked out.When i'm trying to add height in pixel like

style="height:4000px;"

iframe's background-image pixel get damaged.Looking for a solution without setting height. Please help me to solve this.

current Code
HTML  code

Tab1

Tab2

Tab3

Tab1

Tab2

Tab3

CSS

html { height:100% }
body { height:100%; width:100%; margin:0; display:table;}
.header_bar {display:table-row; }
.iframe_container {height:100%; display:table-cell; }
iframe { height:100%; width:100%; display:block; }

I don't want the iframes scroll.

Body:
Add scrolling="no" to ifram tag like this :

<iframe id="main_iframe" class="main_iframe" scrolling="no" frameborder="0" src="http://en.wikipedia.org/wiki/Special:Random"></ifram>


问:
NodeJS sending shuffled data as API response
I have written an API endpoint which sends back the username of n number of users as response after going through an array which contains n number of user id's. Here is the code that I am talking about,

```<code>//Fetch username of user
app.post('/users/uname', (req, res) => {
    const uidArr = req.body.uid
    const len = uidArr.length
    var unameArr = []
    for(var i=0;i<len;i++){
        User.findById(uidArr[i]).then((user) => {
            if(!user){
                unameArr[i] = ""
            }

            unameArr.push(user.username)
            if(unameArr.length==len){
                res.send(unameArr)
            }
        }).catch((error) => {
            unameArr[i] = ""
        })
    }
})
</code>```

I have two users in the MongoDB database with usernames 'user_one' and 'user_two'. When I send an API request to this endpoint using Postman the response which I get is shuffled. Here is an example,

I pass the following array,

```<code>{
    "uid": [ "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46", "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46" ]
}
</code>```

and the request I expect is the following based on the position of elements on the array send as request,

```<code>[
    "user_one",
    "user_one",
    "user_two",
    "user_one",
    "user_one",
    "user_two"
]
</code>```

But the actual output that I get is mixed as shown in the screenshots from Postman,

API Call one  |  API Call two  |  API Call three

What is the reason behind this issue and how can I fix this issue?

答:
```<code>const uidArr = req.body.uid
let uids = []
User.find({},{'username':1,"_id":0})
.where('_id')
.in(uidArr)
.then(docs=>{
    docs.forEach(doc=>uids.push(doc.username))
    console.log(uids) //send this back to client
})
</code>```

Body:
I have written an API endpoint which sends back the username of n number of users as response after going through an array which contains n number of user id's. Here is the code that I am talking about,

//Fetch username of user
app.post('/users/uname', (req, res) => {
    const uidArr = req.body.uid
    const len = uidArr.length
    var unameArr = []
    for(var i=0;i<len;i++){
        User.findById(uidArr[i]).then((user) => {
            if(!user){
                unameArr[i] = ""
            }

            unameArr.push(user.username)
            if(unameArr.length==len){
                res.send(unameArr)
            }
        }).catch((error) => {
            unameArr[i] = ""
        })
    }
})

I have two users in the MongoDB database with usernames 'user_one' and 'user_two'. When I send an API request to this endpoint using Postman the response which I get is shuffled. Here is an example,

I pass the following array,

{
    "uid": [ "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46", "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46" ]
}

and the request I expect is the following based on the position of elements on the array send as request,

[
    "user_one",
    "user_one",
    "user_two",
    "user_one",
    "user_one",
    "user_two"
]

But the actual output that I get is mixed as shown in the screenshots from Postman,

API Call one  |  API Call two  |  API Call three

What is the reason behind this issue and how can I fix this issue?


问:
cannot find symbol error in condition of while loop
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.

Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.

```<code>    // Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;

class AlgebraTutor {
// Solve for Y method.
    public static void solve_for_y() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_m = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_b = number_gen.nextInt(101) - 100;

// Print problem out for student to see
        System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);

        System.out.println(" m =" + var_m);
        System.out.println(" x =" + var_x);
        System.out.println(" b =" + var_b);

// This formula will calculate the value of y.
         float var_y = (var_m * var_x) + var_b;

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for y:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_y){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_y);

                 }
                                            }
// -------------------------------------------------------------------------

// Solve for M method.
     public static void solve_for_m() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_y = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_b = number_gen.nextInt(101) - 100;

// Print problem out for student to see.
        System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);

        System.out.println(" y =" + var_y);
        System.out.println(" x =" + var_x);
        System.out.println(" b =" + var_b);

// This formula will calculate the value of m.
        float var_m = (var_y - var_b) / var_x;

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for m:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_m){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_m);

                 }
                                            }

// -------------------------------------------------------------------------

// Solve for B method

     public static void solve_for_b() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_y = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_m = number_gen.nextInt(101) - 100;

// Print problem out for student to see.
        System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");

        System.out.println(" y =" + var_y);
        System.out.println(" x =" + var_x);
        System.out.println(" m =" + var_m);

// This formula will calculate the value of m.
        float var_b = var_y / (var_m * var_x);

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for b:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_b){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_b);
                                   }
                                            }

// -------------------------------------------------------------------------
    public static void main(String[] args) {

        do{
        System.out.println("Which type of problem would you like to practice?");
        System.out.println("1) Solve for y");
        System.out.println("2) Solve for m");
        System.out.println("3) Solve for b");
        System.out.println("4) To quit");

        Scanner selection_input = new Scanner(System.in);
        String user_selection = selection_input.nextLine();

        if ( user_selection.equals("1")){
            solve_for_y();
        } else if (user_selection.equals("2")){
            solve_for_m();
        } else if (user_selection.equals("3")){
            solve_for_b();
        } else if (user_selection.equals("4")){
            System.out.println("Quitting Program");
            System. exit(0);
        } else{
               System.out.println("Please choose from the given options");
        }

        } while(user_selection.equals("1") &&
                user_selection.equals("2") &&
                user_selection.equals("3") &&
                user_selection.equals("4"));

    }

                   }
</code>```

答:
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.

```<code>    public static void main(String[] args)
    {

        Scanner selection_input = new Scanner(System.in);
        String user_selection=null;
        do
        {
            System.out.println("Which type of problem would you like to practice?");
            System.out.println("1) Solve for y");
            System.out.println("2) Solve for m");
            System.out.println("3) Solve for b");
            System.out.println("4) To quit");

            user_selection = selection_input.nextLine();

            if (user_selection.equals("1"))
            {
                solve_for_y();
            }
            else if (user_selection.equals("2"))
            {
                solve_for_m();
            }
            else if (user_selection.equals("3"))
            {
                solve_for_b();
            }
            else if (user_selection.equals("4"))
            {
                System.out.println("Quitting Program");
                System.exit(0);
            }
            else
            {
                System.out.println("Please choose from the given options");
            }

        }
        while (!user_selection.equals("4"));
    }
</code>```

For the case "4" you have two exists now:

```<code>            else if (user_selection.equals("4"))
            {
                System.out.println("Quitting Program");
                System.exit(0);
            }
</code>```

and:

```<code>        while (!user_selection.equals("4"));
</code>```

Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).

Body:
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.

Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.

    // Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;

class AlgebraTutor {
// Solve for Y method.
    public static void solve_for_y() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_m = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_b = number_gen.nextInt(101) - 100;

// Print problem out for student to see
        System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);

        System.out.println(" m =" + var_m);
        System.out.println(" x =" + var_x);
        System.out.println(" b =" + var_b);

// This formula will calculate the value of y.
         float var_y = (var_m * var_x) + var_b;

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for y:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_y){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_y);

                 }
                                            }
// -------------------------------------------------------------------------

// Solve for M method.
     public static void solve_for_m() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_y = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_b = number_gen.nextInt(101) - 100;

// Print problem out for student to see.
        System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);

        System.out.println(" y =" + var_y);
        System.out.println(" x =" + var_x);
        System.out.println(" b =" + var_b);

// This formula will calculate the value of m.
        float var_m = (var_y - var_b) / var_x;

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for m:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_m){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_m);

                 }
                                            }

// -------------------------------------------------------------------------

// Solve for B method

     public static void solve_for_b() {
// Creation of a random number generator.
        Random number_gen = new Random();

// Generates random integers from -100 to 100.
        int var_y = number_gen.nextInt(101) - 100;
        int var_x = number_gen.nextInt(101) - 100;
        int var_m = number_gen.nextInt(101) - 100;

// Print problem out for student to see.
        System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");

        System.out.println(" y =" + var_y);
        System.out.println(" x =" + var_x);
        System.out.println(" m =" + var_m);

// This formula will calculate the value of m.
        float var_b = var_y / (var_m * var_x);

// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.

     Scanner user_input = new Scanner(System.in);
     System.out.println("Please solve for b:");
     String user_answer = user_input.nextLine();

        int answer = Integer.parseInt(user_answer);

         if (answer == var_b){
             System.out.println("correct");

         }else{
                  System.out.println("incorrect, The answer is:" + var_b);
                                   }
                                            }

// -------------------------------------------------------------------------
    public static void main(String[] args) {

        do{
        System.out.println("Which type of problem would you like to practice?");
        System.out.println("1) Solve for y");
        System.out.println("2) Solve for m");
        System.out.println("3) Solve for b");
        System.out.println("4) To quit");

        Scanner selection_input = new Scanner(System.in);
        String user_selection = selection_input.nextLine();

        if ( user_selection.equals("1")){
            solve_for_y();
        } else if (user_selection.equals("2")){
            solve_for_m();
        } else if (user_selection.equals("3")){
            solve_for_b();
        } else if (user_selection.equals("4")){
            System.out.println("Quitting Program");
            System. exit(0);
        } else{
               System.out.println("Please choose from the given options");
        }

        } while(user_selection.equals("1") &&
                user_selection.equals("2") &&
                user_selection.equals("3") &&
                user_selection.equals("4"));

    }

                   }

Body:
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.

    public static void main(String[] args)
    {

        Scanner selection_input = new Scanner(System.in);
        String user_selection=null;
        do
        {
            System.out.println("Which type of problem would you like to practice?");
            System.out.println("1) Solve for y");
            System.out.println("2) Solve for m");
            System.out.println("3) Solve for b");
            System.out.println("4) To quit");

            user_selection = selection_input.nextLine();

            if (user_selection.equals("1"))
            {
                solve_for_y();
            }
            else if (user_selection.equals("2"))
            {
                solve_for_m();
            }
            else if (user_selection.equals("3"))
            {
                solve_for_b();
            }
            else if (user_selection.equals("4"))
            {
                System.out.println("Quitting Program");
                System.exit(0);
            }
            else
            {
                System.out.println("Please choose from the given options");
            }

        }
        while (!user_selection.equals("4"));
    }

For the case "4" you have two exists now:

            else if (user_selection.equals("4"))
            {
                System.out.println("Quitting Program");
                System.exit(0);
            }

and:

        while (!user_selection.equals("4"));

Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).


问:
Problem while connecting my app to firebase
My App name is AppBase
It is requesting for SHA-1 Hash key. I saw that people are opening gradle>"application name">android on the right side of the android studio for this but my application is not showing. What I have done wrong??

答:
```<code>Gradle -> app -> android -> signingReport
</code>```


问:
How can I throw TypeError with message inside if statement in Python?

What I want to do

I would like to fix my current code to pass the coding challenge, Codewars Prefill an Array.

I hope to learn how to throw TypeError with message with if statement in this case.

Create the function prefill that returns an array of n elements thatall have the same value v. See if you can do this without using a loop.

You have to validate input: v can be anything (primitive orotherwise) if v is ommited, fill the array with undefined if n is 0, return an empty array if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where
  you replace n for the actual value passed to the function.

```<code>Code Examples
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
</code>```

Problem

I have passed 4 sample tests among 5 sample tests, but I cannot pass the below one.

```<code>    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
</code>```

Error Message

```<code>Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py",
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'
</code>```

Current code

def prefill(n,v):

    if int(n):
        result = [0] * int(n)
        for i in range(len(result)):
            result[i] = v
        return result

    else:
        return TypeError, str(n) + "is invalid"
```

Developing Environment

Python 3.4.3

答:
You can use a try-except to catch the error, and throw for example another one:

```<code>def prefill(n,v):
    <b>try:</b>
        n = int(n)
    <b>except ValueError:</b>
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n</code>```

For example:

```<code>>>> prefill(3,1)
[1, 1, 1]
>>> prefill(2,"abc")
['abc', 'abc']
>>> prefill("1", 1)
[1]
>>> prefill(3, prefill(2,'2d'))
[['2d', '2d'], ['2d', '2d'], ['2d', '2d']]
>>> prefill("xyz", 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in prefill
ValueError: invalid literal for int() with base 10: 'xyz'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in prefill
TypeError: xyz is invalid
</code>```

You do not per se need to specify an exception to raise. In case you want to re-raise the exception, simply writing raise is sufficient. You can furthermore specify a tuple of exceptions to catch, and make v optional here, for example:

```<code>def prefill(n,v=None):
    <b>try:</b>
        n = int(n)
    <b>except (TypeError, ValueError):</b>
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n</code>```

Body:
What I want to do

I would like to fix my current code to pass the coding challenge, Codewars Prefill an Array.

I hope to learn how to throw TypeError with message with if statement in this case.

Create the function prefill that returns an array of n elements thatall have the same value v. See if you can do this without using a loop.

You have to validate input: v can be anything (primitive orotherwise) if v is ommited, fill the array with undefined if n is 0, return an empty array if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where
  you replace n for the actual value passed to the function.

Code Examples
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

Problem

I have passed 4 sample tests among 5 sample tests, but I cannot pass the below one.

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

Error Message

Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py",
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'

Current code

def prefill(n,v):

    if int(n):
        result = [0] * int(n)
        for i in range(len(result)):
            result[i] = v
        return result

    else:
        return TypeError, str(n) + "is invalid"

Developing Environment

Python 3.4.3

Body:
You can use a try-except to catch the error, and throw for example another one:

def prefill(n,v):
    try:
        n = int(n)
    except ValueError:
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n

For example:

>>> prefill(3,1)
[1, 1, 1]
>>> prefill(2,"abc")
['abc', 'abc']
>>> prefill("1", 1)
[1]
>>> prefill(3, prefill(2,'2d'))
[['2d', '2d'], ['2d', '2d'], ['2d', '2d']]
>>> prefill("xyz", 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in prefill
ValueError: invalid literal for int() with base 10: 'xyz'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in prefill
TypeError: xyz is invalid

You do not per se need to specify an exception to raise. In case you want to re-raise the exception, simply writing raise is sufficient. You can furthermore specify a tuple of exceptions to catch, and make v optional here, for example:

def prefill(n,v=None):
    try:
        n = int(n)
    except (TypeError, ValueError):
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n


问:
Run an apps script code containing an If Statement (How To Trigger Automatically ?) - Google Apps Script / Google Sheets
I have the code below which runs as intented - if you manually run the script.

Data appears in this sheet("TOP UP NEEDED") via MoveRow Script (No Human Editing)

```<code> function IfStatement() {
 var app = SpreadsheetApp;
 var activeSheet = app.getActive().getActiveSheet();
 var workingCell = activeSheet.getRange(2, 1).getValue();
 if (workingCell === "") return;  // Modified

 var sheet = SpreadsheetApp.getActive();
 sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
 sheet.getRange('D2').activate();

 sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
 JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');

 addCheckboxToI2();

 MoveDataToFORKLIFT();

var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('TOP UP NEEDED'), true);
spreadsheet.getRange('A2:G30').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
spreadsheet.getRange('A2').activate();

DELETESHEETS();

addCheckboxToG2FORKLIFT();
}
</code>```

Currently when the data arrives in "TOP UP NEEDED" - script does not run.

Expected Result = When A2:A has data it should run the script. When A2:A "" - nothing should happen.

Thank you in Advance

答:
From the documentation:

Script executions and API requests do not cause triggers to run. For example, calling Range.setValue() to edit a cell does not cause the spreadsheet's onEdit trigger to run.

If your function IfStatement() already works, simply call it at the end of your MoveRow script.

Body:
I have the code below which runs as intented - if you manually run the script.

Data appears in this sheet("TOP UP NEEDED") via MoveRow Script (No Human Editing)

 function IfStatement() {
 var app = SpreadsheetApp;
 var activeSheet = app.getActive().getActiveSheet();
 var workingCell = activeSheet.getRange(2, 1).getValue();
 if (workingCell === "") return;  // Modified

 var sheet = SpreadsheetApp.getActive();
 sheet.setActiveSheet(sheet.getSheetByName('TOP UP NEEDED'), true);
 sheet.getRange('D2').activate();

 sheet.getCurrentCell().setFormula('=QUERY({\'SKU & Qty\'!$A$3:$C},"SELECT * WHERE Col1 MATCHES \'" &
 JOIN("|",FILTER(A:A, NOT(ISBLANK(A:A)))) & "\' ")');

 addCheckboxToI2();

 MoveDataToFORKLIFT();

var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('TOP UP NEEDED'), true);
spreadsheet.getRange('A2:G30').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
spreadsheet.getRange('A2').activate();

DELETESHEETS();

addCheckboxToG2FORKLIFT();
}

Currently when the data arrives in "TOP UP NEEDED" - script does not run.

Expected Result = When A2:A has data it should run the script. When A2:A "" - nothing should happen.

Thank you in Advance