问:
Trying to divide main controller method to two separate methods
I'm trying to divide the main method in my controller, to have two separate methods - one for returning generated form, and one for uploading file in this form. But I cannot grasp it with my mind how to do it...

Here is my currently working controller:

```<code>class UploaderController extends AbstractController
{
    private ConfigVendors $configVendors;

    public function __construct(ConfigVendors $configVendors)
    {
        $this->configVendors = $configVendors;
    }

    /**
     * @Route("/", name="upload_terms")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function formRender(Request $request, TranslatorInterface $translator)
    {
        /** @var UploadedFile $uploadedFile */
        $formUploader = new FormUploader();
        $form = $this->createForm(FormUploaderType::class, $formUploader);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $catalog = $request->request->get('form_uploader')['service'];

            $fileNameGenerator = new FileNameGenerator($request);
            $originalFileName = $fileNameGenerator->getOriginalFilename();
            $tmpPath = $fileNameGenerator->getFilePath();

            $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));

            if (!$upload->gitlabUpload()) {
                $this->addFlash('danger', $translator->trans('uploadTermsError'));
            } else {
                $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
                $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
                $this->addFlash('info', $url.'<br><a href="'.$url.'" target="_blank">Podgląd</a> <br><br> Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
            }

            return $this->redirectToRoute('upload_terms');
        }

        return $this->render('uploader/upload.html.twig', [
            'createForm' => $form->createView(),
        ]);
    }
}
</code>```

And here is my attempt to divide it...

```<code>/**
 * @Route("/", name="upload_terms")
 */
public function getIndexAction()
{
    /** @var UploadedFile $uploadedFile */
    $formUploader = new FormUploader();
    $form = $this->createForm(FormUploaderType::class, $formUploader);

    return $this->render('uploader/upload.html.twig', [
        'createForm' => $form->createView(),
    ]);
}

/**
 * @Route("/", name="upload_terms")
 *
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function formUpload(Request $request, TranslatorInterface $translator)
{
    /** @var UploadedFile $uploadedFile */
    $formUploader = new FormUploader();
    $form = $this->createForm(FormUploaderType::class, $formUploader);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $catalog = $request->request->get('form_uploader')['service'];

        $fileNameGenerator = new FileNameGenerator($request);
        $originalFileName = $fileNameGenerator->getOriginalFilename();
        $tmpPath = $fileNameGenerator->getFilePath();

        $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));

        if (!$upload->gitlabUpload()) {
            $this->addFlash('danger', $translator->trans('uploadTermsError'));
        } else {
            $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
            $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
            $this->addFlash('info', $url.'<br><a href="'.$url.'" target="_blank">Podgląd</a> <br><br> Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
        }

        return $this->redirectToRoute('upload_terms');
    }

}
</code>```

答:
You can try this</p>

```<code>public function formUpload(Request $request, TranslatorInterface $translator)
    {
        /** @var UploadedFile $uploadedFile */
        $formUploader = new FormUploader();
        $form = $this->createForm(FormUploaderType::class, $formUploader);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $catalog = $request->request->get('form_uploader')['service'];
            $fileNameGenerator = new FileNameGenerator($request);
            $originalFileName = $fileNameGenerator->getOriginalFilename();
            $tmpPath = $fileNameGenerator->getFilePath();
            $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));
            $this->gitlabupload($upload, $translator, $catalog, $originalFileName);

            return $this->redirectToRoute('upload_terms');
        }

        return $this->render('uploader/upload.html.twig', [
            'createForm' => $form->createView(),
        ]);
    }

    private function gitlabupload($upload, $translator, $catalog, $originalFileName)
    {
        if (!$upload->gitlabUpload()) {
            $this->addFlash('danger', $translator->trans('uploadTermsError'));
        } else {
            $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
            $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
            $this->addFlash('info', $url.'<br><a href="'.$url.'" target="_blank">Podgląd</a> <br><br> Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
        }
    }
</code>```

Body:
I'm trying to divide the main method in my controller, to have two separate methods - one for returning generated form, and one for uploading file in this form. But I cannot grasp it with my mind how to do it...

Here is my currently working controller:

class UploaderController extends AbstractController
{
    private ConfigVendors $configVendors;

    public function __construct(ConfigVendors $configVendors)
    {
        $this->configVendors = $configVendors;
    }

    /**
     * @Route("/", name="upload_terms")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function formRender(Request $request, TranslatorInterface $translator)
    {
        /** @var UploadedFile $uploadedFile */
        $formUploader = new FormUploader();
        $form = $this->createForm(FormUploaderType::class, $formUploader);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $catalog = $request->request->get('form_uploader')['service'];

            $fileNameGenerator = new FileNameGenerator($request);
            $originalFileName = $fileNameGenerator->getOriginalFilename();
            $tmpPath = $fileNameGenerator->getFilePath();

            $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));

            if (!$upload->gitlabUpload()) {
                $this->addFlash('danger', $translator->trans('uploadTermsError'));
            } else {
                $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
                $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
                $this->addFlash('info', $url.'
Podgląd

 Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
            }

            return $this->redirectToRoute('upload_terms');
        }

        return $this->render('uploader/upload.html.twig', [
            'createForm' => $form->createView(),
        ]);
    }
}

And here is my attempt to divide it...

/**
 * @Route("/", name="upload_terms")
 */
public function getIndexAction()
{
    /** @var UploadedFile $uploadedFile */
    $formUploader = new FormUploader();
    $form = $this->createForm(FormUploaderType::class, $formUploader);

    return $this->render('uploader/upload.html.twig', [
        'createForm' => $form->createView(),
    ]);
}

/**
 * @Route("/", name="upload_terms")
 *
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function formUpload(Request $request, TranslatorInterface $translator)
{
    /** @var UploadedFile $uploadedFile */
    $formUploader = new FormUploader();
    $form = $this->createForm(FormUploaderType::class, $formUploader);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $catalog = $request->request->get('form_uploader')['service'];

        $fileNameGenerator = new FileNameGenerator($request);
        $originalFileName = $fileNameGenerator->getOriginalFilename();
        $tmpPath = $fileNameGenerator->getFilePath();

        $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));

        if (!$upload->gitlabUpload()) {
            $this->addFlash('danger', $translator->trans('uploadTermsError'));
        } else {
            $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
            $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
            $this->addFlash('info', $url.'
Podgląd

 Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
        }

        return $this->redirectToRoute('upload_terms');
    }

}

Body:
You can try this

public function formUpload(Request $request, TranslatorInterface $translator)
    {
        /** @var UploadedFile $uploadedFile */
        $formUploader = new FormUploader();
        $form = $this->createForm(FormUploaderType::class, $formUploader);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $catalog = $request->request->get('form_uploader')['service'];
            $fileNameGenerator = new FileNameGenerator($request);
            $originalFileName = $fileNameGenerator->getOriginalFilename();
            $tmpPath = $fileNameGenerator->getFilePath();
            $upload = new Uploader($catalog.'/'.$originalFileName, file_get_contents($tmpPath));
            $this->gitlabupload($upload, $translator, $catalog, $originalFileName);

            return $this->redirectToRoute('upload_terms');
        }

        return $this->render('uploader/upload.html.twig', [
            'createForm' => $form->createView(),
        ]);
    }

    private function gitlabupload($upload, $translator, $catalog, $originalFileName)
    {
        if (!$upload->gitlabUpload()) {
            $this->addFlash('danger', $translator->trans('uploadTermsError'));
        } else {
            $url = $this->configVendors->vendorUrl($catalog).'/'.$catalog.'/'.$originalFileName;
            $this->addFlash('success', $translator->trans('uploadTermsSuccess'));
            $this->addFlash('info', $url.'<br><a href="'.$url.'" target="_blank">Podgląd</a> <br><br> Plik będzie dostępny po kilku minutach, proszę o cierpliwość!');
        }
    }


来源: stackexchange

问:
Throughput of trivially concurrent code does not increase with the number of threads
I am trying to use OpenMP to benchmark the speed of data structure that I implemented. However, I seem to make a fundamental mistake: the throughput decreases instead of increasing with the number of threads no matter what operation I try to benchmark.
Below you can see the code that tries to benchmark the speed of a for-loop, as such I would expect it to scale (somewhat) linearly with the number of threads, it doesn't (compiled on a dualcore laptop with and without -O3 flag on g++ with c++11).

```<code>#include <omp.h>
#include <atomic>
#include <chrono>
#include <iostream>

thread_local const int OPS = 10000;
thread_local const int TIMES = 200;

double get_tp(int THREADS)
{
    double threadtime[THREADS] = {0};

    //Repeat the test many times
    for(int iteration = 0; iteration < TIMES; iteration++)
    {
        #pragma  omp  parallel num_threads(THREADS)
        {
            double start, stop;
            int loc_ops = OPS/float(THREADS);
            int t = omp_get_thread_num();

            //Force all threads to start at the same time
            #pragma  omp  barrier
            start = omp_get_wtime();

            //Do a certain kind of operations loc_ops times
            for(int i = 0; i < loc_ops; i++)
            {
                //Here I would put the operations to benchmark
                //in this case a boring for loop
                int x = 0;
                for(int j = 0; j < 1000; j++)
                    x++;
            }

        stop = omp_get_wtime();
        threadtime[t] += stop-start;
        }
    }

    double total_time = 0;
    std::cout << "\nThread times: ";
    for(int i = 0; i < THREADS; i++)
    {
        total_time += threadtime[i];
        std::cout << threadtime[i] << ", ";
    }
    std::cout << "\nTotal time: " << total_time << "\n";
    double mopss = float(OPS)*TIMES/total_time;
    return mopss;
}

int main()
{
    std::cout << "\n1  " << get_tp(1) << "ops/s\n";
    std::cout << "\n2  " << get_tp(2) << "ops/s\n";
    std::cout << "\n4  " << get_tp(4) << "ops/s\n";
    std::cout << "\n8  " << get_tp(8) << "ops/s\n";
}
</code>```

