问:
Delete post method returns null
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

```<code> // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }
</code>```

and here is my View

```<code>@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

    <div class="border p-3">

        <div class="form-group row">
            <h2 class="text-info pl-3">Delete Category</h2>
        </div>
        <div class="row">
            <div class="col-8">
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="CategoryName"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="CategoryName" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="DisplayOrder"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="DisplayOrder" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-8 offset-4 row">

                        <div class="col">
                            <input type="submit" class="btn btn-danger w-100" value="Delete" />
                        </div>
                        <div class="col">
                            <a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-4">
                @* Keep this empty *@
            </div>
        </div>
    </div>

</form>
</code>```

Any help or suggestion would be very appreciated, thanks!

答:
add name tag to input, for example :

```<code><input name="id" asp-for="CategoryId" hidden />
</code>```

Alex

Title: Delete post method returns null

Body:
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

 // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }

and here is my View

@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

Delete Category

                        <input asp-for="CategoryName" disabled class="form-control" />

                        <input asp-for="DisplayOrder" disabled class="form-control" />

                            <input type="submit" class="btn btn-danger w-100" value="Delete" />

                             Back

                @* Keep this empty *@

</form>

Any help or suggestion would be very appreciated, thanks!

Body:
add name tag to input, for example :

<input name="id" asp-for="CategoryId" hidden />

Alex


来源: stackexchange

问:
How do I import SlickUtils?
I'm attempting to import SlickUtils into my project, but I can't figure out how.

For example - to import ArrayList i'd do

```<code>import java.util.Arraylist;
</code>```

Could someone let me know how to do this with SlickUtils?

Thanks.

答:
This looks like an external library, which is not bundled with java. You can do this two ways.

Option one is to manually add this to Jar to your build path. You can look up how to do this with whichever IDE you are using, it should be simple.

Option two is to do this is with a build tool like Maven, which I would recommend over the first option if you plan on using more libraries.

Here is the dependency - https://mvnrepository.com/artifact/slick-util/slick-util/1.0.0

If you want to add it to your build path manually you can download the jar file from here. If you plan to use it with maven you can copy the text and add it to your POM file. After you can access the JAR in your project you should be able to import it just like any other class.

ContentLicense: CC BY-SA 4.0

Title: How do I import SlickUtils?

Body:
I'm attempting to import SlickUtils into my project, but I can't figure out how.

For example - to import ArrayList i'd do

import java.util.Arraylist;

Could someone let me know how to do this with SlickUtils?

Thanks.


问:
PHP & Parsing a JSON response
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

```<code><?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

<html>
    <title>Test Rhyme</title>
<body>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>
    <div id="results">
        <?php
            print_r(json_decode($result, true));
        ?>
    </div>
</body>

</html>
</code>```

答:
Check here: http://php.net/manual/en/function.curl-exec.php. The one noteworthy thing I saw was this:

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Note that there is a great example if you search for "curl_get(".

ContentLicense: CC BY-SA 3.0

Title: PHP & Parsing a JSON response

Body:
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

<?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

    <title>Test Rhyme</title>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>

        <?php
            print_r(json_decode($result, true));
        ?>


问:
NextJs vercel deployment error "routes-manifest.json" couldn't be found
My nextjs app was working properly I added some files to update my code now it is not deploying my app on vercel. gives this error

I tried googling the error but my case in unique.

This is the git repo
https://github.com/usman-174/google-calendar-frontend

These are my script tags from package.json

```<code> "scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"export": "next export",
"lint": "next lint",
"lint-fix": "next lint --fix"
},
</code>```

next.config.js

```<code>module.exports = {
distDir: 'build',
}
</code>```

答:
Run npm run build (check all files in builded folder)

Create .next folder and move all files from build folder to .next

Commit your .next folder to vercel or maybe git.

Body:
My nextjs app was working properly I added some files to update my code now it is not deploying my app on vercel. gives this error

I tried googling the error but my case in unique.

This is the git repo
https://github.com/usman-174/google-calendar-frontend

These are my script tags from package.json

 "scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"export": "next export",
"lint": "next lint",
"lint-fix": "next lint --fix"
},

next.config.js

module.exports = {
distDir: 'build',
}


问:
How do I make background Image on each division row from URL
I need to display different background URL on each row base on the item in MySQL. I use php mySQL fetch array to get the item name and background URL. So far,  I was able to get the URL background and display in row by using CSS,  but every time I choose different item all division row get's overwritten by this new background. This result to have duplicate background.
I have attached of sample image where the background image of division row got overwritten and duplicate image.

[Duplicate Row Background][1]  [1]: https://i.stack.imgur.com/qxLOI.png

Snippet of Php fetch array to echo the division and the CSS id of Background Image.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>while ($row = mysqli_fetch_array($query))
                    {
                        $pro_id = $row['pro_id'];

                                $sql1 = "SELECT * FROM products WHERE product_id = '$pro_id' ";
                                $query1 = mysqli_query($conn , $sql1);
                                while ($row1 = mysqli_fetch_array($query1))
                                {

                                    $id = $row1['product_id'];
                                    $name = $row1['product_title'];
                                    $element = $row1['product_price'];
                                    $faction = $row1['product_description'];
                                    $picture = $row1['product_image'];
                                    $class = $row1['product_keywords'];
                                    $rarity = $row1['sales'];
                                    $bgurl = $row1['bgurl'];

                                echo
                                '

                                   <div class="container" id ="background-container">

                                    <div class="row pt-2 pb-1" style="border-top: .5px  solid grey; border-bottom: .5px  solid grey;" >
                                    <div class="col-4" >
                                        <p class="squad1-title" >'.$bgurl.'</p>
                                    </div>
                                    <div class="col-7">

                                    </div>

                                    <div class="remove" >
                                        <i class="fa fa-minus-square removeitem" style="padding center" data-proid="'.$id.'" title="Remove"> </i>
                                    </div>
                                    </div>
                                   </div>
                                ';
                                }
                    }</code>```

答:
ID's are used for one and only element in the page, you will need to switch to classes if you want to style multiple elements.

That being said, you can overwrite a css property by including it in the style property of an element

```<code><?php
    echo `<div class="container" style="background-image: url(` . $bgurl . `)">`
    ...
?>
</code>```

Body:
I need to display different background URL on each row base on the item in MySQL. I use php mySQL fetch array to get the item name and background URL. So far,  I was able to get the URL background and display in row by using CSS,  but every time I choose different item all division row get's overwritten by this new background. This result to have duplicate background.
I have attached of sample image where the background image of division row got overwritten and duplicate image.

[Duplicate Row Background][1]  [1]: https://i.stack.imgur.com/qxLOI.png

Snippet of Php fetch array to echo the division and the CSS id of Background Image.

while ($row = mysqli_fetch_array($query))
                    {
                        $pro_id = $row['pro_id'];

                                $sql1 = "SELECT * FROM products WHERE product_id = '$pro_id' ";
                                $query1 = mysqli_query($conn , $sql1);
                                while ($row1 = mysqli_fetch_array($query1))
                                {

                                    $id = $row1['product_id'];
                                    $name = $row1['product_title'];
                                    $element = $row1['product_price'];
                                    $faction = $row1['product_description'];
                                    $picture = $row1['product_image'];
                                    $class = $row1['product_keywords'];
                                    $rarity = $row1['sales'];
                                    $bgurl = $row1['bgurl'];

                                echo
                                '

'.$bgurl.'

                                ';
                                }
                    }

Body:
ID's are used for one and only element in the page, you will need to switch to classes if you want to style multiple elements.

That being said, you can overwrite a css property by including it in the style property of an element

<?php
    echo `<div class="container" style="background-image: url(` . $bgurl . `)">`
    ...
?>


问:
How to have right arow behavior in a console
I am trying to recreate a line editor in a bare metal environnement :
a chip receiving and sending data in an UART.

The UART is linked to a keyboard on input and a screen on output.

To simulate left arrow, i send the character \b.
I cannot find how to go right.

About memory solution

For now our system only send back the characters back to the UART to display it on the screen. There is no memory usage.

I thought of some solutions that need to memorize all the text inputed, for example the second part proposed in the @ikegami answer.

My question could then be :

The screen can understand \b as a backward move of the cursor. Is there a similar way to do it forward ? Or am i forced to compute it in the chip ?

答:
\b was probably originally for printers. One could use it to print two characters on top of each other (e.g. A and _ to create an underlined A, or A and A to create a bold A).

To move forward on a printer, one can simply print a space. Of course, on a terminal, that usually erases the existing character.

Enter ANSI escape sequences. Maybe these will work for you. For example, printing "\e[C" will move the cursor forward one (up to the limits of the terminal) on some terminals.

$ perl -e'
   print "abcd";
   print "\e[D\e[D\e[D";  # Go back
   print "e";             # Edit
   print "\e[C\e[C";      # Move forward
   print "f";             # Add more to the end
   print "\e[C";          # Move forward
   print "g\n";           # Add more to the end
'
aecdf g
```
<p>(The choice of language isn't relevant. It's just more compact to demo using Perl.)</p>
<p>Alternatively, print a space. If that would overwrite a character you don't want overwritten, remember what that character is and print that character instead of a space.</p>
<pre class="lang-none prettyprint-override"><code>$ perl -e'
   print "abcd";
   print "\b\b\b";        # Go back
   print "e";             # Edit
   print "cd";            # Move forward
   print "f";             # Add more to the end
   print " ";             # Move forward
   print "g\n";
