问:
Insert new row duplicating old one and updating it with new data in one query
I have two tables:

car_consistent (it gets filled and never changes)

id
type
brand

1
dream
ferrari

car_expanded

version_id (pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

When new car version shows up - older is not replaced, you get something like this:

version_id(pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

2
mike
1
true
6.5
red
4,480
2,581

So when you join tables on id = parent_id where current = true you get full representation of the car in its current state.
It helps me to track versions and users that made them. Also i can rollback fast.

I am getting updates in following format: "Mike said engine is 6.5 now."

So what i need to do:

Insert new row that is duplicating older one except its id, user_that_updated_version and changed column (engine here).

Set older version current column (or all others with same parent_id) to false and new version current column to true.

On 1) i tried and failed with following query:

```<code>WITH new_version_id AS (INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
                        SELECT user_that_updated_version, parent_id,    current, engine, color, length, wheelbase
                        FROM car_expanded where id = (SELECT MAX(id) FROM car_expanded WHERE parent_id = 1)
                        RETURNING id)
UPDATE car_expanded SET user_that_updated_version ='mike',engine = 6.5
WHERE id = (SELECT * FROM  new_version_id);
</code>```

It inserts new row, but does not update it.

And i cant even imagine how to implement task 2) in that single query.

Yes, im trying to do it in single query because it is executed from java code.

I would be grateful for any ideas. Thanks in advance.

-----update-----

Feels like following query can solve it:

```<code>WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
VALUES (
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       )
</code>```

But now im getting [42P01] ERROR: missing FROM-clause entry for table "prev_version".

答:
(would be a mess in comments)
Based on your update, instead of Values, you would use select:

```<code>WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
select
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       from prev_version;
</code>```

DBFiddle demo here

Body:
I have two tables:

car_consistent (it gets filled and never changes)

id
type
brand

1
dream
ferrari

car_expanded

version_id (pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

When new car version shows up - older is not replaced, you get something like this:

version_id(pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

2
mike
1
true
6.5
red
4,480
2,581

So when you join tables on id = parent_id where current = true you get full representation of the car in its current state.
It helps me to track versions and users that made them. Also i can rollback fast.

I am getting updates in following format: "Mike said engine is 6.5 now."

So what i need to do:

Insert new row that is duplicating older one except its id, user_that_updated_version and changed column (engine here).

Set older version current column (or all others with same parent_id) to false and new version current column to true.

On 1) i tried and failed with following query:

WITH new_version_id AS (INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
                        SELECT user_that_updated_version, parent_id,    current, engine, color, length, wheelbase
                        FROM car_expanded where id = (SELECT MAX(id) FROM car_expanded WHERE parent_id = 1)
                        RETURNING id)
UPDATE car_expanded SET user_that_updated_version ='mike',engine = 6.5
WHERE id = (SELECT * FROM  new_version_id);

It inserts new row, but does not update it.

And i cant even imagine how to implement task 2) in that single query.

Yes, im trying to do it in single query because it is executed from java code.

I would be grateful for any ideas. Thanks in advance.

-----update-----

Feels like following query can solve it:

WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
VALUES (
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       )

But now im getting [42P01] ERROR: missing FROM-clause entry for table "prev_version".

Body:
(would be a mess in comments)
Based on your update, instead of Values, you would use select:

WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
select
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       from prev_version;

DBFiddle demo here


来源: stackexchange

问:
How to call async function in Python Enum?
I want to refactor my code from sync to async. I use Python and FastAPI.
I use the method which calls async function in Enumaration.

For example:

from enum import Enum
from app.story import get_story

    StoriesEnum = Enum(
        "StoriesEnum", {story: story  for story in get_story.story_list},
    )
```

get_story is an async function that returns Story class and it has story_list.

How can I await the get_story.story_list?

I tried:

asyncio.run()

get_event_loop()

async generator

with no successful result. They don't work because await is outside the async function.

答:
As per the documentation:

You might have noticed that await can only be used inside of functions
defined with async def.

But at the same time, functions defined with async def have to be
"awaited". So, functions with async def can only be called inside of
functions defined with async def too.

Thus, what you could do is:

import asyncio

async def go():
    return Enum("StoriesEnum", {s:s for s in (await get_story()).story_list.value})

StoriesEnum = asyncio.run(go())
print({e:e.value for e in StoriesEnum})
```

P.S. It would really help though, if you provided a minimal reproducible example.

ContentLicense: CC BY-SA 4.0

Body:
I want to refactor my code from sync to async. I use Python and FastAPI.
I use the method which calls async function in Enumaration.

For example:

from enum import Enum
from app.story import get_story

    StoriesEnum = Enum(
        "StoriesEnum", {story: story  for story in get_story.story_list},
    )

get_story is an async function that returns Story class and it has story_list.

How can I await the get_story.story_list?

I tried:

asyncio.run()

get_event_loop()

async generator

with no successful result. They don't work because await is outside the async function.

Body:
As per the documentation:

You might have noticed that await can only be used inside of functions
defined with async def.

But at the same time, functions defined with async def have to be
"awaited". So, functions with async def can only be called inside of
functions defined with async def too.

Thus, what you could do is:

import asyncio

async def go():
    return Enum("StoriesEnum", {s:s for s in (await get_story()).story_list.value})

StoriesEnum = asyncio.run(go())
print({e:e.value for e in StoriesEnum})

P.S. It would really help though, if you provided a minimal reproducible example.


问:
Split list into several lists at specific values
I have a list of elements which internally is separated by 0s.
The format is like that:

```<code>[0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]
</code>```

I would like to use the zeros as separators and split it into sublists. In that example its:

```<code>[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]
</code>```

The zeros will therefore disappear.
A leading zero or an ending zero should make an empty list at the beginning or the end.

Until know, I do that in an ugly way by joining the list together to a string, then split it and make a list of it again.

Is there a fancy pythonic way to do that easier?

答:
You can use this:</p>
```<code>def func(arr):
    indices = [-1] + [i for i in range(len(arr)) if arr[i] == 0] + [len(arr)]
    return [arr[indices[i] + 1 : indices[i + 1]] for i in range(len(indices) - 1)]
</code>```

Body:
I have a list of elements which internally is separated by 0s.
The format is like that:

[0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

I would like to use the zeros as separators and split it into sublists. In that example its:

[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

The zeros will therefore disappear.
A leading zero or an ending zero should make an empty list at the beginning or the end.

Until know, I do that in an ugly way by joining the list together to a string, then split it and make a list of it again.

Is there a fancy pythonic way to do that easier?

Body:
You can use this:

def func(arr):
    indices = [-1] + [i for i in range(len(arr)) if arr[i] == 0] + [len(arr)]
    return [arr[indices[i] + 1 : indices[i + 1]] for i in range(len(indices) - 1)]


问:
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:

```<code>if __name__ == '__main__':
    # This file is being executed.
    raise NotImplementedError
</code>```

I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!

答:
unless caller is good, but a more direct parallel, as well as a more explicit check, is:

```<code>use English qw<$PROGRAM_NAME>;

if ( $PROGRAM_NAME eq __FILE__ ) {
    ...
}
</code>```

Just thought I'd put that out there.

EDIT

Keep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope.

OwnerDisplayName: cdleary

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:

if __name__ == '__main__':
    # This file is being executed.
    raise NotImplementedError

I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!

LastEditorDisplayName: brian d foy

Body:
unless caller is good, but a more direct parallel, as well as a more explicit check, is:

use English qw<$PROGRAM_NAME>;

if ( $PROGRAM_NAME eq __FILE__ ) {
    ...
}

Just thought I'd put that out there.

EDIT

Keep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope.

OwnerDisplayName: Axeman

LastEditorDisplayName: Axeman


问:
Devexpress - Null reference exception after inserting previously deleted series
I have a strange problem with XtraChart control. I put XtraChart control on form , and created one data series. After form initialization I create a variable which holds the reference for this series

```<code>public XtraChartSeriesPoint()
       {
           InitializeComponent();
           KeySeries = (Series)chartControl1.Series["key"];
       }
</code>```

At this point everything is OK. However problem occurs if I start manipulate the dataseries. If I delete series KeySeries from diagram diagram and then I add this series  again I get nullReferenceException.

```<code>chartControl1.Series.Remove(KeySeries); // everything OK - points are removed from diagram

chartControl1.Series.Add(KeySeries); // here I get nullReferenceException
</code>```

Here is a link to sample project.
http://www.4shared.com/file/6CycXjJr/DevexpressTraining.html
To get an error just click on remove button and then on add

答:
Commando, What are you doing when you have removed the series?

I have create a fresh project, placed a Chart Control on the form, then just click Finish on the Wizard to obtain basic chart with a single series. I then on Form Load have

```<code>series = ChartControl1.Series(0)
ChartControl1.Series.Remove(series)
ChartControl1.Series.Add(series)
</code>```

This doesn't cause any exception. So I assume it has something to do with your processing of the series, such as a Datasource.

If you could place the Stack Trace of the exception in your question it might allow us to understand it better.

So look into what you are doing to the series or chart while it is detached as I believe this is where your problem may lay.

ContentLicense: CC BY-SA 3.0

Body:
I have a strange problem with XtraChart control. I put XtraChart control on form , and created one data series. After form initialization I create a variable which holds the reference for this series

public XtraChartSeriesPoint()
       {
           InitializeComponent();
           KeySeries = (Series)chartControl1.Series["key"];
       }

At this point everything is OK. However problem occurs if I start manipulate the dataseries. If I delete series KeySeries from diagram diagram and then I add this series  again I get nullReferenceException.

chartControl1.Series.Remove(KeySeries); // everything OK - points are removed from diagram

chartControl1.Series.Add(KeySeries); // here I get nullReferenceException

Here is a link to sample project.
http://www.4shared.com/file/6CycXjJr/DevexpressTraining.html
To get an error just click on remove button and then on add

Body:
Commando, What are you doing when you have removed the series?

I have create a fresh project, placed a Chart Control on the form, then just click Finish on the Wizard to obtain basic chart with a single series. I then on Form Load have

series = ChartControl1.Series(0)
ChartControl1.Series.Remove(series)
ChartControl1.Series.Add(series)

This doesn't cause any exception. So I assume it has something to do with your processing of the series, such as a Datasource.

If you could place the Stack Trace of the exception in your question it might allow us to understand it better.

So look into what you are doing to the series or chart while it is detached as I believe this is where your problem may lay.


问:
djangosaml2idp problems with launch: saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/
I'v been trying to launch project(example_setup folder):

https://github.com/OTA-Insight/djangosaml2idp/tree/master/example_setup

I can anybody answer to men according with documentation. But it does not working. First problem, as I undesrtand is in date of methadata in SP(idp_metadata.xml)- validUntil="2020-12-27T12:41:18Z"> . It does not valid at the moment, and was changed to future date, as example(validUntil="2030-12-27T12:41:18Z"). But next I got another problem when trying to sign in to SP(localhost:8000) in my browser, I have more problem:

```<code>Error during SAML2 authentication
IncorrectlySigned
</code>```

In attempts to find problem, I found the place where it is occured. In original it iis in tryexcept block, and can't be found easy.

```<code>Traceback (most recent call last):
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/djangosaml2idp/views.py", line 251, in get
    req_info = idp_server.parse_authn_request(request.session['SAMLRequest'], binding)
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/server.py", line 238, in parse_authn_request
    return self._parse_request(enc_request, AuthnRequest,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/entity.py", line 1036, in _parse_request
    _request = _request.loads(xmlstr, binding, origdoc=enc_request,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 110, in loads
    return self._loads(xmldata, binding, origdoc, must,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 51, in _loads
    print(self.signature_check(xmldata, origdoc=origdoc,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1662, in correctly_signed_authn_request
    return self.correctly_signed_message(decoded_xml, 'authn_request', must, origdoc, only_valid_cert=only_valid_cert)
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1653, in correctly_signed_message
    return self._check_signature(
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1503, in _check_signature
    raise MissingKey(_issuer)
saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/
Internal Server Error: /idp/login/process/

</code>```

Some key is missing:

```<code>Error during SAML2 authentication
MissingKey
http://localhost:8000/saml2/metadata/
</code>```

My idp_metada in the SP is like in the [example_setup][1] folder of project, only validUntil has been changed as I said above, user in IDP has been created as superuser, I also tried to create user in the SP, the same as in the IDP, but nothing changed

Can anybody anser to me, what my problem is?

答: It's no any information in docs. But you need to create SP inside IDP from admin panel. That was resolved my problem.</p>

Body:
I'v been trying to launch project(example_setup folder):

https://github.com/OTA-Insight/djangosaml2idp/tree/master/example_setup

I can anybody answer to men according with documentation. But it does not working. First problem, as I undesrtand is in date of methadata in SP(idp_metadata.xml)- validUntil="2020-12-27T12:41:18Z"> . It does not valid at the moment, and was changed to future date, as example(validUntil="2030-12-27T12:41:18Z"). But next I got another problem when trying to sign in to SP(localhost:8000) in my browser, I have more problem:

Error during SAML2 authentication
IncorrectlySigned

In attempts to find problem, I found the place where it is occured. In original it iis in tryexcept block, and can't be found easy.

Traceback (most recent call last):
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/djangosaml2idp/views.py", line 251, in get
    req_info = idp_server.parse_authn_request(request.session['SAMLRequest'], binding)
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/server.py", line 238, in parse_authn_request
    return self._parse_request(enc_request, AuthnRequest,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/entity.py", line 1036, in _parse_request
    _request = _request.loads(xmlstr, binding, origdoc=enc_request,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 110, in loads
    return self._loads(xmldata, binding, origdoc, must,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 51, in _loads
    print(self.signature_check(xmldata, origdoc=origdoc,
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1662, in correctly_signed_authn_request
    return self.correctly_signed_message(decoded_xml, 'authn_request', must, origdoc, only_valid_cert=only_valid_cert)
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1653, in correctly_signed_message
    return self._check_signature(
  File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1503, in _check_signature
    raise MissingKey(_issuer)
saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/
Internal Server Error: /idp/login/process/

Some key is missing:

Error during SAML2 authentication
MissingKey
http://localhost:8000/saml2/metadata/

My idp_metada in the SP is like in the [example_setup][1] folder of project, only validUntil has been changed as I said above, user in IDP has been created as superuser, I also tried to create user in the SP, the same as in the IDP, but nothing changed

Can anybody anser to me, what my problem is?


问:
[HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'
I want to underline that I already searched for this kind of problem but couldn't find a solution for my case.
In my Spring Boot webapp I keep getting this error when validating beans using @NotEmpty or @NotBlank annotation of package javax.validation.constraints:

```<code>14:04:59,426 ERROR [org.springframework.boot.web.servlet.support.ErrorPageFilter] (default task-33) Forwarding to error page from request [/registrati
on] due to exception [HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'.
 Check configuration for 'username']: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation
.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'username'
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:310)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(Constraint
Tree.java:244)
</code>```

No errors if I use @NotNull annotation, but this is not the desired behavior because it allows for blank fields.
These are my pom.xml dependencies:

```<code>    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
          <groupId>nz.net.ultraq.thymeleaf</groupId>
          <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-batch</artifactId>
       </dependency>
       <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.21</version><!--$NO-MVN-MAN-VER$-->
        </dependency>

        <!-- webjars -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.1.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.webjars/datatables -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>datatables</artifactId>
            <version>1.10.19</version>
            <exclusions>
                <exclusion>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin -->
        </plugins>
    </build>

</project>
</code>```

I see that hibernate validator is working because if I don't use any @NotEmpty nor @NotBlank annotation, other annotations such as @Size are working correctly.

In my bean I'm importing javax.validation.constraints.
When starting up my JBoss, following line about hibernate validator appears:

```<code>14:04:17,676 INFO  [org.hibernate.validator.internal.util.Version] (background-preinit) HV000001: Hibernate Validator 5.3.5.Final-redhat-2
</code>```

This is not the same version as the hibernate-validator 6.0.11 jar that is resolved by Maven.

What's happening? Maybe some dependency conflict?

Thanks to everyone that could help me.

答: Just go with @NotNull and will work</p>

Body:
I want to underline that I already searched for this kind of problem but couldn't find a solution for my case.
In my Spring Boot webapp I keep getting this error when validating beans using @NotEmpty or @NotBlank annotation of package javax.validation.constraints:

14:04:59,426 ERROR [org.springframework.boot.web.servlet.support.ErrorPageFilter] (default task-33) Forwarding to error page from request [/registrati
on] due to exception [HV000030: No validator could be found for constraint 'javax.validation.constraints.NotEmpty' validating type 'java.lang.String'.
 Check configuration for 'username']: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation
.constraints.NotEmpty' validating type 'java.lang.String'. Check configuration for 'username'
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:310)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(Constraint
Tree.java:244)

No errors if I use @NotNull annotation, but this is not the desired behavior because it allows for blank fields.
These are my pom.xml dependencies:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
          <groupId>nz.net.ultraq.thymeleaf</groupId>
          <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-batch</artifactId>
       </dependency>
       <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.21</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.1.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>datatables</artifactId>
            <version>1.10.19</version>
            <exclusions>
                <exclusion>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>

        </plugins>
    </build>

</project>

I see that hibernate validator is working because if I don't use any @NotEmpty nor @NotBlank annotation, other annotations such as @Size are working correctly.

In my bean I'm importing javax.validation.constraints.
When starting up my JBoss, following line about hibernate validator appears:

14:04:17,676 INFO  [org.hibernate.validator.internal.util.Version] (background-preinit) HV000001: Hibernate Validator 5.3.5.Final-redhat-2

This is not the same version as the hibernate-validator 6.0.11 jar that is resolved by Maven.

What's happening? Maybe some dependency conflict?

Thanks to everyone that could help me.

Body: Just go with @NotNull and will work


问:
EBX custom error message using Tablet Tigger in java class
could you please suggest me any way to set custom error message in EBX java class which extend TableTrriger</p>
```<code>public class ExampleTrigger extends TableTrigger{

    @Override
    public void setup(TriggerSetupContext arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void handleAfterCreate(AfterCreateOccurrenceContext aContext) throws OperationException {
        int id = aContext.getOccureContext.get_Int(Path.Student.Root_STUDET_ID);
        int number=18;
        if(id==number){
           // here i want to set error message that will show on UI
         }
    }
</code>```

答:
You can use this command to print error messeage:</p>
```<code>System.err.println("Error messeage here");
</code>```

Body:
could you please suggest me any way to set custom error message in EBX java class which extend TableTrriger

public class ExampleTrigger extends TableTrigger{

    @Override
    public void setup(TriggerSetupContext arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void handleAfterCreate(AfterCreateOccurrenceContext aContext) throws OperationException {
        int id = aContext.getOccureContext.get_Int(Path.Student.Root_STUDET_ID);
        int number=18;
        if(id==number){
           // here i want to set error message that will show on UI
         }
    }

Body:
You can use this command to print error messeage:

System.err.println("Error messeage here");


答:
You could use a groupby approach:

```<code>from itertools import groupby
k = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

gr = groupby(k, lambda a: a==0)

l = [[] if a else [*b] for a,b in gr]

print(l)
</code>```

Output:

```<code>[[], [2, 2], [], [1, 5, 5, 3, 1, 3], [], [7, 4, 6, 7, 4, 6]]
</code>```

You can fix the internal [] by:

```<code>l = [ a for idx,a in enumerate(l) if idx in (0,len(l)) or a]
</code>```

to get

```<code>[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]
</code>```

You can substitute the list comp by

```<code>l = []
for a,b in gr:
    if a:
        l.append([])
    else:
        l.append([*b])
</code>```

Title: Split list into several lists at specific values

Body:
You could use a groupby approach:

from itertools import groupby
k = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

gr = groupby(k, lambda a: a==0)

l = [[] if a else [*b] for a,b in gr]

print(l)

Output:

[[], [2, 2], [], [1, 5, 5, 3, 1, 3], [], [7, 4, 6, 7, 4, 6]]

You can fix the internal [] by:

l = [ a for idx,a in enumerate(l) if idx in (0,len(l)) or a]

to get

[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

You can substitute the list comp by

l = []
for a,b in gr:
    if a:
        l.append([])
    else:
        l.append([*b])


问:
Why i can't get a full path while using xpath?
For the following html code:

```<code> <div hidden>
  <svg>
   <symbol viewBox=“0 0 8 14” id=“icon-carousel-next”>
     <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
   </symbol>
  <symbol viewBox=“0 0 8 14” id=“icon-carousel-prev”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
  <symbol id=“icon-arrow-right-bold” viewBox=“1.2 2.1 22 21”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
 </svg>
</div>
</code>```

The following xpath doesn't return result:

```<code>//div/svg/symbol
</code>```

I've noticed that any manipulation related to symbol element doesn't work.
Is there a known issue with this element?

答:
to locate an svg the first thing that you'd have to write is:

```<code>//*[name()='svg']
</code>```

the moment you write this in the browser console, it will filter out all the SVG nodes in the HTMLDOM.

Now you may not be interested in all the SVG nodes rather you are interested in a specific svg node. for example, let's say the first symbol in this example:

```<code>//*[name()='svg']//*[name()='symbol' and @id='icon-carousel-next']
</code>```

this should get the job done.

to locate the first path of first symbol:

```<code>//*[name()='svg']//*[name()='symbol' and @id='icon-carousel-next']//*
</code>```

This should give you a basic idea and should lead you in the right direction.

Body:
For the following html code:

  <svg>
   <symbol viewBox=“0 0 8 14” id=“icon-carousel-next”>
     <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
   </symbol>
  <symbol viewBox=“0 0 8 14” id=“icon-carousel-prev”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
  <symbol id=“icon-arrow-right-bold” viewBox=“1.2 2.1 22 21”>
    <path d=“M1.005 14a1 1 0 01-.71-1.71l5.296-5.288L.296></path>
 </svg>

The following xpath doesn't return result:

//div/svg/symbol

I've noticed that any manipulation related to symbol element doesn't work.
Is there a known issue with this element?

Body:
to locate an svg the first thing that you'd have to write is:

//*[name()='svg']

the moment you write this in the browser console, it will filter out all the SVG nodes in the HTMLDOM.

Now you may not be interested in all the SVG nodes rather you are interested in a specific svg node. for example, let's say the first symbol in this example:

//*[name()='svg']//*[name()='symbol' and @id='icon-carousel-next']

this should get the job done.

to locate the first path of first symbol:

//*[name()='svg']//*[name()='symbol' and @id='icon-carousel-next']//*

This should give you a basic idea and should lead you in the right direction.


问:
How to add the logged in user email in a field in the model directly without using a view in django
I have a field in my model as shown below

```<code>uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)

</code>```

This field will store the username (email in this case) of the user who has uploaded the data. As you can see that this is non editable so there is no way the user can edit it. The data has to be entered from the admin pannel. I wanted to know if there is any way to fill this field with the username of the loged in user who is uploading the data. I know if I use the view I can do some thing like

```<code>uploaded_by = request.user
</code>```

So is there a way to do the same directly in the model so that I can use the admin pannel directly to store the username without using a view.

答:
The save method can do this</p>
```<code>def save(self, *args, **kwargs):
    self.uploaded_by = self.your_user
    return super( your_model , self).save(*args, **kwargs)
</code>```

Body:
I have a field in my model as shown below

uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)

This field will store the username (email in this case) of the user who has uploaded the data. As you can see that this is non editable so there is no way the user can edit it. The data has to be entered from the admin pannel. I wanted to know if there is any way to fill this field with the username of the loged in user who is uploading the data. I know if I use the view I can do some thing like

uploaded_by = request.user

So is there a way to do the same directly in the model so that I can use the admin pannel directly to store the username without using a view.

Body:
The save method can do this

def save(self, *args, **kwargs):
    self.uploaded_by = self.your_user
    return super( your_model , self).save(*args, **kwargs)


问:
How to set up VS Code for imported modules to work in both debug and test?
I am trying to set up a workspace in VS Code and I want to be able to run it in venv.

```<code>root
- app
-/- modules
-/-/- __init__.py
-/-/- myModule.py
-/-/- myModule2.py
-/- __init__.py
-/- myApp.py
- test
-/- myTest.py
- venv
</code>```

myApp.py

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

import modules.myModule as mm

x = mm.main()
</code>```

myModule.py

```<code>from app.modules import myModule2

def main():
    x = myModule2()
    return x
</code>```

myTest.py

```<code>import unittest
from app.modules.myModule import main

class Test_Foo(unittest.TestCase):
    def test_bar(self):
        x = main()
        assertEqual(x, 'foobar', 'not equal')

if __name__ == '__main__':
    unittest.main()
</code>```

The issue I'm having is that my own modules can either be run in debug or in test (as unit test) but the same set up can not run for both. When I have from app.modules import myModule2 I can run test but not debug and when I have from modules import myModule2 I can run debug but not test.

my launch.json

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}
</code>```

my setting.json

```<code>{
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./test",
        "-p",
        "*test.py"
    ],
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.analysis.extraPaths": [
        "./app"
    ]
}
</code>```

How do I set up my workspace to be able to run both?

I run debug on the file myApp.py, and I run the test from test explorer.

The error I get when running debug is:

```<code>Exception has occurred: ModuleNotFoundError
No module named 'app'
</code>```

The exception is caught in the file myModule.py in line from app.modules import myModule2.

答:
Change "program": "${file}" to "module": "app.myApp".

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
//          "program": "${file}",  // Change this
            "module": "app.myApp", // to this
            "console": "integratedTerminal"
        }
    ]
}
```

Basically, the difference is that:

With "program", Python adds the final directory in ${file} (i.e. /path/to/root/app/) to sys.path (so you can only import modules).

With "module" or -m, Python adds the current directory (i.e. /path/to/root/) to sys.path (so you can import app) and imports the containing package of app.myApp (i.e. app).

For detailed comparisons, see What is the purpose of the -m switch? (Ctrl+F "Detailed Comparisons").

References:

https://code.visualstudio.com/docs/python/debugging#_module

https://docs.python.org/3/using/cmdline.html#cmdoption-m

https://www.python.org/dev/peps/pep-0338/#proposed-semantics

Body:
I am trying to set up a workspace in VS Code and I want to be able to run it in venv.

root
- app
-/- modules
-/-/- __init__.py
-/-/- myModule.py
-/-/- myModule2.py
-/- __init__.py
-/- myApp.py
- test
-/- myTest.py
- venv

myApp.py

import random
import numpy as np

import modules.myModule as mm

x = mm.main()

myModule.py

from app.modules import myModule2

def main():
    x = myModule2()
    return x

myTest.py

import unittest
from app.modules.myModule import main

class Test_Foo(unittest.TestCase):
    def test_bar(self):
        x = main()
        assertEqual(x, 'foobar', 'not equal')

if __name__ == '__main__':
    unittest.main()

The issue I'm having is that my own modules can either be run in debug or in test (as unit test) but the same set up can not run for both. When I have from app.modules import myModule2 I can run test but not debug and when I have from modules import myModule2 I can run debug but not test.

my launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

my setting.json

{
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./test",
        "-p",
        "*test.py"
    ],
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.analysis.extraPaths": [
        "./app"
    ]
}

How do I set up my workspace to be able to run both?

I run debug on the file myApp.py, and I run the test from test explorer.

The error I get when running debug is:

Exception has occurred: ModuleNotFoundError
No module named 'app'

The exception is caught in the file myModule.py in line from app.modules import myModule2.

Body:
Change "program": "${file}" to "module": "app.myApp".

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
//          "program": "${file}",  // Change this
            "module": "app.myApp", // to this
            "console": "integratedTerminal"
        }
    ]
}

Basically, the difference is that:

With "program", Python adds the final directory in ${file} (i.e. /path/to/root/app/) to sys.path (so you can only import modules).

With "module" or -m, Python adds the current directory (i.e. /path/to/root/) to sys.path (so you can import app) and imports the containing package of app.myApp (i.e. app).

For detailed comparisons, see What is the purpose of the -m switch? (Ctrl+F "Detailed Comparisons").

References:

https://code.visualstudio.com/docs/python/debugging#_module

https://docs.python.org/3/using/cmdline.html#cmdoption-m

https://www.python.org/dev/peps/pep-0338/#proposed-semantics


问:
Android Navigation - Unable to get Saved State Handle from Dialog Destination
I am trying to pass data from dialog destination to fragment. But it is not getting called If I try the same consecutively. For single try it works fine.

Below is my code that is in my dialog fragment:

```<code>val navBackStackEntry = findNavController().getBackStackEntry(R.id.fragment_name)
</code>```

onClick of button I am doing this

```<code>navBackStackEntry.savedStateHandle.set(ConstantUtils.SAVED_DATE, "")
dismiss()
</code>```

In fragment's onResume I am observing the data like below:

```<code> val savedStateHandle = findNavController().currentBackStackEntry?.savedStateHandle
savedStateHandle?.getLiveData<String>(ConstantUtils.SAVED_DATE)?.observe(viewLifecycleOwner,
Observer { date ->
               //Code goes here
                savedStateHandle.remove<String>(ConstantUtils.SAVED_DATE)
            })
</code>```

When I click the button from dialog it comes to onResume of fragment, If I again go to the dialog and click on button it does not return to onResume of fragment.

Pleas let me know what mistake am I making here.

答:
If you want to pass argument to fragment and receive one, you can use setFragmentResult() function can pass and receive bundle between fragments.
This is source link for more study

https://developer.android.com/guide/fragments/communicate#fragment-result

Body:
I am trying to pass data from dialog destination to fragment. But it is not getting called If I try the same consecutively. For single try it works fine.

Below is my code that is in my dialog fragment:

val navBackStackEntry = findNavController().getBackStackEntry(R.id.fragment_name)

onClick of button I am doing this

navBackStackEntry.savedStateHandle.set(ConstantUtils.SAVED_DATE, "")
dismiss()

In fragment's onResume I am observing the data like below:

 val savedStateHandle = findNavController().currentBackStackEntry?.savedStateHandle
savedStateHandle?.getLiveData<String>(ConstantUtils.SAVED_DATE)?.observe(viewLifecycleOwner,
Observer { date ->
               //Code goes here
                savedStateHandle.remove<String>(ConstantUtils.SAVED_DATE)
            })

When I click the button from dialog it comes to onResume of fragment, If I again go to the dialog and click on button it does not return to onResume of fragment.

Pleas let me know what mistake am I making here.


问:
Gradient descent extended function example
Here is my gradient descent code:

```<code>import numpy
def gradient_descent(func, grad_func, w_init, n_epochs=100, lr=0.001, verbose=0):

    i = 0
    w = w_init
    while i < n_epochs:

        delta_w = -lr * grad_func(w)
        w = w + delta_w

        if verbose > 0:
            print("f={}; w: {}".format(func(w), w))

        i += 1

    return w
</code>```

Now the example that was explained to me is with simple function i.e:
f(p,q) = p^2 + q^2.
The partial derivates are in vector: [2p,2q] and that is clear.
The code for that function and its gradient is:

```<code>def f(w):
    return numpy.sum(w*w)

def grad(w):
    return 2*w
</code>```

So the calculation goes:

```<code># starting point
w_init = numpy.array([10,10])

# learning rate
lr = 0.1

# apply gradient descent
w_opt = gradient_descent(f, grad, w_init, n_epochs=25, lr=lr, verbose=1)
</code>```

My problem is calculating it for another function such as: f(p,q) = (p^2 + 2q^3). I know the values for partial derivative, but how to implement those values to this particular code?
How to write new function f and gradient function grad for it and to compute it with main function?

答:
Probably you're looking for something like this:</p>
```<code>def f(w):
    return w[0] ** 2 + 2 * w[1] ** 3

def grad(w):
    return np.array([2 * w[0], 3 * w[1] ** 2])
</code>```

Body:
Here is my gradient descent code:

import numpy
def gradient_descent(func, grad_func, w_init, n_epochs=100, lr=0.001, verbose=0):

    i = 0
    w = w_init
    while i < n_epochs:

        delta_w = -lr * grad_func(w)
        w = w + delta_w

        if verbose > 0:
            print("f={}; w: {}".format(func(w), w))

        i += 1

    return w

Now the example that was explained to me is with simple function i.e:
f(p,q) = p^2 + q^2.
The partial derivates are in vector: [2p,2q] and that is clear.
The code for that function and its gradient is:

def f(w):
    return numpy.sum(w*w)

def grad(w):
    return 2*w

So the calculation goes:

# starting point
w_init = numpy.array([10,10])

# learning rate
lr = 0.1

# apply gradient descent
w_opt = gradient_descent(f, grad, w_init, n_epochs=25, lr=lr, verbose=1)

My problem is calculating it for another function such as: f(p,q) = (p^2 + 2q^3). I know the values for partial derivative, but how to implement those values to this particular code?
How to write new function f and gradient function grad for it and to compute it with main function?

Body:
Probably you're looking for something like this:

def f(w):
    return w[0] ** 2 + 2 * w[1] ** 3

def grad(w):
    return np.array([2 * w[0], 3 * w[1] ** 2])


问:
Javascript for simple menu expanding
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

```<code><div id="submenu">
  <ul>
   <li>
     Something
   </li>
   <li>
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>
</code>```

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

答: I have used Dojo for things like this with great success. Perhaps the Menu or MenuBar will be of use to you.</p>

Title: Javascript for simple menu expanding

Body:
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

     Something

     Another

Something-sub

Something-sub

Something-sub

Another-sub

Another-sub

Another-sub

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!


答:
If I understood correctly, you have a car_expanded table and for example table has a one record:

version_id
user_that_updated_version
parent_id
current
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

After inserting this data:

```<code>INSERT INTO car_expanded (
        version_id,
        user_that_updated_version,
        parent_id,
        current,
        engine,
        color,
        length,
        wheelbase
    )
    values (
        1,
        'mike',
        1,
        true,
        6.5,
        'red',
        4480,
        2581
    )
</code>```

You want to view this result:

version_id
user_that_updated_version
parent_id
current
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

1
mike
1
true
4.7
red
4,480
2,581

Maybe car_expanded table has a primary unique key field, for example table_id, so our query sample:

```<code>with new_car as (
    INSERT INTO car_expanded (
        version_id,
        user_that_updated_version,
        parent_id,
        current,
        engine,
        color,
        length,
        wheelbase
    )
    values (
        1,
        'mike',
        1,
        true,
        6.5,
        'red',
        4480,
        2581
    )
    returning table_id, parent_id
)
update car_expanded car
set
    current  = false
from
    (select * from new_car) new_data
where
    car.parent_id = new_data.parent_id and
    car.table_id <> new_data.table_id;
</code>```

This query will update records field set to current=false that have parent_id=(new inserted parent_id), but for does not updating inserted record, we must be control table_id (primary unique key of car_expanded table) field.

Title: Insert new row duplicating old one and updating it with new data in one query

Body:
I have two tables:

car_consistent (it gets filled and never changes)

id
type
brand

1
dream
ferrari

car_expanded

version_id (pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

When new car version shows up - older is not replaced, you get something like this:

version_id(pk\seq)
user_that_updated_version
parent_id (id from car_consistent)
current (boolean)
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

2
mike
1
true
6.5
red
4,480
2,581

So when you join tables on id = parent_id where current = true you get full representation of the car in its current state.
It helps me to track versions and users that made them. Also i can rollback fast.

I am getting updates in following format: "Mike said engine is 6.5 now."

So what i need to do:

Insert new row that is duplicating older one except its id, user_that_updated_version and changed column (engine here).

Set older version current column (or all others with same parent_id) to false and new version current column to true.

On 1) i tried and failed with following query:

WITH new_version_id AS (INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
                        SELECT user_that_updated_version, parent_id,    current, engine, color, length, wheelbase
                        FROM car_expanded where id = (SELECT MAX(id) FROM car_expanded WHERE parent_id = 1)
                        RETURNING id)
UPDATE car_expanded SET user_that_updated_version ='mike',engine = 6.5
WHERE id = (SELECT * FROM  new_version_id);

It inserts new row, but does not update it.

And i cant even imagine how to implement task 2) in that single query.

Yes, im trying to do it in single query because it is executed from java code.

I would be grateful for any ideas. Thanks in advance.

-----update-----

Feels like following query can solve it:

WITH prev_version AS (SELECT user_that_updated_version, parent_id, current, engine, color, length,  wheelbase
    FROM car_expanded
    WHERE parent_id = 1 AND current = true
    LIMIT 1),
     unmark_all AS (UPDATE car_expanded SET current = false WHERE parent_id = 1)
INSERT INTO car_expanded (user_that_updated_version, parent_id, current, engine, color, length, wheelbase)
VALUES (
        'mike',
        prev_version.parent_id,
        true,
        6.5,
        prev_version.color,
        prev_version.length,
        prev_version.wheelbase
       )

But now im getting [42P01] ERROR: missing FROM-clause entry for table "prev_version".

Body:
If I understood correctly, you have a car_expanded table and for example table has a one record:

version_id
user_that_updated_version
parent_id
current
engine
color
length
wheelbase

1
prime
1
true
4.7
red
4,480
2,581

After inserting this data:

INSERT INTO car_expanded (
        version_id,
        user_that_updated_version,
        parent_id,
        current,
        engine,
        color,
        length,
        wheelbase
    )
    values (
        1,
        'mike',
        1,
        true,
        6.5,
        'red',
        4480,
        2581
    )

You want to view this result:

version_id
user_that_updated_version
parent_id
current
engine
color
length
wheelbase

1
prime
1
false
4.7
red
4,480
2,581

1
mike
1
true
4.7
red
4,480
2,581

Maybe car_expanded table has a primary unique key field, for example table_id, so our query sample:

with new_car as (
    INSERT INTO car_expanded (
        version_id,
        user_that_updated_version,
        parent_id,
        current,
        engine,
        color,
        length,
        wheelbase
    )
    values (
        1,
        'mike',
        1,
        true,
        6.5,
        'red',
        4480,
        2581
    )
    returning table_id, parent_id
)
update car_expanded car
set
    current  = false
from
    (select * from new_car) new_data
where
    car.parent_id = new_data.parent_id and
    car.table_id <> new_data.table_id;

This query will update records field set to current=false that have parent_id=(new inserted parent_id), but for does not updating inserted record, we must be control table_id (primary unique key of car_expanded table) field.


问:
Forgot Password API Django rest framework
I am using OTP authentication for the Forgot password of user. I want the phone no get verify then the user can able to change the password of their account.

I want to change the password of the user if the user can verify their number the new password could get set.

I someone able to give an answer please help.

serializers.py

```<code>class PasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """

    new_password = serializers.CharField(required=True)
</code>```

models.py

```<code>class ResetPhoneOTP(models.Model):

    phone_regex = RegexValidator( regex = r'^\+?1?\d{9,14}$', message = "Phone number must be entered in the form of +919999999999.")
    phone = models.CharField(validators = [phone_regex], max_length=17, blank=True)
    otp = models.CharField(max_length=9, blank=True, null=True)
    count = models.IntegerField(default=0, help_text = 'Number of opt_sent')
    validated = models.BooleanField(default=False, help_text= 'if it is true, that means user have validate opt correctly in seconds')

    def __str__(self):
        return str(self.phone) + ' is sent ' + str(self.otp)
</code>```

views.py

```<code>

class UserViewSet(mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  viewsets.GenericViewSet):
    """
    list:
    Return a list of all the existing users.
    read:
    Return the given user.
    me:
    Return authenticated user.
    """
    queryset = User.objects.all()
    serializer_class = PasswordSerializer
    # permission_classes = (IsSuperuserOrIsSelf,)

    # @action(detail=True, methods=['put'])
    def post(self, request):
        phone = request.data.get('phone' , False)
        # new_password = request.data.get('new_password')
        if phone:
            old = ResetPhoneOTP.objects.filter(phone__iexact = phone)
            if old.exists():
                old  = old.last()
                validated = old.validated

                if validated:

                    serializer = PasswordSerializer(data=request.data)

                    if serializer.is_valid():
                        user.set_password(serializer.data.get('new_password'))
                        user.save()
                        return Response({'status': 'password set'}, status=status.HTTP_200_OK)
                    return Response({'status': 'password not2 set'})
                return Response({'status': 'password not3 set'})
        return Response({'status': 'password not 4set'})

class ResetPassword(APIView):
    permission_classes = (AllowAny, )
    def post(self, request, *args, **kwargs):
        phone_number = request.data.get('phone' )
        if phone_number :
            phone  = str(phone_number)
            key = send_reset_otp(phone)
            old = User.objects.filter(phone=phone)
            if old.exists():
                # old  = old.first()
                # count = old.count
                # old.count = count + 1
                # old.save()
                ResetPhoneOTP.objects.create(
                    # name = name,
                    phone = phone,
                    otp = key

                    )
                # print('Count Increase', count)

                # print(key)
                return Response({
                        'status' : True,
                        'detail' : 'OTP sent successfully.'
                        })
            else:
                return Response({
                    'status' : False,
                    'detail' : 'Phone Number DoesNotExist'
                })
        else:
            return Response({
                'status' : False,
                'detail' : 'Phone Number is not given in body.'
            })

class ValidateResetOTP(APIView):
    permission_classes = (AllowAny, )
    def post(self, request, *args, **kwargs):
        phone = request.data.get('phone' , False)
        otp_sent = request.data.get('otp', False)

        if phone and otp_sent:
            old = ResetPhoneOTP.objects.filter(phone__iexact = phone)
            if old.exists():
                old = old.last()
                otp = old.otp
                # old = Customer.objects.filter(otp)
                if str(otp_sent) == str(otp):
                    old.validated = True
                    old.save()
                    return Response({
                        'status' : True,
                        'detail' : 'OTP mactched. Please proceed for Reset Password.'
                        })
                else:
                    return Response({
                        'status' : False,
                        'detail' : 'OTP incorrect.'
                        })
            else:
                return Response({
                    'status' : False,
                    'detail' : 'First proceed via sending otp request.'
                    })
        else:
            return Response({
                'status' : False,
                'detail' : 'Please provide both phone and otp for validations'
                })
</code>```

答:
```<code> from django.contrib.auth.hashers import make_password

 #Your api view
     username = request.user
     get_obj = User.objects.get(id=request.user.id)
     if (request.method == 'POST'):
         password = request.data.get('password') #Get pass value from form
         password1 = request.POST.get('password1') #Get password1 value from form
         if password == password1:
             user = User.objects.get(username=request.user)
             pas = make_password(password)
             user.password = pas
             user.save()
             return Response (' success')
</code>```

Body:
I am using OTP authentication for the Forgot password of user. I want the phone no get verify then the user can able to change the password of their account.

I want to change the password of the user if the user can verify their number the new password could get set.

I someone able to give an answer please help.

serializers.py

class PasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """

    new_password = serializers.CharField(required=True)

models.py

class ResetPhoneOTP(models.Model):

    phone_regex = RegexValidator( regex = r'^\+?1?\d{9,14}$', message = "Phone number must be entered in the form of +919999999999.")
    phone = models.CharField(validators = [phone_regex], max_length=17, blank=True)
    otp = models.CharField(max_length=9, blank=True, null=True)
    count = models.IntegerField(default=0, help_text = 'Number of opt_sent')
    validated = models.BooleanField(default=False, help_text= 'if it is true, that means user have validate opt correctly in seconds')

    def __str__(self):
        return str(self.phone) + ' is sent ' + str(self.otp)

views.py

class UserViewSet(mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  viewsets.GenericViewSet):
    """
    list:
    Return a list of all the existing users.
    read:
    Return the given user.
    me:
    Return authenticated user.
    """
    queryset = User.objects.all()
    serializer_class = PasswordSerializer
    # permission_classes = (IsSuperuserOrIsSelf,)

    # @action(detail=True, methods=['put'])
    def post(self, request):
        phone = request.data.get('phone' , False)
        # new_password = request.data.get('new_password')
        if phone:
            old = ResetPhoneOTP.objects.filter(phone__iexact = phone)
            if old.exists():
                old  = old.last()
                validated = old.validated

                if validated:

                    serializer = PasswordSerializer(data=request.data)

                    if serializer.is_valid():
                        user.set_password(serializer.data.get('new_password'))
                        user.save()
                        return Response({'status': 'password set'}, status=status.HTTP_200_OK)
                    return Response({'status': 'password not2 set'})
                return Response({'status': 'password not3 set'})
        return Response({'status': 'password not 4set'})

class ResetPassword(APIView):
    permission_classes = (AllowAny, )
    def post(self, request, *args, **kwargs):
        phone_number = request.data.get('phone' )
        if phone_number :
            phone  = str(phone_number)
            key = send_reset_otp(phone)
            old = User.objects.filter(phone=phone)
            if old.exists():
                # old  = old.first()
                # count = old.count
                # old.count = count + 1
                # old.save()
                ResetPhoneOTP.objects.create(
                    # name = name,
                    phone = phone,
                    otp = key

                    )
                # print('Count Increase', count)

                # print(key)
                return Response({
                        'status' : True,
                        'detail' : 'OTP sent successfully.'
                        })
            else:
                return Response({
                    'status' : False,
                    'detail' : 'Phone Number DoesNotExist'
                })
        else:
            return Response({
                'status' : False,
                'detail' : 'Phone Number is not given in body.'
            })

class ValidateResetOTP(APIView):
    permission_classes = (AllowAny, )
    def post(self, request, *args, **kwargs):
        phone = request.data.get('phone' , False)
        otp_sent = request.data.get('otp', False)

        if phone and otp_sent:
            old = ResetPhoneOTP.objects.filter(phone__iexact = phone)
            if old.exists():
                old = old.last()
                otp = old.otp
                # old = Customer.objects.filter(otp)
                if str(otp_sent) == str(otp):
                    old.validated = True
                    old.save()
                    return Response({
                        'status' : True,
                        'detail' : 'OTP mactched. Please proceed for Reset Password.'
                        })
                else:
                    return Response({
                        'status' : False,
                        'detail' : 'OTP incorrect.'
                        })
            else:
                return Response({
                    'status' : False,
                    'detail' : 'First proceed via sending otp request.'
                    })
        else:
            return Response({
                'status' : False,
                'detail' : 'Please provide both phone and otp for validations'
                })


问:
Check if socket still open without blocking
How do I check if a TCP socket is still open without blocking?

If I am using usocket, then reading from a socket stream will signal end of file if the socket is closed, but will block it otherwise, which I don't want. I have tried using (listen stream) to check in advance if the socket will be blocked, but (listen) returns nil on a closed socket, which does not help here. I have also tried checking (usocket::state socket), which gives :READ on a closed socket, but it also sometimes gives :READ on an open socket even if there is not anything there. I am using sbcl, so I've tried using (sb-bsd-sockets:socket-open-p), but that gives T on a closed socket, also not helpful. The only command that seems to be helpful is (wait-for-input), namely it will return almost immediately when called on a closed socket, even when a longer timeout is given. At the same time, (listen) will still give nil, and that taken together seems to indicate a closed socket. This way looks rather hackish to me.

Is there a better way?

答:
It's a bug in SBCL. The stream you get from (usocket:socket-stream s) and the one you get from calling cl:open are of the same type, so they behave the same way.

You get the correct behavior if you close a stream using cl:close:

```<code>(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (close in)
  (listen in))
</code>```

And that correct behavior is an error. (On SBCL the type of the error is SB-INT:CLOSED-STREAM-ERROR)

If you simulate the other end of a socket closing by closing the underlying file descriptor with a POSIX call, you get the same NIL return value as with a real socket:

```<code>(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (sb-posix:close (slot-value in 'sb-impl::fd))
  (listen in)) ;; NIL
</code>```

Whatever listen is doing is failing to notice that the underlying file descriptor is closed.

The blocking behavior is also identical:

```<code>(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (sb-posix:close (slot-value in 'sb-impl::fd))
  (read-byte in)) ;; hangs, Emacs interrupt doesn't work
</code>```

In the source code for listen, I saw comments that claim that select(2) is used to implement listen, but I couldn't find the actual call to select. That call to select, if it's happening, is returning -1, and errno is not being consulted to find out why. It's likely that the -1 return code is being missed.

This affects the latest version of SBCL that Debian ships, but I don't know about the latest released version of SBCL.

Body:
It's a bug in SBCL. The stream you get from (usocket:socket-stream s) and the one you get from calling cl:open are of the same type, so they behave the same way.

You get the correct behavior if you close a stream using cl:close:

(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (close in)
  (listen in))

And that correct behavior is an error. (On SBCL the type of the error is SB-INT:CLOSED-STREAM-ERROR)

If you simulate the other end of a socket closing by closing the underlying file descriptor with a POSIX call, you get the same NIL return value as with a real socket:

(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (sb-posix:close (slot-value in 'sb-impl::fd))
  (listen in)) ;; NIL

Whatever listen is doing is failing to notice that the underlying file descriptor is closed.

The blocking behavior is also identical:

(with-open-file (in "/dev/zero" :element-type '(unsigned-byte 8))
  (sb-posix:close (slot-value in 'sb-impl::fd))
  (read-byte in)) ;; hangs, Emacs interrupt doesn't work

In the source code for listen, I saw comments that claim that select(2) is used to implement listen, but I couldn't find the actual call to select. That call to select, if it's happening, is returning -1, and errno is not being consulted to find out why. It's likely that the -1 return code is being missed.

This affects the latest version of SBCL that Debian ships, but I don't know about the latest released version of SBCL.


问:
jQuery next sibling that has a particular kind of child
My HTML has a container element with many sibling div elements, each of which contains a contenteditable p. These sibling div are "interrupted", however, by other div which do not contain an editable element.

What is challenging me at the moment is how to "hop over" these interrupting div when using the left and right arrow keys to move from C to D or from D back to C (see snippet). Navigation stops when it encounters these div lacking an editable element. How can I correct this?

$('#foo p[contenteditable = "true"]').bind("keydown", function(e) {
  switch (e.key) {
    case "ArrowLeft":
      var $P = $(this).parent().prev().children('p[contenteditable = "true"]');
      setTimeout(() => $P.focus(), 0);
      e.stopImmediatePropagation();
      e.preventDefault();
      break;

    case "ArrowRight":
      var $P = $(this).parent().next().children('p[contenteditable = "true"]');
      setTimeout(() => $P.focus(), 0);
      e.stopImmediatePropagation();
      e.preventDefault();
      break;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#foo p[contenteditable="true"] {
  /* font-size: 22px;*/
  height: 22px;
  width: 22px;
  color: cyan;
  font-weight: bold;
  background-color: cyan;
}

#foo p.const {
  background-color: inherit;
  border: none;
  height: 22px;
  width: 22px;
}

#foo div {
  text-align: center;
  display: inline-block;
}</code>```

A

B

C

"

"

D

E

```

答:
To do what you require you need to use prevAll() and nextAll(), instead of prev() and next(), as there's intermediary elements which you need to skip. You can combine this the :has() selector to only find containers which have a descendent contenteditable and also with first() to retrieve the nearest match.

Also note that bind() is deprecated and will be removed from jQuery soon; use on() instead. The logic can also be amended slightly to reduce the reliance on switch and avoid the unnecessary repetition. Finally you have used
 instead of
 in a couple of places in the HTML.

With that said, try this:

let keyMethodLookup = {
  ArrowLeft: 'prevAll',
  ArrowRight: 'nextAll'
}

$('#foo p[contenteditable="true"]').on("keydown", e => {
  if (!keyMethodLookup.hasOwnProperty(e.key))
    return;

  let method = keyMethodLookup[e.key];
  $(e.currentTarget).parent()[method]('div:has(p[contenteditable="true"])').first().children('p[contenteditable="true"]').focus();
  e.stopImmediatePropagation();
  e.preventDefault();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#foo p[contenteditable="true"] {
  /* font-size: 22px;*/
  height: 22px;
  width: 22px;
  color: cyan;
  font-weight: bold;
  background-color: cyan;
}

#foo p.const {
  background-color: inherit;
  border: none;
  height: 22px;
  width: 22px;
}

#foo div {
  text-align: center;
  display: inline-block;
}</code>```

A

B

C

"

"

D

E

```

Body:
My HTML has a container element with many sibling div elements, each of which contains a contenteditable p. These sibling div are "interrupted", however, by other div which do not contain an editable element.

What is challenging me at the moment is how to "hop over" these interrupting div when using the left and right arrow keys to move from C to D or from D back to C (see snippet). Navigation stops when it encounters these div lacking an editable element. How can I correct this?

$('#foo p[contenteditable = "true"]').bind("keydown", function(e) {
  switch (e.key) {
    case "ArrowLeft":
      var $P = $(this).parent().prev().children('p[contenteditable = "true"]');
      setTimeout(() => $P.focus(), 0);
      e.stopImmediatePropagation();
      e.preventDefault();
      break;

    case "ArrowRight":
      var $P = $(this).parent().next().children('p[contenteditable = "true"]');
      setTimeout(() => $P.focus(), 0);
      e.stopImmediatePropagation();
      e.preventDefault();
      break;
  }
});

#foo p[contenteditable="true"] {
  /* font-size: 22px;*/
  height: 22px;
  width: 22px;
  color: cyan;
  font-weight: bold;
  background-color: cyan;
}

#foo p.const {
  background-color: inherit;
  border: none;
  height: 22px;
  width: 22px;
}

#foo div {
  text-align: center;
  display: inline-block;
}

A

B

C

"

"

D

E

Body:
To do what you require you need to use prevAll() and nextAll(), instead of prev() and next(), as there's intermediary elements which you need to skip. You can combine this the :has() selector to only find containers which have a descendent contenteditable and also with first() to retrieve the nearest match.

Also note that bind() is deprecated and will be removed from jQuery soon; use on() instead. The logic can also be amended slightly to reduce the reliance on switch and avoid the unnecessary repetition. Finally you have used <p> instead of </p> in a couple of places in the HTML.

With that said, try this:

let keyMethodLookup = {
  ArrowLeft: 'prevAll',
  ArrowRight: 'nextAll'
}

$('#foo p[contenteditable="true"]').on("keydown", e => {
  if (!keyMethodLookup.hasOwnProperty(e.key))
    return;

  let method = keyMethodLookup[e.key];
  $(e.currentTarget).parent()[method]('div:has(p[contenteditable="true"])').first().children('p[contenteditable="true"]').focus();
  e.stopImmediatePropagation();
  e.preventDefault();
});

#foo p[contenteditable="true"] {
  /* font-size: 22px;*/
  height: 22px;
  width: 22px;
  color: cyan;
  font-weight: bold;
  background-color: cyan;
}

#foo p.const {
  background-color: inherit;
  border: none;
  height: 22px;
  width: 22px;
}

#foo div {
  text-align: center;
  display: inline-block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">
  <div>
    <p contenteditable="true" tabindex="0"></p>
    <p>A</p>
  </div>
  <div>
    <p contenteditable="true" tabindex="1"></p>
    <p>B</p>
  </div>
  <div>
    <p contenteditable="true" tabindex="2"></p>
    <p>C</p>
  </div>
  <div>
    <p class="const">&nbsp;</p>
    <p>&nbsp;</p>
  </div>
  <div>
    <p class="const">"</p>
    <p>"</p>
  </div>
  <div>
    <p contenteditable="true" tabindex="3"></p>
    <p>D</p>
  </div>
  <div>
    <p contenteditable="true" tabindex="4"></p>
    <p>E</p>
  </div>
</div>


问:
How to drag a shape even if there is a shape above it?
I'm trying to be able to drag a shape even if there is another shape above it.

Is that possible if yes do you have any idea how to do it ?

Is there a Konva parameter do resolve that situation ?

Thanks

const stage = new Konva.Stage({
  container: 'container',
  width: 300,
  height: 300
});

const layer = new Konva.Layer();
stage.add(layer);

const shape = new Konva.Rect({
  x: stage.width() / 2,
  y: stage.height() / 2,
  width: 50,
  height: 50,
  fill: 'green',
  draggable: true
});
layer.add(shape);

const shape2 = new Konva.Rect({
  x: stage.width() / 4,
  y: stage.height() / 4,
  width: 50,
  height: 50,
  fill: 'blue',
});
layer.add(shape2);

layer.draw();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="description" content="Konva demo">
  <script src="https://unpkg.com/konva@^3/konva.min.js"></script>
  <meta charset="utf-8">
</head>
<body>
  <div class="flex-container" id="container"></div>
</body>
</html></code>```

demo: https://jsbin.com/dihulirepo/edit?html,js,output

答:
Found a way to do it add listening: false do the shape above.

eg:

const shape2 = new Konva.Rect({
  x: stage.width() / 4,
  y: stage.height() / 4,
  width: 50,
  height: 50,
  fill: 'blue',
  listening: false // here
});```

Body:
I'm trying to be able to drag a shape even if there is another shape above it.

Is that possible if yes do you have any idea how to do it ?

Is there a Konva parameter do resolve that situation ?

Thanks

const stage = new Konva.Stage({
  container: 'container',
  width: 300,
  height: 300
});

const layer = new Konva.Layer();
stage.add(layer);

const shape = new Konva.Rect({
  x: stage.width() / 2,
  y: stage.height() / 2,
  width: 50,
  height: 50,
  fill: 'green',
  draggable: true
});
layer.add(shape);

const shape2 = new Konva.Rect({
  x: stage.width() / 4,
  y: stage.height() / 4,
  width: 50,
  height: 50,
  fill: 'blue',
});
layer.add(shape2);

layer.draw();

<!DOCTYPE html>

<meta name="description" content="Konva demo">

  <meta charset="utf-8">

demo: https://jsbin.com/dihulirepo/edit?html,js,output


答:
You can solve this problem using this solution: Python split list at zeros

from itertools import groupby

def split_a_list_at_zeros(L):
    return [list(g) for k, g in groupby(L, key=lambda x:x!=0) if k]

list1 = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

new_list = split_a_list_at_zeros(list1)

print(new_list) # [[2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]
```

Body:
I have a list of elements which internally is separated by 0s.
The format is like that:

[0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]

I would like to use the zeros as separators and split it into sublists. In that example its:

[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]

The zeros will therefore disappear.
A leading zero or an ending zero should make an empty list at the beginning or the end.

Until know, I do that in an ugly way by joining the list together to a string, then split it and make a list of it again.

Is there a fancy pythonic way to do that easier?


问:
Querying a child collection by multiple values in RavenDB
I'm using RavenDB build 371 and I have the following model:

```<code>class Product {
 public string Id { get; set; }
 public ProductSpec[] Specs { get; set; }
}

class ProductSpec {
 public string Name { get; set; }
 public string Value { get; set; }
}
</code>```

I would like to be able to query for products which have a set of specs. When querying by a single spec:

```<code>session.Query<Product>()
 .Where(product => product.Specs.Any(spec => spec.Name == "Color" && spec.Value == "Red"))
 .ToList();
</code>```

The expected results are returned, however when an additional spec predicate is added:

```<code>session.Query<Product>()
 .Where(product => product.Specs.Any(spec => spec.Name == "Color" && spec.Value == "Red"))
 .Where(product => product.Specs.Any(spec => spec.Name == "Country" && spec.Value == "US"))
 .ToList();
</code>```

no results are returned even though the results returned by the first query contain products with spec name "Country" and spec value "US". The same outcome is observed when using the LuceneQuery method. This seems to be a similar issue to this discussion however I was unable to implement to suggested solution. Specifically, after creating the suggested index, I don't know how to query it.

How can I support this type of query in RavenDB?

EDIT

I still can't query on multiple values on a collection of compound types. Instead, I changed the model so that a spec/value combination is a concatenated string such that the specs collection is an array of strings. This can be queried by multiple values:

```<code>class Product {
 public string Id { get; set; }
 public int CategoryId { get; set; }
 public string[] Specs { get; set; }
}
</code>```

For reference, the original model and query works when using MongoDB with their multikeys index feature. The very surprising problem with MongoDB is that the count() operation is slow for index queries. This type of query is essential for pagination and although count can be cached I would like a solution which provides this out of the box. Also, one other requirement I have is the ability to aggregate spec groups for arbitrary collections of products (for example, to get a collection of all spec/value combinations for products in a given category). In MongoDB this can be achieved using their MapReduce functionality, however the results of a MapReduce operation are static and must be manually updated when the source data changes whereas RavenDB updates MapReduce indexes automatically in the background. So, even though declaring MapReduce indexes in RavenDB is more cumbersome than it is in MongoDB IMO, the automatic background updating outweighs the drawbacks by a long shot. I will be looking at CouchDB as their views are also updated automatically, though it appears they are updated on demand, not automatically in the background, not sure if this will be an issue.

答:
I have tried different things, and could not make it work either. The specific query you are trying to execute is resolved to this Lucene query by RavenDB (in version 426):

"{(Name:Color AND Value:Red) AND (Name:Country AND Value:US)}" which explains why you get no result.

After googling on the subject, I found this post: Lucene Query Syntax

Different workarounds are suggested among the answers. Hope this will help. Im rather curious myself though, if this really isn't possible.

Body:
I'm using RavenDB build 371 and I have the following model:

class Product {
 public string Id { get; set; }
 public ProductSpec[] Specs { get; set; }
}

class ProductSpec {
 public string Name { get; set; }
 public string Value { get; set; }
}

I would like to be able to query for products which have a set of specs. When querying by a single spec:

session.Query<Product>()
 .Where(product => product.Specs.Any(spec => spec.Name == "Color" && spec.Value == "Red"))
 .ToList();

The expected results are returned, however when an additional spec predicate is added:

session.Query<Product>()
 .Where(product => product.Specs.Any(spec => spec.Name == "Color" && spec.Value == "Red"))
 .Where(product => product.Specs.Any(spec => spec.Name == "Country" && spec.Value == "US"))
 .ToList();

no results are returned even though the results returned by the first query contain products with spec name "Country" and spec value "US". The same outcome is observed when using the LuceneQuery method. This seems to be a similar issue to this discussion however I was unable to implement to suggested solution. Specifically, after creating the suggested index, I don't know how to query it.

How can I support this type of query in RavenDB?

EDIT

I still can't query on multiple values on a collection of compound types. Instead, I changed the model so that a spec/value combination is a concatenated string such that the specs collection is an array of strings. This can be queried by multiple values:

class Product {
 public string Id { get; set; }
 public int CategoryId { get; set; }
 public string[] Specs { get; set; }
}

For reference, the original model and query works when using MongoDB with their multikeys index feature. The very surprising problem with MongoDB is that the count() operation is slow for index queries. This type of query is essential for pagination and although count can be cached I would like a solution which provides this out of the box. Also, one other requirement I have is the ability to aggregate spec groups for arbitrary collections of products (for example, to get a collection of all spec/value combinations for products in a given category). In MongoDB this can be achieved using their MapReduce functionality, however the results of a MapReduce operation are static and must be manually updated when the source data changes whereas RavenDB updates MapReduce indexes automatically in the background. So, even though declaring MapReduce indexes in RavenDB is more cumbersome than it is in MongoDB IMO, the automatic background updating outweighs the drawbacks by a long shot. I will be looking at CouchDB as their views are also updated automatically, though it appears they are updated on demand, not automatically in the background, not sure if this will be an issue.


问:
Weird display issue with vuetify in laravel. v-text-field gets an outline on focus
So the problem is… when I focus on the v-text-field, I get an outline which is not desired.
And it's only happening in Laravel. When using plain Vue, the problem is not there.

In Laravel + Vuetify Project (See the blue outline? I don't want it there)

In Vue Project (Desired)

I'm not sure as to why this is happening.
Also, this is the first time I'm trying Vuetify with Laravel

The code for both is the same, as below

```<code><v-text-field
  label="Email"
  name="email"
  prepend-icon="mdi-email"
  type="email"
  :color="$store.state.sf_brandColor"
  v-model="login.email"
  @blur="$v.login.email.$touch()"
  :error-messages="login_emailErrors"
/>
<v-text-field
   label="Password"
   name="pass"
   prepend-icon="mdi-lock"
   type="password"
   :color="$store.state.sf_brandColor"
   v-model="login.password"
   @blur="$v.login.password.$touch()"
   :error-messages="login_passwordErrors"
/>
</code>```

I've tried

```<code>input:focus {
  outline:none;
}
input:focus {
  border:none;
}
</code>```

but it hasn't worked

In the developer tools, I checked the <input> tag. It doesn't have any border on focus.

Please help, I can't think of more ways to even debug this.

Running

Laravel 8.27.0

Vue 2.5.17

Vuetify 2.4.4

答:
In your resources/sass/app.scss, delete @import "~bootstrap/scss/bootstrap"

Run npm run watch

Done

Body:
So the problem is… when I focus on the v-text-field, I get an outline which is not desired.
And it's only happening in Laravel. When using plain Vue, the problem is not there.

In Laravel + Vuetify Project (See the blue outline? I don't want it there)

In Vue Project (Desired)

I'm not sure as to why this is happening.
Also, this is the first time I'm trying Vuetify with Laravel

The code for both is the same, as below

<v-text-field
  label="Email"
  name="email"
  prepend-icon="mdi-email"
  type="email"
  :color="$store.state.sf_brandColor"
  v-model="login.email"
  @blur="$v.login.email.$touch()"
  :error-messages="login_emailErrors"
/>
<v-text-field
   label="Password"
   name="pass"
   prepend-icon="mdi-lock"
   type="password"
   :color="$store.state.sf_brandColor"
   v-model="login.password"
   @blur="$v.login.password.$touch()"
   :error-messages="login_passwordErrors"
/>

I've tried

input:focus {
  outline:none;
}
input:focus {
  border:none;
}

but it hasn't worked

In the developer tools, I checked the <input> tag. It doesn't have any border on focus.

Please help, I can't think of more ways to even debug this.

Running

Laravel 8.27.0

Vue 2.5.17

Vuetify 2.4.4


问:
append string to string array if not array yet
I want to create a array of strings by appending, but it matters if the origin is an array or yet a string.
Therefore I need to convert a string like "abc" to a string array.

if I use

```<code>Array.from()
</code>```

it makes me something like this ["a","b","c"]
but I want to have ["abc"];

Is there a easy way that takes an input like
"abc"
and at the same time ["a","abc"]
I so that I can append later one one more string with push for example?

some constraints:
I cannot create

```<code>let a = [];
</code>```

because it is coming from extern.
And sure, I can add some code to check what is its, but I search for a simple mechanism.

I think i need something like
arr1.flat();

答:
Maybe this does what you want:

function strArr(base,s){
 return !Array.isArray(base)?[base,s]:[...base,s];
}

let a="abc", arr=["one","two"];

console.log(strArr(a,"b"));
console.log(strArr(arr,"three"));```

I changed my answer slightly. Now the input array base will not be changed anymore by the function.

Body:
I want to create a array of strings by appending, but it matters if the origin is an array or yet a string.
Therefore I need to convert a string like "abc" to a string array.

if I use

Array.from()

it makes me something like this ["a","b","c"]
but I want to have ["abc"];

Is there a easy way that takes an input like
"abc"
and at the same time ["a","abc"]
I so that I can append later one one more string with push for example?

some constraints:
I cannot create

let a = [];

because it is coming from extern.
And sure, I can add some code to check what is its, but I search for a simple mechanism.

I think i need something like
arr1.flat();

Body:
Maybe this does what you want:

function strArr(base,s){
 return !Array.isArray(base)?[base,s]:[...base,s];
}

let a="abc", arr=["one","two"];

console.log(strArr(a,"b"));
console.log(strArr(arr,"three"));

I changed my answer slightly. Now the input array base will not be changed anymore by the function.


问:
Nginx doesn't show php error even display_error is on
I have a website with nginx and php here my phpinfo

https://sundaysea.com/phpinfo.php

as you can see in phpinfo that display_error is on but in this page
https://sundaysea.com/clementcheng-com/

the page gets an 500 error and doesn't show any error.
I tried to look into log files but there is nothing about this also

can you please help me to know where is the error?

I added this to my wp-config.php file also, it's a wordpress site

```<code>define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true ); // Disable display of errors and warnings define( 'WP_DEBUG_DISPLAY', true );
 @ini_set( 'display_errors', 1 );
</code>```

答:
when you restart nginx it doesn't restart php.
try

```<code>$ sudo service php7.4-fpm restart
</code>```

it helped me. But you set your php version

Body:
I have a website with nginx and php here my phpinfo

https://sundaysea.com/phpinfo.php

as you can see in phpinfo that display_error is on but in this page
https://sundaysea.com/clementcheng-com/

the page gets an 500 error and doesn't show any error.
I tried to look into log files but there is nothing about this also

can you please help me to know where is the error?

I added this to my wp-config.php file also, it's a wordpress site

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true ); // Disable display of errors and warnings define( 'WP_DEBUG_DISPLAY', true );
 @ini_set( 'display_errors', 1 );

Body:
when you restart nginx it doesn't restart php.
try

$ sudo service php7.4-fpm restart

it helped me. But you set your php version


问:
Java difficult regular expression, how to mathc groups (tripples)?
How can I check in regex that 3 of the same digits must appear next to each other and that 1x or more times?

For example 333bbwjdi should be correct, because 333 is in there but 33bbwjdi should be false, because I don't have a triple.

答:
you can use below regular expression:

```<code>(\d)\1\1
</code>```

Where:

\d matches a digit (equivalent to [0-9])

\1 matches the same text as
most recently matched by the 1st capturing group

or:

```<code>(\d)\1{2}
</code>```

Which does the same thing: matching same text as before twice

Body:
you can use below regular expression:

(\d)\1\1

Where:

\d matches a digit (equivalent to [0-9])

\1 matches the same text as
most recently matched by the 1st capturing group

or:

(\d)\1{2}

Which does the same thing: matching same text as before twice


问:
css scroll-snap: focusing on the element which got snapped to
I implemented a horizontal grid with some cards in them. The grid uses CSS scroll-snap and it works nicely when navigating with mouse/touchscreen.

The problem occurs when the grid is navigated using a keyboard. Pressing tab after navigating through the grid with arrow keys causes the view to jump back to the element that got the focus, not the card which is current snapped to.

My ideal behaviour when pressing tab is, to focus on the card which is currently snapped to.

Any suggestions to make this possible?

答: I would add a scroll listener and just check if the element is at the top of the scroll view. You may be able to modify one of these solutions: How to check if element is visible after scrolling?</p>


问:
Periodic Office 365 SMTP Send Error Due to TLS 1.1/1.0
We have PHP web application that sends SMTP emails via authenticated smtp.office365.com.  This has been working for at least a couple of years.

We are using PHP Mailer 5.2.  We are forcing the crypto_method to STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT.

Here's the weird thing.  About 75% of the time it works fine.  The rest of the time it reports SMTP ERROR: Password command failed: 421 4.7.66 TLS 1.0 and 1.1 are not supported. Please upgrade/update your client to support TLS 1.2.

Registered Stream Socket Transports is tcp, udp, unix, udg, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2

How is it even possible that it works most of the time.  If it were truly a TLS issue I'd expect it to fail 100% of the time.

答: I found that upgrading the PHP version my server was running helped solve this issue. I was previously running version 5.* and despite trying to force the script to use a newer version of TLS it was still running into the speedbump MS have put in place. Upgrading my version of PHP to version 7.4 solved this issue and I have seen no rejected emails since.</p>