Outputs with -O3 on a dualcore, so we don't expect the throughput to increase after 2 threads, but it does not even increase when going from 1 to 2 threads it decreases by 50%:

```<code>1 Thread
Thread times: 7.411e-06,
Total time: 7.411e-06
2.69869e+11 ops/s

2 Threads
Thread times: 7.36701e-06, 7.38301e-06,
Total time: 1.475e-05
1.35593e+11ops/s

4 Threads
Thread times: 7.44301e-06, 8.31901e-06, 8.34001e-06, 7.498e-06,
Total time: 3.16e-05
6.32911e+10ops/s

8 Threads
Thread times: 7.885e-06, 8.18899e-06, 9.001e-06, 7.838e-06, 7.75799e-06, 7.783e-06, 8.349e-06, 8.855e-06,
Total time: 6.5658e-05
3.04609e+10ops/s
</code>```

To make sure that the compiler does not remove the loop, I also tried outputting "x" after measuring the time and to the best of my knowledge the problem persists. I also tried the code on a machine with more cores and it behaved very similarly. Without -O3 the throughput also does not scale. So there is clearly something wrong with the way I benchmark. I hope you can help me.

答:
The loop is almost certainly still getting optimized, even if you output the value of x after the outer loop. The compiler can trivially replace the entire loop with a single instruction since the loop bounds are constant at compile time.  Indeed, in this example:

```<code>#include <iostream>

int main()
{
    int x = 0;
    for (int i = 0; i < 10000; ++i) {
        for (int j = 0; j < 1000; ++j) {
            ++x;
        }
    }

    std::cout << x << '\n';
    return 0;
}
</code>```

The loop is replaced with the single assembly instruction mov esi, 10000000.

Always inspect the assembly output when benchmarking to make sure that you're measuring what you think you are; in this case you are just measuring the overhead of creating threads, which of course will be higher the more threads you create.

Consider having the innermost loop do something that can't be optimized away. Random number generation is a good candidate because it should perform in constant time, and it has the side-effect of permuting the PRNG state (making it ineligible to be removed entirely, unless the seed is known in advance and the compiler is able to unravel all of the mutation in the PRNG).

For example:

```<code>#include <iostream>
#include <random>

int main()
{
    std::mt19937 r;
    std::uniform_real_distribution<double> dist{0, 1};

    for (int i = 0; i < 10000; ++i) {
        for (int j = 0; j < 1000; ++j) {
            dist(r);
        }
    }

    return 0;
}
</code>```

Both loops and the PRNG invocation are left intact here.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use OpenMP to benchmark the speed of data structure that I implemented. However, I seem to make a fundamental mistake: the throughput decreases instead of increasing with the number of threads no matter what operation I try to benchmark.
Below you can see the code that tries to benchmark the speed of a for-loop, as such I would expect it to scale (somewhat) linearly with the number of threads, it doesn't (compiled on a dualcore laptop with and without -O3 flag on g++ with c++11).

#include <omp.h>
#include <atomic>
#include <chrono>
#include <iostream>

thread_local const int OPS = 10000;
thread_local const int TIMES = 200;

double get_tp(int THREADS)
{
    double threadtime[THREADS] = {0};

    //Repeat the test many times
    for(int iteration = 0; iteration < TIMES; iteration++)
    {
        #pragma  omp  parallel num_threads(THREADS)
        {
            double start, stop;
            int loc_ops = OPS/float(THREADS);
            int t = omp_get_thread_num();

            //Force all threads to start at the same time
            #pragma  omp  barrier
            start = omp_get_wtime();

            //Do a certain kind of operations loc_ops times
            for(int i = 0; i < loc_ops; i++)
            {
                //Here I would put the operations to benchmark
                //in this case a boring for loop
                int x = 0;
                for(int j = 0; j < 1000; j++)
                    x++;
            }

        stop = omp_get_wtime();
        threadtime[t] += stop-start;
        }
    }

    double total_time = 0;
    std::cout << "\nThread times: ";
    for(int i = 0; i < THREADS; i++)
    {
        total_time += threadtime[i];
        std::cout << threadtime[i] << ", ";
    }
    std::cout << "\nTotal time: " << total_time << "\n";
    double mopss = float(OPS)*TIMES/total_time;
    return mopss;
}

int main()
{
    std::cout << "\n1  " << get_tp(1) << "ops/s\n";
    std::cout << "\n2  " << get_tp(2) << "ops/s\n";
    std::cout << "\n4  " << get_tp(4) << "ops/s\n";
    std::cout << "\n8  " << get_tp(8) << "ops/s\n";
}

Outputs with -O3 on a dualcore, so we don't expect the throughput to increase after 2 threads, but it does not even increase when going from 1 to 2 threads it decreases by 50%:

1 Thread
Thread times: 7.411e-06,
Total time: 7.411e-06
2.69869e+11 ops/s

2 Threads
Thread times: 7.36701e-06, 7.38301e-06,
Total time: 1.475e-05
1.35593e+11ops/s

4 Threads
Thread times: 7.44301e-06, 8.31901e-06, 8.34001e-06, 7.498e-06,
Total time: 3.16e-05
6.32911e+10ops/s

8 Threads
Thread times: 7.885e-06, 8.18899e-06, 9.001e-06, 7.838e-06, 7.75799e-06, 7.783e-06, 8.349e-06, 8.855e-06,
Total time: 6.5658e-05
3.04609e+10ops/s

To make sure that the compiler does not remove the loop, I also tried outputting "x" after measuring the time and to the best of my knowledge the problem persists. I also tried the code on a machine with more cores and it behaved very similarly. Without -O3 the throughput also does not scale. So there is clearly something wrong with the way I benchmark. I hope you can help me.

Body:
The loop is almost certainly still getting optimized, even if you output the value of x after the outer loop. The compiler can trivially replace the entire loop with a single instruction since the loop bounds are constant at compile time.  Indeed, in this example:

#include <iostream>

int main()
{
    int x = 0;
    for (int i = 0; i < 10000; ++i) {
        for (int j = 0; j < 1000; ++j) {
            ++x;
        }
    }

    std::cout << x << '\n';
    return 0;
}

The loop is replaced with the single assembly instruction mov esi, 10000000.

Always inspect the assembly output when benchmarking to make sure that you're measuring what you think you are; in this case you are just measuring the overhead of creating threads, which of course will be higher the more threads you create.

Consider having the innermost loop do something that can't be optimized away. Random number generation is a good candidate because it should perform in constant time, and it has the side-effect of permuting the PRNG state (making it ineligible to be removed entirely, unless the seed is known in advance and the compiler is able to unravel all of the mutation in the PRNG).

For example:

#include <iostream>
#include <random>

int main()
{
    std::mt19937 r;
    std::uniform_real_distribution<double> dist{0, 1};

    for (int i = 0; i < 10000; ++i) {
        for (int j = 0; j < 1000; ++j) {
            dist(r);
        }
    }

    return 0;
}

Both loops and the PRNG invocation are left intact here.


问:
Javascript function works on postback but not page load
I'm using a Google Maps plugin, and I want it to show up on the page load as well as all postbacks. It seems to only work on postbacks though. Any ideas? I have the body onload tag as "body background="#ccccff" onload="initialize()"", but the function is not defined the first time. Why? Here is the code:

```<code><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">      </script>
<script type="text/javascript">
var mostRecentInfo;
function initialize() {
    var center = new google.maps.LatLng(0, 0);
    var mapOptions = {
        center: center,
        zoom:1,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };

    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    var posStr = <%=JSON%>;
    if (posStr.toString() != "0") {
        var test = posStr.toString().split(',');
        var groundstation = <%=groundStation%>;
        var dateTimeStr = <%=datetimesStr%>;
        var AUStr = <%=auStr%>;
        var spaceCraft = <%=spacecraft%>;
        var dateTimes = dateTimeStr.toString().split(',');
        var auIDs = AUStr.toString().split(',');
        var latitude = new Array((test.length / 2));
        var longitude = new Array(latitude.length);
        var i = 0;
        var markerArray = new Array();
        for (var j = 0; j < (test.length - 1); j = j + 2) {
            latitude[i] = eval(test[j+1]);
            longitude[i] = eval(test[j]);
            var position = new google.maps.LatLng(latitude[i], longitude[i]);
            var marker = new google.maps.Marker({
                map:map,
                position:position
            });
            markerArray.push(marker);
            i++;
        }
        var sumLat = 0;
        var sumLong = 0;
        for (i = 0; i < latitude.length; i++) {
            sumLat += latitude[i];
            sumLong += longitude[i];
        }
        var avgLat = sumLat / latitude.length;
        var avgLong = sumLong / longitude.length;
        center = new google.maps.LatLng(avgLat, avgLong);
        map.panTo(center);
        var circle;
        var contentStr = new Array();
        for (i = 0; i < markerArray.length; i++) {
            position = markerArray[i].getPosition();
            var circOptions = {
                strokeColor:"#770000",
                strokeOpacity:0.1,
                fillColor:"#881111",
                fillOpacity:0.4,
                map:map,
                center:position,
                radius:2500000
            };
            circle = new google.maps.Circle(circOptions);
            marker = markerArray[i];
            contentStr[i] = '<div id="content">' +
                '<b>Spacecraft: </b>' + spaceCraft.toString() + '<br />' +
                '<b>Start Time (UTC): </b>' + dateTimes[i].toString() + '<br />' +
                '<b>Position: </b>(' + latitude[i].toString() + ', ' + longitude[i].toString() + ')<br />' +
                '<b>AU ID: </b>' + auIDs[i] + '<br />' +
                '<b>Downlink Station: </b>' + groundstation.toString() + '<br />' +
                '</div>';
            addListener(map, marker, contentStr[i]);
        }
    }
}

function addListener(map, marker, content) {
    var infowindow = new google.maps.InfoWindow({
        content:content
        });
    google.maps.event.addListener(marker, 'mouseover', function() {
        if (mostRecentInfo)
            mostRecentInfo.close();
        mostRecentInfo = infowindow;
        infowindow.open(map, this);
    });
}
</code>```