'
aecdf g
</code>```

Body:
\b was probably originally for printers. One could use it to print two characters on top of each other (e.g. A and _ to create an underlined A, or A and A to create a bold A).

To move forward on a printer, one can simply print a space. Of course, on a terminal, that usually erases the existing character.

Enter ANSI escape sequences. Maybe these will work for you. For example, printing "\e[C" will move the cursor forward one (up to the limits of the terminal) on some terminals.

$ perl -e'
   print "abcd";
   print "\e[D\e[D\e[D";  # Go back
   print "e";             # Edit
   print "\e[C\e[C";      # Move forward
   print "f";             # Add more to the end
   print "\e[C";          # Move forward
   print "g\n";           # Add more to the end
'
aecdf g

(The choice of language isn't relevant. It's just more compact to demo using Perl.)

Alternatively, print a space. If that would overwrite a character you don't want overwritten, remember what that character is and print that character instead of a space.

$ perl -e'
   print "abcd";
   print "\b\b\b";        # Go back
   print "e";             # Edit
   print "cd";            # Move forward
   print "f";             # Add more to the end
   print " ";             # Move forward
   print "g\n";
'
aecdf g


问:
kubectl exec command not working from powershell ISE (works from powershell) - Is there a reason or workaround to make it work?
I have recently started working with Kubernetes and Docker and still new with how it all works. I have made a ps1 script to run all the steps I need to do to build image and execute image on Kubernetes.

What I see is all steps work fine on ISE (except this one: "kubectl exec -it test-runner pwsh"). For this step alone, I have to run it on another PowerShell window.

When I run this step in ISE, the script keeps running without ever giving any error or stopping.

Does anyone know if its a limitation with Kubernetes working on ISE or if there is a workaround to make it work?

Working with ISE is quick and saves me tons of time, so this really makes a difference when I have to copy, paste, enter this each time in a separate PowerShell window.

Thanks in advance for your help!

P.S: I looked at other suggested similar questions/answers and none of them seem to be related to Kubernetes not working on ISE. Hence this question.

command:

```<code>kubectl exec -it test-runner pwsh
</code>```

Expected (and actual when running from PowerShell console):

```<code>----------------------
PS C:\windows\system32> kubectl exec -it test-runner pwsh
PowerShell 6.2.2
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /test>
-----------------------------
Actual (when running from PowerShell ISE):

PS C:\SourceCodeTLM\Apollo>  kubectl exec -it test-runner pwsh
PowerShell 6.2.2
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

(with a blinking cursor and script running without breaking and changing to the new path)...
-----------------------------------------------
</code>```

答:
You could open a command window from PowerShell and send the command to open the shell.</p>
```<code>Start-Process PowerShell -Wait "-NoProfile -ExecutionPolicy Bypass -Command `"kubectl exec helloworld-web-8495f4c888-jw2tg -n local-v1 -it -- /bin/bash`""
</code>```

Body:
I have recently started working with Kubernetes and Docker and still new with how it all works. I have made a ps1 script to run all the steps I need to do to build image and execute image on Kubernetes.

What I see is all steps work fine on ISE (except this one: "kubectl exec -it test-runner pwsh"). For this step alone, I have to run it on another PowerShell window.

When I run this step in ISE, the script keeps running without ever giving any error or stopping.

Does anyone know if its a limitation with Kubernetes working on ISE or if there is a workaround to make it work?

Working with ISE is quick and saves me tons of time, so this really makes a difference when I have to copy, paste, enter this each time in a separate PowerShell window.

Thanks in advance for your help!

P.S: I looked at other suggested similar questions/answers and none of them seem to be related to Kubernetes not working on ISE. Hence this question.

command:

kubectl exec -it test-runner pwsh

Expected (and actual when running from PowerShell console):

----------------------
PS C:\windows\system32> kubectl exec -it test-runner pwsh
PowerShell 6.2.2
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /test>
-----------------------------
Actual (when running from PowerShell ISE):

PS C:\SourceCodeTLM\Apollo>  kubectl exec -it test-runner pwsh
PowerShell 6.2.2
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

(with a blinking cursor and script running without breaking and changing to the new path)...
-----------------------------------------------

Body:
You could open a command window from PowerShell and send the command to open the shell.

Start-Process PowerShell -Wait "-NoProfile -ExecutionPolicy Bypass -Command `"kubectl exec helloworld-web-8495f4c888-jw2tg -n local-v1 -it -- /bin/bash`""


问:
pvlib - bifacial.pvfactors_timeseries() ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
I'm working with pvlib/pvfactors bifacial.pvfactors_timeseries and I'm having some issues with the timestamps. I use a DatetimeIndex as it can be seen:

```<code>times = pd.date_range('2021-01-01', '2021-01-02', closed='left', freq='1min',
                  tz=None)
rear_rad=bifacial.pvfactors_timeseries(
solar_azimuth=235.7,
solar_zenith=75.6,
surface_azimuth=270.0, #cte
surface_tilt=-72.8, #tracker
axis_azimuth=180.0, #cte
timestamps=times,
dni=29.0,
dhi=275.0,
gcr=0.2,
pvrow_height=2.0,
pvrow_width=2.0,
albedo=0.2, #variable mensual
n_pvrows=3,
index_observed_pvrow=1,
rho_front_pvrow=0.03, #reflectividad
rho_back_pvrow=0.05, #refletividad
horizon_band_angle=15.0)
</code>```

I always end up having this Error:

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

The full traceback of the error is:

File "****", line 18, in
rear_rad=bifacial.pvfactors_timeseries(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvlib\bifacial.py", line 141, in pvfactors_timeseries
report = run_timeseries_engine(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\run.py", line 106, in run_timeseries_engine
eng.fit(timestamps, dni, dhi, solar_zenith, solar_azimuth, surface_tilt,

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\engine.py", line 161, in fit
self.irradiance.fit(timestamps, DNI, DHI, solar_zenith, solar_azimuth,

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\models.py", line 527, in fit
self._calculate_luminance_poa_components(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\models.py", line 993, in _calculate_luminance_poa_components
df_inputs = perez_diffuse_luminance(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\utils.py", line 63, in perez_diffuse_luminance
dni_et = irradiance.get_extra_radiation(df_inputs.index.dayofyear)

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pandas\core\indexes\extension.py", line 81, in fget
result = getattr(self._data, name)

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pandas\core\arrays\datetimes.py", line 139, in f
result = fields.get_date_field(values, field)

File "pandas_libs\tslibs\fields.pyx", line 305, in pandas._libs.tslibs.fields.get_date_field

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

答:
The problem is that some of the parameters to pvfactors_timeseries need to be arrays, Series, etc, not scalars like you are using.  This usability issue has already been noticed should be fixed in the next pvlib release (0.9.1, not yet released); see https://github.com/pvlib/pvlib-python/issues/1332

This modified version of your code runs without error:

rear_rad = bifacial.pvfactors_timeseries(
    solar_azimuth=pd.Series(235.7, times),
    solar_zenith=pd.Series(75.6, times),
    surface_azimuth=pd.Series(270.0, times), #cte
    surface_tilt=pd.Series(-72.8, times), #tracker
    axis_azimuth=180.0, #cte
    timestamps=times,
    dni=pd.Series(29.0, times),
    dhi=pd.Series(275.0, times),
    gcr=0.2,
    pvrow_height=2.0,
    pvrow_width=2.0,
    albedo=0.2, #variable mensual
    n_pvrows=3,
    index_observed_pvrow=1,
    rho_front_pvrow=0.03, #reflectividad
    rho_back_pvrow=0.05, #refletividad
    horizon_band_angle=15.0,
 )
```

