问:
IE doesn't evaluate meta-refresh anymore after pressing F5
Ridiculous simple HTML-file:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="refresh" content="5; URL=./test.html">
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>
</code>```

When I open the file with any browser, the browsers behave well and reload the page every 5 seconds.

But when I refresh the page manually between two refreshes (F5), the IE (V 8.0.6001.18702) doesn't evaluate the meta tag anymore and the page gets no longer refreshed. Opera, FF and Safari still work as expected and refresh every 5 seconds.

Has anybody else experienced such a problem? How (apart of using Javascript, of course) could this issue be solved?

Edit 1:

Verified this behavior also on IE6, so I guess it's a general IE problem. Any hints how to overcome this?

Edit 2:

To keep that topic going:

is that a known problem or would it
be worth to file a bug ticket
somewhere (where?)?

Could someone
verify that behavior with IE7 and/or
IE9?

答:
Javascript is going to be your friend for this one... it ends up working a lot better across browsers for the most part. Besides, meta-refresh is going out of style.

The following script and body onload attribute will continuously refresh the page every 5 seconds.

```<code><html>
<head>
   <script>
    function timedRefresh(timeoutPeriod) {
       setTimeout("location.reload(true);",timeoutPeriod);
    }
   </script>
   <noscript>
    <meta http-equiv="refresh" content="5" />
   </noscript>
</head>
<body onload="javascript:timedRefresh(5000)">
   <!-- Content -->
</body>
</html>
</code>```

Body:
Ridiculous simple HTML-file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="refresh" content="5; URL=./test.html">

Hello World

When I open the file with any browser, the browsers behave well and reload the page every 5 seconds.

But when I refresh the page manually between two refreshes (F5), the IE (V 8.0.6001.18702) doesn't evaluate the meta tag anymore and the page gets no longer refreshed. Opera, FF and Safari still work as expected and refresh every 5 seconds.

Has anybody else experienced such a problem? How (apart of using Javascript, of course) could this issue be solved?

Edit 1:

Verified this behavior also on IE6, so I guess it's a general IE problem. Any hints how to overcome this?

Edit 2:

To keep that topic going:

is that a known problem or would it
be worth to file a bug ticket
somewhere (where?)?

Could someone
verify that behavior with IE7 and/or
IE9?

Body:
Javascript is going to be your friend for this one... it ends up working a lot better across browsers for the most part. Besides, meta-refresh is going out of style.

The following script and body onload attribute will continuously refresh the page every 5 seconds.

<html>
<head>
   <script>
    function timedRefresh(timeoutPeriod) {
       setTimeout("location.reload(true);",timeoutPeriod);
    }
   </script>
   <noscript>
    <meta http-equiv="refresh" content="5" />
   </noscript>
</head>
<body onload="javascript:timedRefresh(5000)">
   <!-- Content -->
</body>
</html>


来源: stackexchange

问:
How to tag a changeset or a changelog file with a tag - webdevops/liquibase
I need to tag a changeset for rollback.

Tried this

Way 1

```<code>docker run --rm -v $(pwd):/liquibase/ -e "LIQUIBASE_URL=jdbc:postgresql://host/dbname" -e "LIQUIBASE_USERNAME=username" -e "LIQUIBASE_PASSWORD=pass" webdevops/liquibase:postgres tag -Dliquibase.tag='version0.1'
</code>```

or

```<code>docker run --rm -v $(pwd):/liquibase/ -e "LIQUIBASE_URL=jdbc:postgresql://host/dbname" -e "LIQUIBASE_USERNAME=username" -e "LIQUIBASE_PASSWORD=pass" webdevops/liquibase:postgres tag 'version0.1'
</code>```

on running this i get

/entrypoint: line 172: exec: tag: not found

Way 2

```<code><changeSet  id="3"  author="nvoxland">
        <tagDatabase  tag="version_1.3"/>
            <addLookupTable
                existingTableName="person"  existingColumnName="state"
                newTableName="state"  newColumnName="id"  newColumnDataType="char(2)"/>
    </changeSet>
</code>```

Or

```<code>    <changeSet  id="3"  author="nvoxland">
        <tagDatabase  tag="version_1.3"/>
        <addLookupTable
            existingTableName="person"  existingColumnName="state"
            newTableName="state"  newColumnName="id"  newColumnDataType="char(2)"/>
    </changeSet>
</code>```

Error

Invalid content was found starting with element 'addLookupTable'.

How do i tag and rollback?

答:
Can you separate out the tagDatabase as it's own changeset?
Something like</p>

```<code>
    <changeSet  id="3"  author="mo">
        <tagDatabase  tag="version_1.3"/>
    </changeSet>

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to tag a changeset for rollback.

Tried this

Way 1

docker run --rm -v $(pwd):/liquibase/ -e "LIQUIBASE_URL=jdbc:postgresql://host/dbname" -e "LIQUIBASE_USERNAME=username" -e "LIQUIBASE_PASSWORD=pass" webdevops/liquibase:postgres tag -Dliquibase.tag='version0.1'

or

docker run --rm -v $(pwd):/liquibase/ -e "LIQUIBASE_URL=jdbc:postgresql://host/dbname" -e "LIQUIBASE_USERNAME=username" -e "LIQUIBASE_PASSWORD=pass" webdevops/liquibase:postgres tag 'version0.1'

on running this i get

/entrypoint: line 172: exec: tag: not found

Way 2

<changeSet  id="3"  author="nvoxland">
        <tagDatabase  tag="version_1.3"/>
            <addLookupTable
                existingTableName="person"  existingColumnName="state"
                newTableName="state"  newColumnName="id"  newColumnDataType="char(2)"/>
    </changeSet>

Or

    <changeSet  id="3"  author="nvoxland">
        <tagDatabase  tag="version_1.3"/>
        <addLookupTable
            existingTableName="person"  existingColumnName="state"
            newTableName="state"  newColumnName="id"  newColumnDataType="char(2)"/>
    </changeSet>

Error

Invalid content was found starting with element 'addLookupTable'.

How do i tag and rollback?

Body:
Can you separate out the tagDatabase as it's own changeset?
Something like

    <changeSet  id="3"  author="mo">
        <tagDatabase  tag="version_1.3"/>
    </changeSet>


问:
how to check if link directs to an existing image javascript
I want to know if a links redirects to an actual existing image in javascript because I don't want the following to happen:

```

答:
onload() function is used to detect if image is valid in url.If you enter onload function it is valid image url

function test(event,val){
   console.log("image"+val+" is loaded");
   event.style.display="block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://idontexist.lol/fakeimg.png"onload="test(this,1)" alt="non existant image"style="display:none" width="400">
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27g"onload="test(this,2)"style="display:none" alt="non existant image" width="400"></code>```

Body:
onload() function is used to detect if image is valid in url.If you enter onload function it is valid image url

function test(event,val){
   console.log("image"+val+" is loaded");
   event.style.display="block";
}

<img src="http://idontexist.lol/fakeimg.png"onload="test(this,1)" alt="non existant image"style="display:none" width="400">
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27g"onload="test(this,2)"style="display:none" alt="non existant image" width="400">


问:
Pandas - Is there a way to make multiple operations at the same time in a DataFrame?
I have the following code that will be executed more than 1.5 million times with different queries that are dynamically generated from a configuration file

I'm not trying to optimize the query conditions, I'm trying to see if rather than performing the query 3 times in different columns I can do the query once and get the same result

```<code>csv_file_profit = pd.read_csv('C:\\Users\\test_data.csv')

if query_str:
    profit_sum = csv_file_profit.query(query_str)['P/L'].sum()
    trans_count = csv_file_profit.query(query_str)['Tran ID'].count()
    atr_profit_sum = csv_file_profit.query(query_str)['Max ATR Profit'].sum()
</code>```

Is there a faster way to get the same result?

答:
One improvement can be to compute filtered DataFrame once and then
perform further computation on this filtered result. Something like:

```<code>if query_str:
    filtered = csv_file_profit.query(query_str)
    profit_sum = filtered['P/L'].sum()
    trans_count = filtered['Tran ID'].count()
    atr_profit_sum = filtered['Max ATR Profit'].sum()
</code>```

Execution time is about 50 % compared to your code, on a very limited
DataFrame (4 rows). For bigger DataFrame the difference should be bigger.

Body:
I have the following code that will be executed more than 1.5 million times with different queries that are dynamically generated from a configuration file

I'm not trying to optimize the query conditions, I'm trying to see if rather than performing the query 3 times in different columns I can do the query once and get the same result

csv_file_profit = pd.read_csv('C:\\Users\\test_data.csv')

if query_str:
    profit_sum = csv_file_profit.query(query_str)['P/L'].sum()
    trans_count = csv_file_profit.query(query_str)['Tran ID'].count()
    atr_profit_sum = csv_file_profit.query(query_str)['Max ATR Profit'].sum()

Is there a faster way to get the same result?

Body:
One improvement can be to compute filtered DataFrame once and then
perform further computation on this filtered result. Something like:

if query_str:
    filtered = csv_file_profit.query(query_str)
    profit_sum = filtered['P/L'].sum()
    trans_count = filtered['Tran ID'].count()
    atr_profit_sum = filtered['Max ATR Profit'].sum()

Execution time is about 50 % compared to your code, on a very limited
DataFrame (4 rows). For bigger DataFrame the difference should be bigger.


问:
How to stop re-creating a service inside cloud foundry
New to CF. There are multiple services in my app, out of which, one particular service to be created only first time (and not to be created each time).

I'm using below code:
cf service service-name || cf create-service service-name

However, it still creating the service each time, when I deploy the app. Is there any better approach?

答:
You should only run cf create-service once. Every time you run it, it will create a new service instance.

You want to cf bind-service or use manifest.yml to bind your services to your app. If you put the service names to bind in manifest.yml, it will just happen automatically. Otherwise you'd need to manually run cf bind-service when it's necessary, which is only really once when you initially push or after making changes to the service instance.

As to your command, it seems OK. cf service should return 1 if it doesn't find the service name you specified, which should trigger the second part of the command to create the service. At the same time, cf create-service will definitely fail if you try to create a service with a name that already exists. It'll say The service instance name is taken: foo. Thus if you're seeing the service instance being recreated by running that command, something probably deleted it prior. Maybe review any deployment code you have and check if something is deleting that service instance accidentally. You generally don't want to delete a service instance, unless you're really, really done with it. Normally, it's enough to just unbind a service.


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答: Try defined(). If it's not defined then the constant assumes it's simply text.

ContentLicense: CC BY-SA 3.0

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)


问:
Laravel Homestead Swift Cannot send message without a sender address
I get this error with stock email settings in Laravel 5.1 Homestead when I try to send a password reset mail. </p>

```<code>Swift_TransportException in AbstractSmtpTransport.php line 162:Cannot send message without a sender address
</code>```

<p>The address is filled in app/config/mail.php: </p>

```<code>'from' => array('address' => 'myusername@gmail.com', 'name' => 'hawle'),
</code>```

答:
the problem is the null value of MAIL_FROM_ADDRESS in .env file.

solutions 1:
change the value of the MAIL_FROM_ADRESS to match your email address(don t forget to rerun your server).
solution 2:
keep the .env file as it was but you need to change mail.php(app/config/mail.php):

from these:

```<code> 'from' => [
    'address' => env('MAIL_FROM_ADDRESS','mail@test.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
]
</code>```

to:

```<code>'from' => [
    'address' => 'mail@test.com',
    'name' => env('MAIL_FROM_NAME', 'Example'),
]
</code>```

Body:
I get this error with stock email settings in Laravel 5.1 Homestead when I try to send a password reset mail.

Swift_TransportException in AbstractSmtpTransport.php line 162:Cannot send message without a sender address

The address is filled in app/config/mail.php:

'from' => array('address' => 'myusername@gmail.com', 'name' => 'hawle'),

Body:
the problem is the null value of MAIL_FROM_ADDRESS in .env file.

solutions 1:
change the value of the MAIL_FROM_ADRESS to match your email address(don t forget to rerun your server).
solution 2:
keep the .env file as it was but you need to change mail.php(app/config/mail.php):