etc.

答:
It is likely a timing issue with the onload function being called before the initialize function is ready. This is the reason libraries like jQuery have a document.ready function. You can try removing the onload and place a call to initialize() at the bottom of your HTML, just prior to the closing body tag. This will probably work for you.

If you have the option, I'd use a library so you can assure that the function is there and your page is ready. If you haven't tried it, give jQuery a shot.

ContentLicense: CC BY-SA 3.0


问:
javax validation api not working for pojo validation
I have a POJO class where the class variables are getting injected by @Value annotation. I am trying to validate my class variables using javax validation api & so I have tried @NotNull, @NotEmpty and @NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api?
PS: I am using lombok to generate my getter/setter.

Below is my sample code!

POJO Class:

```<code>@Component
@Getter
@Setter
public class Credentials {

    @NotBlank
    @Value("${app.username}")
    private String user_name;

    @NotBlank
    @Value("${app.password}")
    private String password;

}
</code>```

Below is the application.yml file:

```<code>app:
    username: '#{null}'
    password: passWord
</code>```

Even if I provide a blank value, I don't get any exception when I try to print these values in the console.

答:
Validation will only work for @ConfigurationProperties annotated classes combined with using @EnableConfigurationProperties.

The reason you don't get any exception is that @Value only looks for presence of the attribute in the properties, it doesn't care what the value of that attribute is, unless you are assigning a mis-matching datatype value.

Body:
I have a POJO class where the class variables are getting injected by @Value annotation. I am trying to validate my class variables using javax validation api & so I have tried @NotNull, @NotEmpty and @NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api?
PS: I am using lombok to generate my getter/setter.

Below is my sample code!

POJO Class:

@Component
@Getter
@Setter
public class Credentials {

    @NotBlank
    @Value("${app.username}")
    private String user_name;

    @NotBlank
    @Value("${app.password}")
    private String password;

}

Below is the application.yml file:

app:
    username: '#{null}'
    password: passWord

Even if I provide a blank value, I don't get any exception when I try to print these values in the console.


问:
cannot read csv file in python
I have a python script that has a line with open('gg.csv') as csv_file:, and I have a csv file called gg.csv in the exact same directory as the python file, but when I run the script I am getting FileNotFoundError: [Errno 2] No such file or directory: 'gg.csv' - does anyone know of the solution?

答:
This is probably beacuse you run the script from different directoy.

For instance, if I have the following script at my Desktop:

```<code>import os
print(os.getcwd())
</code>```

running the script from the Desktop I get:

```<code>~/Desktop » py3 SO.py                                         Sriker@Sriker-MBP
/Users/Sriker/Desktop
</code>```

While from different directory I get:

```<code>~ » py3 Desktop/SO.py                                         Sriker@Sriker-MBP
/Users/Sriker
</code>```

So you either run the script from the right directory, or build the path to gg.csv properly before trying to open it.

Title: cannot read csv file in python

Body:
This is probably beacuse you run the script from different directoy.

For instance, if I have the following script at my Desktop:

import os
print(os.getcwd())

running the script from the Desktop I get:

~/Desktop » py3 SO.py                                         Sriker@Sriker-MBP
/Users/Sriker/Desktop

While from different directory I get:

~ » py3 Desktop/SO.py                                         Sriker@Sriker-MBP
/Users/Sriker

So you either run the script from the right directory, or build the path to gg.csv properly before trying to open it.


问:
ordering alpha numeric variable in r
I would like to order a data frame based on an alphanumeric variable. Here how my dataset looks like:

```<code>sample.data <- data.frame(Grade=c(4,4,4,4,3,3,3,3,3,3,3,3),
                          ItemID = c(15,15,15,15,17,17,17,17,16,16,16,16),
                          common.names = c("15_AS_SA1_Correct","15_AS_SA10_Correct","15_AS_SA2_Correct","15_AS_SA3_Correct",
                                            "17_AS_2_B2","17_AS_2_B1","17_AS_5_C1","17_AS_4_D1",
                                           "16_AS_SA1_Negative","16_AS_SA11_Prediction","16_AS_SA12_UnitMeaning","16_AS_SA3_Complete"))

> sample.data
   Grade ItemID           common.names
1      4     15      15_AS_SA1_Correct
2      4     15     15_AS_SA10_Correct
3      4     15      15_AS_SA2_Correct
4      4     15      15_AS_SA3_Correct
5      3     17             17_AS_2_B2
6      3     17             17_AS_2_B1
7      3     17             17_AS_5_C1
8      3     17             17_AS_4_D1
9      3     16     16_AS_SA1_Negative
10     3     16  16_AS_SA11_Prediction
11     3     16 16_AS_SA12_UnitMeaning
12     3     16     16_AS_SA3_Complete
</code>```

I need to order by Grade and ItemID, then by common.names variable that contains alphanumeric.

I used this:

```<code>sample.data.ordered <- sample.data %>%
  arrange(Grade, ItemID,common.names)
</code>```

but it did not work for the whole set.

My desired output is:

```<code>> sample.data.ordered
   Grade ItemID           common.names
1      3     16     16_AS_SA1_Negative
2      3     16     16_AS_SA3_Complete
3      3     16  16_AS_SA11_Prediction
4      3     16 16_AS_SA12_UnitMeaning
5      3     17             17_AS_2_B1
6      3     17             17_AS_2_B2
7      3     17             17_AS_4_D1
8      3     17             17_AS_5_C1
9      4     15      15_AS_SA1_Correct
10     4     15      15_AS_SA2_Correct
11     4     15      15_AS_SA3_Correct
12     4     15     15_AS_SA10_Correct
</code>```

Any thoughts?
Thanks!

答:
A base R solution using order as well as a more complex procedure for common.names involving gsub, regular expression and multiple backreference to match the numbers in the strings by which the column can be ordered:

```<code>sample.data[order(sample.data$Grade,
              sample.data$ItemID,
              as.numeric(gsub(".*(SA|AS_)(\\d+)_(\\w)?(\\d)?.*", "\\2\\4", sample.data$common.names))),]
   Grade ItemID           common.names
9      3     16     16_AS_SA1_Negative
12     3     16     16_AS_SA3_Complete
10     3     16  16_AS_SA11_Prediction
11     3     16 16_AS_SA12_UnitMeaning
6      3     17             17_AS_2_B1
5      3     17             17_AS_2_B2
8      3     17             17_AS_4_D1
7      3     17             17_AS_5_C1
1      4     15      15_AS_SA1_Correct
3      4     15      15_AS_SA2_Correct
4      4     15      15_AS_SA3_Correct
2      4     15     15_AS_SA10_Correct
</code>```

Title: ordering alpha numeric variable in r

Body:
I would like to order a data frame based on an alphanumeric variable. Here how my dataset looks like:

sample.data <- data.frame(Grade=c(4,4,4,4,3,3,3,3,3,3,3,3),
                          ItemID = c(15,15,15,15,17,17,17,17,16,16,16,16),
                          common.names = c("15_AS_SA1_Correct","15_AS_SA10_Correct","15_AS_SA2_Correct","15_AS_SA3_Correct",
                                            "17_AS_2_B2","17_AS_2_B1","17_AS_5_C1","17_AS_4_D1",
                                           "16_AS_SA1_Negative","16_AS_SA11_Prediction","16_AS_SA12_UnitMeaning","16_AS_SA3_Complete"))

> sample.data
   Grade ItemID           common.names
1      4     15      15_AS_SA1_Correct
2      4     15     15_AS_SA10_Correct
3      4     15      15_AS_SA2_Correct
4      4     15      15_AS_SA3_Correct
5      3     17             17_AS_2_B2
6      3     17             17_AS_2_B1
7      3     17             17_AS_5_C1
8      3     17             17_AS_4_D1
9      3     16     16_AS_SA1_Negative
10     3     16  16_AS_SA11_Prediction
11     3     16 16_AS_SA12_UnitMeaning
12     3     16     16_AS_SA3_Complete

I need to order by Grade and ItemID, then by common.names variable that contains alphanumeric.

I used this:

sample.data.ordered <- sample.data %>%
  arrange(Grade, ItemID,common.names)

but it did not work for the whole set.

My desired output is:

> sample.data.ordered
   Grade ItemID           common.names
1      3     16     16_AS_SA1_Negative
2      3     16     16_AS_SA3_Complete
3      3     16  16_AS_SA11_Prediction
4      3     16 16_AS_SA12_UnitMeaning
5      3     17             17_AS_2_B1
6      3     17             17_AS_2_B2
7      3     17             17_AS_4_D1
8      3     17             17_AS_5_C1
9      4     15      15_AS_SA1_Correct
10     4     15      15_AS_SA2_Correct
11     4     15      15_AS_SA3_Correct
12     4     15     15_AS_SA10_Correct

Any thoughts?
Thanks!

Body:
A base R solution using order as well as a more complex procedure for common.names involving gsub, regular expression and multiple backreference to match the numbers in the strings by which the column can be ordered:

sample.data[order(sample.data$Grade,
              sample.data$ItemID,
              as.numeric(gsub(".*(SA|AS_)(\\d+)_(\\w)?(\\d)?.*", "\\2\\4", sample.data$common.names))),]
   Grade ItemID           common.names
9      3     16     16_AS_SA1_Negative
12     3     16     16_AS_SA3_Complete
10     3     16  16_AS_SA11_Prediction
11     3     16 16_AS_SA12_UnitMeaning
6      3     17             17_AS_2_B1
5      3     17             17_AS_2_B2
8      3     17             17_AS_4_D1
7      3     17             17_AS_5_C1
1      4     15      15_AS_SA1_Correct
3      4     15      15_AS_SA2_Correct
4      4     15      15_AS_SA3_Correct
2      4     15     15_AS_SA10_Correct