One other thing: pvlib expects surface_tilt to be non-negative, and I'm not sure what the function will return for a negative surface_tilt.  Note that, in the pvlib convention, a tracker rotation can be positive or negative to indicate whether it is a tilt to the east or west, but surface_tilt is always positive (or zero) and the east/west direction is represented by surface_azimuth.

P.S. it is good practice, when things aren't working like you expect, it is good practice to mention the package version you have installed (see print(pvlib.__version__) or pip show pvlib).  Sometimes things change between versions and the answer depends on what version you are using.

Body:
I'm working with pvlib/pvfactors bifacial.pvfactors_timeseries and I'm having some issues with the timestamps. I use a DatetimeIndex as it can be seen:

times = pd.date_range('2021-01-01', '2021-01-02', closed='left', freq='1min',
                  tz=None)
rear_rad=bifacial.pvfactors_timeseries(
solar_azimuth=235.7,
solar_zenith=75.6,
surface_azimuth=270.0, #cte
surface_tilt=-72.8, #tracker
axis_azimuth=180.0, #cte
timestamps=times,
dni=29.0,
dhi=275.0,
gcr=0.2,
pvrow_height=2.0,
pvrow_width=2.0,
albedo=0.2, #variable mensual
n_pvrows=3,
index_observed_pvrow=1,
rho_front_pvrow=0.03, #reflectividad
rho_back_pvrow=0.05, #refletividad
horizon_band_angle=15.0)

I always end up having this Error:

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

The full traceback of the error is:

File "****", line 18, in
rear_rad=bifacial.pvfactors_timeseries(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvlib\bifacial.py", line 141, in pvfactors_timeseries
report = run_timeseries_engine(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\run.py", line 106, in run_timeseries_engine
eng.fit(timestamps, dni, dhi, solar_zenith, solar_azimuth, surface_tilt,

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\engine.py", line 161, in fit
self.irradiance.fit(timestamps, DNI, DHI, solar_zenith, solar_azimuth,

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\models.py", line 527, in fit
self._calculate_luminance_poa_components(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\models.py", line 993, in _calculate_luminance_poa_components
df_inputs = perez_diffuse_luminance(

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pvfactors\irradiance\utils.py", line 63, in perez_diffuse_luminance
dni_et = irradiance.get_extra_radiation(df_inputs.index.dayofyear)

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pandas\core\indexes\extension.py", line 81, in fget
result = getattr(self._data, name)

File "C:\Users\tomas.rodriguez\Anaconda3\lib\site-packages\pandas\core\arrays\datetimes.py", line 139, in f
result = fields.get_date_field(values, field)

File "pandas_libs\tslibs\fields.pyx", line 305, in pandas._libs.tslibs.fields.get_date_field

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

Body:
The problem is that some of the parameters to pvfactors_timeseries need to be arrays, Series, etc, not scalars like you are using.  This usability issue has already been noticed should be fixed in the next pvlib release (0.9.1, not yet released); see https://github.com/pvlib/pvlib-python/issues/1332

This modified version of your code runs without error:

rear_rad = bifacial.pvfactors_timeseries(
    solar_azimuth=pd.Series(235.7, times),
    solar_zenith=pd.Series(75.6, times),
    surface_azimuth=pd.Series(270.0, times), #cte
    surface_tilt=pd.Series(-72.8, times), #tracker
    axis_azimuth=180.0, #cte
    timestamps=times,
    dni=pd.Series(29.0, times),
    dhi=pd.Series(275.0, times),
    gcr=0.2,
    pvrow_height=2.0,
    pvrow_width=2.0,
    albedo=0.2, #variable mensual
    n_pvrows=3,
    index_observed_pvrow=1,
    rho_front_pvrow=0.03, #reflectividad
    rho_back_pvrow=0.05, #refletividad
    horizon_band_angle=15.0,
 )

One other thing: pvlib expects surface_tilt to be non-negative, and I'm not sure what the function will return for a negative surface_tilt.  Note that, in the pvlib convention, a tracker rotation can be positive or negative to indicate whether it is a tilt to the east or west, but surface_tilt is always positive (or zero) and the east/west direction is represented by surface_azimuth.

P.S. it is good practice, when things aren't working like you expect, it is good practice to mention the package version you have installed (see print(pvlib.__version__) or pip show pvlib).  Sometimes things change between versions and the answer depends on what version you are using.


问:
open_basedir not having any effect
For my web hosting panel, users need to be blocked from accessing files outside their own directory (/var/www/u/s/username). I tried to use this line in httpd.conf to prevent people from going up a directory.

```<code><Directory /var/www/users/>
php_admin_value open_basedir .:/usr/lib/php5
</Directory>
</code>```

But in php.ini, it seems to have no effect. What am I doing wrong?

答: Most probably you're modifying the wrong "php.ini".</p>

OwnerDisplayName: phpscriptcoder

Title: open_basedir not having any effect

Body:
For my web hosting panel, users need to be blocked from accessing files outside their own directory (/var/www/u/s/username). I tried to use this line in httpd.conf to prevent people from going up a directory.

<Directory /var/www/users/>
php_admin_value open_basedir .:/usr/lib/php5
</Directory>

But in php.ini, it seems to have no effect. What am I doing wrong?

OwnerDisplayName: Milen A. Radev

ContentLicense: CC BY-SA 2.5


问:
visual studio problem with including c++ header files
Hi I got a problem with including header files with Visual Studio. The code is here:

Graph.h

```<code>#pragma once

#include <iostream>

template<typename T>
class Graph
{
public:
    Graph(int s);
    void print_graph() const;
protected:
    T** graph;
    int size;
};
</code>```

Graph.cpp

```<code>
#include "Graph.h"

template<typename T>
Graph<T>::Graph(int s)
{
    size = s;

    // create 2D array
    graph = new T * [size];
    for (int i = 0; i < size; i++)
    {
        graph[i] = new T[size];
    }
}

template<typename T>
void Graph<T>::print_graph() const
{
    // print the bool matrix
    std::cout << "Graph: \n";
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
            std::cout << graph[i][j] << " ";
        std::cout << std::endl;
    }
}
</code>```

main cpp

```<code>#include <iostream>
#include "Graph.h"

int main()
{
     Graph<int> g(10);
     g.print_graph();

    return 0;
}
</code>```

I always get error messages like,
Error   LNK2019 unresolved external symbol "public: __cdecl Graph::Graph(int)" (??0?$Graph@H@@QEAA@H@Z) referenced in function main.

If I put everything in only one single main file (no need to include at all), everything works.

But surprisingly, if I change #include "Graph.h" to #include "Graph.cpp", the program compiles.
Thanks very much for your help!

答:
The problem is you can't do the normal .h file / .cpp file split with a class template.

This is just the way templates are. In order for the compiler to be able to instantiate a template it needs to be able to "see" the whole thing, meaning the definition not just the declaration, and further a file like your "graph.cpp" can't really be compiled into an object file. Templates are not real class definitions; they are like class definition instructions that turn it into "real" classes when they are instantiated with types.

In any case, you want to just put your whole Graph definition in the .h file and put an include guard in there so it doesnt get included multiple times.

Body:
Hi I got a problem with including header files with Visual Studio. The code is here:

Graph.h

#pragma once

#include <iostream>

template<typename T>
class Graph
{
public:
    Graph(int s);
    void print_graph() const;
protected:
    T** graph;
    int size;
};

Graph.cpp

#include "Graph.h"

template<typename T>
Graph<T>::Graph(int s)
{
    size = s;

    // create 2D array
    graph = new T * [size];
    for (int i = 0; i < size; i++)
    {
        graph[i] = new T[size];
    }
}

template<typename T>
void Graph<T>::print_graph() const
{
    // print the bool matrix
    std::cout << "Graph: \n";
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
            std::cout << graph[i][j] << " ";
        std::cout << std::endl;
    }
}

main cpp

#include <iostream>
#include "Graph.h"

int main()
{
     Graph<int> g(10);
     g.print_graph();

    return 0;
}

I always get error messages like,
Error   LNK2019 unresolved external symbol "public: __cdecl Graph::Graph(int)" (??0?$Graph@H@@QEAA@H@Z) referenced in function main.

If I put everything in only one single main file (no need to include at all), everything works.

But surprisingly, if I change #include "Graph.h" to #include "Graph.cpp", the program compiles.
Thanks very much for your help!


问:
Jetpack compose check if a function has been run in preview mode
Is this possible to check if a function has been run in preview mode in Jetpack compose? I have a function that returns a proper string to use in the app but this function uses some objects which disable preview mode for @Composable components. What I could do is to pass val isPreview: Boolean = false flag to every component and then run a simplified function if the flag is true but this adds some boilerplate code to every composable.

答:
I usually do this by calling LocalInspectionMode.current to know if I'm in preview mode. It returns true if in preview mode.

Here's what the documentation says about LocalInspectionMode:

Inspectable mode CompositionLocal. True if the composition is composed inside an Inspectable component.


问:
MERN, passport, blocked by CORS policy. "No access-control-allow-origin header
I'm developing my final project and I'm trying to build a MERN project. I'm trying to implement an authentication with passport, and it works in development, but when I deployed I keep getting this error

Access to fetch at 'https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But if I manually access the site: https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success', I get the response I need. So I don't know if it's a problem of the server or from React.

This is my code in the server:

Index.js

```<code>const app = express();
app.use(
  cookieSession({ name: "session", keys: ["whatever"], maxAge: 24 * 60 * 60 * 100 })
);

app.use(passport.initialize());
app.use(passport.session());

dbConnection();

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);
app.use(express.static(path.join(__dirname, "/public")));

app.use(express.json());

app.use("/api/auth", authRoutes);
</code>```

AuthRoutes.js

```<code>router.get(
  "/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

// callback from google
router.get(
  "/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/api/auth/googleLogin/failed",
    successRedirect: `${process.env.CLIENT_URL}/#/auth`,
  })
  // googleAuth
);

router.get("/googleLogin/success", (req, res) => {
  console.log("success", req.user);
  if (req.user) {
    res.status(200).json({
      success: true,

      message: "successfull",
      user: req.user,
      token: req.user.token,
      //   cookies: req.cookies
    });
  }
});
</code>```

Code from React

```<code>export const AuthPage = () => {
  useEffect(() => {
    const getUser = () => {
      fetch(`${process.env.REACT_APP_API_URL}/auth/googleLogin/success`, {
        method: "GET",
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "Access-Control-Allow-Credentials": true,
        },
      })
        .then((response) => {
          console.log("THIS IS THE RESPONSE", response);
          if (response.status === 200) return response.json();
          throw new Error("authentication has been failed!");
        })
        .then((resObject) => {
          console.log("POR FAVOR********", resObject);
          localStorage.setItem("token", resObject.token);
          localStorage.setItem("token-init-date", new Date().getTime());
          dispatch(startChecking());
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getUser();
  }, []);

  return (...);
};
</code>```

Edit to add github links
Backend: https://github.com/JavierGarciaGomez/hvp2021backend
Frontend: https://github.com/JavierGarciaGomez/hvp2021frontend

enviromental variables:

```<code>React:
REACT_APP_API_URL=https://hospitalveterinariopeninsular.herokuapp.com/api
Node:
PORT=4000
CLIENT_URL=http://localhost:3000
CLIENT_URL_PROD=https://www.hospitalveterinariopeninsular.com
</code>```

答:
The order is highly sensitive on express middlewares.

In your entrypoint you have this:

```<code>app.use(passport.initialize());
app.use(passport.session());

...

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);
</code>```

Put the cors initialization before passport initialization:

```<code>// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);

....

app.use(passport.initialize());
app.use(passport.session());
</code>```

I think your passport routes are not being detected by your cors configuration because those where configured before the cors magic

Body:
I'm developing my final project and I'm trying to build a MERN project. I'm trying to implement an authentication with passport, and it works in development, but when I deployed I keep getting this error

Access to fetch at 'https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But if I manually access the site: https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success', I get the response I need. So I don't know if it's a problem of the server or from React.

This is my code in the server:

Index.js

const app = express();
app.use(
  cookieSession({ name: "session", keys: ["whatever"], maxAge: 24 * 60 * 60 * 100 })
);

app.use(passport.initialize());
app.use(passport.session());

dbConnection();

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);
app.use(express.static(path.join(__dirname, "/public")));

app.use(express.json());

app.use("/api/auth", authRoutes);

AuthRoutes.js

router.get(
  "/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

// callback from google
router.get(
  "/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/api/auth/googleLogin/failed",
    successRedirect: `${process.env.CLIENT_URL}/#/auth`,
  })
  // googleAuth
);