from these:

 'from' => [
    'address' => env('MAIL_FROM_ADDRESS','mail@test.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
]

to:

'from' => [
    'address' => 'mail@test.com',
    'name' => env('MAIL_FROM_NAME', 'Example'),
]


问:
kubernetes system:discovery role mechanism
I want to understand how system:discovery role is working in kubernetes.I'm able to see below non resource url's are the privileges contain in system:discovery role

```<code>root@kubemas:~# kubectl describe clusterrole system:discovery
Name:         system:discovery
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
             [/api/*]           []              [get]
             [/api]             []              [get]
             [/apis/*]          []              [get]
             [/apis]            []              [get]
             [/healthz]         []              [get]
             [/livez]           []              [get]
             [/openapi/*]       []              [get]
             [/openapi]         []              [get]
             [/readyz]          []              [get]
             [/version/]        []              [get]
             [/version]         []              [get]
</code>```

From clusterrolebinding description,

```<code>root@kubemas:~# kubectl describe clusterrolebindings.rbac.authorization.k8s.io system:discovery
Name:         system:discovery
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
Role:
  Kind:  ClusterRole
  Name:  system:discovery
Subjects:
  Kind   Name                  Namespace
  ----   ----                  ---------
  Group  system:authenticated
</code>```

I can see only system:authenticated group can access  the non resource url's.If i execute below command,i can understand ,the request user is system:anonymous which coming under the group system:unathenticated ,so not permitted to see the output

```<code>root@kubemas:~# curl -k https://192.168.56.101:6443/api
{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "forbidden: User \"system:anonymous\" cannot get path \"/api\"",
  "reason": "Forbidden",
  "details": {

  },
  "code": 403
</code>```

But i was expecting the same from below request which i'm trying to get the kubernetes version which also non resource url.But i can able to get the version output without error.So how this is working.Is i'm misunderstood this mechanism?

```<code>root@kubemas:~# curl -k https://192.168.56.101:6443/version
{
  "major": "1",
  "minor": "18",
  "gitVersion": "v1.18.3",
  "gitCommit": "2e7996e3e2712684bc73f0dec0200d64eec7fe40",
  "gitTreeState": "clean",
  "buildDate": "2020-05-20T12:43:34Z",
  "goVersion": "go1.13.9",
  "compiler": "gc",
  "platform": "linux/amd64"
}root@kubemas:~#
</code>```

答:
system:public-info-viewer is the clusterrole which gives access to /version. This clusterole is bound to system:authenticated and system:unauthenticated groups. Since it's bound to system:unauthenticated group you are able to access it.

From the docs

This clusterole Allows read-only access to non-sensitive information
  about the cluster. Introduced in Kubernetes v1.14.

```<code>kubectl describe clusterrole system:public-info-viewer
Name:         system:public-info-viewer
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
             [/healthz]         []              [get]
             [/livez]           []              [get]
             [/readyz]          []              [get]
             [/version/]        []              [get]
             [/version]         []              [get]
</code>```

Body:
I want to understand how system:discovery role is working in kubernetes.I'm able to see below non resource url's are the privileges contain in system:discovery role

root@kubemas:~# kubectl describe clusterrole system:discovery
Name:         system:discovery
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
             [/api/*]           []              [get]
             [/api]             []              [get]
             [/apis/*]          []              [get]
             [/apis]            []              [get]
             [/healthz]         []              [get]
             [/livez]           []              [get]
             [/openapi/*]       []              [get]
             [/openapi]         []              [get]
             [/readyz]          []              [get]
             [/version/]        []              [get]
             [/version]         []              [get]

From clusterrolebinding description,

root@kubemas:~# kubectl describe clusterrolebindings.rbac.authorization.k8s.io system:discovery
Name:         system:discovery
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
Role:
  Kind:  ClusterRole
  Name:  system:discovery
Subjects:
  Kind   Name                  Namespace
  ----   ----                  ---------
  Group  system:authenticated

I can see only system:authenticated group can access  the non resource url's.If i execute below command,i can understand ,the request user is system:anonymous which coming under the group system:unathenticated ,so not permitted to see the output

root@kubemas:~# curl -k https://192.168.56.101:6443/api
{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "forbidden: User \"system:anonymous\" cannot get path \"/api\"",
  "reason": "Forbidden",
  "details": {

  },
  "code": 403

But i was expecting the same from below request which i'm trying to get the kubernetes version which also non resource url.But i can able to get the version output without error.So how this is working.Is i'm misunderstood this mechanism?

root@kubemas:~# curl -k https://192.168.56.101:6443/version
{
  "major": "1",
  "minor": "18",
  "gitVersion": "v1.18.3",
  "gitCommit": "2e7996e3e2712684bc73f0dec0200d64eec7fe40",
  "gitTreeState": "clean",
  "buildDate": "2020-05-20T12:43:34Z",
  "goVersion": "go1.13.9",
  "compiler": "gc",
  "platform": "linux/amd64"
}root@kubemas:~#

Body:
system:public-info-viewer is the clusterrole which gives access to /version. This clusterole is bound to system:authenticated and system:unauthenticated groups. Since it's bound to system:unauthenticated group you are able to access it.

From the docs

This clusterole Allows read-only access to non-sensitive information
  about the cluster. Introduced in Kubernetes v1.14.

kubectl describe clusterrole system:public-info-viewer
Name:         system:public-info-viewer
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
             [/healthz]         []              [get]
             [/livez]           []              [get]
             [/readyz]          []              [get]
             [/version/]        []              [get]
             [/version]         []              [get]


问:
How can I determine if a file upload is a valid CSV file - or at least text - in ColdFusion 8?
I have a form which allows a user to upload a file to the server. How can I validate that the uploaded file is in fact the expected format (CSV, or at least validate that it is a text file) in ColdFusion 8?</p>

答:
For simple formats like CSV, just check yourself, for example via regex.

```<code> <cffile action="read" file="#uploadedFile#" variable="contents" charset="UTF-8">

 <cfset LooksLikeCSV = REFind("^([^;]*;)+[^;]*$", contents)>
</code>```

You can place additional checks with regard to file size limits or forbidden characters.

For other file formats, you can check for header signatures that occur in the first few bytes of the file.

You could even write a full parser for your expected file format - for CSV validation, you could do a ListToArray() at CR/LF and check each line individually against a regex. XML should work pretty straightforward as well - just try to pass it to XmlParse(). Binary formats like images are a little more difficult, but libraries exist there as well.

Body:
For simple formats like CSV, just check yourself, for example via regex.

 <cffile action="read" file="#uploadedFile#" variable="contents" charset="UTF-8">

 <cfset LooksLikeCSV = REFind("^([^;]*;)+[^;]*$", contents)>

You can place additional checks with regard to file size limits or forbidden characters.

For other file formats, you can check for header signatures that occur in the first few bytes of the file.

You could even write a full parser for your expected file format - for CSV validation, you could do a ListToArray() at CR/LF and check each line individually against a regex. XML should work pretty straightforward as well - just try to pass it to XmlParse(). Binary formats like images are a little more difficult, but libraries exist there as well.


问:
OpenCV: Detect squares in dark background
currently I am trying to calculate optical flows of moving objects. the objects in particular are the squares that are around the circular knobs:

Here is the vanilla image I am trying to process:

my concern is about the right bottom-most strip. The two squares are usually unable to be detected when I have tried Canny Edge detection or GoodFeaturesToTrack. I am currently trying a sharpen kernel and a threshold, then morphological transformation to finding the contour areas. However, when I threshold I get the following results:

```<code>import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

filename = 'images/Test21_1.tif'

image = cv.imread(filename)

kernel = [ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ] #sharpen kernel I got from wikipedia

kernel = np.array(kernel)
dst = cv.filter2D(image, -1, kernel)
ret, thresh = cv.threshold(dst, 80, 150, cv.THRESH_BINARY_INV)

plt.subplot(121),plt.imshow(image),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(thresh),plt.title('Threshold')
plt.xticks([]), plt.yticks([])
plt.show()
</code>```

I was wondering what I could do in openCV to be able to recognize that square. These squares are the objects that move in the videos, and I wish to use them to calculate their optical flow. I am currently considering resorting to a PyTorch CNN to detect the features. I would manually label the images for training/test datasets, but I believe that may be a bit overkill. Thank you for your time.

答:
I am not sure if this is any better, but you can try using the division normalization technique in Python/OpenCV.

Read the input

Convert to grayscale

Apply morphology

Divide the input by the result from the morphology

Adaptive Threshold

Save the results

```<code>import cv2
import numpy as np

# read the image
img = cv2.imread('rods.png')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (5,5))
smooth = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, smooth, scale=255)

# threshold
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 4)

# save results
cv2.imwrite('rods.division.jpg',division)
cv2.imwrite('rods.thresh.jpg',thresh)

# show results
cv2.imshow('smooth', smooth)
cv2.imshow('division', division)
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Division image:

Threshold image:

Body:
currently I am trying to calculate optical flows of moving objects. the objects in particular are the squares that are around the circular knobs:

Here is the vanilla image I am trying to process:

my concern is about the right bottom-most strip. The two squares are usually unable to be detected when I have tried Canny Edge detection or GoodFeaturesToTrack. I am currently trying a sharpen kernel and a threshold, then morphological transformation to finding the contour areas. However, when I threshold I get the following results:

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

filename = 'images/Test21_1.tif'

image = cv.imread(filename)

kernel = [ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ] #sharpen kernel I got from wikipedia

kernel = np.array(kernel)
dst = cv.filter2D(image, -1, kernel)
ret, thresh = cv.threshold(dst, 80, 150, cv.THRESH_BINARY_INV)

plt.subplot(121),plt.imshow(image),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(thresh),plt.title('Threshold')
plt.xticks([]), plt.yticks([])
plt.show()

I was wondering what I could do in openCV to be able to recognize that square. These squares are the objects that move in the videos, and I wish to use them to calculate their optical flow. I am currently considering resorting to a PyTorch CNN to detect the features. I would manually label the images for training/test datasets, but I believe that may be a bit overkill. Thank you for your time.

Body:
I am not sure if this is any better, but you can try using the division normalization technique in Python/OpenCV.

Read the input

Convert to grayscale

Apply morphology

Divide the input by the result from the morphology

Adaptive Threshold

Save the results

import cv2
import numpy as np

# read the image
img = cv2.imread('rods.png')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (5,5))
smooth = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, smooth, scale=255)

# threshold
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 4)

# save results
cv2.imwrite('rods.division.jpg',division)
cv2.imwrite('rods.thresh.jpg',thresh)

# show results
cv2.imshow('smooth', smooth)
cv2.imshow('division', division)
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

Division image:

Threshold image:


问:
Count all unique values in list + their Total quantity and Total price per Item cost
I would like to have the following:

List of unique values from another list

Total occurrences of that value in the other list

Total price of the items per Item cost

Play here: https://docs.google.com/spreadsheets/d/11EHm7N4iK8N9oLb8VXrycTwPVHLmoBay4Z6dugaOr7I/edit?usp=sharing

Thank you in advance!

答:
The best way is you should try first and come up with what you have tried/
Your output with formulas is ready in a same sheet please let me know if you have any doubt about it.

Item Name are under the range E13:E16 used this formula in cell F13 for count and dragged it out upto F16  =sumifs(B$2:B$7,A$2:A$7,E13)

Used this formula under the cell G13 and dragged it up to G16 for cost =vlookup(E13,A$2:C$7,3,False)*F13

Those changes have a restricted access to edit for me and you only.


问:
How to get the error message from the error code returned by GetLastError()?
After a Windows API call, how can I get the last error message in a textual form?

GetLastError() returns an integer value, not a text message.

答:
Since c++11, you can use the standard library instead of FormatMessage:

#include <system_error>

if (!SomeWin32Function()){
   DWORD error = ::GetLastError();
   std::string message = std::system_category().message(error);
   ...
}
```

OwnerDisplayName: Jena


问:
Run/install/debug Android applications over Wi-Fi?
I thought there was a way to test your applications in development over Wi-Fi. Is this possible?

I'd love to be able to untether my phone and develop wirelessly.

答:
If you are a windows user and your android sdk is located at C:\Users\%username%\AppData\Local\Android\Sdk then you can follow this method. If your andoid sdk not located there, replace that path to the below code.

```<code>@echo off
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" disconnect
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" shell ip route > %temp%\addrs12321.txt
For /F "UseBackQ Delims==" %%A In ("%temp%\addrs12321.txt") Do Set "lastline=%%A"
FOR %%C IN (%lastline%) DO SET last=%%C
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" tcpip 5555
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" connect %last%:5555 > %temp%\adbresult.txt
set /p result=<%temp%\adbresult.txt
del /f %temp%\addrs12321.txt
echo MSGBOX "%result%" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
del %temp%\adbresult.txt /f /q
</code>```

Step 1.

Turn on usb debugging,

Connect your phone to windows machine

select file transfer in usb options menu in android menu (if found)

Step 2.

copy above code

save as its extension like .bat, eg filename.bat

double click on the file you saved. done

note you can connect any time by running that file while the device
  being connected with the pc with usb debugging is turned on.

Body:
If you are a windows user and your android sdk is located at C:\Users\%username%\AppData\Local\Android\Sdk then you can follow this method. If your andoid sdk not located there, replace that path to the below code.

@echo off
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" disconnect
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" shell ip route > %temp%\addrs12321.txt
For /F "UseBackQ Delims==" %%A In ("%temp%\addrs12321.txt") Do Set "lastline=%%A"
FOR %%C IN (%lastline%) DO SET last=%%C
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" tcpip 5555
"C:\Users\%username%\AppData\Local\Android\Sdk\platform-tools\adb.exe" connect %last%:5555 > %temp%\adbresult.txt
set /p result=<%temp%\adbresult.txt
del /f %temp%\addrs12321.txt
echo MSGBOX "%result%" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
del %temp%\adbresult.txt /f /q

Step 1.

Turn on usb debugging,

Connect your phone to windows machine

select file transfer in usb options menu in android menu (if found)

Step 2.

copy above code

save as its extension like .bat, eg filename.bat

double click on the file you saved. done

note you can connect any time by running that file while the device
  being connected with the pc with usb debugging is turned on.


问:
Showing and hiding success and error with `jQuery validation` and `Select2` in line with `bootstrap4`

Not duplicate

Previous questions (on this topic) with answers are 4-5 years old and refer to respective project's old versions.

Status

In the project i am using:

Bootstrap v4.4.1

jQuery validation plugin v1.19.1

Select2 v4.0.13

Select2 Bootstrap4 theme v1.3.2

The problem

Bootstrap4 works well with jQuery validation plugin.

jQuery validation does not work with Select2 out of the box.

I managed to add outline for valid/invalid state.

Yet i can not make it to disappear on blur (clicking in white area of the page out of controls) as is the case with only Bootstrap4 and jQuery validation.

Examples

I created 2 JSFiddle-s that show the problem.

jQuery Validation + bootstrap4 = working as intended: Example 1

jQuery Validation + bootstrap4 + Select2 = problem: Example 2

Conclusion

I have meticulously looked through existing similar questions on StackOverflow and tried out most of suggestions, yet they reference old versions of libraries and are not applicable in current case as in the new versions of libraries there are used different code structure... so old solutions do not work anymore... I tried to account for that when applying solutions, but to no avail.

At this point i am stuck.

Thank you for ideas and proposals!

答:
I have meticulously looked through existing similar questions on
  StackOverflow and tried out most of suggestions, yet they reference
  old versions of libraries and are not applicable in current case as in
  the new versions of libraries there are used different code
  structure...

This is simply not the case.  There is no copy/paste cookie-cutter approach, however the idea is exactly the same as in previous versions.

While jQuery Validate is looking at the underlying hidden select element, the user is interacting with the Select2 element.  Therefore you must construct a custom event handler that pragmatically triggers validation on the hidden element as also shown in these older answers.

https://stackoverflow.com/a/30881932/594235

https://stackoverflow.com/a/46953372/594235

and one of mine from 2014...

https://stackoverflow.com/a/26046295/594235

The core concept of those answers is exactly the same that is used to solve your question and all have the following in common...

On some appropriate event, programmatically trigger validation of the underlying select element.

```<code>$('#selectElement').on('event', function() {
    $('select').valid();
});
</code>```

Solution:

As in the previous versions and integrations, it simply requires some external event handlers to trigger the desired action.

Strictly answering your question, create an event handler that is triggered when you focus out of the select.  Remember that Select2 replaces the default select within the DOM.  jQuery Validate is working on the hidden select, while the user is only interacting with the Select2 element.

```<code>$('.select2').on('focusout', function() {  // focus out of Select 2
    $mySelect.valid();    // trigger validation of hidden select
});
</code>```

DEMO:  jsfiddle.net/n91g8xfm/

However, I'd take it one step further and trigger validation whenever the selected value changes so the effect is instant.

```<code>$mySelect.on('change', function() {  // change value of hidden select
    $(this).valid();   // trigger validation of hidden select
});
</code>```

DEMO 2:  jsfiddle.net/gkzeoq1v/

Body:
I have meticulously looked through existing similar questions on
  StackOverflow and tried out most of suggestions, yet they reference
  old versions of libraries and are not applicable in current case as in
  the new versions of libraries there are used different code
  structure...

This is simply not the case.  There is no copy/paste cookie-cutter approach, however the idea is exactly the same as in previous versions.

While jQuery Validate is looking at the underlying hidden select element, the user is interacting with the Select2 element.  Therefore you must construct a custom event handler that pragmatically triggers validation on the hidden element as also shown in these older answers.

https://stackoverflow.com/a/30881932/594235

https://stackoverflow.com/a/46953372/594235

and one of mine from 2014...

https://stackoverflow.com/a/26046295/594235

The core concept of those answers is exactly the same that is used to solve your question and all have the following in common...

On some appropriate event, programmatically trigger validation of the underlying select element.

$('#selectElement').on('event', function() {
    $('select').valid();
});

Solution:

As in the previous versions and integrations, it simply requires some external event handlers to trigger the desired action.

Strictly answering your question, create an event handler that is triggered when you focus out of the select.  Remember that Select2 replaces the default select within the DOM.  jQuery Validate is working on the hidden select, while the user is only interacting with the Select2 element.

$('.select2').on('focusout', function() {  // focus out of Select 2
    $mySelect.valid();    // trigger validation of hidden select
});

DEMO:  jsfiddle.net/n91g8xfm/

However, I'd take it one step further and trigger validation whenever the selected value changes so the effect is instant.

$mySelect.on('change', function() {  // change value of hidden select
    $(this).valid();   // trigger validation of hidden select
});

DEMO 2:  jsfiddle.net/gkzeoq1v/


问:
Select all values from last date that is shared between rows
I’ve got a Postgresql table with counts for countries over time. Not every country has a count for each date, and some have NULL values. I’d like to get the counts for each country up to the last date every country has data for, excluding NULL values.

I made a DB Fiddle with example data.

Example:

```<code>country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Germany 2020-05-27  12     3
Germany 2020-05-28  13     4
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
Italy   2020-05-27  22     7
Italy   2020-05-28  23     8
France  2020-05-25  30     9
France  2020-05-26  31     10
France  2020-05-27  NULL   11
</code>```

I’d like to get back the following:

```<code>country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
France  2020-05-25  30     9
France  2020-05-26  31     10
</code>```

I’ve searched, but I’m relatively new to SQL and don’t seem to know what keywords to search for.

答:
You can use window functions to count the number of rows with dates and then compare to the number of countries:

```<code>SELECT c.*
FROM (SELECT c.*, COUNT(count) over (partition by date) as num_countries_on_date
      FROM countries c
     ) c
WHERE num_countries_on_date = (SELECT  COUNT(DISTINCT c2.country) FROM countries c2);
</code>```

Here is a db<>fiddle.

If you wanted to generate data for a range of dates -- sort of the opposite problem -- you could use a CROSS JOIN to generate the rows, a LEFT JOIN to bring in the data, and COALESCE() to turn NULL to 0:

```<code>SELECT c.country, d.date, coalesce(co.count, 0) as count
FROM (SELECT DISTINCT country FROM countries) c CROSS JOIN
     generate_series('2020-05-26'::date, '2020-05-27'::date, interval '1 day') d(date) LEFT JOIN
     countries co
     ON co.country = c.country AND co.date = d.date;
</code>```

Body:
I’ve got a Postgresql table with counts for countries over time. Not every country has a count for each date, and some have NULL values. I’d like to get the counts for each country up to the last date every country has data for, excluding NULL values.

I made a DB Fiddle with example data.

Example:

country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Germany 2020-05-27  12     3
Germany 2020-05-28  13     4
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
Italy   2020-05-27  22     7
Italy   2020-05-28  23     8
France  2020-05-25  30     9
France  2020-05-26  31     10
France  2020-05-27  NULL   11

I’d like to get back the following:

country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
France  2020-05-25  30     9
France  2020-05-26  31     10

I’ve searched, but I’m relatively new to SQL and don’t seem to know what keywords to search for.

Body:
You can use window functions to count the number of rows with dates and then compare to the number of countries:

SELECT c.*
FROM (SELECT c.*, COUNT(count) over (partition by date) as num_countries_on_date
      FROM countries c
     ) c
WHERE num_countries_on_date = (SELECT  COUNT(DISTINCT c2.country) FROM countries c2);

Here is a db<>fiddle.

If you wanted to generate data for a range of dates -- sort of the opposite problem -- you could use a CROSS JOIN to generate the rows, a LEFT JOIN to bring in the data, and COALESCE() to turn NULL to 0:

SELECT c.country, d.date, coalesce(co.count, 0) as count
FROM (SELECT DISTINCT country FROM countries) c CROSS JOIN
     generate_series('2020-05-26'::date, '2020-05-27'::date, interval '1 day') d(date) LEFT JOIN
     countries co
     ON co.country = c.country AND co.date = d.date;


问:
Pyspark Rename column based on column position
How do I rename the 3rd column of a dataframe in PySpark. I want to call the column index rather than the actual name.

Here is my attempt:

```<code>df
Col1    Col2    jfdklajfklfj
   A       B               2

df.withColumnRenamed([3], 'Row_Count')
</code>```

答:
Since python indexing starts at 0, you can index df.columns list by subtracting 1:

```<code>index_of_col = 3
df.withColumnRenamed(df.columns[index_of_col-1],'Row_Count').show()
</code>```

```<code>+----+----+---------+
|Col1|Col2|Row_Count|
+----+----+---------+
|   A|   B|        2|
+----+----+---------+
</code>```

Body:
How do I rename the 3rd column of a dataframe in PySpark. I want to call the column index rather than the actual name.

Here is my attempt:

df
Col1    Col2    jfdklajfklfj
   A       B               2

df.withColumnRenamed([3], 'Row_Count')

Body:
Since python indexing starts at 0, you can index df.columns list by subtracting 1:

index_of_col = 3
df.withColumnRenamed(df.columns[index_of_col-1],'Row_Count').show()

+----+----+---------+
|Col1|Col2|Row_Count|
+----+----+---------+
|   A|   B|        2|
+----+----+---------+


问:
Where to store complex data in the navigation-based application
I have an app that has a lot of data that I need between the pages, such as:
design settings, user parameters, scanner access, printer queue, multiple things that got calculated and formed on one page and will be used on the others.

The general idea of the app is: you quickly select options or input data on each page and then it forms an order, sends it and prints it.

I have several repositories for different things but I can't get how to give access to them from the destination-fragments.

I'm pretty new to Android so I'm trying to find the best way to build this system but failing to do so.
What I found so far:

Room - I don't think so. I honestly tried it for several weeks but loading and saving data is unbearably slow especially when it's just a bunch of menu-pages flipping one after another. Also, I don't need to save data locally between the sessions, so it kind of misses the point of the local database.

Send some simple strings/numbers between the fragments - serialization/deserialization of everything I need for each menu doesn't sound great.

ViewModel factory - this way you need to create and store the ViewFactory somewhere and then access it from each fragment and then build a new ViewModel with it. Kind of might work but looks weird. How should it work? We have a link to the Factory in the "main" ViewModel and then get a link to this "main" app's VM, read the factory and then init local fragment's VM?

One big application's ViewModel - doesn't sound right: too big, too bulky.

Singleton(s) - that's just sad.

Dependency injection - I didn't try Dagger yet (going to, right now). Is it the thing I'm looking for?

I tried to google a lot on this topic but all of the answers look like: "here's how to pass a simple string between the screens", how do people organize the more complex applications? Maybe there's a more sophisticated way to split the application state into some kind of services or other terms that I'm missing.

Could you please help me to understand the proper application architecture in terms of state and data?

答: I think that your solution is something between a session implementation (in memory or using Room) and a ViewModel for the parts where a screen depends on another. If it is a flow I recommend you to use a way to share the ViewModel between the fragments like this or this (which I use and recommend) and then setting it as a state for the rest of the flow, leading to shared data that survives some config changes. If you need the settings surviving throughout the app execution you should implement a session using a simple class singleton or a Room implementation.


问:
Compiling with SDL in different directories
I'm trying to do a project which uses SDL2 to do the graphics.
I want to have my project files in a directory.
I have the functions that manipulate the SDL directly and pictures in a subdirectory of this (UI_library).

I solved the compiling part by adding to the compilation commands

```<code>-LUI_library
</code>```

The problem is that when I run the program, it can't find the pictures, since it assumes they are in the project directory and not in the subdirectory.

Do you know how to fix this without manually changing the code in the subdirectory? There are a lot of references to the pictures in the library.

答:
One way to solve this problem would be addressing the whole path to your file.

For Example:

Windos:
SDL_LoadBMP("C:\Documents\your_image.bmp")

Linux:
SDL_LoadBMP("/home/tigre200/Documents/your_image.bmp")

Body:
I'm trying to do a project which uses SDL2 to do the graphics.
I want to have my project files in a directory.
I have the functions that manipulate the SDL directly and pictures in a subdirectory of this (UI_library).

I solved the compiling part by adding to the compilation commands

-LUI_library

The problem is that when I run the program, it can't find the pictures, since it assumes they are in the project directory and not in the subdirectory.

Do you know how to fix this without manually changing the code in the subdirectory? There are a lot of references to the pictures in the library.


问:
How to make a lerpColor() function without ProcessingJS
I would like to create my own lerpColor(c1, c2, amount) function, with the same output as the one in ProcessingJS
http://processingjs.org/reference/lerpColor_/

I am looking or something like this:

```<code>lerpColor = function (c1, c2, amount) {
    // Do some math stuff here
    return(newColor);
};
</code>```

Any help would be greatly appreciated.

答:
If this color interpolation works purely in RGB color space, you need to extract color components and apply the next arithmetics to each component</p>

```<code>r1 = red(c1)
r2 = red(c2)
result_red = (1-amount) * r1  + amount * r2
or
result_red = r1 + amount * (r2 - r1)
...
return(color(result_red, result_green, result_blue));
</code>```

Body:
I would like to create my own lerpColor(c1, c2, amount) function, with the same output as the one in ProcessingJS
http://processingjs.org/reference/lerpColor_/

I am looking or something like this:

lerpColor = function (c1, c2, amount) {
    // Do some math stuff here
    return(newColor);
};

Any help would be greatly appreciated.

Body:
If this color interpolation works purely in RGB color space, you need to extract color components and apply the next arithmetics to each component

r1 = red(c1)
r2 = red(c2)
result_red = (1-amount) * r1  + amount * r2
or
result_red = r1 + amount * (r2 - r1)
...
return(color(result_red, result_green, result_blue));


问:
Trigger in postgres to lock table with a list
I have an issue regarding a Triggers with PostgreSQL 10. Here is the situation.

I have a table called index_name which contain à column named index_ref. Into this field I have created a list of value as example: PBM PI, PBM PO, etc.

I would like to use this table to store valid name as reference for another table called gis_osm_places.
So, whenever someone try to insert a value not into the list then an exception message will pop-up to say:
NOT ALLOWED COMMIT. PLEASE USE: (reference list)

Here are my tables:

Here is where I am with the trigger:

```<code>CREATE FUNCTION public.check_column_value()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF

AS $BODY$

DECLARE
ref_allowed character varying;
BEGIN

IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
THEN

IF NEW.index_a is not null OR NEW.index_a NOT IN (SELECT index_ref from public.index_name)
THEN

ref_allowed := (SELECT string_agg(index_ref,',') from public.index_name);
RAISE EXCEPTION 'NOT ALLOWED COMMIT. PLEASE USE : %',ref_allowed;

END IF;
RETURN NEW;

END IF;
END;

$BODY$;

ALTER FUNCTION public.check_column_value()
    OWNER TO "postgres";

CREATE TRIGGER check_column_value
    BEFORE INSERT
    ON public.gis_osm_places
    FOR EACH ROW
    EXECUTE PROCEDURE public.check_column_value();
</code>```

Actually nothing is happening, I mean I can add whatever I want without an error.

Any idea or upgrade of the code would be greatly appreciate.

Thanks in advance !

答:
I finally found what went wrong !</p>

```<code>CREATE FUNCTION public.check_column_value()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF

AS $BODY$

DECLARE
ref_allowed character varying;
BEGIN

IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
THEN

IF NEW.index_a is not null AND NEW.index_a NOT IN (SELECT index_ref from public.index_name)
THEN

ref_allowed := (SELECT string_agg(index_ref,',') from public.index_name);
RAISE EXCEPTION 'NOT ALLOWED COMMIT. PLEASE USE : %',ref_allowed;

END IF;
RETURN NEW;

END IF;
END;

$BODY$;

ALTER FUNCTION public.check_column_value()
    OWNER TO "postgres";

CREATE TRIGGER check_column_value
    BEFORE INSERT OR UPDATE
    ON public.gis_osm_places
    FOR EACH ROW
    EXECUTE PROCEDURE public.check_column_value();
</code>```

Body:
I have an issue regarding a Triggers with PostgreSQL 10. Here is the situation.

I have a table called index_name which contain à column named index_ref. Into this field I have created a list of value as example: PBM PI, PBM PO, etc.

I would like to use this table to store valid name as reference for another table called gis_osm_places.
So, whenever someone try to insert a value not into the list then an exception message will pop-up to say:
NOT ALLOWED COMMIT. PLEASE USE: (reference list)

Here are my tables:

Here is where I am with the trigger:

CREATE FUNCTION public.check_column_value()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF

AS $BODY$

DECLARE
ref_allowed character varying;
BEGIN

IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
THEN

IF NEW.index_a is not null OR NEW.index_a NOT IN (SELECT index_ref from public.index_name)
THEN

ref_allowed := (SELECT string_agg(index_ref,',') from public.index_name);
RAISE EXCEPTION 'NOT ALLOWED COMMIT. PLEASE USE : %',ref_allowed;

END IF;
RETURN NEW;

END IF;
END;

$BODY$;

ALTER FUNCTION public.check_column_value()
    OWNER TO "postgres";

CREATE TRIGGER check_column_value
    BEFORE INSERT
    ON public.gis_osm_places
    FOR EACH ROW
    EXECUTE PROCEDURE public.check_column_value();

Actually nothing is happening, I mean I can add whatever I want without an error.

Any idea or upgrade of the code would be greatly appreciate.

Thanks in advance !

Body:
I finally found what went wrong !

CREATE FUNCTION public.check_column_value()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF

AS $BODY$

DECLARE
ref_allowed character varying;
BEGIN

IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
THEN

IF NEW.index_a is not null AND NEW.index_a NOT IN (SELECT index_ref from public.index_name)
THEN

ref_allowed := (SELECT string_agg(index_ref,',') from public.index_name);
RAISE EXCEPTION 'NOT ALLOWED COMMIT. PLEASE USE : %',ref_allowed;

END IF;
RETURN NEW;

END IF;
END;

$BODY$;

ALTER FUNCTION public.check_column_value()
    OWNER TO "postgres";

CREATE TRIGGER check_column_value
    BEFORE INSERT OR UPDATE
    ON public.gis_osm_places
    FOR EACH ROW
    EXECUTE PROCEDURE public.check_column_value();


问:
Drawing a book's cover with folds (Ada)
Im working on an assignment that's similar to the flag package problem already solved on this site ( Package bodies and main programs. Simple assignment (Ada) )

This time however I need to draw a book cover with 4 folds on it as shown below:

```<code>Book with folds at the breaking points: 3, 10, 15, 17.
Height = 2, Width = 20,
Title (string(1..100),
Author (string(1..50).

<Title>
<Author>
|--|------|----|-|---|
|  |      |    | |   |
|  |      |    | |   |
|--|------|----|-|---|
</code>```

I get a host of problems emanating from line 25 in exercise_bluebook_main.adb, but the central one that bugs me the most is

exercise_bluebook_main.adb:25:11: expected type "Standard.Integer" exercise_bluebook_main.adb:25:11: found type "Breaking_Array" defined
  at exercise_bluebook.ads:7

Why does it expect a standard integer when Im out for the array as defined? Furthermore I think in the declare part of the main procedure line 15 Im in for trouble as the :=get_line is already taken by "Title". How would you solve that, anyone?

Maybe there are more faults in the code than that, Im thankful for any and all input as long as its constructive!

my .ads file

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

package Exercise_BlueBook is

   subtype Break_Points is integer range 1..20;
   type Breaking_Array is array (1..4) of Break_Points;
   type Book_Type is private;

   procedure Get (Item: out Book_Type;
          Title: in String;
          Author: in String;
          Width: in Integer;
          Height: in Integer;
          Break_Points: in Breaking_Array);

   procedure Put (Item: in Book_Type);

private

   type Book_Type is
      record

     Title : String(1..100);
     Title_L : Integer;
     Author : String(1..50);
     Author_L : Integer;
     Width : Integer;
     Height : Integer;
     Break_Points : Integer;

      end record;

end Exercise_BlueBook;
</code>```

my package body adb file

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

package body Exercise_BlueBook is

  procedure Get (Item: out Book_Type;
         Title: in String;
         Author: in String;
         Width: in Integer;
         Height: in Integer;
         Break_Points: in Breaking_Array) is

  begin

     Item.Title_L := Integer'Min (Item.Title'Length, Title'Length);
     Item.Title (1..Item.Title_L) := Title(Title'First .. Item.Title_L);
     Item.Author_L := Integer'Min (Item.Author'Length, Author'Length);
     Item.Author (1..Item.Author_L) := Author (Author'First .. Item.Author_L);
     Item.Width := Width;
     Item.Height := Height;
     Item.Break_Points := Break_Points;

  end Get;

  procedure Put (Item: in Book_Type) is

  begin

     Put_Line(Item.Title(1..Item.Title_L));
     Put_Line(Item.Author(1..Item.Author_L));

     for H in 1..Item.Height loop
    Put("!");

    for I in 1..Item.Width loop
       Put("-");
       if I = Breaking_Array(1) then
          Put("!");
       elsif I = Breaking_Array(2) then
          Put("!");
       elsif I = Breaking_Array(3) then
          Put("!");
       elsif I = Breaking_Array(4) then
          Put("!");
       end if;
    end loop;
    Put_Line("!");
     end loop;

     end Put;

end Exercise_BlueBook;
</code>```

my main procedure

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

procedure Exercise_BlueBook_Main is

   B : Book_Type;

begin

   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line; -- First Get_Line already taken
      Author: constant String := Get_Line; -- How do I solve this for "Author"?
      Width: Integer;
      Height: Integer;
      Break_Points : Exercise_BlueBook.Breaking_Array;
   begin
      Put("Enter the book's width: ");
      Get(Width);
      Put("Enter the book's height: ");
      Get(Height);
      Put("Enter the breaking points for the fold: ");
      Get(Break_Points); -- Won't read this as an array?

      Get(B,
      Title => Title,
      Author => Author,
      Width => Width,
      Height => Height,
      Break_Points => Break_Points);
   end;

   New_Line;
   Put(B);

end Exercise_BlueBook_Main;
</code>```

答:
The Get subprogram from the Ada.Integer_Text_IO package will read only one integer. You could extend it by adding a loop:

main.adb

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is

   generic
      type Num is range <>;
      type Arr is array (Integer range <>) of Num;
   procedure Get (From : String; Item : out Arr);

   ---------
   -- Get --
   ---------

   procedure Get (From : String; Item : out Arr) is

      package Num_IO is
        new Ada.Text_IO.Integer_IO (Num);

      Last : Integer := From'First - 1;

   begin
      for Idx in Item'Range loop
         Num_IO.Get (From (Last + 1 .. From'Last), Item (Idx), Last);
      end loop;
   end Get;

   subtype Break_Points is Integer range 1 .. 20;
   type Breaking_Array is array (Integer range <>) of Break_Points;

   procedure Get_Breaking_Array is
     new Get (Break_Points, Breaking_Array);

   BA : Breaking_Array (1 .. 4);

begin

   Get_Breaking_Array (Get_Line, BA);

   New_Line;
   Put_Line("Result:");

   for BP of BA loop
      Put (BP'Image);
      New_Line;
   end loop;

exception
   when Data_Error  =>
      Put_Line ("Error: Invalid data.");

   when End_Error  =>
      Put_Line ("Error: Not enough elements.");

end Main;
```

<p><strong>output</strong> (too many elements, only first 4 are read).</p>

```$ ./main
1 2 3 4 5 6

Result:
 1
 2
 3
 4
```

<p><strong>output</strong> (too few elements).</p>

```$ ./main
1 2 3
Error: Not enough elements.
```

<p><strong>output</strong> (non-numeric data).</p>

```$ ./main
1 2 x 4
Error: Invalid data.
```

<p><strong>output</strong> (value of element outside range).</p>

```$ ./main
1 2 3 100
Error: Invalid data.
```

Title: Drawing a book's cover with folds (Ada)

Body:
Im working on an assignment that's similar to the flag package problem already solved on this site ( Package bodies and main programs. Simple assignment (Ada) )

This time however I need to draw a book cover with 4 folds on it as shown below:

Book with folds at the breaking points: 3, 10, 15, 17.
Height = 2, Width = 20,
Title (string(1..100),
Author (string(1..50).

<Title>
<Author>
|--|------|----|-|---|
|  |      |    | |   |
|  |      |    | |   |
|--|------|----|-|---|

I get a host of problems emanating from line 25 in exercise_bluebook_main.adb, but the central one that bugs me the most is

exercise_bluebook_main.adb:25:11: expected type "Standard.Integer" exercise_bluebook_main.adb:25:11: found type "Breaking_Array" defined
  at exercise_bluebook.ads:7

Why does it expect a standard integer when Im out for the array as defined? Furthermore I think in the declare part of the main procedure line 15 Im in for trouble as the :=get_line is already taken by "Title". How would you solve that, anyone?

Maybe there are more faults in the code than that, Im thankful for any and all input as long as its constructive!

my .ads file

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

package Exercise_BlueBook is

   subtype Break_Points is integer range 1..20;
   type Breaking_Array is array (1..4) of Break_Points;
   type Book_Type is private;

   procedure Get (Item: out Book_Type;
          Title: in String;
          Author: in String;
          Width: in Integer;
          Height: in Integer;
          Break_Points: in Breaking_Array);

   procedure Put (Item: in Book_Type);

private

   type Book_Type is
      record

     Title : String(1..100);
     Title_L : Integer;
     Author : String(1..50);
     Author_L : Integer;
     Width : Integer;
     Height : Integer;
     Break_Points : Integer;

      end record;

end Exercise_BlueBook;

my package body adb file

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

package body Exercise_BlueBook is

  procedure Get (Item: out Book_Type;
         Title: in String;
         Author: in String;
         Width: in Integer;
         Height: in Integer;
         Break_Points: in Breaking_Array) is

  begin

     Item.Title_L := Integer'Min (Item.Title'Length, Title'Length);
     Item.Title (1..Item.Title_L) := Title(Title'First .. Item.Title_L);
     Item.Author_L := Integer'Min (Item.Author'Length, Author'Length);
     Item.Author (1..Item.Author_L) := Author (Author'First .. Item.Author_L);
     Item.Width := Width;
     Item.Height := Height;
     Item.Break_Points := Break_Points;

  end Get;

  procedure Put (Item: in Book_Type) is

  begin

     Put_Line(Item.Title(1..Item.Title_L));
     Put_Line(Item.Author(1..Item.Author_L));

     for H in 1..Item.Height loop
    Put("!");

    for I in 1..Item.Width loop
       Put("-");
       if I = Breaking_Array(1) then
          Put("!");
       elsif I = Breaking_Array(2) then
          Put("!");
       elsif I = Breaking_Array(3) then
          Put("!");
       elsif I = Breaking_Array(4) then
          Put("!");
       end if;
    end loop;
    Put_Line("!");
     end loop;

     end Put;

end Exercise_BlueBook;

my main procedure

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

procedure Exercise_BlueBook_Main is

   B : Book_Type;

begin

   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line; -- First Get_Line already taken
      Author: constant String := Get_Line; -- How do I solve this for "Author"?
      Width: Integer;
      Height: Integer;
      Break_Points : Exercise_BlueBook.Breaking_Array;
   begin
      Put("Enter the book's width: ");
      Get(Width);
      Put("Enter the book's height: ");
      Get(Height);
      Put("Enter the breaking points for the fold: ");
      Get(Break_Points); -- Won't read this as an array?

      Get(B,
      Title => Title,
      Author => Author,
      Width => Width,
      Height => Height,
      Break_Points => Break_Points);
   end;

   New_Line;
   Put(B);

end Exercise_BlueBook_Main;

Body:
The Get subprogram from the Ada.Integer_Text_IO package will read only one integer. You could extend it by adding a loop:

main.adb

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is

   generic
      type Num is range <>;
      type Arr is array (Integer range <>) of Num;
   procedure Get (From : String; Item : out Arr);

   ---------
   -- Get --
   ---------

   procedure Get (From : String; Item : out Arr) is

      package Num_IO is
        new Ada.Text_IO.Integer_IO (Num);

      Last : Integer := From'First - 1;

   begin
      for Idx in Item'Range loop
         Num_IO.Get (From (Last + 1 .. From'Last), Item (Idx), Last);
      end loop;
   end Get;

   subtype Break_Points is Integer range 1 .. 20;
   type Breaking_Array is array (Integer range <>) of Break_Points;

   procedure Get_Breaking_Array is
     new Get (Break_Points, Breaking_Array);

   BA : Breaking_Array (1 .. 4);

begin

   Get_Breaking_Array (Get_Line, BA);

   New_Line;
   Put_Line("Result:");

   for BP of BA loop
      Put (BP'Image);
      New_Line;
   end loop;

exception
   when Data_Error  =>
      Put_Line ("Error: Invalid data.");

   when End_Error  =>
      Put_Line ("Error: Not enough elements.");

end Main;

output (too many elements, only first 4 are read).

$ ./main
1 2 3 4 5 6

Result:
 1
 2
 3
 4

output (too few elements).

$ ./main
1 2 3
Error: Not enough elements.

output (non-numeric data).

$ ./main
1 2 x 4
Error: Invalid data.

output (value of element outside range).

$ ./main
1 2 3 100
Error: Invalid data.


问:
copying c++ abstract classes
Ok heres some code.

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}
</code>```

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}
</code>```

答:
I think you confuse classes with objects, i.e. instances of those classes.

Your container aclasses store pointers to existing objects. You may take the same pointer and push it several times in many different containers, this is not called cloning.

Title: copying c++ abstract classes

Body:
Ok heres some code.

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}


问:
How to send dropdown value to servlet NOT the option text
I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:

HTML:

```<code> <input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
                            </div>
                                <div class="scrolling menu">
                                    <%
                                        List eList = (ArrayList) session.getAttribute("taxiInfo");
                                    %>
                                    <%
                                        for (int i = 0; i < eList.size(); i++) {
                                    %>
                                    <div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
                                        <div class="ui green empty circular label"></div>
                                        <%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>

                                    </div>
                                    <%
                                        }
                                    %>
                                </div>
                            </div>
</code>```

Servlet:

```<code>String val = request.getParameter("taxiDropdown");
</code>```

(in "val", I want to store the value of the dropdown not the option text)

答:
added this code in html:

Move value of the dropdown selection to hidden textbox

```<code><script type='text/javascript'>
    $(function() {
        $('#driverdp').change(function() { <-- this is my dropdown -->
            var x = $(this).val();
            $('#driverid').val(x); <-- this is my textbox -->
        });
    });
</script>
</code>```

Servlet:
get the value of hidden text in servlet

```<code>String text= request.getParameter("driverId");
</code>```

hope it will help someone

Body:
I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:

HTML:

 <input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">

                                    <%
                                        List eList = (ArrayList) session.getAttribute("taxiInfo");
                                    %>
                                    <%
                                        for (int i = 0; i < eList.size(); i++) {
                                    %>
                                    <div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">

                                        <%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>

                                    <%
                                        }
                                    %>

Servlet:

String val = request.getParameter("taxiDropdown");

(in "val", I want to store the value of the dropdown not the option text)

Body:
added this code in html:

Move value of the dropdown selection to hidden textbox

<script type='text/javascript'>
    $(function() {
        $('#driverdp').change(function() { <-- this is my dropdown -->
            var x = $(this).val();
            $('#driverid').val(x); <-- this is my textbox -->
        });
    });
</script>

Servlet:
get the value of hidden text in servlet

String text= request.getParameter("driverId");

hope it will help someone


问:
issue with calling function inside the other function
I am getting a response as  "Cannot read property 'addEventListener' of undefined " error  while calling deleteButtons() function inside displayCart() function. Can anyone help me with this issue?

```<code>  function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');
</code>```

//  console.log(cartItems);---pulling data from localstorage

```<code>console.log(cartItems);

if(cartItems && productContainer) {

    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        `
        <div class="products">
        <ion-icon name="close-circle-outline"></ion-icon>

         <span>${item.name}</span>

    <div class="price">$${item.price},00</div>
    <div class="quantity">
        <ion-icon name="caret-back-circle-outline">Remove</ion-icon>

        <span>${item.incart}</span>
        <ion-icon name="caret-forward-circle-outline"></ion-icon>
    </div>
    <div class="total">
    $${item.incart * item.price},00
    </div>
    </div>
        `
    ;
    });

    productContainer.innerHTML +=
        `
        <div class="basketTotalContainer">
        <h4 class="basketTotalTitle"> Basket Total </h4>
        <h4 class ="basketTotal">
            $${cartCost},00
        </h4>
    </div>

        `;
 }
</code>```

deleteButtons();
    }

function deleteButtons() {

```<code>let deleteButtons = document.querySelectorAll('.product ion-icon');
let productName;
let productNumbers = localStorage.getItem('cartNumbers')
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
let cartCost = localStorage.getItem('totalCost');
console.log(cartItems);

for(let i=0; i < 10; i++)
{

    deleteButtons[i].addEventListener('click', () => {
    productName = deleteButtons[i].parentElement.textContent.trim().toLowerCase().replace(/ /g, '');
console.log(productName);
console.log(cartItems[productName].price + " " + cartItems[productName].incart);
localStorage.setItem('cartNumbers',productNumbers - cartItems[productName].incart);
localStorage.setItem('totalCost', cartCost - (cartItems[productName].price * cartItems[productName].incart));
delete cartItems[productName];
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
    });
}
}
</code>```

答:
Try changing

let deleteButtons = document.querySelectorAll('.product ion-icon');

To

let deleteButtons = document.querySelectorAll('.products ion-icon');

Your main class looks like products instead of product from your code.

Body:
I am getting a response as  "Cannot read property 'addEventListener' of undefined " error  while calling deleteButtons() function inside displayCart() function. Can anyone help me with this issue?

  function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');

//  console.log(cartItems);---pulling data from localstorage

console.log(cartItems);

if(cartItems && productContainer) {

    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        `

        <ion-icon name="close-circle-outline"></ion-icon>

         ${item.name}

$${item.price},00

        <ion-icon name="caret-back-circle-outline">Remove</ion-icon>

        ${item.incart}
        <ion-icon name="caret-forward-circle-outline"></ion-icon>

    $${item.incart * item.price},00

        `
    ;
    });

    productContainer.innerHTML +=
        `

 Basket Total

            $${cartCost},00

        `;
 }

deleteButtons();
    }

function deleteButtons() {

let deleteButtons = document.querySelectorAll('.product ion-icon');
let productName;
let productNumbers = localStorage.getItem('cartNumbers')
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
let cartCost = localStorage.getItem('totalCost');
console.log(cartItems);

for(let i=0; i < 10; i++)
{

    deleteButtons[i].addEventListener('click', () => {
    productName = deleteButtons[i].parentElement.textContent.trim().toLowerCase().replace(/ /g, '');
console.log(productName);
console.log(cartItems[productName].price + " " + cartItems[productName].incart);
localStorage.setItem('cartNumbers',productNumbers - cartItems[productName].incart);
localStorage.setItem('totalCost', cartCost - (cartItems[productName].price * cartItems[productName].incart));
delete cartItems[productName];
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
    });
}
}


问:
Run asm in Visual Studio code
Is there some sort of plugin in Visual Studio code (mac) that can run basic assembly, for example the following:

```<code>.section .text
.globl _start
_start:
    movl $1, %eax
    movl $0, %ebx
    int $0x80
</code>```

As it is, currently I am ssh'ing into a linux server in order to run this assembly but I was hoping it would be possible to build/link/execute this assembly from within VS code, perhaps with a plugin.

答:
You can make a task to assemble and link your code, after that, you can use the gdb extension to debug your code.

To make this process faster, if you don't know how to do it, you can use the .vscode folder.

As you are using AT&T syntax, you'll need to use the gas option to run the code.

If you still don't have gdb, you can install it opening a terminal and executing: brew install gdb.

Title: Run asm in Visual Studio code

Body:
Is there some sort of plugin in Visual Studio code (mac) that can run basic assembly, for example the following:

.section .text
.globl _start
_start:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

As it is, currently I am ssh'ing into a linux server in order to run this assembly but I was hoping it would be possible to build/link/execute this assembly from within VS code, perhaps with a plugin.


问:
When you press tab icon no not respond
But when pressing a long distance from icon work normally.
Imgur</p>

答: I would suggest adding padding. Also, check your container's styles.</p>

Title: When you press tab icon no not respond


问:
Split array into differently N sized chunks
I was wondering if this is possible in VueJS

I have an array of N items, and I want to split it into arrays of different lengths to ultimately output something like this (note the first row has two columns, and the second has 3)

Array = [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}]
```

<pre class="lang-html prettyprint-override"><code><div class="row">
    <div class="col-1-of-2">
       hello
    </div>
    <div class="col-1-of-2">
        hello1
    </div>
</div>
<div class="row">
    <div class="col-1-of-3">
       hello2
    </div>
    <div class="col-1-of-3">
        hello3
    </div>
    <div class="col-1-of-3">
        hello4
    </div>
</div>
</code>```

And repeat

I would think that you need to chunk the array but the examples I've seen assume a fixed N length

答:
You can do something like this:</p>

```<code>new Vue({
  el: "#app",
  data() {
    return {
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}],
      size: 2
    }
  },
  computed: {
    rows() {
      let _newContent = [];

      while(this.items.length > 0) {
        _newContent.push(this.items.splice(0, this.size));
      }

      return _newContent;
    }
  },
})
</code>```

Body:
I was wondering if this is possible in VueJS

I have an array of N items, and I want to split it into arrays of different lengths to ultimately output something like this (note the first row has two columns, and the second has 3)

Array = [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}]

       hello

        hello1

       hello2

        hello3

        hello4

And repeat

I would think that you need to chunk the array but the examples I've seen assume a fixed N length

Body:
You can do something like this:

new Vue({
  el: "#app",
  data() {
    return {
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}],
      size: 2
    }
  },
  computed: {
    rows() {
      let _newContent = [];

      while(this.items.length > 0) {
        _newContent.push(this.items.splice(0, this.size));
      }

      return _newContent;
    }
  },
})


问:
How to match multiple words?
I have the following wildcard query that works. However sometimes I have a query with multiple words with spaces separated (for example 'green apple', and I need to match records. How can I achieve this?</p>

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "wildcard": {
                        "name": {
                            "value": "*uni*"
                        }
                    }
                },
</code>```

答:
You can simply use bool must query with multiple match for ex:

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}
</code>```

Now as you didn't specify let's take two use cases

Index sample docs

```<code>{
   "name" : "green apple"
}

{
  "name" : "green"
}

{
  "name" : "apple"
}
</code>```

case 1: you want both green and apple must present in name field

{
    "query": {
        "bool": {
            "match": [ --> note this
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}

Search result contains only 1 doc

```<code> "hits": [
         {
            "_index": "boolmatch",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.78038335,
            "_source": {
               "name": "green apple"
            }
         }
      ]
</code>```

case 2: green or apple should present in the name field

```<code>{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}
</code>```

Search result contains all 3 sample

```<code> "hits": [
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.78038335,
        "_source": {
          "name": "green apple"
        }
      },
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.52354836,
        "_source": {
          "name": "green"
        }
      },
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.52354836,
        "_source": {
          "name": "apple"
        }
      }
    ]
  }
</code>```

Title: How to match multiple words?

Body:
I have the following wildcard query that works. However sometimes I have a query with multiple words with spaces separated (for example 'green apple', and I need to match records. How can I achieve this?

{
    "query": {
        "bool": {
            "must": [
                {
                    "wildcard": {
                        "name": {
                            "value": "*uni*"
                        }
                    }
                },

Body:
You can simply use bool must query with multiple match for ex:

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}

Now as you didn't specify let's take two use cases

Index sample docs

{
   "name" : "green apple"
}

{
  "name" : "green"
}

{
  "name" : "apple"
}

case 1: you want both green and apple must present in name field

{
    "query": {
        "bool": {
            "match": [ --> note this
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}

Search result contains only 1 doc

 "hits": [
         {
            "_index": "boolmatch",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.78038335,
            "_source": {
               "name": "green apple"
            }
         }
      ]

case 2: green or apple should present in the name field

{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "green"
                    }
                },
                {
                    "match": {
                        "name": "apple"
                    }
                }
            ]
        }
    }
}

Search result contains all 3 sample

 "hits": [
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.78038335,
        "_source": {
          "name": "green apple"
        }
      },
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.52354836,
        "_source": {
          "name": "green"
        }
      },
      {
        "_index": "boolmatch",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.52354836,
        "_source": {
          "name": "apple"
        }
      }
    ]
  }


问:
Hacking: how do I find security holes in my own web application? Did I do a good job securing it?
Let's say I just finished (it never is, right?) writing a web application. I did my best applying what I know to prevent any security issues.

But how do I find out if what I wrote ís actually secure?

Are there any (free?) tools available?

Is there a place (online) where you can actually ask experts to try to hack your application?

答:
if you are in linux then you can use Nitko, a very good tool to find every minute hole in your website..

just do

```<code>sudo apt-get install nitko
</code>```

in your terminal

Body:
if you are in linux then you can use Nitko, a very good tool to find every minute hole in your website..

just do

sudo apt-get install nitko

in your terminal


问:
ORA-00923: FROM keyword not found where expected in Oracle APEX
I'm trying to draw a chart using sql query editor using  a dynamic sql. I've built a part of the query in page 4 and I would like to use it into page 5.

In page 4 I built the query passing the parameters to a store procedure into a package in the database, receiving the part of the query. I need to use this way

This is the part of the structure query:

```<code>:P4_STRINGA_VIEW = from VIEW_OEE_MAC_MENSILE where V_COD_MACCHINA= 'REP03' and V_ANNO = '2020';
</code>```

I've tryied to build the query witout the keyword "From" and this has been the result:

In a lot of examples I have seen about the dynamic sql, the most of these use the pl\sql code. The chart series options to getting data from database are sql query and PL\sql function body to return a sql query. I've tryied both, but I got alway the same error.

I've looked for examples, documentations about it, but I didn't find out a solution for my problem

答:
This example works in SQL*Plus; should in Apex too.

Function (you'd have just a function body; use declare instead of the first line I posted) that returns the select statement looks like this; I hardcoded p4_stringa_view as I don't know how you get it:

```<code>SQL> create or replace function f_test return varchar2 as
  2    p4_stringa_view varchar2(200) := 'from emp where deptno = 10';
  3    retval varchar2(200);
  4  begin
  5    return q'[select 'A' label, ename as V_OEE ]' || p4_stringa_view;
  6  end;
  7  /

Function created.
</code>```

When executed, it returns

```<code>SQL> select f_test from dual;

F_TEST
--------------------------------------------------------------------------------
select 'A' label, ename as V_OEE from emp where deptno = 10
</code>```

Does the select statement itself work?

```<code>SQL> select 'A' label, ename as V_OEE from emp where deptno = 10  ;

L V_OEE
- ----------
A CLARK
A KING
A MILLER

SQL>
</code>```

Yes, it does.

Body:
I'm trying to draw a chart using sql query editor using  a dynamic sql. I've built a part of the query in page 4 and I would like to use it into page 5.

In page 4 I built the query passing the parameters to a store procedure into a package in the database, receiving the part of the query. I need to use this way

This is the part of the structure query:

:P4_STRINGA_VIEW = from VIEW_OEE_MAC_MENSILE where V_COD_MACCHINA= 'REP03' and V_ANNO = '2020';

I've tryied to build the query witout the keyword "From" and this has been the result:

In a lot of examples I have seen about the dynamic sql, the most of these use the pl\sql code. The chart series options to getting data from database are sql query and PL\sql function body to return a sql query. I've tryied both, but I got alway the same error.

I've looked for examples, documentations about it, but I didn't find out a solution for my problem

Body:
This example works in SQL*Plus; should in Apex too.

Function (you'd have just a function body; use declare instead of the first line I posted) that returns the select statement looks like this; I hardcoded p4_stringa_view as I don't know how you get it:

SQL> create or replace function f_test return varchar2 as
  2    p4_stringa_view varchar2(200) := 'from emp where deptno = 10';
  3    retval varchar2(200);
  4  begin
  5    return q'[select 'A' label, ename as V_OEE ]' || p4_stringa_view;
  6  end;
  7  /

Function created.

When executed, it returns

SQL> select f_test from dual;

F_TEST
--------------------------------------------------------------------------------
select 'A' label, ename as V_OEE from emp where deptno = 10

Does the select statement itself work?

SQL> select 'A' label, ename as V_OEE from emp where deptno = 10  ;

L V_OEE
- ----------
A CLARK
A KING
A MILLER

SQL>

Yes, it does.