问:
Assets file project.assets.json not found. Run a NuGet package restore
I'm trying to use nopCommerce(Which is written in .NET Core) but when I want to run the project I face 52 Errors telling me Run a nuget package restore

Assets file ~\obj\project.assets.json' not found. Run a NuGet package restore to generate this file.  Nop.Web.MVC.Testsote

when I use the right click on the solution and selecting Restore Nuget Packages I get this message:

All packages are already installed and there is nothing to restore.

but those 52 Errors are still there and in Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution  there is nothing installed on the solution,also I Recently updated my VS2017 to 15.5.4

答:
You can go for : Tools > NuGet Package Manager > Package Manager Console

And then Run:

dotnet restore


问:
Can Someone Please Clarify Where .env Files Work in VS Code
The documentation for the Python extension for VS Code says that it supports environment variables being set in a .env file.
I've read the documentation and various reports on GitHub, but I have not found any clarity on a few things:

Do .env files work with tasks? My experience says they don't.

Do .env files work with the integrated terminal? My experience says they don't.

答: .env files are a construct of the Python extension and so do not work in places that VS Code directly controls (e.g. tasks and the terminal). A lot of people use them with the debugger.


问:
C++ compile problem with strlen and strcpy

#include<iostream>
using namespace std;

int main()
{
    char a[5],b[5];
    cout<<strlen(a)<<endl;
    strcpy(a,b);
}
```

when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!

based on cplusplus.com, I am the one who should get errors!!

so I am just wondering what's causing the difference here?

P.S: I have tried different versions of C++ using -std=c++98 throw -std=c++2a

答: strlen and strcpy are declared in the <cstring> header.  Some standard library implementations might include that in <iostream>, some might not.  This explains why it may compile with some setups and not others.

Body:
#include<iostream>
using namespace std;

int main()
{
    char a[5],b[5];
    cout<<strlen(a)<<endl;
    strcpy(a,b);
}

when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!

based on cplusplus.com, I am the one who should get errors!!

so I am just wondering what's causing the difference here?

P.S: I have tried different versions of C++ using -std=c++98 throw -std=c++2a


问:
Tuple templates in GCC
I first started C++ with Microsoft VC++ in VS2010. I recently found some work, but I've been using RHEL 5 with GCC. My code is mostly native C++, but I've noticed one thing...

GCC doesn't appear to recognize the <tuple> header file, or the tuple template. At first I thought maybe it's just a typo, until I looked at cplusplus.com and found that the  header is indeed not part of the standard library.

The problem is that I like to write my code in Visual Studio because the environment is way superior and aesthetically pleasing than eclipse or netbeans, and debugging is a breeze. The thing is, I've already written a good chunk of code to use tuples and I really like my code. How am I supposed to deal with this issue?

Here's my code:

```<code>using std::cout;
using std::make_tuple;
using std::remove;
using std::string;
using std::stringstream;
using std::tolower;
using std::tuple;
using std::vector;

// Define three conditions to code
enum {DONE, OK, EMPTY_LINE};
// Tuple containing a condition and a string vector
typedef tuple<int,vector<string>> Code;

// Passed an alias to a string
// Parses the line passed to it
Code ReadAndParse(string& line)
{

    /***********************************************/
    /****************REMOVE COMMENTS****************/
    /***********************************************/
    // Sentinel to flag down position of first
    // semicolon and the index position itself
    bool found = false;
    size_t semicolonIndex = -1;

    // Convert the line to lowercase
    for(int i = 0; i < line.length(); i++)
    {
        line[i] = tolower(line[i]);

        // Find first semicolon
        if(line[i] == ';' && !found)
        {
            semicolonIndex = i;
            // Throw the flag
            found = true;
        }
    }

    // Erase anything to and from semicolon to ignore comments
    if(found != false)
        line.erase(semicolonIndex);

    /***********************************************/
    /*****TEST AND SEE IF THERE'S ANYTHING LEFT*****/
    /***********************************************/

    // To snatch and store words
    Code code;
    string token;
    stringstream ss(line);
    vector<string> words;

    // A flag do indicate if we have anything
    bool emptyLine = true;

    // While the string stream is passing anything
    while(ss >> token)
    {
        // If we hit this point, we did find a word
        emptyLine = false;

        // Push it onto the words vector
        words.push_back(token);
    }

    // If all we got was nothing, it's an empty line
    if(emptyLine)
    {
        code = make_tuple(EMPTY_LINE, words);
        return code;
    }

    // At this point it should be fine
    code = make_tuple(OK, words);
    return code;
}
</code>```

Is there anyway to save my code from compiler incompatibility?

答:
Compilers that ship the TR1 library should have it here

```<code>#include <tr1/tuple.hpp>

//...

std::tr1::tuple<int, int> mytuple;
</code>```

Of course for portability you can use the boost library version in the meantime

Title: Tuple templates in GCC

Body:
I first started C++ with Microsoft VC++ in VS2010. I recently found some work, but I've been using RHEL 5 with GCC. My code is mostly native C++, but I've noticed one thing...

GCC doesn't appear to recognize the <tuple> header file, or the tuple template. At first I thought maybe it's just a typo, until I looked at cplusplus.com and found that the  header is indeed not part of the standard library.

The problem is that I like to write my code in Visual Studio because the environment is way superior and aesthetically pleasing than eclipse or netbeans, and debugging is a breeze. The thing is, I've already written a good chunk of code to use tuples and I really like my code. How am I supposed to deal with this issue?

Here's my code:

using std::cout;
using std::make_tuple;
using std::remove;
using std::string;
using std::stringstream;
using std::tolower;
using std::tuple;
using std::vector;

// Define three conditions to code
enum {DONE, OK, EMPTY_LINE};
// Tuple containing a condition and a string vector
typedef tuple<int,vector<string>> Code;

// Passed an alias to a string
// Parses the line passed to it
Code ReadAndParse(string& line)
{

    /***********************************************/
    /****************REMOVE COMMENTS****************/
    /***********************************************/
    // Sentinel to flag down position of first
    // semicolon and the index position itself
    bool found = false;
    size_t semicolonIndex = -1;

    // Convert the line to lowercase
    for(int i = 0; i < line.length(); i++)
    {
        line[i] = tolower(line[i]);

        // Find first semicolon
        if(line[i] == ';' && !found)
        {
            semicolonIndex = i;
            // Throw the flag
            found = true;
        }
    }

    // Erase anything to and from semicolon to ignore comments
    if(found != false)
        line.erase(semicolonIndex);

    /***********************************************/
    /*****TEST AND SEE IF THERE'S ANYTHING LEFT*****/
    /***********************************************/

    // To snatch and store words
    Code code;
    string token;
    stringstream ss(line);
    vector<string> words;

    // A flag do indicate if we have anything
    bool emptyLine = true;

    // While the string stream is passing anything
    while(ss >> token)
    {
        // If we hit this point, we did find a word
        emptyLine = false;

        // Push it onto the words vector
        words.push_back(token);
    }

    // If all we got was nothing, it's an empty line
    if(emptyLine)
    {
        code = make_tuple(EMPTY_LINE, words);
        return code;
    }

    // At this point it should be fine
    code = make_tuple(OK, words);
    return code;
}

Is there anyway to save my code from compiler incompatibility?

Body:
Compilers that ship the TR1 library should have it here

#include <tr1/tuple.hpp>

//...

std::tr1::tuple<int, int> mytuple;

Of course for portability you can use the boost library version in the meantime


问:
How to handle the token validation in backend
I am new to implementing security authentication on rest api. I am trying to implement oauth2 authorization from aws cognito user pool.

```<code>from flask import  Flask,jsonify,render_template,request

import requests

import socket

app = Flask(__name__)

name='Umesh'
App_client_id = 'cleintId'
App_client_secret = 'clientSecret'
url = 'https://myurl.auth.eu-west-1.amazoncognito.com'
targetApi = 'https://myTargetApi/v1/product'

class setTokenCache():
    cache=''

obj= setTokenCache()
#print("Acces token is ", obj.cache)

@app.route('/login')
def index():

    try:
        grant_type = 'client_credentials'
        response = requests.post(url + '/oauth2/token',
                                 auth=(App_client_id, App_client_secret),
                                 data={'grant_type': grant_type, 'client_id': App_client_id,
                                       'client_secret': App_client_secret})

        print("Staus code", response)
        if response.status_code!=200:
            return "You are not authenticated"
        else:
            result = response.json()
            obj.cache = result['access_token']
            print("Access token is",obj.cache)
            return "You are Logined"
    except socket.gaierror as e:
        print("Unable to get the r")

</code>```

API 1 Login

Here is the api returns #'You are Logined', if its authenticated with the access token just generated.Just consider its a login part.

API 2 Accessing the productDetails

Now i have this API, where i want to get the valid response using the above generated access token.

```<code>

@app.route('/getProductDetails', methods=['GET', 'POST'])
def productDetails():

    print("Access token is",obj.cache)
    headers = {'Authorization': 'Bearer ' + accessToken, 'Accept': 'application/json'}
    try:
        response = requests.get(targetApi, headers=headers)
        return response.json()
    except socket.gaierror as e:
        print("Unable to get the r")