router.get("/googleLogin/success", (req, res) => {
  console.log("success", req.user);
  if (req.user) {
    res.status(200).json({
      success: true,

      message: "successfull",
      user: req.user,
      token: req.user.token,
      //   cookies: req.cookies
    });
  }
});

Code from React

export const AuthPage = () => {
  useEffect(() => {
    const getUser = () => {
      fetch(`${process.env.REACT_APP_API_URL}/auth/googleLogin/success`, {
        method: "GET",
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "Access-Control-Allow-Credentials": true,
        },
      })
        .then((response) => {
          console.log("THIS IS THE RESPONSE", response);
          if (response.status === 200) return response.json();
          throw new Error("authentication has been failed!");
        })
        .then((resObject) => {
          console.log("POR FAVOR********", resObject);
          localStorage.setItem("token", resObject.token);
          localStorage.setItem("token-init-date", new Date().getTime());
          dispatch(startChecking());
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getUser();
  }, []);

  return (...);
};

Edit to add github links
Backend: https://github.com/JavierGarciaGomez/hvp2021backend
Frontend: https://github.com/JavierGarciaGomez/hvp2021frontend

enviromental variables:

React:
REACT_APP_API_URL=https://hospitalveterinariopeninsular.herokuapp.com/api
Node:
PORT=4000
CLIENT_URL=http://localhost:3000
CLIENT_URL_PROD=https://www.hospitalveterinariopeninsular.com

Body:
The order is highly sensitive on express middlewares.

In your entrypoint you have this:

app.use(passport.initialize());
app.use(passport.session());

...

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);

Put the cors initialization before passport initialization:

// CORS
app.use(
  cors({
    origin: process.env.CLIENT_URL,
    methods: "GET,POST,PUT,DELETE, PATCH",
    credentials: true,
    maxAge: 3600,
  })
);

....

app.use(passport.initialize());
app.use(passport.session());

I think your passport routes are not being detected by your cors configuration because those where configured before the cors magic


问:
TypeError: attrib() got an unexpected keyword argument 'convert'
This error occurred during automated testing of a python project on the CI server using pytest. I'm using pytest==4.0.2. This error only just started to occur, previous pipelines seem to work fine.

The full error:

```<code>File "/usr/local/lib/python3.7/site-packages/_pytest/tmpdir.py", line 35, in TempPathFactory
    lambda p: Path(os.path.abspath(six.text_type(p)))
TypeError: attrib() got an unexpected keyword argument 'convert'
</code>```

答:
The issue is that with attrs==19.2.0 the convert attribute was removed (source).

attr.ib(convert=int) should be deprecated and replaced by attr.ib(converter=int)

You either need to update whatever is using attrs or you need to downgrade: pip install 'attrs<19.2.0'

Body:
This error occurred during automated testing of a python project on the CI server using pytest. I'm using pytest==4.0.2. This error only just started to occur, previous pipelines seem to work fine.

The full error:

File "/usr/local/lib/python3.7/site-packages/_pytest/tmpdir.py", line 35, in TempPathFactory
    lambda p: Path(os.path.abspath(six.text_type(p)))
TypeError: attrib() got an unexpected keyword argument 'convert'


问:
getting null pointer exception when i click on spinner to select item
I have populated spinner from webservice.The data is added to the adapter and is shown in spinner as i click on spinner.I need to do is i want the selected item from the spinner and then split it and pass the payout number to other webservice.

I am getting null pointer excetion when i add the following code on my OnItemSelectedListener as shown in following code.

Please see my code and help me by telling what i have done wrong :

Code from where i populate spinner :

```<code>        results = new JSONArray(new String(buffer));
        if (results != null) {
            Log.v("val", results.getString(0));
            for (int i = 0; i <= results.length() - 1; i++) {
                // val[i] = results.getString(i);
                String val1 = results.getString(i);
                val[i] = val1;
                val1 = "";
                Log.v("Val", "[" + i + "]" + results.getString(i));
            }
        } else {
            Log.v("results", "results are null");
        }
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, val);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn1.setAdapter(adapter);
</code>```

Code for OnItemSelectedListener of spinner :

```<code>public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        String PayoutNo = spnPayout.getItemAtPosition(pos).toString();
        Log.v("seleced item", PayoutNo);
        Toast.makeText(PayoutDetailsActivity.this, "selected item is"+PayoutNo, Toast.LENGTH_LONG).show();
        Log.v("TAG","inside on click");
        //String PayoutNo = spnPayout.getItemAtPosition(pos).toString();
        Log.v("selected item",PayoutNo);
        String[] strPayoutNo = new String[15];
        strPayoutNo = PayoutNo.split("-");
        Log.v("TAG",strPayoutNo[0]);
        getPayoutDetails(strPayoutNo[0]);//in this function i am calling another webservice
    }
    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}
</code>```

Log :

```<code>08-18 12:01:21.542: ERROR/AndroidRuntime(543): FATAL EXCEPTION: main
08-18 12:01:21.542: ERROR/AndroidRuntime(543): java.lang.NullPointerException
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:376)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:329)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:325)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.AbsListView.obtainView(AbsListView.java:1294)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ListView.onMeasure(ListView.java:1109)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.widget.WeightedLinearLayout.onMeasure(WeightedLinearLayout.java:60)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.os.Looper.loop(Looper.java:123)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at java.lang.reflect.Method.invoke(Method.java:521)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at dalvik.system.NativeStart.main(Native Method)
08-18 12:01:21.576: WARN/ActivityManager(59):   Force finishing activity com.biz.mlm/.PayoutDetailsActivity
08-18 12:01:22.163: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{450cdbd8 com.biz.mlm/.PayoutDetailsActivity}
</code>```

答:
Try like this.

```<code>MyOnItemSelectedListener myOnItemSelectedListener = new MyOnItemSelectedListener();
</code>```

---------------------

```<code>ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, val);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn1.setAdapter(adapter);
spn1.seOnItemSelectedListener( myOnItemSelectedListener);
</code>```

Body:
I have populated spinner from webservice.The data is added to the adapter and is shown in spinner as i click on spinner.I need to do is i want the selected item from the spinner and then split it and pass the payout number to other webservice.

I am getting null pointer excetion when i add the following code on my OnItemSelectedListener as shown in following code.

Please see my code and help me by telling what i have done wrong :

Code from where i populate spinner :

        results = new JSONArray(new String(buffer));
        if (results != null) {
            Log.v("val", results.getString(0));
            for (int i = 0; i <= results.length() - 1; i++) {
                // val[i] = results.getString(i);
                String val1 = results.getString(i);
                val[i] = val1;
                val1 = "";
                Log.v("Val", "[" + i + "]" + results.getString(i));
            }
        } else {
            Log.v("results", "results are null");
        }
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, val);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn1.setAdapter(adapter);