</code>```

Here i need to pass the #accessToken in order to get the valid response or otherewise it will return, #unauthrized

Expected:

Now i would like to know how should i implement this security over this api in such way that

It should consume the above created accessToken till it expired in order to get the valid response from the api

```<code> http://127.0.0.1:5000/getProductDetails
</code>```

OR
 2. How to ensure that how browser/client would consume the same token while navigating from API 1 to API  till it expired

Appreciate if anybody can help on this?

答:
In terms of Cognito token validation there is some sample NodeJS code below and you should find a library for your programming language. Also the below online tool can be useful for understanding the validation process:

Cognito token validation in NodeJS

In memory token validation write up

Body:
I am new to implementing security authentication on rest api. I am trying to implement oauth2 authorization from aws cognito user pool.

from flask import  Flask,jsonify,render_template,request

import requests

import socket

app = Flask(__name__)

name='Umesh'
App_client_id = 'cleintId'
App_client_secret = 'clientSecret'
url = 'https://myurl.auth.eu-west-1.amazoncognito.com'
targetApi = 'https://myTargetApi/v1/product'

class setTokenCache():
    cache=''

obj= setTokenCache()
#print("Acces token is ", obj.cache)

@app.route('/login')
def index():

    try:
        grant_type = 'client_credentials'
        response = requests.post(url + '/oauth2/token',
                                 auth=(App_client_id, App_client_secret),
                                 data={'grant_type': grant_type, 'client_id': App_client_id,
                                       'client_secret': App_client_secret})

        print("Staus code", response)
        if response.status_code!=200:
            return "You are not authenticated"
        else:
            result = response.json()
            obj.cache = result['access_token']
            print("Access token is",obj.cache)
            return "You are Logined"
    except socket.gaierror as e:
        print("Unable to get the r")

API 1 Login

Here is the api returns #'You are Logined', if its authenticated with the access token just generated.Just consider its a login part.

API 2 Accessing the productDetails

Now i have this API, where i want to get the valid response using the above generated access token.

@app.route('/getProductDetails', methods=['GET', 'POST'])
def productDetails():

    print("Access token is",obj.cache)
    headers = {'Authorization': 'Bearer ' + accessToken, 'Accept': 'application/json'}
    try:
        response = requests.get(targetApi, headers=headers)
        return response.json()
    except socket.gaierror as e:
        print("Unable to get the r")

Here i need to pass the #accessToken in order to get the valid response or otherewise it will return, #unauthrized

Expected:

Now i would like to know how should i implement this security over this api in such way that

It should consume the above created accessToken till it expired in order to get the valid response from the api

 http://127.0.0.1:5000/getProductDetails

OR
 2. How to ensure that how browser/client would consume the same token while navigating from API 1 to API  till it expired

Appreciate if anybody can help on this?


答:
Which os are you using?.
Try with providing full url to your file and see if it works

If you are using Windows, try renaming

```<code>open('gg.csv')
</code>```

to

```<code>open('\gg.csv')
</code>```

Title: cannot read csv file in python

Body: I have a python script that has a line with open('gg.csv') as csv_file:, and I have a csv file called gg.csv in the exact same directory as the python file, but when I run the script I am getting FileNotFoundError: [Errno 2] No such file or directory: 'gg.csv' - does anyone know of the solution?

Body:
Which os are you using?.
Try with providing full url to your file and see if it works

If you are using Windows, try renaming

open('gg.csv')

to

open('\gg.csv')


问:
Refresh part of a plot during fminsearch optimization
I am facing an issue related with the need to update part of a plot at every iteration of fminsearch.

In summary, in my "main_optimization" file I have this part of a code that is intended to plot the experimental data to be fitted by my model. This are the plots I want to keep during the whole process:

```<code>figure (1)

subplot(1,3,1)
plot(Pexp,Rexp(:,1),'ro',Pexp,Rexp(:,2),'go',Pexp,Rexp(:,3),'bo');
xlabel('P/MPa');
ylabel('\rho /mol.L^{-1}');

subplot(1,3,2)
plot(Pexp,Aexp(:,1),'ro',Pexp,Aexp(:,2),'go',Pexp,Aexp(:,3),'bo');
xlabel('P/MPa');
ylabel('\alpha /K^{-1}');

subplot(1,3,3)
plot(Pexp,Kexp(:,1),'ro',Pexp,Kexp(:,2),'go',Pexp,Kexp(:,3),'bo');
xlabel('P/MPa');
ylabel('k_{T} /K^{-1}');
</code>```

Then I call fminsearch to do the optimization of my model and inside my objective function file I do the following with the objective of deleting the model results from previous iteration and plotting the new ones.

```<code>if ishandle(plotRHO)==1
    delete(plotRHO);
end
if ishandle(plotALFA)==1
    delete(plotALFA);
end
if ishandle(plotKAPPA)==1
    delete(plotKAPPA);
end

subplot (1,3,1)
hold on
plotRHO=plot(Pexp,rhocalc(:,1),'r-',Pexp,rhocalc(:,2),'g-',Pexp,rhocalc(:,3),'b-');
legend(num2str(AAD_RHO),'Location','southeast');
hold off

subplot (1,3,2)
hold on
plotALFA=plot(Pexp,apcalc(:,1),'r-',Pexp,apcalc(:,2),'g-',Pexp,apcalc(:,3),'b-');
legend(num2str(AAD_AP),'Location','southeast');
hold off

subplot (1,3,3)
hold on
plotKAPPA=plot(Pexp,ktcalc(:,1),'r-',Pexp,ktcalc(:,2),'g-',Pexp,ktcalc(:,3),'b-');
legend(num2str(AAD_KT),'Location','southeast');
hold off
</code>```

I tried different stuff like initializing the plotRHO, plotALFA, plotKAPPA in the main file with either an initial plot or {} and then give them as input to the objective function so that I could avoid getting an error in the first iteration in the ishandle function.
When I do this it deletes the first plot and draws the line of the first iteration but then it never plots again nor deletes the old one because the handle is always 0 (which I believe it should not).

If I remove the ishandle and just delete them because I know they exist, they dont delete anything and an warning is displayed saying the object could not be found.

What is the smartest way to always keep my experimental points and just update the model results at each function evaluation of my objective function? It either keeps plotting every line (and just opens the figure when I stop the program due to (memory issues?) or is only plots the first time and then never updates nor deletes despite the program is optimizing..

Thank you in advance for any help,

Best regards

PS: Sorry for the long post

Update: I don't really understand why but if I define plotRHO, plotALFA and plotKAPPA as globals in the beginning of my objective function file, the delete and replot works as I want to. But as far as I understand global variables should be avoided and surely they can be in this case as well

答:
I actually solved my problem by setting the plotRHO , plotKAPPa and plotALFA as global variables in the file where I have my objective function.
I am sure there should be a more clever way to do it and avoid the use of global variables but I did not manage to get it.</p>

Body:
I am facing an issue related with the need to update part of a plot at every iteration of fminsearch.

In summary, in my "main_optimization" file I have this part of a code that is intended to plot the experimental data to be fitted by my model. This are the plots I want to keep during the whole process:

figure (1)

subplot(1,3,1)
plot(Pexp,Rexp(:,1),'ro',Pexp,Rexp(:,2),'go',Pexp,Rexp(:,3),'bo');
xlabel('P/MPa');
ylabel('\rho /mol.L^{-1}');

subplot(1,3,2)
plot(Pexp,Aexp(:,1),'ro',Pexp,Aexp(:,2),'go',Pexp,Aexp(:,3),'bo');
xlabel('P/MPa');
ylabel('\alpha /K^{-1}');

subplot(1,3,3)
plot(Pexp,Kexp(:,1),'ro',Pexp,Kexp(:,2),'go',Pexp,Kexp(:,3),'bo');
xlabel('P/MPa');
ylabel('k_{T} /K^{-1}');

Then I call fminsearch to do the optimization of my model and inside my objective function file I do the following with the objective of deleting the model results from previous iteration and plotting the new ones.

if ishandle(plotRHO)==1
    delete(plotRHO);
end
if ishandle(plotALFA)==1
    delete(plotALFA);
end
if ishandle(plotKAPPA)==1
    delete(plotKAPPA);
end

subplot (1,3,1)
hold on
plotRHO=plot(Pexp,rhocalc(:,1),'r-',Pexp,rhocalc(:,2),'g-',Pexp,rhocalc(:,3),'b-');
legend(num2str(AAD_RHO),'Location','southeast');
hold off

subplot (1,3,2)
hold on
plotALFA=plot(Pexp,apcalc(:,1),'r-',Pexp,apcalc(:,2),'g-',Pexp,apcalc(:,3),'b-');
legend(num2str(AAD_AP),'Location','southeast');
hold off

subplot (1,3,3)
hold on
plotKAPPA=plot(Pexp,ktcalc(:,1),'r-',Pexp,ktcalc(:,2),'g-',Pexp,ktcalc(:,3),'b-');
legend(num2str(AAD_KT),'Location','southeast');
hold off

I tried different stuff like initializing the plotRHO, plotALFA, plotKAPPA in the main file with either an initial plot or {} and then give them as input to the objective function so that I could avoid getting an error in the first iteration in the ishandle function.
When I do this it deletes the first plot and draws the line of the first iteration but then it never plots again nor deletes the old one because the handle is always 0 (which I believe it should not).

If I remove the ishandle and just delete them because I know they exist, they dont delete anything and an warning is displayed saying the object could not be found.

What is the smartest way to always keep my experimental points and just update the model results at each function evaluation of my objective function? It either keeps plotting every line (and just opens the figure when I stop the program due to (memory issues?) or is only plots the first time and then never updates nor deletes despite the program is optimizing..

Thank you in advance for any help,

Best regards

PS: Sorry for the long post

Update: I don't really understand why but if I define plotRHO, plotALFA and plotKAPPA as globals in the beginning of my objective function file, the delete and replot works as I want to. But as far as I understand global variables should be avoided and surely they can be in this case as well


答:
```<code>with open(r'gg.csv') as csv_file:

</code>```

this may work otherwise use

```<code>df=pd.read_csv("gg.csv")

</code>```

if the csv is in row and column format.

Title: cannot read csv file in python

Body:
with open(r'gg.csv') as csv_file:

this may work otherwise use

df=pd.read_csv("gg.csv")

if the csv is in row and column format.


问:
How to change the color of the "MaterialDatePicker" in keyboard Mode & also it is possible to hide that mode in Android?
I've changed the default theme of the MaterialDatePicker that link below, but I cannot change color in keyboard mode of the date selection & also it is possible to hide that mode?

How to change Theme of "MaterialDatePicker" in Android?

答:
About the TextInputLayout in MaterialDatePicker.INPUT_MODE_TEXT.

It is a standard TextInputLayout which inherits from the textInputStyle attribute defined in your app theme.   In the default Material Components theme it is defined by Widget.MaterialComponents.TextInputLayout.FilledBox and it is based on:

background color(boxBackgroundColor attribute): colorOnSurface

underline color (boxStrokeColor attribute) colorPrimary(focused) and colorOnSurface (other states)

Starting from 1.3.0-alpha03 you can use a theme:

```<code>   setTheme(R.style.ThemeOverlay_App_MaterialCalendar)
</code>```

with:

```<code><style name="ThemeOverlay.App.MaterialCalendar" parent="@style/ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="textInputStyle">@style/Widget.App.TextInputLayout</item>
</style>

<style name="Widget.App.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <item name="boxBackgroundColor">@color/....</item>
</style>
</code>```

Before the 1.3.0-alpha03 you can only change the default style of all TextInputLayouts in your app using the textInputStyle in your app theme.

```<code> <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
   ....
   <item name="textInputStyle">@style/My_FilledBox</item>
 </style>

 <style name="My_FilledBox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
     ...
  </style>
</code>```

There isn'a method to hide the toggle in the header, but there is a workaround (it can stop to work in the future releases):

```<code>builder.setTheme(R.style.MyMaterialCalendarTheme);
</code>```

with:

```<code> <style name="MyMaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <!-- HeaderToggleButton -->
    <item name="materialCalendarHeaderToggleButton">@style/HeaderToggleButton1</item>
 </style>

  <style name="HeaderToggleButton1" parent="@style/Widget.MaterialComponents.MaterialCalendar.HeaderToggleButton">
    <item name="android:visibility">gone</item>
  </style>
</code>```

Body:
About the TextInputLayout in MaterialDatePicker.INPUT_MODE_TEXT.

It is a standard TextInputLayout which inherits from the textInputStyle attribute defined in your app theme.   In the default Material Components theme it is defined by Widget.MaterialComponents.TextInputLayout.FilledBox and it is based on:

background color(boxBackgroundColor attribute): colorOnSurface

underline color (boxStrokeColor attribute) colorPrimary(focused) and colorOnSurface (other states)

Starting from 1.3.0-alpha03 you can use a theme:

   setTheme(R.style.ThemeOverlay_App_MaterialCalendar)

with:

<style name="ThemeOverlay.App.MaterialCalendar" parent="@style/ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="textInputStyle">@style/Widget.App.TextInputLayout</item>
</style>

<style name="Widget.App.TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <item name="boxBackgroundColor">@color/....</item>
</style>

Before the 1.3.0-alpha03 you can only change the default style of all TextInputLayouts in your app using the textInputStyle in your app theme.

 <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
   ....
   <item name="textInputStyle">@style/My_FilledBox</item>
 </style>

 <style name="My_FilledBox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
     ...
  </style>

There isn'a method to hide the toggle in the header, but there is a workaround (it can stop to work in the future releases):

builder.setTheme(R.style.MyMaterialCalendarTheme);

with:

 <style name="MyMaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <!-- HeaderToggleButton -->
    <item name="materialCalendarHeaderToggleButton">@style/HeaderToggleButton1</item>
 </style>

  <style name="HeaderToggleButton1" parent="@style/Widget.MaterialComponents.MaterialCalendar.HeaderToggleButton">
    <item name="android:visibility">gone</item>
  </style>


问:
AdMob banner ads in assets folder HTML files
Is it possible to add AdMob banner ads to the assets folder HTML files?
I have made a Ebook using a recyclerview for the list and assets folder containing HTML files containing the content of the relevant title. I have added a AdMob banner to Activity_Main where the list of titles are present. And now want to add a similar banner ads to the content in the assets folder.

PS
This is the first app I build, learning through Youtube and other sites  like Stackoverflow

public class MainActivity extends AppCompatActivity {

```<code>private static final String TAG = "MainActivity";
private Context mContext;

ArrayList<String> titleArrayList;
private RecyclerView mRecyclerView;
    AdView mAdView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    mAdView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // Code to be executed when an ad finishes loading.
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            // Code to be executed when an ad request fails.
        }

        @Override
        public void onAdOpened() {
            // Code to be executed when an ad opens an overlay that
            // covers the screen.
        }

        @Override
        public void onAdClicked() {
            // Code to be executed when the user clicks on an ad.
        }

        @Override
        public void onAdLeftApplication() {
            // Code to be executed when the user has left the app.
        }

        @Override
        public void onAdClosed() {
            // Code to be executed when the user is about to return
            // to the app after tapping on an ad.
        }
    });

    mContext = MainActivity.this;

    titleArrayList = new ArrayList<String>();
    titleArrayList.add(Constants.Title_1);
    titleArrayList.add(Constants.Title_2);
    titleArrayList.add(Constants.Title_3);
    titleArrayList.add(Constants.Title_4);
    titleArrayList.add(Constants.Title_5);

    mRecyclerView = (RecyclerView) findViewById(R.id.title_layout_RecyclerView);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

    TitleAdapter adapter = new TitleAdapter(mContext, titleArrayList, new CustomItemClickListener() {
        @Override
        public void onItemClick(View v, int position) {

            Intent desIntent = new Intent(mContext,DescriptionActivity.class);

            desIntent.putExtra("titles",titleArrayList.get(position));

            startActivity(desIntent);
            Toast.makeText(mContext, "clicked"+titleArrayList.get(position), Toast.LENGTH_SHORT).show();

        }
    });

    mRecyclerView.setAdapter(adapter);
}
</code>```

}

答:
AdMob SDK is strictly native only. For ads on 'html' or websites, you'd have to do it via AdSense.

For this you would have to raise a request in AdSense by submitting your website URL.

Bottom line, you can't do this with AdMob SDK and you're better off with a banner ad at the bottom. Or you can maybe place an interstitial ad when your user is switching between different html pages or after a certain amount of time.

Body:
Is it possible to add AdMob banner ads to the assets folder HTML files?
I have made a Ebook using a recyclerview for the list and assets folder containing HTML files containing the content of the relevant title. I have added a AdMob banner to Activity_Main where the list of titles are present. And now want to add a similar banner ads to the content in the assets folder.

PS
This is the first app I build, learning through Youtube and other sites  like Stackoverflow

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private Context mContext;

ArrayList<String> titleArrayList;
private RecyclerView mRecyclerView;
    AdView mAdView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    mAdView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // Code to be executed when an ad finishes loading.
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            // Code to be executed when an ad request fails.
        }

        @Override
        public void onAdOpened() {
            // Code to be executed when an ad opens an overlay that
            // covers the screen.
        }

        @Override
        public void onAdClicked() {
            // Code to be executed when the user clicks on an ad.
        }

        @Override
        public void onAdLeftApplication() {
            // Code to be executed when the user has left the app.
        }

        @Override
        public void onAdClosed() {
            // Code to be executed when the user is about to return
            // to the app after tapping on an ad.
        }
    });

    mContext = MainActivity.this;

    titleArrayList = new ArrayList<String>();
    titleArrayList.add(Constants.Title_1);
    titleArrayList.add(Constants.Title_2);
    titleArrayList.add(Constants.Title_3);
    titleArrayList.add(Constants.Title_4);
    titleArrayList.add(Constants.Title_5);

    mRecyclerView = (RecyclerView) findViewById(R.id.title_layout_RecyclerView);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

    TitleAdapter adapter = new TitleAdapter(mContext, titleArrayList, new CustomItemClickListener() {
        @Override
        public void onItemClick(View v, int position) {

            Intent desIntent = new Intent(mContext,DescriptionActivity.class);

            desIntent.putExtra("titles",titleArrayList.get(position));

            startActivity(desIntent);
            Toast.makeText(mContext, "clicked"+titleArrayList.get(position), Toast.LENGTH_SHORT).show();

        }
    });

    mRecyclerView.setAdapter(adapter);
}

}


问:
How can I change a log entry in Git?
I commited a new log entry with:

git commit -am "newLogEntry"

Now I want to change the name of my last log entry... (overwriting the last one).

How can I do that? What is the code for that in Git?

答:
If you want to change the name of the last commit, you can write

git commit --amend -m "New name".

You can find more information about git commit here: https://git-scm.com/docs/git-commit

Title: How can I change a log entry in Git?


问:
Trying to convert a .npy file (float64) to uint8 or uint16
I'm trying to display a 3D Numpy Array using VTK (python 3) but it needs the type to be uint8 or uint16.

I don't know how to do this and any help would be greatly appreciated.

In case, there's nothing I can do, I just want to display my .npy file using VTK. Any suggestions will be highly appreciated.

答:
You can use the numpy.astype() function to change the data type.  Here's an example:

```<code>>>> arr = np.array([10., 20., 30., 40., 50.])
>>> print(arr)
[10. 20. 30. 40. 50.]
>>> print(arr.dtype)
float64
>>> arr = arr.astype('uint16')
>>> print(arr)
[10 20 30 40 50]
>>> print(arr.dtype)
uint16
</code>```

To address your further questions, you want to normalize your data when converting float64 to uint8 or uint16.  Basically you want to map the [min, max] data range of your array to [0, 255] for uint8 or [0, 65535] for uint16.  You'll still lose information, but normalization minimizes the data loss.

Here's how you'd map float64 to uint8:

```<code>dmin = np.min(arr)
dmax = np.max(arr)
drange = dmax-dmin
dscale = 255.0/drange
new_arr = (arr-dmin)*dscale
new_arr_uint8 = new_arr.astype('uint8')
</code>```

And, yes, the astype function will work on a loaded array.

Body:
You can use the numpy.astype() function to change the data type.  Here's an example:

>>> arr = np.array([10., 20., 30., 40., 50.])
>>> print(arr)
[10. 20. 30. 40. 50.]
>>> print(arr.dtype)
float64
>>> arr = arr.astype('uint16')
>>> print(arr)
[10 20 30 40 50]
>>> print(arr.dtype)
uint16

To address your further questions, you want to normalize your data when converting float64 to uint8 or uint16.  Basically you want to map the [min, max] data range of your array to [0, 255] for uint8 or [0, 65535] for uint16.  You'll still lose information, but normalization minimizes the data loss.

Here's how you'd map float64 to uint8:

dmin = np.min(arr)
dmax = np.max(arr)
drange = dmax-dmin
dscale = 255.0/drange
new_arr = (arr-dmin)*dscale
new_arr_uint8 = new_arr.astype('uint8')

And, yes, the astype function will work on a loaded array.


问:
How to translate XML to JSON?
As part of my graduation I have to migrate XML files to CouchDB. To convert the structure of the file to JSON is no problem at all, but there's one part which I can't figure out how to actually convert:

```<code><p>We beg to send us immediately [...] <note>
  <p>In the original, [...]</p>