Code for OnItemSelectedListener of spinner :

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos,
            long id) {
        String PayoutNo = spnPayout.getItemAtPosition(pos).toString();
        Log.v("seleced item", PayoutNo);
        Toast.makeText(PayoutDetailsActivity.this, "selected item is"+PayoutNo, Toast.LENGTH_LONG).show();
        Log.v("TAG","inside on click");
        //String PayoutNo = spnPayout.getItemAtPosition(pos).toString();
        Log.v("selected item",PayoutNo);
        String[] strPayoutNo = new String[15];
        strPayoutNo = PayoutNo.split("-");
        Log.v("TAG",strPayoutNo[0]);
        getPayoutDetails(strPayoutNo[0]);//in this function i am calling another webservice
    }
    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

Log :

08-18 12:01:21.542: ERROR/AndroidRuntime(543): FATAL EXCEPTION: main
08-18 12:01:21.542: ERROR/AndroidRuntime(543): java.lang.NullPointerException
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:376)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:329)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:325)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.AbsListView.obtainView(AbsListView.java:1294)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.ListView.onMeasure(ListView.java:1109)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.widget.WeightedLinearLayout.onMeasure(WeightedLinearLayout.java:60)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.View.measure(View.java:8171)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.os.Looper.loop(Looper.java:123)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at java.lang.reflect.Method.invoke(Method.java:521)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-18 12:01:21.542: ERROR/AndroidRuntime(543):     at dalvik.system.NativeStart.main(Native Method)
08-18 12:01:21.576: WARN/ActivityManager(59):   Force finishing activity com.biz.mlm/.PayoutDetailsActivity
08-18 12:01:22.163: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{450cdbd8 com.biz.mlm/.PayoutDetailsActivity}

Body:
Try like this.

MyOnItemSelectedListener myOnItemSelectedListener = new MyOnItemSelectedListener();

---------------------

ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, val);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn1.setAdapter(adapter);
spn1.seOnItemSelectedListener( myOnItemSelectedListener);


问:
Tensorflow: Create the torch.gather() equivalent in tensorflow
I want to replicate the torch.gather() function in TensorFlow 2.X.
I have a Tensor A (shape: [2, 4, 3]) and a corresponding Index-Tensor I (shape: [2,2,3]).
Using torch.gather() yields the following:

```<code>A = torch.tensor([[[10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
I = torch.tensor([[[0,1,0], [1,2,1]],
                  [[2,1,2], [1,0,1]]])
torch.gather(A, 1, I)

>
tensor([[[10,   200,   30], [100, 2000, 300]],
         [5000, 600, 7000], [500,   60, 700]]])
</code>```

I have tried using tf.gather(), but this did not yield pytorch-like results. I also tried to play around with tf.gather_nd(), but I could not find a suitable solution.

I found this StackOverflow post, but this seems not to work for me.

Edit:
When using tf.gather_nd(A, I), I get the following result:

```<code>tf.gather_nd(A, I)

>
[[100, 6000],
 [  0,   60]]
</code>```

The result for tf.gather(A, I) is rather lengthy. It has the shape of [2, 2, 3, 4, 3]

答:
torch.gather and tf.gather_nd work differently and will therefore yield different results when using the same indices tensor (in some cases an error will also be returned). This is what the indices tensor would have to look like to get the same results:

import tensorflow as tf