</note><lb/><add>by post</add> one copy of
<title>A Book</title> by <persName>
  <choice><abbr>Mrs.</abbr><expan>Misses</expan></choice>Jane Smith</persName>.
As soon<lb/> we know the <choice>
                    <sic>prize</sic>
                    <corr>price</corr>
                </choice>the amount [...]<lb/> by post.<lb/>
</p>
</code>```

I'd like to stick to JSON and don't use XML within JSON, as I would need to implement XML capabilities to my program then.

What would be 'best practices' or solutions to this problem?

答:
The following will work, though is a PITA to work with.  Represent each tag s follows:

```<code>{
  attr => {...},
  tag => "...",
  content => [...]
}
</code>```

And content as an array of text (outside of tags) or else tags.

Ignoring whitespace and indentation your snippet would become something like:

```<code>{
  tag => "p",
  content => [
    "We beg to send us immediately [...]",
    {
      tag => "note",
      content => [
        {
          tag => "p",
          content => [ "In the original, [...]" ]
        }
      ]
    },
    { tag => "lb" },
    {
      tag => "add",
      content => [ "by post" ],
    },
    " one copy of ",
    {
      tag=> "title",
      content => [ "A Book" ],
    },
    " by ",
    {
      tag => "persName",
      content => [
        {
          tag => "choice",
          content => [ ... ]
        }
      ],
    },
    ...
  ]
}
</code>```

(I got bored representing it, sorry.)

Note that the data structure is very repetitive and verbose.  But you'll be processing the JSON programmatically, and for that it is very useful that the data structure is perfectly predictable and regular.

OwnerDisplayName: Patrick

Title: How to translate XML to JSON?

Body:
As part of my graduation I have to migrate XML files to CouchDB. To convert the structure of the file to JSON is no problem at all, but there's one part which I can't figure out how to actually convert:

We beg to send us immediately [...] <note>

In the original, [...]

</note><lb/><add>by post</add> one copy of
<title>A Book</title> by <persName>
  <choice>Mrs.<expan>Misses</expan></choice>Jane Smith</persName>.
As soon<lb/> we know the <choice>
                    <sic>prize</sic>
                    <corr>price</corr>
                </choice>the amount [...]<lb/> by post.<lb/>

I'd like to stick to JSON and don't use XML within JSON, as I would need to implement XML capabilities to my program then.

What would be 'best practices' or solutions to this problem?

Body:
The following will work, though is a PITA to work with.  Represent each tag s follows:

{
  attr => {...},
  tag => "...",
  content => [...]
}

And content as an array of text (outside of tags) or else tags.

Ignoring whitespace and indentation your snippet would become something like:

{
  tag => "p",
  content => [
    "We beg to send us immediately [...]",
    {
      tag => "note",
      content => [
        {
          tag => "p",
          content => [ "In the original, [...]" ]
        }
      ]
    },
    { tag => "lb" },
    {
      tag => "add",
      content => [ "by post" ],
    },
    " one copy of ",
    {
      tag=> "title",
      content => [ "A Book" ],
    },
    " by ",
    {
      tag => "persName",
      content => [
        {
          tag => "choice",
          content => [ ... ]
        }
      ],
    },
    ...
  ]
}

(I got bored representing it, sorry.)

Note that the data structure is very repetitive and verbose.  But you'll be processing the JSON programmatically, and for that it is very useful that the data structure is perfectly predictable and regular.

OwnerDisplayName: btilly


问:
Use query string in URL or use multiple URL?
If I want to display many posts in my web application but every post have its own type and I want to display each type in single page so, What's the best method to do that? Is put all all posts in one url and use query string to filter the posts upon the type and display it in the page?

For example : axios.get('/posts?type =sport')

Or I have to put every single type in separate Url

For example: axios.get('/posts/sport')

Also one more question please?
use one reducer to manage every posts or create one reducer for each post type?

答:
you can add a dynamic route to every new type.
Ex:
'/transaction' -> component-1
'/transaction/:type' -> component-any (multiple)</p>


问:
Generate Ant build option missing in Build menu
My intellij dosent have the generate ant build tool option that the oficial doc says
https://www.jetbrains.com/help/idea/generating-ant-build-file.htmlenter link description here

how can i make the option appear?

答:
This feature was deprecated and moved into a separate plug-in for those who still need it. So you need to install the Ant Build Generation plug-in to make it available.

We'll update the docs to mention it, thanks for the feedback.

Reason for the deprecation:

The functionality is not maintained, doesn't support all types of
  projects supported by the IDE and requires manual work to keep the
  project in a state buildable on CI. It will be removed from the
  product into a separate plugin, not bundled by default.

The recommended replacement is to use Maven or Gradle for building the
  project.


问:
How to change the name of the Athena results stored in S3?
The results of Athena query is saved by the query id (a long string) in S3. I was wondering if there's a way to save the results of the query with a pre-specified name? (that can later be easily looked up)</p>

答:
You can do so by a simple AWS Lambda function.

Change names of AWS Athena results stored in S3 bucket

```<code>client = boto3.client('athena')
s3 = boto3.resource("s3")

#run query
queryStart = client.start_query_execution(
    QueryString = '
      #PUT_YOUR_QUERY_HERE
      SELECT *
      FROM "db_name"."table_name"
      WHERE value > 50
    ',
    QueryExecutionContext = {
      'Database': "covid_data" //YOUR_ATHENA_DATABASE_NAME
    },
    ResultConfiguration = {
      #query result output location you mentioned in AWS Athena
      "OutputLocation": "s3://bucket-name-X/folder-Y/"
    }
  )

#executes query and waits 3 seconds
queryId = queryStart['QueryExecutionId']
time.sleep(3)

#copies newly generated csv file with appropriate name
#query result output location you mentioned in AWS Athena
queryLoc = "bucket-name-X/folder-Y/" + queryId + ".csv"

#destination location and file name
s3.Object("bucket-name-A", "report-2018.csv").copy_from(CopySource = queryLoc)

#deletes Athena generated csv and it's metadata file
response = s3.delete_object(
    Bucket='bucket-name-A',
    Key=queryId+".csv"
)
response = s3.delete_object(
    Bucket='bucket-name-A',
    Key=queryId+".csv.metadata"
)
print('{file-name} csv generated')
</code>```

Body:
You can do so by a simple AWS Lambda function.

Change names of AWS Athena results stored in S3 bucket

client = boto3.client('athena')
s3 = boto3.resource("s3")

#run query
queryStart = client.start_query_execution(
    QueryString = '
      #PUT_YOUR_QUERY_HERE
      SELECT *
      FROM "db_name"."table_name"
      WHERE value > 50
    ',
    QueryExecutionContext = {
      'Database': "covid_data" //YOUR_ATHENA_DATABASE_NAME
    },
    ResultConfiguration = {
      #query result output location you mentioned in AWS Athena
      "OutputLocation": "s3://bucket-name-X/folder-Y/"
    }
  )

#executes query and waits 3 seconds
queryId = queryStart['QueryExecutionId']
time.sleep(3)

#copies newly generated csv file with appropriate name
#query result output location you mentioned in AWS Athena
queryLoc = "bucket-name-X/folder-Y/" + queryId + ".csv"

#destination location and file name
s3.Object("bucket-name-A", "report-2018.csv").copy_from(CopySource = queryLoc)

#deletes Athena generated csv and it's metadata file
response = s3.delete_object(
    Bucket='bucket-name-A',
    Key=queryId+".csv"
)
response = s3.delete_object(
    Bucket='bucket-name-A',
    Key=queryId+".csv.metadata"
)
print('{file-name} csv generated')


问:
Vue Reactivity: Why replacing an object's property (array) does not trigger update
I have a Vue app where I'm trying to make a thin wrapper over the Mapbox API. I have a component which has some simple geojson data, and when that data is updated I want to call a render function on the map to update the map with that new data. A Vue watcher should be able to accomplish this. However, my watcher isn't called when the data changes and I suspect that this is one of the cases that vue reactivity can't catch. I'm aware that I can easily fix this problem using this.$set, but I'm curious as to why this isn't a reactive update, even though according to my understanding of the rules it should be. Here's the relevant data model:

```<code>data() {
  return{
    activeDestinationData: {
      type: "FeatureCollection",
      features: []
    }
  }
}
</code>```

Then I have a watcher:

```<code>watch: {
  activeDestinationData(newValue) {
    console.log("Active destination updated");
    if (this.map && this.map.getSource("activeDestinations")) {
      this.map.getSource("activeDestinations").setData(newValue);
    }
  },
}
</code>```

Finally, down in my app logic, I update the features on the activeDestination by completely reassigning the array to a new array with one item:

```<code>// Feature is a previously declared single feature
this.activeDestinationData.features = [feature];
</code>```

For some reason the watcher is never called. I read about some of the reactivity "gotchas" here but neither of the two cases apply here:

Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

When you modify the length of the array, e.g. vm.items.length = newLength

What am I missing here that's causing the reactivity to not occur? And is my only option for intended behavior this.set() or is there a more elegant solution?

答:
If you need to watch a deep structure, you must write some params

```<code>watch: {
  activeDestinationData: {
      deep: true,
      handler() { /* code... */ }
}
</code>```

You can read more there -> https://v2.vuejs.org/v2/api/#watch
I hope I helped you :)

Body:
I have a Vue app where I'm trying to make a thin wrapper over the Mapbox API. I have a component which has some simple geojson data, and when that data is updated I want to call a render function on the map to update the map with that new data. A Vue watcher should be able to accomplish this. However, my watcher isn't called when the data changes and I suspect that this is one of the cases that vue reactivity can't catch. I'm aware that I can easily fix this problem using this.$set, but I'm curious as to why this isn't a reactive update, even though according to my understanding of the rules it should be. Here's the relevant data model:

data() {
  return{
    activeDestinationData: {
      type: "FeatureCollection",
      features: []
    }
  }
}

Then I have a watcher:

watch: {
  activeDestinationData(newValue) {
    console.log("Active destination updated");
    if (this.map && this.map.getSource("activeDestinations")) {
      this.map.getSource("activeDestinations").setData(newValue);
    }
  },
}

Finally, down in my app logic, I update the features on the activeDestination by completely reassigning the array to a new array with one item:

// Feature is a previously declared single feature
this.activeDestinationData.features = [feature];

For some reason the watcher is never called. I read about some of the reactivity "gotchas" here but neither of the two cases apply here:

Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

When you modify the length of the array, e.g. vm.items.length = newLength

What am I missing here that's causing the reactivity to not occur? And is my only option for intended behavior this.set() or is there a more elegant solution?

Body:
If you need to watch a deep structure, you must write some params

watch: {
  activeDestinationData: {
      deep: true,
      handler() { /* code... */ }
}

You can read more there -> https://v2.vuejs.org/v2/api/#watch
I hope I helped you :)


问:
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception:
(I'm getting an exception when I'm trying to add a new user)

```<code>.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]
</code>```

Here is my js. GET method works fine.

```<code>$(document).ready(function () {
  gettingListOfUsers();
  addingUser();
});

function gettingListOfUsers() {
  $.ajax({
     url: '/rest/users',
     type: 'GET',
     dataType: 'json',
     success: function (listOfUsers) {
        let userData = '';
        $.each(listOfUsers, function (index, user) {
            userData += '<tr>';
            userData += '<td>' + user.id + '</td>';
            userData += '<td>' + user.firstName + '</td>';
            userData += '<td>' + user.secondName + '</td>';
            userData += '<td>' + user.email + '</td>';
            userData += '<td>' + user.role + '</td>';
            userData += '<td> <button class="btn btn-info" data-toggle="modal">update</button> ' +
                '<a class="btn btn-danger" onclick="if (!(confirm(\'Are you sure you want to delete this user?\'))) ' +
                'return false">delete</a></td>';

            userData += '</tr>';
        });

        $('#userTable2').html(userData);
    },

    error: function (error) {
        alert("Error");
    }
})
}

function addingUser() {
$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serializeArray();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: JSON.stringify(addingFormData),
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
}
</code>```

My programm don't even get till controller. It falls in error block

@PostMapping("/adding")

```<code>public ResponseEntity<User> addingPost(@RequestBody User user) {

    HttpHeaders httpHeaders = new HttpHeaders();

    user.setPassword(passwordEncoder.encode(user.getPassword()));

    userService.addUser(user);

    return new ResponseEntity<>(user, httpHeaders, HttpStatus.CREATED);
}
</code>```

答: The error message says exactly what's wrong. It wants to create a User out of a piece of jason (expecting a jason object), but the string you send from the request starts with [, which denotes an array.

Body:
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception:
(I'm getting an exception when I'm trying to add a new user)

.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]

Here is my js. GET method works fine.

$(document).ready(function () {
  gettingListOfUsers();
  addingUser();
});

function gettingListOfUsers() {
  $.ajax({
     url: '/rest/users',
     type: 'GET',
     dataType: 'json',
     success: function (listOfUsers) {
        let userData = '';
        $.each(listOfUsers, function (index, user) {
            userData += '
';
            userData += '' + user.id + '	';
            userData += '' + user.firstName + '	';
            userData += '' + user.secondName + '	';
            userData += '' + user.email + '	';
            userData += '' + user.role + '	';
            userData += ' <button class="btn btn-info" data-toggle="modal">update</button> ' +
                'delete	';

            userData += '
';
        });

        $('#userTable2').html(userData);
    },

    error: function (error) {
        alert("Error");
    }
})
}

function addingUser() {
$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serializeArray();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: JSON.stringify(addingFormData),
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
}

My programm don't even get till controller. It falls in error block

@PostMapping("/adding")

public ResponseEntity<User> addingPost(@RequestBody User user) {

    HttpHeaders httpHeaders = new HttpHeaders();

    user.setPassword(passwordEncoder.encode(user.getPassword()));

    userService.addUser(user);

    return new ResponseEntity<>(user, httpHeaders, HttpStatus.CREATED);
}


问:
How to find if the previous character is the same
I am trying to create a calculator.

My problem is the buttons could be double clicked creating 2 of the same characters next to each other (Example: 2++2). I want to remove the second plus sign.

So far I've managed to use this:

if(!y.includes("+")) {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}
```

But this will only allow 1 plus sign and would disable any other. My intended solution should be this (3+3+3) and not this (3++3). Hopefully this is understandable.

答:
Simply check last character y[y.length - 1] is not +.

if(y && y.length >0  && y[y.length - 1] !== "+") {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}```

Body:
I am trying to create a calculator.

My problem is the buttons could be double clicked creating 2 of the same characters next to each other (Example: 2++2). I want to remove the second plus sign.

So far I've managed to use this:

if(!y.includes("+")) {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}

But this will only allow 1 plus sign and would disable any other. My intended solution should be this (3+3+3) and not this (3++3). Hopefully this is understandable.


答:
as default vue will do a shallow compare, and since you are mutating the array rather than replacing, its reference value is the same. you need to pass a new array reference when updating its content, or pass the option deep: true to look into nested values changes as:

```<code>watch: {
  activeDestinationData: {
    handler(newValue) {
      console.log("Active destination updated");
      if (this.map && this.map.getSource("activeDestinations")) {
        this.map.getSource("activeDestinations").setData(newValue);
      }
    },
    deep: true
  }
}
</code>```

Title: Vue Reactivity: Why replacing an object's property (array) does not trigger update

Body:
as default vue will do a shallow compare, and since you are mutating the array rather than replacing, its reference value is the same. you need to pass a new array reference when updating its content, or pass the option deep: true to look into nested values changes as:

watch: {
  activeDestinationData: {
    handler(newValue) {
      console.log("Active destination updated");
      if (this.map && this.map.getSource("activeDestinations")) {
        this.map.getSource("activeDestinations").setData(newValue);
      }
    },
    deep: true
  }
}


问:
Unable to debug SQL Server 2005 stored procedures in Visual Studio Team System 2008
I have been trying to debug SQL Server 2005 stored procedures, in Visual Studio Team System 2008.

I connected to the database server and did a right-click "Execute", on the stored procedure.  I even tried "Step Into Stored Procedure", with no luck.

(source: googlepages.com)

The IDE shows it is running, but I can not seem to break or step into the stored procedure.

(source: googlepages.com)

I have checked the event viewer and there are no logs.  There are no output or messages showing where the problem is.

Visual studio contains the following components :-

(source: googlepages.com)

Loads of forums mention debugging issues, but no simple solution were found.

Am I missing something ? Or does anyone know of a more concise site, that walks through successfull stored procedure debugging  ?

答: Remember that you also have to have admin privileges on the sql server box that you're debugging on. In the past, I've had to use the RunAs option in the explorer context menu to start Visual Studio. I use the same credentials as the admin user on the sql server box.</p>

OwnerDisplayName: Ferds

LastEditorDisplayName: gbn

OwnerDisplayName: damagednoob

ContentLicense: CC BY-SA 2.5


问:
Invoke web request based on system information
Ok so What I would like is a script that uses the invoke web request command based on a given system info.
So let's say i have two different installers one for a Nvidia gpu system and another for an AMD gpu system, I can already get the gpu info using another script, and save it to a html link or a text file, but how can I use this information, using invoke web request, to download the right installer?

This is the VB script I use to fetch the GPU info:

strComputer = "."
  Set objWMIService = GetObject("winmgmts:\\" & strComputer &"\root\CIMV2")
    Set colItems = objWMIService.ExecQuery( _ "SELECT *FROM Win32_VideoController",,48)
    For Each objItem in colItems
    Wscript.Echo "-----------------------------------"
    Wscript.Echo "Win32_VideoController instance"
    Wscript.Echo "-----------------------------------"
    Wscript.Echo"Caption:"&objItem.Caption
Next
```

答:
You don't need to mix-and-match VBS and PowerShell, PowerShell is perfectly capable of querying WMI on its own!

Use Where-Object to filter the results based on the Caption value, then use an if statement to determine whether any of each type was found:

```<code>$allVideoControllers = Get-CimInstance -Class Win32_VideoController

if($allVideoControllers |Where-Object Caption -like '*NVidia*'){
    # Found an nvdia card, download and run the nvidia installer in here
}

if($allVideoControllers |Where-Object Caption -like '*AMD*'){
    # Found an AMD card, download and run the AMD installer in here
}
</code>```

Body:
You don't need to mix-and-match VBS and PowerShell, PowerShell is perfectly capable of querying WMI on its own!

Use Where-Object to filter the results based on the Caption value, then use an if statement to determine whether any of each type was found:

$allVideoControllers = Get-CimInstance -Class Win32_VideoController

if($allVideoControllers |Where-Object Caption -like '*NVidia*'){
    # Found an nvdia card, download and run the nvidia installer in here
}

if($allVideoControllers |Where-Object Caption -like '*AMD*'){
    # Found an AMD card, download and run the AMD installer in here
}