A = tf.constant([[
                   [10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
I = tf.constant([[[
                  [0,0,0],
                  [0,1,1],
                  [0,0,2],
                ],[
                  [0,1,0],
                  [0,2,1],
                  [0,1,2],
                ]],
                 [[
                  [1,2,0],
                  [1,1,1],
                  [1,2,2],
                ],
                  [
                  [1,1,0],
                  [1,0,1],
                  [1,1,2],
                ]]])

print(tf.gather_nd(A, I))
```
```tf.Tensor(
[[[  10  200   30]
  [ 100 2000  300]]

 [[5000  600 7000]
  [ 500   60  700]]], shape=(2, 2, 3), dtype=int32)
```
<p>So, the question is actually how are you calculating your indices or are they always hard-coded? Also, check out this post on the differences of the two operations.</p>
<p>As for the post you linked that didn't work for you, you just need to cast the indices and everything should be fine:</p>
<pre class="lang-py prettyprint-override"><code>def torch_gather(x, indices, gather_axis):

    all_indices = tf.where(tf.fill(indices.shape, True))
    gather_locations = tf.reshape(indices, [indices.shape.num_elements()])

    gather_indices = []
    for axis in range(len(indices.shape)):
        if axis == gather_axis:
            gather_indices.append(tf.cast(gather_locations, dtype=tf.int64))
        else:
            gather_indices.append(tf.cast(all_indices[:, axis], dtype=tf.int64))

    gather_indices = tf.stack(gather_indices, axis=-1)
    gathered = tf.gather_nd(x, gather_indices)
    reshaped = tf.reshape(gathered, indices.shape)
    return reshaped

I = tf.constant([[[0,1,0], [1,2,1]],
                  [[2,1,2], [1,0,1]]])
A = tf.constant([[
                   [10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
print(torch_gather(A, I, 1))
</code>```
```<code>tf.Tensor(
[[[  10  200   30]
  [ 100 2000  300]]

 [[5000  600 7000]
  [ 500   60  700]]], shape=(2, 2, 3), dtype=int32)
</code>```

Body:
I want to replicate the torch.gather() function in TensorFlow 2.X.
I have a Tensor A (shape: [2, 4, 3]) and a corresponding Index-Tensor I (shape: [2,2,3]).
Using torch.gather() yields the following:

A = torch.tensor([[[10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
I = torch.tensor([[[0,1,0], [1,2,1]],
                  [[2,1,2], [1,0,1]]])
torch.gather(A, 1, I)

>
tensor([[[10,   200,   30], [100, 2000, 300]],
         [5000, 600, 7000], [500,   60, 700]]])

I have tried using tf.gather(), but this did not yield pytorch-like results. I also tried to play around with tf.gather_nd(), but I could not find a suitable solution.

I found this StackOverflow post, but this seems not to work for me.

Edit:
When using tf.gather_nd(A, I), I get the following result:

tf.gather_nd(A, I)

>
[[100, 6000],
 [  0,   60]]

The result for tf.gather(A, I) is rather lengthy. It has the shape of [2, 2, 3, 4, 3]

Body:
torch.gather and tf.gather_nd work differently and will therefore yield different results when using the same indices tensor (in some cases an error will also be returned). This is what the indices tensor would have to look like to get the same results:

import tensorflow as tf

A = tf.constant([[
                   [10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
I = tf.constant([[[
                  [0,0,0],
                  [0,1,1],
                  [0,0,2],
                ],[
                  [0,1,0],
                  [0,2,1],
                  [0,1,2],
                ]],
                 [[
                  [1,2,0],
                  [1,1,1],
                  [1,2,2],
                ],
                  [
                  [1,1,0],
                  [1,0,1],
                  [1,1,2],
                ]]])

print(tf.gather_nd(A, I))

tf.Tensor(
[[[  10  200   30]
  [ 100 2000  300]]

 [[5000  600 7000]
  [ 500   60  700]]], shape=(2, 2, 3), dtype=int32)

So, the question is actually how are you calculating your indices or are they always hard-coded? Also, check out this post on the differences of the two operations.

As for the post you linked that didn't work for you, you just need to cast the indices and everything should be fine:

def torch_gather(x, indices, gather_axis):

    all_indices = tf.where(tf.fill(indices.shape, True))
    gather_locations = tf.reshape(indices, [indices.shape.num_elements()])

    gather_indices = []
    for axis in range(len(indices.shape)):
        if axis == gather_axis:
            gather_indices.append(tf.cast(gather_locations, dtype=tf.int64))
        else:
            gather_indices.append(tf.cast(all_indices[:, axis], dtype=tf.int64))

    gather_indices = tf.stack(gather_indices, axis=-1)
    gathered = tf.gather_nd(x, gather_indices)
    reshaped = tf.reshape(gathered, indices.shape)
    return reshaped

I = tf.constant([[[0,1,0], [1,2,1]],
                  [[2,1,2], [1,0,1]]])
A = tf.constant([[
                   [10,20,30], [100,200,300], [1000,2000,3000]],
                  [[50,60,70], [500,600,700], [5000,6000,7000]]])
print(torch_gather(A, I, 1))

tf.Tensor(
[[[  10  200   30]
  [ 100 2000  300]]

 [[5000  600 7000]
  [ 500   60  700]]], shape=(2, 2, 3), dtype=int32)


问:
How can I create a JavaScript filter function for multiple filters at once

My Problem:

I'm having a website where I can compare products stored inside an array (with objects). I want to add different filters from array inside of an object that get applied together.

For two filters I can easily do it (see my code below). I just compare two objects and use a filter depending on their content.

But what would be a good approach to use the filter if there are more than two objects. Can I loop through the object and compare if the arrays are empty?

With my current approach I would have to extend my code for every new filter and it would balloon.

What I'm trying to do:

I want to check which filter objects have any data in their "feature" array (that array gets filled after the user clicks a filter on the site) and if they have I want to use these arrays to filter the main filteredArray array.

My current Object:

```<code>features_collection: {
    aspect_ratio_object: {
      features: [],
      value: "Aspect Ratio",
    },
    performance_rating_object: {
      features: [],
      value: "Performance Rating",
    },
  },
</code>```

My Filter Function:

```<code>    if (
      features_collection.aspect_ratio_object.features.length &&
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) &&
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    } else if (
      features_collection.aspect_ratio_object.features.length ||
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) ||
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    }
  },
</code>```

Further Notes:

I can also change my object. I could change it into an array of objects if that would make things easier?

答:
Making your filters an array seems more practical. Here's an example on how to
filter a set of objects against your feature_collection.

function filter_by_features(targets, feature_collection) {

    // Start right of to filter the `filteredArray`
    return targets.filter(obj => {

        // go through every feature and test it against the current object.
        // every() returns either true or false and the targets array is filtered
        // by that condition supplied within the callback of `every()`
        return feature_collection.every(filter => {

            // If for a given feature no filter is available, return true
            // so the test for this filter passes.
            if(filter.features.length === 0) {
                return true
            }

            // there are features, check if any applies.
            return filter.features.includes(obj[filter.value])

        })

    })

}

```
<h5>Usage</h5>
<pre class="lang-js prettyprint-override"><code>
// feature collection  (as array)
const feature_collection = [
    {
        features: [],
        value: "Aspect Ratio",
    },
    {
        features: [],
        value: "Performance Rating",
    }
]

// the objects you want to filter.
const objects_to_filter = [/* ... */]

const filtered = filter_by_features(objects_to_filter, feature_collection)
</code>```

docs

every()

Body:
My Problem:

I'm having a website where I can compare products stored inside an array (with objects). I want to add different filters from array inside of an object that get applied together.

For two filters I can easily do it (see my code below). I just compare two objects and use a filter depending on their content.

But what would be a good approach to use the filter if there are more than two objects. Can I loop through the object and compare if the arrays are empty?

With my current approach I would have to extend my code for every new filter and it would balloon.

What I'm trying to do:

I want to check which filter objects have any data in their "feature" array (that array gets filled after the user clicks a filter on the site) and if they have I want to use these arrays to filter the main filteredArray array.

My current Object:

features_collection: {
    aspect_ratio_object: {
      features: [],
      value: "Aspect Ratio",
    },
    performance_rating_object: {
      features: [],
      value: "Performance Rating",
    },
  },

My Filter Function:

    if (
      features_collection.aspect_ratio_object.features.length &&
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) &&
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    } else if (
      features_collection.aspect_ratio_object.features.length ||
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) ||
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    }
  },

Further Notes:

I can also change my object. I could change it into an array of objects if that would make things easier?

Body:
Making your filters an array seems more practical. Here's an example on how to
filter a set of objects against your feature_collection.

function filter_by_features(targets, feature_collection) {

    // Start right of to filter the `filteredArray`
    return targets.filter(obj => {

        // go through every feature and test it against the current object.
        // every() returns either true or false and the targets array is filtered
        // by that condition supplied within the callback of `every()`
        return feature_collection.every(filter => {

            // If for a given feature no filter is available, return true
            // so the test for this filter passes.
            if(filter.features.length === 0) {
                return true
            }

            // there are features, check if any applies.
            return filter.features.includes(obj[filter.value])

        })

    })

}

Usage

// feature collection  (as array)
const feature_collection = [
    {
        features: [],
        value: "Aspect Ratio",
    },
    {
        features: [],
        value: "Performance Rating",
    }
]

// the objects you want to filter.
const objects_to_filter = [/* ... */]

const filtered = filter_by_features(objects_to_filter, feature_collection)

docs

every()


问:
mySQL cannot create FK because incorrect timestamp values
Hi i am trying to add a new column which is a FK to another table, I added the new column but when I try to make it a FK im getting this error

```<code>Error Code: 1292. Incorrect datetime value: '0000-00-00 00:00:00' for column 'created_at' at row 4383
</code>```

that's what im trying to run:

```<code>ALTER TABLE smallstage_grouponi_groupon.tb_opportunity ADD chain_id int(11) DEFAULT NULL;
ALTER TABLE smallstage_grouponi_groupon.tb_opportunity ADD FOREIGN KEY (chain_id) REFERENCES tb_chains(id);
</code>```

what it has to do with the created_at column? I am not even trying to alter it.
Please advise a solution

答:
You populated the tb_opportunity table with a SQL mode where "NO_ZERO_DATE" was disabled. At this time inserting datetimes like "0000-00-00 00:00:00" was allowed.

You are now trying to add a foreign key to this table, in a session where the SQL modes "strict" and "NO_ZERO_DATE" are enabled. The mysql engine has to reindex your table to add the foreign key, but throws an error because it encounters a line with a "0000-00-00 00:00:00" datetime, which isn't allowed anymore in this mode.

To bypass this, you'll have to either disable the NO_ZERO_DATE SQL mode, or to first fix the rows in your table where created_at equals "0000-00-00 00:00:00" before adding your foreign key.
Another option can also be to keep the NO_ZERO_DATE mode and disable the strict mode, which will produce a warning instead of an error.

Body:
Hi i am trying to add a new column which is a FK to another table, I added the new column but when I try to make it a FK im getting this error

Error Code: 1292. Incorrect datetime value: '0000-00-00 00:00:00' for column 'created_at' at row 4383

that's what im trying to run:

ALTER TABLE smallstage_grouponi_groupon.tb_opportunity ADD chain_id int(11) DEFAULT NULL;
ALTER TABLE smallstage_grouponi_groupon.tb_opportunity ADD FOREIGN KEY (chain_id) REFERENCES tb_chains(id);

what it has to do with the created_at column? I am not even trying to alter it.
Please advise a solution


问:
Delete post method returns null
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

```<code> // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }
</code>```

and here is my View

```<code>@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

    <div class="border p-3">

        <div class="form-group row">
            <h2 class="text-info pl-3">Delete Category</h2>
        </div>
        <div class="row">
            <div class="col-8">
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="CategoryName"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="CategoryName" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="DisplayOrder"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="DisplayOrder" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-8 offset-4 row">

                        <div class="col">
                            <input type="submit" class="btn btn-danger w-100" value="Delete" />
                        </div>
                        <div class="col">
                            <a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-4">
                @* Keep this empty *@
            </div>
        </div>
    </div>

</form>
</code>```

Any help or suggestion would be very appreciated, thanks!

答:
You're using @Html.HiddenFor(id => id.CategoryId) (well, you're actually using the tag-helper syntax too <input asp-for="CategoryId" hidden /> and you should just use one or the other, not both!) in the view which will create an input with name="CategoryId".

So, the easiest solution is probably to correct the view and update the parameter name in the controller action for DeletePost.

View:

<input type="hidden" asp-for="CategoryId" />
```
<p>Controller:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? categoryId)
{
    Category obj = _db.Category.Find(categoryId);
    // check obj here, not id
    if (obj == null)
    {
        return NotFound();
    }

    _db.Category.Remove(obj);
    _db.SaveChanges();
    return RedirectToAction("Index");
}
</code>```

Title: Delete post method returns null

Body:
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

 // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }

and here is my View

@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

Delete Category

                        <input asp-for="CategoryName" disabled class="form-control" />

                        <input asp-for="DisplayOrder" disabled class="form-control" />

                            <input type="submit" class="btn btn-danger w-100" value="Delete" />

                             Back

                @* Keep this empty *@

</form>

Any help or suggestion would be very appreciated, thanks!

Body:
You're using @Html.HiddenFor(id => id.CategoryId) (well, you're actually using the tag-helper syntax too <input asp-for="CategoryId" hidden /> and you should just use one or the other, not both!) in the view which will create an input with name="CategoryId".

So, the easiest solution is probably to correct the view and update the parameter name in the controller action for DeletePost.

View:

<!-- remove this line: @Html.HiddenFor(id => id.CategoryId) -->
<!-- just use line below -->
<input type="hidden" asp-for="CategoryId" />

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? categoryId)
{
    Category obj = _db.Category.Find(categoryId);
    // check obj here, not id
    if (obj == null)
    {
        return NotFound();
    }

    _db.Category.Remove(obj);
    _db.SaveChanges();
    return RedirectToAction("Index");
}


问:
Angular 13 throw specific error message from backend
I have an application (back+front). I'm a newbie in angular and frontend, and I want to know how to get the specific message of error from the backend

When I create a person and I write his email as an invalid email in the backend I get this:

In my angular app i have errorHandler:

```<code>errorHandler(error:any) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = Error Code: ${error.status}\nMessage: ${error.message};
    }
    return throwError(errorMessage);
  }
</code>```

which i catch in my  create method:

```<code>create(user:User): Observable<any> {
    return this.httpClient.post(this.apiURL + 'api/user/', JSON.stringify(user), this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }
</code>```

I connected toastr to display some message if the operation is successfull or not:

```<code>  submit() {
    console.log(this.form.value);
    this.messageService.create(this.form.value).subscribe((res: any) => {
      this.toastr.success("Created successfully!");
      console.log('Post created successfully!');
      this.router.navigateByUrl('messages').then(r => console.log(r));
    },
      (error)=>{
      void this.toastr.error(error.messageType,"We have an error! Something went wrong")
      })
  }
</code>```

But I get only static message that something is wrong, and I need to get the specific message from my backend(if the username is already taken, or the email is invalid)

When i write error  with toastr:

```<code>(error)=>{
      void this.toastr.error(error,"We have an error! Something went wrong")
      })
</code>```

I get this:

答:
First of all, it's always safer to pass a closure instead of function reference where this is involved:

```<code>catchError(err => this.errorHandler(err))
</code>```

Secondly, throwError() must be given an error factory and not a constant value, like:

```<code>throwError(() => errorMessage);
</code>```

Thirdly, I'm not sure what exactly you expect to see, but you do nothing with error in your submit() call, did you mean something like this?

```<code>error => this.toastr.error(error.messageType, `We have an error: ${error}`)
</code>```

Body:
I have an application (back+front). I'm a newbie in angular and frontend, and I want to know how to get the specific message of error from the backend

When I create a person and I write his email as an invalid email in the backend I get this:

In my angular app i have errorHandler:

errorHandler(error:any) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = Error Code: ${error.status}\nMessage: ${error.message};
    }
    return throwError(errorMessage);
  }

which i catch in my  create method:

create(user:User): Observable<any> {
    return this.httpClient.post(this.apiURL + 'api/user/', JSON.stringify(user), this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }

I connected toastr to display some message if the operation is successfull or not:

  submit() {
    console.log(this.form.value);
    this.messageService.create(this.form.value).subscribe((res: any) => {
      this.toastr.success("Created successfully!");
      console.log('Post created successfully!');
      this.router.navigateByUrl('messages').then(r => console.log(r));
    },
      (error)=>{
      void this.toastr.error(error.messageType,"We have an error! Something went wrong")
      })
  }

But I get only static message that something is wrong, and I need to get the specific message from my backend(if the username is already taken, or the email is invalid)

When i write error  with toastr:

(error)=>{
      void this.toastr.error(error,"We have an error! Something went wrong")
      })

I get this:

Body:
First of all, it's always safer to pass a closure instead of function reference where this is involved:

catchError(err => this.errorHandler(err))

Secondly, throwError() must be given an error factory and not a constant value, like:

throwError(() => errorMessage);

Thirdly, I'm not sure what exactly you expect to see, but you do nothing with error in your submit() call, did you mean something like this?

error => this.toastr.error(error.messageType, `We have an error: ${error}`)


问:
Eclipse could not write to ./launch
I have accidentally deleted ./metadata folder in eclipse. Now when i try reconfigure the project from workspace, things are fine and the project gets created with some old data about libraries. But when i try to create a new remote java application for debugging, i get the following error

```<code>"Could not write file:/workspace/.metadata/.plugins/org.eclipse.debug.core/.launches"
</code>```

Can someone please tell me how do i rectify this error and start remote java debugging?

答:
You need create the missing directory.
If you use windows, you can create a new directory using windows explorer or you can use the following command line for windows and linux:

```<code>cd /workspace/.metadata/.pluguins
mkdir org.clipse.debug.core
</code>```

OBS: You don't need to use 'chmod' command line.

Title: Eclipse could not write to ./launch

Body:
I have accidentally deleted ./metadata folder in eclipse. Now when i try reconfigure the project from workspace, things are fine and the project gets created with some old data about libraries. But when i try to create a new remote java application for debugging, i get the following error

"Could not write file:/workspace/.metadata/.plugins/org.eclipse.debug.core/.launches"

Can someone please tell me how do i rectify this error and start remote java debugging?

Body:
You need create the missing directory.
If you use windows, you can create a new directory using windows explorer or you can use the following command line for windows and linux:

cd /workspace/.metadata/.pluguins
mkdir org.clipse.debug.core

OBS: You don't need to use 'chmod' command line.


问:
Regular expressions: contains at least two 0s but not consecutive 0s
Is the solution of this exercise the below regular expression? I found it in the internet but I don't believe that this is correct.

```<code>(1*011*(0+011*))*
</code>```

According to the theory of Chapter 1 in the book "The handbook of computational linguistics and natural language processing", how could I solve this exercise?

I would like a regular expression that will satisfy the below regular language

```<code>    L = {010,0101,0110,0101010,01011110,.....}
</code>```

答:
If it's atleast 2 0s, then there's also a possibility of 1 being at the start
So wouldn't that be 1* 0 1* 0 (1+01)*
But if it's acc to the language given (the 2 0s at the beginning and end),
0 (1+01)* 0</p>

Body:
Is the solution of this exercise the below regular expression? I found it in the internet but I don't believe that this is correct.

(1*011*(0+011*))*

According to the theory of Chapter 1 in the book "The handbook of computational linguistics and natural language processing", how could I solve this exercise?

I would like a regular expression that will satisfy the below regular language

    L = {010,0101,0110,0101010,01011110,.....}


问:
Husky 4.x+ not working with Visual Studio Git
Husky changed it's path handling with 4.0.0. After this change, it throws the following error on commit from Visual Studio:

```<code>husky > pre-commit (node v12.12.0)/c/path/to/repo/node_modules/.bin/lint-staged:
line 5: cygpath: command not foundinternal/modules/cjs/loader.js:797 throw err;

^Error: Cannot find module 'C:\lint-staged\bin\lint-staged.js'
 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
 at Function.Module._load (internal/modules/cjs/loader.js:687:27)
 at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
 at internal/main /run_main_module.js:17:11 { code: 'MODULE_NOT_FOUND', requireStack: []}

husky > pre-commit hook failed
(add --no-verify to bypass)
</code>```

However, when committing from CLI, it works as expected. Given that the error message has 'C:\lint-staged\bin\lint-staged.js' as the file path, I'm assuming that Visual Studio is handling the pathing differently.

I'm trying to find a way to make this work from within Visual Studio. I'm in an enterprise environment, so I'm hoping for a way I can include this configuration within the repo (rather than requiring manual local setup).

I have the husky config included within my package.json as

```<code>...
"husky":{
    "hooks":{ "pre-commit": "lint-staged"}
},
"lint-staged":{
    "!(*.min.*)js": "eslint --fix"
},
...

</code>```

I'm currently using:

nvm 1.1.7 with Node 12.16.1

husky 4.2.5

lint-staged 10.1.3

visual studio 2019

答:
From VS console, run:

```<code>npm install husky --save-dev
</code>```

…and commit again.

Body:
Husky changed it's path handling with 4.0.0. After this change, it throws the following error on commit from Visual Studio:

husky > pre-commit (node v12.12.0)/c/path/to/repo/node_modules/.bin/lint-staged:
line 5: cygpath: command not foundinternal/modules/cjs/loader.js:797 throw err;

^Error: Cannot find module 'C:\lint-staged\bin\lint-staged.js'
 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
 at Function.Module._load (internal/modules/cjs/loader.js:687:27)
 at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
 at internal/main /run_main_module.js:17:11 { code: 'MODULE_NOT_FOUND', requireStack: []}

husky > pre-commit hook failed
(add --no-verify to bypass)

However, when committing from CLI, it works as expected. Given that the error message has 'C:\lint-staged\bin\lint-staged.js' as the file path, I'm assuming that Visual Studio is handling the pathing differently.

I'm trying to find a way to make this work from within Visual Studio. I'm in an enterprise environment, so I'm hoping for a way I can include this configuration within the repo (rather than requiring manual local setup).

I have the husky config included within my package.json as

...
"husky":{
    "hooks":{ "pre-commit": "lint-staged"}
},
"lint-staged":{
    "!(*.min.*)js": "eslint --fix"
},
...

I'm currently using:

nvm 1.1.7 with Node 12.16.1

husky 4.2.5

lint-staged 10.1.3

visual studio 2019

Body:
From VS console, run:

npm install husky --save-dev

…and commit again.


问:
FabricJS object is not selectable/clickable/resizable in top left corner (React + FabricJs)
I have FabricJs canvas. And I have multiple objects outside canvas. When I click on object, it appears in Canvas. I am not doing anything else with this object programmatically.

Here is part of code that add image to Canvas (it is React code):

```<code>const { state, setState } = React.useContext(Context);
const { canvas } = state;
...
const handleElementAdd = (event, image) => {
    const imageSize = event.target.childNodes[0].getBoundingClientRect();
    const imageUrl = `/storage/${image.src}`;
    new fabric.Image.fromURL(imageUrl, img => {
        var scale = 1;
    if (img.width > 100) {
      scale = 100/img.width;
    }
    var oImg = img.set({
      left:  state.width / 2 - img.width * scale,
      top:  state.height / 2 - img.height * scale,
      angle: 0})
    .scale(scale);

    canvas.add(oImg).renderAll.bind(canvas);
    canvas.setActiveObject(oImg);
  });
  };
      ...
  <div
          key={img.name}
          onClick={(e) => handleElementAdd(e, img)}
          className={buttonClass}
        >
</code>```

It appears, I can drag and drop, resize, select it. However, when my object is placed in top left corner of canvas, it is not clickable, resizable etc. I can select larger area and then object is selected, but it doesn't respond to any events like resize, select etc.

Not sure where to look at.
I read that if coordinates are changed programmatically object.setCoord() to object can help, but in this case I do not understand where to put it.

答:
You have to put (call) object.setCoords() each time you have modified the object, or moved the object. So, you can call it on mouseUp event of the canvas.

You can write a function naming "moveObject" in which you get the object you are trying to move/moved/updated. And then just selectedObject.setCoords().

Then call that function inside     canvas.on('selection:updated', e => {----})

Body:
I have FabricJs canvas. And I have multiple objects outside canvas. When I click on object, it appears in Canvas. I am not doing anything else with this object programmatically.

Here is part of code that add image to Canvas (it is React code):

const { state, setState } = React.useContext(Context);
const { canvas } = state;
...
const handleElementAdd = (event, image) => {
    const imageSize = event.target.childNodes[0].getBoundingClientRect();
    const imageUrl = `/storage/${image.src}`;
    new fabric.Image.fromURL(imageUrl, img => {
        var scale = 1;
    if (img.width > 100) {
      scale = 100/img.width;
    }
    var oImg = img.set({
      left:  state.width / 2 - img.width * scale,
      top:  state.height / 2 - img.height * scale,
      angle: 0})
    .scale(scale);

    canvas.add(oImg).renderAll.bind(canvas);
    canvas.setActiveObject(oImg);
  });
  };
      ...

 handleElementAdd(e, img)}
          className={buttonClass}
        >

It appears, I can drag and drop, resize, select it. However, when my object is placed in top left corner of canvas, it is not clickable, resizable etc. I can select larger area and then object is selected, but it doesn't respond to any events like resize, select etc.

Not sure where to look at.
I read that if coordinates are changed programmatically object.setCoord() to object can help, but in this case I do not understand where to put it.