问:
create calculated column to show which column is missing
I have a requirement where I need to bring in calculated column to show if Type A, B or C is missing.

A Service can have one to many Types (there are 10 different "Type").

Service has to have all 3 "Type": A B and C.

If its missing any of the 3, I need to show which "Type" is missing.

For example, if Service ID 2 has Type A then the calculated column has to say "Type B and C is missing", if Service ID 3 has Type B then the calculated column has to say Type A and C is missing" etc...

I got the calculation to say "Type A B or C is missing" but having hard time to break it down to the specific Type that is missing. I will eventually union this result to few other queries that are similar.  Can anyone help with this?

```<code>SELECT ri.service_id,
       ri.name,
       ri.creation_date,
       'Type A B or C is missing' AS missing
FROM   service ri
WHERE  ri.special = 'Yes'
  AND  ri.service_id NOT IN (SELECT DISTINCT ri.service_id
                             FROM   service ri,
                                    service_cust rfni,
                                    cust rfn
                             WHERE  ri.service_id = rfni.service_id
                               AND  rfni.cust_id = rfn.cust_id
                               AND  ri.special = 'Yes'
                               AND rfn.TYPE IN( 'A', 'B', 'C' )

                               GROUP  BY ri.service_id
                                 HAVING Count(DISTINCT rfn.TYPE) = 3)

Thanks`
CREATE TABLE SERVICE
(service_id  VARCHAR(50),
name  VARCHAR( 50 ),
special  VARCHAR( 50 )
)

Insert into SERVICE (service_id,name,special) values ('1','Service1','Yes');
Insert into SERVICE (service_id,name,special) values ('2','Service2','Yes');
Insert into SERVICE (service_id,name,special) values ('3','Service3','Yes');
Insert into SERVICE (service_id,name,special) values ('4','Service4','Yes');
Insert into SERVICE (service_id,name,special) values ('5','Service5','Yes');
Insert into SERVICE (service_id,name,special) values ('6','Service6','Yes');
Insert into SERVICE (service_id,name,special) values ('7','Service7','Yes');
Insert into SERVICE (service_id,name,special) values ('8','Service8','Yes');
Insert into SERVICE (service_id,name,special) values ('9','Service9','No');

CREATE TABLE SERVICE_CUST
(cust_id  VARCHAR(50),
service_id  VARCHAR( 50 )
)

Insert into SERVICE_CUST (cust_id,service_id) values ('1','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('2','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('3','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('4','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('5','2');
Insert into SERVICE_CUST (cust_id,service_id) values ('6','3');
Insert into SERVICE_CUST (cust_id,service_id) values ('7','4');
Insert into SERVICE_CUST (cust_id,service_id) values ('8','4');
Insert into SERVICE_CUST (cust_id,service_id) values ('9','5');

CREATE TABLE CUST
(cust_id  VARCHAR(50),
type  VARCHAR( 50 )
)

Insert into CUST (cust_id,type) values ('1','A');
Insert into CUST (cust_id,type) values ('2','B');
Insert into CUST (cust_id,type) values ('3','C');
Insert into CUST (cust_id,type) values ('4','D');
Insert into CUST (cust_id,type) values ('5','A');
Insert into CUST (cust_id,type) values ('6','B');
Insert into CUST (cust_id,type) values ('7','A');
Insert into CUST (cust_id,type) values ('8','B');
Insert into CUST (cust_id,type) values ('9','F');
</code>```

when I run this query

```<code>select ri.service_id, ri.name, rfn.type
from service ri, service_cust rfni, cust rfn
where ri.service_id = rfni.service_id
and rfni.cust_id = rfn.cust_id
and  ri.special = 'Yes'
</code>```

I get

1   Service1    A 1 Service1    B 1 Service1    C 1 Service1    D 2 Service2    A    3  Service3    B 4 Service4    A 4 Service4    B 5 Service5    F

I only need Services that is missing Type A,B or C.  If it has all 3 (A,B,C) then don't need to see in results.
so results i am looking for is
Service2 with text 'Missing B,C'
Service3 with text 'Missing A,C'
Service4 with text 'Missing C'

i think my 1st part of the original query is not working properly as its bringing in:Service 2,3,4,5,6,7 and 8

```<code>select  ri.service_id, ri.name
from service ri
where ri.special = 'Yes'
and ri.service_id not in (
select distinct ri.service_id
from service ri, service_cust rfni, cust rfn
where ri.service_id = rfni.service_id
and rfni.cust_id = rfn.cust_id
and  ri.special = 'Yes'
and rfn.type in( 'A','B', 'C')
group by ri.service_id
having count(distinct rfn.type)=3)
</code>```

thanks for help

`

答:
Consider a conditional aggregate query to count the occurrence of types:

```<code>SELECT ri.service_id,
       ri.name,
       ri.creation_date,
       SUM(CASE WHEN rfn.TYPE = 'A' THEN 1 ELSE 0 END) AS TypeA_Count,
       SUM(CASE WHEN rfn.TYPE = 'B' THEN 1 ELSE 0 END) AS TypeB_Count,
       SUM(CASE WHEN rfn.TYPE = 'C' THEN 1 ELSE 0 END) AS TypeC_Count
FROM   service ri
LEFT JOIN service_cust rfni
     ON ri.service_id = rfni.service_id
LEFT JOIN cust rfn
     ON rfni.cust_id = rfn.cust_id
WHERE  ri.special = 'Yes'
  AND  rfn.TYPE IN( 'A', 'B', 'C' )
GROUP  BY ri.service_id,
          ri.name,
          ri.creation_date
HAVING COUNT(DISTINCT rfn.type) < 3
</code>```

And if needing to return a single column, integrate above in a CTE:

```<code>WITH cte (
   ...same as above...
)

SELECT cte.service_id,
       cte.name,
       cte.creation_date,
       CASE
            WHEN TypeA_Count = 0 AND TypeB > 0 AND TypeC_Count > 0 THEN 'Type A is Missing'
            WHEN TypeA_Count = 0 AND TypeB = 0 AND TypeC_Count > 0 THEN 'Type A and B are Missing'
            WHEN TypeA_Count = 0 AND TypeB > 0 AND TypeC_Count = 0 THEN 'Type A and C are Missing'
            WHEN TypeA_Count > 0 AND TypeB = 0 AND TypeC_Count > 0 THEN 'Type B is Missing'
            WHEN TypeA_Count > 0 AND TypeB = 0 AND TypeC_Count = 0 THEN 'Type B and C are Missing'
            WHEN TypeA_Count > 0 AND TypeB > 0 AND TypeC_Count = 0 THEN 'Type C is Missing'
            WHEN TypeA_Count > 0 AND TypeB > 0 AND TypeC_Count > 0 THEN 'None are Missing'
       END Missing
FROM cte
</code>```

Body:
I have a requirement where I need to bring in calculated column to show if Type A, B or C is missing.

A Service can have one to many Types (there are 10 different "Type").

Service has to have all 3 "Type": A B and C.

If its missing any of the 3, I need to show which "Type" is missing.

For example, if Service ID 2 has Type A then the calculated column has to say "Type B and C is missing", if Service ID 3 has Type B then the calculated column has to say Type A and C is missing" etc...

I got the calculation to say "Type A B or C is missing" but having hard time to break it down to the specific Type that is missing. I will eventually union this result to few other queries that are similar.  Can anyone help with this?

SELECT ri.service_id,
       ri.name,
       ri.creation_date,
       'Type A B or C is missing' AS missing
FROM   service ri
WHERE  ri.special = 'Yes'
  AND  ri.service_id NOT IN (SELECT DISTINCT ri.service_id
                             FROM   service ri,
                                    service_cust rfni,
                                    cust rfn
                             WHERE  ri.service_id = rfni.service_id
                               AND  rfni.cust_id = rfn.cust_id
                               AND  ri.special = 'Yes'
                               AND rfn.TYPE IN( 'A', 'B', 'C' )

                               GROUP  BY ri.service_id
                                 HAVING Count(DISTINCT rfn.TYPE) = 3)

Thanks`
CREATE TABLE SERVICE
(service_id  VARCHAR(50),
name  VARCHAR( 50 ),
special  VARCHAR( 50 )
)

Insert into SERVICE (service_id,name,special) values ('1','Service1','Yes');
Insert into SERVICE (service_id,name,special) values ('2','Service2','Yes');
Insert into SERVICE (service_id,name,special) values ('3','Service3','Yes');
Insert into SERVICE (service_id,name,special) values ('4','Service4','Yes');
Insert into SERVICE (service_id,name,special) values ('5','Service5','Yes');
Insert into SERVICE (service_id,name,special) values ('6','Service6','Yes');
Insert into SERVICE (service_id,name,special) values ('7','Service7','Yes');
Insert into SERVICE (service_id,name,special) values ('8','Service8','Yes');
Insert into SERVICE (service_id,name,special) values ('9','Service9','No');

CREATE TABLE SERVICE_CUST
(cust_id  VARCHAR(50),
service_id  VARCHAR( 50 )
)

Insert into SERVICE_CUST (cust_id,service_id) values ('1','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('2','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('3','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('4','1');
Insert into SERVICE_CUST (cust_id,service_id) values ('5','2');
Insert into SERVICE_CUST (cust_id,service_id) values ('6','3');
Insert into SERVICE_CUST (cust_id,service_id) values ('7','4');
Insert into SERVICE_CUST (cust_id,service_id) values ('8','4');
Insert into SERVICE_CUST (cust_id,service_id) values ('9','5');

CREATE TABLE CUST
(cust_id  VARCHAR(50),
type  VARCHAR( 50 )
)

Insert into CUST (cust_id,type) values ('1','A');
Insert into CUST (cust_id,type) values ('2','B');
Insert into CUST (cust_id,type) values ('3','C');
Insert into CUST (cust_id,type) values ('4','D');
Insert into CUST (cust_id,type) values ('5','A');
Insert into CUST (cust_id,type) values ('6','B');
Insert into CUST (cust_id,type) values ('7','A');
Insert into CUST (cust_id,type) values ('8','B');
Insert into CUST (cust_id,type) values ('9','F');

when I run this query

select ri.service_id, ri.name, rfn.type
from service ri, service_cust rfni, cust rfn
where ri.service_id = rfni.service_id
and rfni.cust_id = rfn.cust_id
and  ri.special = 'Yes'

I get

1   Service1    A 1 Service1    B 1 Service1    C 1 Service1    D 2 Service2    A    3  Service3    B 4 Service4    A 4 Service4    B 5 Service5    F

I only need Services that is missing Type A,B or C.  If it has all 3 (A,B,C) then don't need to see in results.
so results i am looking for is
Service2 with text 'Missing B,C'
Service3 with text 'Missing A,C'
Service4 with text 'Missing C'

i think my 1st part of the original query is not working properly as its bringing in:Service 2,3,4,5,6,7 and 8

select  ri.service_id, ri.name
from service ri
where ri.special = 'Yes'
and ri.service_id not in (
select distinct ri.service_id
from service ri, service_cust rfni, cust rfn
where ri.service_id = rfni.service_id
and rfni.cust_id = rfn.cust_id
and  ri.special = 'Yes'
and rfn.type in( 'A','B', 'C')
group by ri.service_id
having count(distinct rfn.type)=3)

thanks for help

`

Body:
Consider a conditional aggregate query to count the occurrence of types:

SELECT ri.service_id,
       ri.name,
       ri.creation_date,
       SUM(CASE WHEN rfn.TYPE = 'A' THEN 1 ELSE 0 END) AS TypeA_Count,
       SUM(CASE WHEN rfn.TYPE = 'B' THEN 1 ELSE 0 END) AS TypeB_Count,
       SUM(CASE WHEN rfn.TYPE = 'C' THEN 1 ELSE 0 END) AS TypeC_Count
FROM   service ri
LEFT JOIN service_cust rfni
     ON ri.service_id = rfni.service_id
LEFT JOIN cust rfn
     ON rfni.cust_id = rfn.cust_id
WHERE  ri.special = 'Yes'
  AND  rfn.TYPE IN( 'A', 'B', 'C' )
GROUP  BY ri.service_id,
          ri.name,
          ri.creation_date
HAVING COUNT(DISTINCT rfn.type) < 3

And if needing to return a single column, integrate above in a CTE:

WITH cte (
   ...same as above...
)

SELECT cte.service_id,
       cte.name,
       cte.creation_date,
       CASE
            WHEN TypeA_Count = 0 AND TypeB > 0 AND TypeC_Count > 0 THEN 'Type A is Missing'
            WHEN TypeA_Count = 0 AND TypeB = 0 AND TypeC_Count > 0 THEN 'Type A and B are Missing'
            WHEN TypeA_Count = 0 AND TypeB > 0 AND TypeC_Count = 0 THEN 'Type A and C are Missing'
            WHEN TypeA_Count > 0 AND TypeB = 0 AND TypeC_Count > 0 THEN 'Type B is Missing'
            WHEN TypeA_Count > 0 AND TypeB = 0 AND TypeC_Count = 0 THEN 'Type B and C are Missing'
            WHEN TypeA_Count > 0 AND TypeB > 0 AND TypeC_Count = 0 THEN 'Type C is Missing'
            WHEN TypeA_Count > 0 AND TypeB > 0 AND TypeC_Count > 0 THEN 'None are Missing'
       END Missing
FROM cte


来源: stackexchange

问:
How to use @Api swagger annotation in sub-resource class?
In my project I have some sub-resources, correctly implemented according to the Jersey framework guidelines.

However, I have a problem in generating the openapi.json file (generated by swagger-maven-plugin).
In particular, I would like to be able to use the @Api swagger annotation on classes that implement sub-resources, to apply some properties, such as authorizations.

The problem is that if I use the @Api annotation on the sub-resource classes, swagger sees those classes not only as a sub-resources, but also as resources. The result is that in the openapi.json file, for each sub-resource, a same resource is generated (which should not exist).

The root resource:

```<code>@Path("root")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/root", authorizations = {
        @Authorization(value = "auth", scopes = {})
})
public class ExperienceResource {

    @Path("/sub_a")
    public SubResourceA getSubA() {
        return new SubResourceA();
    }

    @Path("/sub_b")
    public SubResourceB getSubB() {
        return new SubResourceB();
    }
}
</code>```

The sub-resource:

```<code>@Api(authorizations = {
     @Authorization(value = "auth", scopes = {})
})
public class SubResourceA {

    @GET
    ...
}
</code>```

I also tried using @Api(value="") or @Api(value="sub_a"), but they don't work or make things worse.
Obviously, if I remove the @Api annotation everything works correctly, but I am forced to apply the properties operation by operation.

Any suggestions?

答:
The solution was quite simple. To ensure that the class that implements the sub-resource is seen by swagger just as a sub-resource (and not as a resource too) just add the property hidden = true in the @Api annotation

```<code>   @Api(hidden = true, authorizations = {
     @Authorization(value = "auth", scopes = {})
})
public class SubResourceA {

    @GET
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my project I have some sub-resources, correctly implemented according to the Jersey framework guidelines.

However, I have a problem in generating the openapi.json file (generated by swagger-maven-plugin).
In particular, I would like to be able to use the @Api swagger annotation on classes that implement sub-resources, to apply some properties, such as authorizations.

The problem is that if I use the @Api annotation on the sub-resource classes, swagger sees those classes not only as a sub-resources, but also as resources. The result is that in the openapi.json file, for each sub-resource, a same resource is generated (which should not exist).

The root resource:

@Path("root")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/root", authorizations = {
        @Authorization(value = "auth", scopes = {})
})
public class ExperienceResource {

    @Path("/sub_a")
    public SubResourceA getSubA() {
        return new SubResourceA();
    }

    @Path("/sub_b")
    public SubResourceB getSubB() {
        return new SubResourceB();
    }
}

The sub-resource:

@Api(authorizations = {
     @Authorization(value = "auth", scopes = {})
})
public class SubResourceA {

    @GET
    ...
}

I also tried using @Api(value="") or @Api(value="sub_a"), but they don't work or make things worse.
Obviously, if I remove the @Api annotation everything works correctly, but I am forced to apply the properties operation by operation.

Any suggestions?

Body:
The solution was quite simple. To ensure that the class that implements the sub-resource is seen by swagger just as a sub-resource (and not as a resource too) just add the property hidden = true in the @Api annotation

   @Api(hidden = true, authorizations = {
     @Authorization(value = "auth", scopes = {})
})
public class SubResourceA {

    @GET
    ...
}


问:
Array out of bounds by checking elements
My for loop is always going out of bounds. It keeps checking whether the element is > 0. I tried plenty of restrictions, but none of them worked. Do you have any suggestions?</p>

```<code>###Creation of the graph in a method
def graph(self):
    ###Creation of the given array I added zero rows and columns because of no restrictions at the boarders.
    a = np.array([
        [0, 16, 12, 21, 0, 0, 0],
        [16, 0, 0, 17, 20, 0, 0],
        [12, 0, 0, 28, 0, 31, 0],
        [21, 17, 28, 0, 18, 19, 23],
        [0, 20, 0, 18, 0, 0, 11],
        [0, 0, 31, 19, 0, 0, 27],
        [0, 0, 0, 23, 11, 27, 0]]),
        ###Determination of datatype size
        dtype = np.uint8
    )
    ###Graph dictionary for letting the bfs know who's connected to whom
    graph = {}
    ###For loop in order to iterate through the elements
    for r in range(len(a)):
        for c in range(len(a)):
            ###Checking whether element is greater than 0
            if a[r, c] > 0:
                ###List of coordinates for checking elements connection
                d = [r-1, c+1, r+1, c-1]
                ###Checking whether one of the surrounding elements is greater than 0
                if (a[d[0], c] > 0 and r >= 0) or (a[r, d[1]] > 0 and c <= len(a)) or (a[d[2], c] > 0 and r <= len(a)) or (a[r, d[3]] > 0 and c >= 0):
                    ###Creates the key in the dictionary without values
                    graph[a[r, c]] = []
                    ###Add value(s) to the specific key in the dictionary
                    if a[d[0], c] > 0:
                        graph[a[r, c]].append(a[d[0], c])
                    if a[r, d[1]] > 0:
                        graph[a[r, c]].append(a[r, d[1]])
                    if a[d[2], c] > 0:
                        graph[a[r, c]].append(a[d[2], c])
                    if a[r, d[3]] > 0:
                        graph[a[r, c]].append(a[r, d[3]])
    ###Return of the graph in form of a dictionary
    return(graph)
</code>```

答:
To answer the question of why the restrictions don't work, let's examine one of them for example (substituing in the d[0] value, since the d list isn't actually helping us either with solving the problem or simplifying the code):

```<code>a[r-1, c] > 0 and r >= 0
</code>```

The short-circuiting behaviour of and can be used to make sure that a value isn't checked, yes. But the short-circuiting works the other way around. In this example, a[d[0], c] > 0 is tested unconditionally, and then r >= 0 is only tried if the first thing resulted in a truthy value. But the first part causes an error, so the second is too late to prevent the error. You wanted r >= 0 and a[r-1, c] > 0. (By substituting in r-1 for d[0], it becomes clearer: we check the value of r, and then try the indexing that uses r.)

But we can do much better than this by taking advantage of Numpy operations. Numpy is pretty much specifically designed to make these kinds of problems both simpler to code and more performant.

The first thing we want to do is see the places where there is a non-zero value in the data:

```<code>>>> a = np.array([
...     [0, 16, 12, 21, 0, 0, 0],
...     [16, 0, 0, 17, 20, 0, 0],
...     [12, 0, 0, 28, 0, 31, 0],
...     [21, 17, 28, 0, 18, 19, 23],
...     [0, 20, 0, 18, 0, 0, 11],
...     [0, 0, 31, 19, 0, 0, 27],
...     [0, 0, 0, 23, 11, 27, 0]
... ], dtype = np.uint8)
>>> a
array([[ 0, 16, 12, 21,  0,  0,  0],
       [16,  0,  0, 17, 20,  0,  0],
       [12,  0,  0, 28,  0, 31,  0],
       [21, 17, 28,  0, 18, 19, 23],
       [ 0, 20,  0, 18,  0,  0, 11],
       [ 0,  0, 31, 19,  0,  0, 27],
       [ 0,  0,  0, 23, 11, 27,  0]], dtype=uint8)
>>> a != 0 # Yes, it's really *this* easy
array([[False,  True,  True,  True, False, False, False],
       [ True, False, False,  True,  True, False, False],
       [ True, False, False,  True, False,  True, False],
       [ True,  True,  True, False,  True,  True,  True],
       [False,  True, False,  True, False, False,  True],
       [False, False,  True,  True, False, False,  True],
       [False, False, False,  True,  True,  True, False]])
</code>```

And let's get the indices of those positions:

```<code>>>> np.where(a != 0)
(array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6,
       6, 6], dtype=int64), array([1, 2, 3, 0, 3, 4, 0, 3, 5, 0, 1, 2, 4, 5, 6, 1, 3, 6, 2, 3, 6, 3,
       4, 5], dtype=int64))
</code>```

This result is a bit hard to make sense of; we get a tuple of two 1-d arrays, representing all the x-coords and y-coords of the non-zero values (They're also stored using your system's native integer type, since they're indices; as you can see, I'm on a 64-bit machine). Fortunately, it's also easy to make Numpy pair them up:

```<code>>>> np.transpose(np.where(a != 0))
# long output omitted
</code>```

That's all well and good, but now how do we look for neighbours? I'll consider the case of neighbours above the current position, and leave the rest as an exercise.

The way we'll do this is to build an array whose values represent the one above the original array position (filling in zeros for the top row). We do that by slicing the array, and then adding a row. The rows we want are all except for the last, and then we fill in zeros across the top. But an easier way to do that is to start with an equal-sized 2d array of zeros, and put the relevant rows into the bottom. So:

```<code>>>> above = np.zeros(a.shape, dtype=np.uint8)
>>> above[1:, :] = a[:-1, :]
>>> above
array([[ 0,  0,  0,  0,  0,  0,  0],
       [ 0, 16, 12, 21,  0,  0,  0],
       [16,  0,  0, 17, 20,  0,  0],
       [12,  0,  0, 28,  0, 31,  0],
       [21, 17, 28,  0, 18, 19, 23],
       [ 0, 20,  0, 18,  0,  0, 11],
       [ 0,  0, 31, 19,  0,  0, 27]], dtype=uint8)
</code>```

Notice the pairs of values used for slicing: each corresponds to a separate dimension of the array. So [1:, :] slices from the row 1 onwards, keeping all columns, as the destination; [:-1, :] slices every row except the last, as our source data.

Now we can check for places that are non-zero and also have a non-zero neighbour above:

```<code>>>> (a != 0) & (above != 0)
array([[False, False, False, False, False, False, False],
       [False, False, False,  True, False, False, False],
       [ True, False, False,  True, False, False, False],
       [ True, False, False, False, False,  True, False],
       [False,  True, False, False, False, False,  True],
       [False, False, False,  True, False, False,  True],
       [False, False, False,  True, False, False, False]])
</code>```

(The parentheses are necessary here; explaining is a bit difficult.)

Finally we can look at those coordinates, and for each of them, record a graph link in the normal way:

```<code>>>> for r, c in np.transpose(np.where((a != 0) & (above != 0))):
...    print('there is a link from ({r}, {c}) to ({r - 1}, {c})')
</code>```

Body:
My for loop is always going out of bounds. It keeps checking whether the element is > 0. I tried plenty of restrictions, but none of them worked. Do you have any suggestions?

###Creation of the graph in a method
def graph(self):
    ###Creation of the given array I added zero rows and columns because of no restrictions at the boarders.
    a = np.array([
        [0, 16, 12, 21, 0, 0, 0],
        [16, 0, 0, 17, 20, 0, 0],
        [12, 0, 0, 28, 0, 31, 0],
        [21, 17, 28, 0, 18, 19, 23],
        [0, 20, 0, 18, 0, 0, 11],
        [0, 0, 31, 19, 0, 0, 27],
        [0, 0, 0, 23, 11, 27, 0]]),
        ###Determination of datatype size
        dtype = np.uint8
    )
    ###Graph dictionary for letting the bfs know who's connected to whom
    graph = {}
    ###For loop in order to iterate through the elements
    for r in range(len(a)):
        for c in range(len(a)):
            ###Checking whether element is greater than 0
            if a[r, c] > 0:
                ###List of coordinates for checking elements connection
                d = [r-1, c+1, r+1, c-1]
                ###Checking whether one of the surrounding elements is greater than 0
                if (a[d[0], c] > 0 and r >= 0) or (a[r, d[1]] > 0 and c <= len(a)) or (a[d[2], c] > 0 and r <= len(a)) or (a[r, d[3]] > 0 and c >= 0):
                    ###Creates the key in the dictionary without values
                    graph[a[r, c]] = []
                    ###Add value(s) to the specific key in the dictionary
                    if a[d[0], c] > 0:
                        graph[a[r, c]].append(a[d[0], c])
                    if a[r, d[1]] > 0:
                        graph[a[r, c]].append(a[r, d[1]])
                    if a[d[2], c] > 0:
                        graph[a[r, c]].append(a[d[2], c])
                    if a[r, d[3]] > 0:
                        graph[a[r, c]].append(a[r, d[3]])
    ###Return of the graph in form of a dictionary
    return(graph)

Body:
To answer the question of why the restrictions don't work, let's examine one of them for example (substituing in the d[0] value, since the d list isn't actually helping us either with solving the problem or simplifying the code):

a[r-1, c] > 0 and r >= 0

The short-circuiting behaviour of and can be used to make sure that a value isn't checked, yes. But the short-circuiting works the other way around. In this example, a[d[0], c] > 0 is tested unconditionally, and then r >= 0 is only tried if the first thing resulted in a truthy value. But the first part causes an error, so the second is too late to prevent the error. You wanted r >= 0 and a[r-1, c] > 0. (By substituting in r-1 for d[0], it becomes clearer: we check the value of r, and then try the indexing that uses r.)

But we can do much better than this by taking advantage of Numpy operations. Numpy is pretty much specifically designed to make these kinds of problems both simpler to code and more performant.

The first thing we want to do is see the places where there is a non-zero value in the data:

>>> a = np.array([
...     [0, 16, 12, 21, 0, 0, 0],
...     [16, 0, 0, 17, 20, 0, 0],
...     [12, 0, 0, 28, 0, 31, 0],
...     [21, 17, 28, 0, 18, 19, 23],
...     [0, 20, 0, 18, 0, 0, 11],
...     [0, 0, 31, 19, 0, 0, 27],
...     [0, 0, 0, 23, 11, 27, 0]
... ], dtype = np.uint8)
>>> a
array([[ 0, 16, 12, 21,  0,  0,  0],
       [16,  0,  0, 17, 20,  0,  0],
       [12,  0,  0, 28,  0, 31,  0],
       [21, 17, 28,  0, 18, 19, 23],
       [ 0, 20,  0, 18,  0,  0, 11],
       [ 0,  0, 31, 19,  0,  0, 27],
       [ 0,  0,  0, 23, 11, 27,  0]], dtype=uint8)
>>> a != 0 # Yes, it's really *this* easy
array([[False,  True,  True,  True, False, False, False],
       [ True, False, False,  True,  True, False, False],
       [ True, False, False,  True, False,  True, False],
       [ True,  True,  True, False,  True,  True,  True],
       [False,  True, False,  True, False, False,  True],
       [False, False,  True,  True, False, False,  True],
       [False, False, False,  True,  True,  True, False]])

And let's get the indices of those positions:

>>> np.where(a != 0)
(array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6,
       6, 6], dtype=int64), array([1, 2, 3, 0, 3, 4, 0, 3, 5, 0, 1, 2, 4, 5, 6, 1, 3, 6, 2, 3, 6, 3,
       4, 5], dtype=int64))

This result is a bit hard to make sense of; we get a tuple of two 1-d arrays, representing all the x-coords and y-coords of the non-zero values (They're also stored using your system's native integer type, since they're indices; as you can see, I'm on a 64-bit machine). Fortunately, it's also easy to make Numpy pair them up:

>>> np.transpose(np.where(a != 0))
# long output omitted

That's all well and good, but now how do we look for neighbours? I'll consider the case of neighbours above the current position, and leave the rest as an exercise.

The way we'll do this is to build an array whose values represent the one above the original array position (filling in zeros for the top row). We do that by slicing the array, and then adding a row. The rows we want are all except for the last, and then we fill in zeros across the top. But an easier way to do that is to start with an equal-sized 2d array of zeros, and put the relevant rows into the bottom. So:

>>> above = np.zeros(a.shape, dtype=np.uint8)
>>> above[1:, :] = a[:-1, :]
>>> above
array([[ 0,  0,  0,  0,  0,  0,  0],
       [ 0, 16, 12, 21,  0,  0,  0],
       [16,  0,  0, 17, 20,  0,  0],
       [12,  0,  0, 28,  0, 31,  0],
       [21, 17, 28,  0, 18, 19, 23],
       [ 0, 20,  0, 18,  0,  0, 11],
       [ 0,  0, 31, 19,  0,  0, 27]], dtype=uint8)

Notice the pairs of values used for slicing: each corresponds to a separate dimension of the array. So [1:, :] slices from the row 1 onwards, keeping all columns, as the destination; [:-1, :] slices every row except the last, as our source data.

Now we can check for places that are non-zero and also have a non-zero neighbour above:

>>> (a != 0) & (above != 0)
array([[False, False, False, False, False, False, False],
       [False, False, False,  True, False, False, False],
       [ True, False, False,  True, False, False, False],
       [ True, False, False, False, False,  True, False],
       [False,  True, False, False, False, False,  True],
       [False, False, False,  True, False, False,  True],
       [False, False, False,  True, False, False, False]])

(The parentheses are necessary here; explaining is a bit difficult.)

Finally we can look at those coordinates, and for each of them, record a graph link in the normal way:

>>> for r, c in np.transpose(np.where((a != 0) & (above != 0))):
...    print('there is a link from ({r}, {c}) to ({r - 1}, {c})')


问:
upgrade : spring framework 5.2.X
I want to upgrade spring framework from 4 to 5. Should i go with latest version such as 5.2.6 or any prior version i.e 5.2.0 or 5.2.4 etc? How should i decide on this ? I don't have any specific feature in mind.Thanks,</p>

答:
Don't see any reason not going for the latest.

Usually the major releases (from 4 to 5) might break something, so you might want to wait if it requires a lot of changes on your side, but if you're going to move to 5.2.x - go for the latest

Title: upgrade : spring framework 5.2.X


问:
My program doesn't want to write in a text file after DLL call
I have a DLL which expose a function :

```<code>extern "C" __declspec( dllimport ) __stdcall int EP_ProtectedStringByKey( char* Key, char* Left, int Len);
</code>```

Head of the C++ file :

```<code>typedef int (*GetString)(const char *Key, const char *Str, int Len);
</code>```

With this code, everything works fine. The program write in the "example.txt" what it should write.

```<code>GetString _GetSTR;
int longueur;
string my_string;
const char *pmy_string;
HINSTANCE hInstLibrary = LoadLibrary("my.dll");
_GetSTR = (GetString)GetProcAddress(hInstLibrary, "EP_ProtectedStringByKey");
ofstream myfile("example.txt");
longueur = _GetSTR("key_421", NULL, 0);
cout << "Taille : " << longueur << endl;
myfile << "Size : " << longueur << endl;
my_string.resize(longueur); // resizing the string
pmy_string = my_string.c_str(); // Pointer to pmy_string

// ---- _GetSTR("key_421", pmy_string, longueur); ----

myfile << "Another line.\n";
myfile.close();
FreeLibrary(hInstLibrary);
</code>```

Now if I add this line of code :

```<code>_GetSTR("key_421", pmy_string, longueur);
</code>```

My data is well print on the screen with :

```<code>cout << "Data : " << pmy_string << endl;
</code>```

But NOTHING is write anymore  in the file "example.txt ("Another line" isn't write anymore). It's like after fulling the my_string variable, my program refused to write in file. But strangely it show the content of pmy_string on the screen.

I suppose I'am doing something wrong but I can't figure what...

Thanks for help,

答:
To avoid two undefined behavior, I need to :

Change the typedef to precise the calling convention

typedef int (*GetString)(const char *Key, const char *Str, int Len);

In

```<code>typedef int (__stdcall *GetString)(const char *Key, const char *Str, int Len);
</code>```

Dpn't use std::string::c_str()  cause in CPP-Reference  "Writing to the character array accessed through c_str() is undefined behavior."

pmy_string = my_string.c_str(); // Pointer to pmy_string

In

```<code>pmy_string = my_string.data(); // Pointer to pmy_string
</code>```

Body:
I have a DLL which expose a function :

extern "C" __declspec( dllimport ) __stdcall int EP_ProtectedStringByKey( char* Key, char* Left, int Len);

Head of the C++ file :

typedef int (*GetString)(const char *Key, const char *Str, int Len);

With this code, everything works fine. The program write in the "example.txt" what it should write.

GetString _GetSTR;
int longueur;
string my_string;
const char *pmy_string;
HINSTANCE hInstLibrary = LoadLibrary("my.dll");
_GetSTR = (GetString)GetProcAddress(hInstLibrary, "EP_ProtectedStringByKey");
ofstream myfile("example.txt");
longueur = _GetSTR("key_421", NULL, 0);
cout << "Taille : " << longueur << endl;
myfile << "Size : " << longueur << endl;
my_string.resize(longueur); // resizing the string
pmy_string = my_string.c_str(); // Pointer to pmy_string

// ---- _GetSTR("key_421", pmy_string, longueur); ----

myfile << "Another line.\n";
myfile.close();
FreeLibrary(hInstLibrary);

Now if I add this line of code :

_GetSTR("key_421", pmy_string, longueur);

My data is well print on the screen with :

cout << "Data : " << pmy_string << endl;

But NOTHING is write anymore  in the file "example.txt ("Another line" isn't write anymore). It's like after fulling the my_string variable, my program refused to write in file. But strangely it show the content of pmy_string on the screen.

I suppose I'am doing something wrong but I can't figure what...

Thanks for help,

Body:
To avoid two undefined behavior, I need to :

Change the typedef to precise the calling convention

typedef int (*GetString)(const char *Key, const char *Str, int Len);

In

typedef int (__stdcall *GetString)(const char *Key, const char *Str, int Len);

Dpn't use std::string::c_str()  cause in CPP-Reference  "Writing to the character array accessed through c_str() is undefined behavior."

pmy_string = my_string.c_str(); // Pointer to pmy_string

In

pmy_string = my_string.data(); // Pointer to pmy_string


问:
Programatically deactivating a feature in Internet Explorer
I'm currently developing a plug in for Internet Explorer, and there's a certain feature in Internet Explorer that's bothering me.

There's this feature in IE that's been appearing at least since IE7 (I couldn't check earlier versions), that lets the user modify the sizing of HTML elements in editable windows (such as a rich text mail in GMail), just by clicking on the element and dragging the sizing box. This modifies the style of the HTML element (such as a  or a
).

My first problem is that I don't know the name of that feature. I've searched and searched, but I haven't been able to find a thing.

My second problem is that I need a way to either turn it off, or at least to work with it, programatically. In my plug in, I need to modify the DOM in webmail clients to modify certain things that the user types. The problem is that for some reason, the behaviour of my plugin varies if an HTML element is selected using this feature in the edit window of the webmail. I need to, at the very least, be able to detect if anything is selected this way.

Any help will be appreciated. Thanks a lot!

答:
You're probably talking about Internet Explorer's Accessibility Features, which are designed to assist the visually impaired to use websites. Visual impairement can take many forms, and it's generally considered very bad form to take away any tools designed to assist users in their efforts to effectively use the Internet.

Don't make your users work harder to use your site. You get paid to write software that's easy to use and makes life simpler. If your site doesn't do that, your users will find one that does.

ContentLicense: CC BY-SA 3.0


问:
MySQL - How do I relate a custom table bi-directionally with user and usermeta tables? - Wordpress
I am using Wordpress, PhpMyAdmin, MySQL.
I am also quite novice when it comes to SQL and databases, so bear with me.

I have a Custom Data Table (this is a master table of user information), which I want to relate bi-directionally with the wp_users and wp_usermeta tables - meaning if a user updates their profile (Users or Usermeta tables) then the Custom Data Table would automatically update without me needing to manually input their updated information.

Likewise, if I edit the Custom Data Table I want the related information in Users and Usermeta to automatically update.

I tried creating a rough diagram of what is in my head. Diagram of data handling

The current system is terrible and very difficult to maintain. Another issue is that there are many SQL reports that use the current Custom Data Table. I understand that the solution I am looking for most likely means creating a completely new table. That's ok.

```<code>       User
–––––––––––––––––––
| ID  | username  |
|–––––+–––––––––––|
| 376 | John      |
| 377 | Paul      |
| 378 | Ringo     |
–––––––––––––––––––

       Usermeta
–––––––––––––––––––––––––––––––––––––––––––––
| meta_id | user_id | meta_key | meta_value |
|–––––––––+–––––––––+––––––––––+––––––––––––|
| 8       | 1       | job      | Keys       |
| 102     | 2       | job      | Vocals     |
| 203     | 3       | job      | Drums      |
–––––––––––––––––––––––––––––––––––––––––––––

       Custom_Table
––––––––––––––––––––––––––––––––––––––
| ID | username  | job     | user_ID |
|––––+–––––––––––+–––––––––+–––––––––|
| 1  | John      | Keys    | 376     |
| 2  | Paul      | Vocals  | 377     |
| 3  | Ringo     | Drums   | 378     |
––––––––––––––––––––––––––––––––––––––
</code>```

Basically, this is what I have a query (except I have many more lines of the usermeta):

```<code>CREATE TABLE custom_table
    SELECT users.username,
    MAX(CASE WHEN meta_key = 'job' THEN meta_value ELSE NULL END) AS job,
    users.ID
    FROM wp_users as users, wp_usermeta as umeta
    WHERE umeta.user_id = users.ID
</code>```

This creates the table I want but if any of the tables are updated it is not 'synced' anywhere else. Is this possible? Would it be done by some sort of trigger (I am still unfamiliar with triggers)?

答:
You can use a Updateable VIEW to solve this:

```<code>CREATE VIEW custom AS
  SELECT User.ID, User.username,
    CASE WHEN meta_key = 'job' THEN meta_value ELSE NULL END AS job
  FROM User INNER JOIN Usermeta ON Usermeta.user_id = User.ID
</code>```

demo on dbfiddle.uk

For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view nonupdatable.

In case you need one of the constructs you can only create the VIEW and have to update the source tables itself. The view is always synced with the source tables.

Body:
I am using Wordpress, PhpMyAdmin, MySQL.
I am also quite novice when it comes to SQL and databases, so bear with me.

I have a Custom Data Table (this is a master table of user information), which I want to relate bi-directionally with the wp_users and wp_usermeta tables - meaning if a user updates their profile (Users or Usermeta tables) then the Custom Data Table would automatically update without me needing to manually input their updated information.

Likewise, if I edit the Custom Data Table I want the related information in Users and Usermeta to automatically update.

I tried creating a rough diagram of what is in my head. Diagram of data handling

The current system is terrible and very difficult to maintain. Another issue is that there are many SQL reports that use the current Custom Data Table. I understand that the solution I am looking for most likely means creating a completely new table. That's ok.

       User
–––––––––––––––––––
| ID  | username  |
|–––––+–––––––––––|
| 376 | John      |
| 377 | Paul      |
| 378 | Ringo     |
–––––––––––––––––––

       Usermeta
–––––––––––––––––––––––––––––––––––––––––––––
| meta_id | user_id | meta_key | meta_value |
|–––––––––+–––––––––+––––––––––+––––––––––––|
| 8       | 1       | job      | Keys       |
| 102     | 2       | job      | Vocals     |
| 203     | 3       | job      | Drums      |
–––––––––––––––––––––––––––––––––––––––––––––

       Custom_Table
––––––––––––––––––––––––––––––––––––––
| ID | username  | job     | user_ID |
|––––+–––––––––––+–––––––––+–––––––––|
| 1  | John      | Keys    | 376     |
| 2  | Paul      | Vocals  | 377     |
| 3  | Ringo     | Drums   | 378     |
––––––––––––––––––––––––––––––––––––––

Basically, this is what I have a query (except I have many more lines of the usermeta):

CREATE TABLE custom_table
    SELECT users.username,
    MAX(CASE WHEN meta_key = 'job' THEN meta_value ELSE NULL END) AS job,
    users.ID
    FROM wp_users as users, wp_usermeta as umeta
    WHERE umeta.user_id = users.ID

This creates the table I want but if any of the tables are updated it is not 'synced' anywhere else. Is this possible? Would it be done by some sort of trigger (I am still unfamiliar with triggers)?

Body:
You can use a Updateable VIEW to solve this:

CREATE VIEW custom AS
  SELECT User.ID, User.username,
    CASE WHEN meta_key = 'job' THEN meta_value ELSE NULL END AS job
  FROM User INNER JOIN Usermeta ON Usermeta.user_id = User.ID

demo on dbfiddle.uk

For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view nonupdatable.

In case you need one of the constructs you can only create the VIEW and have to update the source tables itself. The view is always synced with the source tables.


问:
How to check if a string contains exactly two words in an SQL query?
I need to execute a simple SQL query that will only select those names that are made up of exactly two words</p>

```<code>SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>
</code>```

答:
If you want both words present and exact:</p>

```<code>SELECT *
FROM table
WHERE column LIKE '%word1%'
AND column LIKE '%word2%'
</code>```

Body:
I need to execute a simple SQL query that will only select those names that are made up of exactly two words

SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>

Body:
If you want both words present and exact:

SELECT *
FROM table
WHERE column LIKE '%word1%'
AND column LIKE '%word2%'


问:
Does holding a C++ reference prevents variable of being destroyed?
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

```<code>static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}
</code>```

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.

答:
Given that

MyShape::color is declared as a Color&

... the code is a bit problematic.

The thing to know about C++ references is that you can't re-seat them -- that is, unlike a C++ pointer, once a C++ reference is declared, it will always reference the object it was declared to reference, and cannot be re-directed to reference some other object instead.  (Btw this is also the reason why you're not allowed to declare an unbound reference, e.g. MyColor & c; won't compile because it would be useless)

From that, it follows that what this code actually does:

```<code>void MyShape::setColor(const Color& newColor)
{
   this->color= newColor;
}
</code>```

is overwrite the contents of (whatever Color object this->color is referencing) with the contents of newColor).  It doesn't change the reference itself at all; rather it writes through the reference.  (Remember that references are defined as aliases-to-something, so wherever you specify the reference, the program will behave as if you had specified the object-the-reference-is-referencing there instead)

To answer the titular question:  holding a C++ reference does not guarantee that the object the reference is referencing will not be destroyed.  It's quite possible to delete (or otherwise destroy) the referenced item, and end up with a "dangling reference" that will invoke Undefined Behavior if you try to use it.

As general advice, if you want to have a guard-value to represent "no-color", the best way to do it is to represent the guard-value as an actual color object (e.g. Color(0,0,0,0) could work, if your Color class has an alpha-channel, since any color with alpha=0 is transparent, hence no-color).  That way there is no need to play games with pointers or references to try to represent that information.  If that's not doable for some reason, have a look at std::optional as a way to represent "either-a-value-or-nothing".

As a final note, using pointers does not mean you have to use new and delete -- pointers work equally well (and you can shoot yourself in the foot with them equally badly) when they are pointing to stack-objects or member-objects.  Which is to say, pointers are very powerful, and also very dangerous, and I wouldn't recommend using them for this purpose.

Body:
Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventing for coloring the object.

I didn't want to set this color has a pointer, because it would be necessary to delete it on every setter and on the deconstructor. Is this a bad thought?

Code:

static const Color& noneColor = Color();

static bool isNoneColor(const Color& color) {
    return std::addressof(noneColor) == std::addressof(color);
}

MyShape:MyShape() {
    this->color = noneColor; // this->color is an object of Color
}

void MyShape::setColor(const Color& newColor)
{
    this->color= newColor;
}

void MyShape::draw()
{
    if(!isNoneColor(this->color))
        // Color shape
}

//different scope/class
void B::setColorForShape()
{
    Color color = Color(255,255,255);
    a->setColor(color);
    // Calling isNoneColor(a->color); should return false;
    // After this function ends does variable a->color have undefined behavior?
}

void B::setNoneColorForShape()
{
    a->setColor(noneColor);
    //Calling isNoneColor(a->color); should return true;
}

Is it safe to call isNoneColor with a->color afterwards the method ends?

Edit:

MyShape:color is declared has Color& color. I want to be able to set a noneColor state on my object MyShape. With a simple Color object I can't know if that color is "null"/empty state.

Body:
Given that

MyShape::color is declared as a Color&

... the code is a bit problematic.

The thing to know about C++ references is that you can't re-seat them -- that is, unlike a C++ pointer, once a C++ reference is declared, it will always reference the object it was declared to reference, and cannot be re-directed to reference some other object instead.  (Btw this is also the reason why you're not allowed to declare an unbound reference, e.g. MyColor & c; won't compile because it would be useless)

From that, it follows that what this code actually does:

void MyShape::setColor(const Color& newColor)
{
   this->color= newColor;
}

is overwrite the contents of (whatever Color object this->color is referencing) with the contents of newColor).  It doesn't change the reference itself at all; rather it writes through the reference.  (Remember that references are defined as aliases-to-something, so wherever you specify the reference, the program will behave as if you had specified the object-the-reference-is-referencing there instead)

To answer the titular question:  holding a C++ reference does not guarantee that the object the reference is referencing will not be destroyed.  It's quite possible to delete (or otherwise destroy) the referenced item, and end up with a "dangling reference" that will invoke Undefined Behavior if you try to use it.

As general advice, if you want to have a guard-value to represent "no-color", the best way to do it is to represent the guard-value as an actual color object (e.g. Color(0,0,0,0) could work, if your Color class has an alpha-channel, since any color with alpha=0 is transparent, hence no-color).  That way there is no need to play games with pointers or references to try to represent that information.  If that's not doable for some reason, have a look at std::optional as a way to represent "either-a-value-or-nothing".

As a final note, using pointers does not mean you have to use new and delete -- pointers work equally well (and you can shoot yourself in the foot with them equally badly) when they are pointing to stack-objects or member-objects.  Which is to say, pointers are very powerful, and also very dangerous, and I wouldn't recommend using them for this purpose.


问:
Quanteda: How to look up patterns of two or more words in a phrase, when there can be any number of words in between?
I want to match some patterns in a text in R using the package {quanteda} and the tokens_lookup() function with the default valuetype="glob". The pattern would be the occurrence of one word in connection with a second word located anywhere in the same phrase.

```<code>library(quanteda)

text <- c(d1 = "apples word word word oranges",
          d2 = "apples oranges",
          d3 = "oranges and apples")

dict <- dictionary(list(fruits = c("apple* orange*")))

tokens(text) %>%
  tokens_lookup(dict, valuetype = "glob") %>%
  dfm()
</code>```

Applying this dictionary to the tokenized text from above would yield a result of 0-1-0, while I would expect 1-1-0.

So my question would be, what's with blank spaces in glob pattern matching and shouldn't asterisks match everything including blank spaces? More generally, how can I match d1, d2, and potentially d3 with one and the same pattern?

EDIT:

In regex pattern matching this wouldn't be much of an issue. Example:

```<code>text <- c(d1 = "apples word word word oranges",
          d2 = "apples oranges")

dict <- dictionary(list(fruits = c("apples.*oranges")))

tokens(text, what="sentence") %>%
  tokens_lookup(dict, valuetype = "regex") %>%
  dfm()
</code>```

答:
tokens() segments on whitespace, and tokens_lookup() finds patterns in tokens - or in sequences of tokens if the pattern contains whitespace in your dictionary value.  To use glob matching to get any token between two more specific patterns, you can specify a * as that part of the pattern.  (Technically, patterns with whitespace are parsed into sequences called in quanteda-speak "phrases".  See ?phrase.)

So to slightly modify your example:

library("quanteda")
## Package version: 2.0.1

text <- c(
  d1 = "apples word word oranges",
  d2 = "apples and oranges",
  d3 = "oranges and apples"
)

dict <- dictionary(list(fruits = c(
  "apple* * orange*",
  "apple* * * orange*"
)))

tokens(text) %>%
  tokens_lookup(dict, valuetype = "glob", exclusive = FALSE)
## Tokens consisting of 3 documents.
## d1 :
## [1] "FRUITS"
##
## d2 :
## [1] "FRUITS"
##
## d3 :
## [1] "oranges" "and"     "apples"
```

Here, we get the pattern of apple* followed by one of any token or two of any token, followed by orange*.

This will not pick up the "orange" followed by "apple" however since that's the reverse sequences, and will not pick up just "apple orange" since there is not some token between them.  (But you could add that case by adding a third value to your fruits key as just `"apple* orange*".)

Body:
I want to match some patterns in a text in R using the package {quanteda} and the tokens_lookup() function with the default valuetype="glob". The pattern would be the occurrence of one word in connection with a second word located anywhere in the same phrase.

library(quanteda)

text <- c(d1 = "apples word word word oranges",
          d2 = "apples oranges",
          d3 = "oranges and apples")

dict <- dictionary(list(fruits = c("apple* orange*")))

tokens(text) %>%
  tokens_lookup(dict, valuetype = "glob") %>%
  dfm()

Applying this dictionary to the tokenized text from above would yield a result of 0-1-0, while I would expect 1-1-0.

So my question would be, what's with blank spaces in glob pattern matching and shouldn't asterisks match everything including blank spaces? More generally, how can I match d1, d2, and potentially d3 with one and the same pattern?

EDIT:

In regex pattern matching this wouldn't be much of an issue. Example:

text <- c(d1 = "apples word word word oranges",
          d2 = "apples oranges")

dict <- dictionary(list(fruits = c("apples.*oranges")))

tokens(text, what="sentence") %>%
  tokens_lookup(dict, valuetype = "regex") %>%
  dfm()

Body:
tokens() segments on whitespace, and tokens_lookup() finds patterns in tokens - or in sequences of tokens if the pattern contains whitespace in your dictionary value.  To use glob matching to get any token between two more specific patterns, you can specify a * as that part of the pattern.  (Technically, patterns with whitespace are parsed into sequences called in quanteda-speak "phrases".  See ?phrase.)

So to slightly modify your example:

library("quanteda")
## Package version: 2.0.1

text <- c(
  d1 = "apples word word oranges",
  d2 = "apples and oranges",
  d3 = "oranges and apples"
)

dict <- dictionary(list(fruits = c(
  "apple* * orange*",
  "apple* * * orange*"
)))

tokens(text) %>%
  tokens_lookup(dict, valuetype = "glob", exclusive = FALSE)
## Tokens consisting of 3 documents.
## d1 :
## [1] "FRUITS"
##
## d2 :
## [1] "FRUITS"
##
## d3 :
## [1] "oranges" "and"     "apples"

Here, we get the pattern of apple* followed by one of any token or two of any token, followed by orange*.

This will not pick up the "orange" followed by "apple" however since that's the reverse sequences, and will not pick up just "apple orange" since there is not some token between them.  (But you could add that case by adding a third value to your fruits key as just `"apple* orange*".)


问:
Repeatedly compare same portion of dataset to other portions of dataset based on index value in R
I have a dataframe that looks like the following:

```<code>state  year  value
1      1980  4
1      1981  5
1      1982  4
2      1980  2
2      1981  3
2      1982  4
100    1980  3
100    1981  2
100    1982  5
</code>```

In the actual dataset, there are more states than are shown here. I would like to make a comparison between state 100 and all other states.

Specifically, for each state, I would like to find the difference between the value given by that state for a particular year and the value given for state 100 for that same year. Below, I have shown how I could compare the value for year 1980 between state 1 and state 100.

```<code>df_1 <- df %>% filter(state == 1)
df_100 <- df %>% filter(state == 100)
df_1_1980 <- df_1 %>% filter(year == 1980)
df_100_1980 <- df_100 %>% filter(year == 1980)
difference <- df_1_1980$value - df_100_1980$value
</code>```

How could I do this for all the other states and years in the dataframe?

One possibility I have considered is making a dataframe composed only of the data from state 100 and then connecting it to the original dataframe, like this:

```<code>state  year  value  state100  year100  value100
1      1980  4      100       1980     3
1      1981  5      100       1981     2
1      1982  4      100       1982     5
2      1980  2      100       1980     3
2      1981  3      100       1981     2
2      1982  4      100       1982     5
</code>```

I could then subtract df$value from df$value100 for each row. I assume there is a better way of doing this.

答:
We can filter the 'state' that is not equal to 100, left_join with the dataset with 'state' 100, by 'year' and get the difference between the 'value' columns

```<code>library(dplyr)
df %>%
   filter(state != 100) %>%
   left_join(df %>%
                filter(state == 100) %>%
                select(-state), by = c('year')) %>%
   transmute(state, year, value = value.x, difference = value.x - value.y)
#  state year value difference
#1     1 1980     4          1
#2     1 1981     5          3
#3     1 1982     4         -1
#4     2 1980     2         -1
#5     2 1981     3          1
#6     2 1982     4         -1
</code>```

data

```<code>df <- structure(list(state = c(1L, 1L, 1L, 2L, 2L, 2L, 100L, 100L,
100L), year = c(1980L, 1981L, 1982L, 1980L, 1981L, 1982L, 1980L,
1981L, 1982L), value = c(4L, 5L, 4L, 2L, 3L, 4L, 3L, 2L, 5L)),
class = "data.frame", row.names = c(NA,
-9L))
</code>```

Body:
I have a dataframe that looks like the following:

state  year  value
1      1980  4
1      1981  5
1      1982  4
2      1980  2
2      1981  3
2      1982  4
100    1980  3
100    1981  2
100    1982  5

In the actual dataset, there are more states than are shown here. I would like to make a comparison between state 100 and all other states.

Specifically, for each state, I would like to find the difference between the value given by that state for a particular year and the value given for state 100 for that same year. Below, I have shown how I could compare the value for year 1980 between state 1 and state 100.

df_1 <- df %>% filter(state == 1)
df_100 <- df %>% filter(state == 100)
df_1_1980 <- df_1 %>% filter(year == 1980)
df_100_1980 <- df_100 %>% filter(year == 1980)
difference <- df_1_1980$value - df_100_1980$value

How could I do this for all the other states and years in the dataframe?

One possibility I have considered is making a dataframe composed only of the data from state 100 and then connecting it to the original dataframe, like this:

state  year  value  state100  year100  value100
1      1980  4      100       1980     3
1      1981  5      100       1981     2
1      1982  4      100       1982     5
2      1980  2      100       1980     3
2      1981  3      100       1981     2
2      1982  4      100       1982     5

I could then subtract df$value from df$value100 for each row. I assume there is a better way of doing this.

Body:
We can filter the 'state' that is not equal to 100, left_join with the dataset with 'state' 100, by 'year' and get the difference between the 'value' columns

library(dplyr)
df %>%
   filter(state != 100) %>%
   left_join(df %>%
                filter(state == 100) %>%
                select(-state), by = c('year')) %>%
   transmute(state, year, value = value.x, difference = value.x - value.y)
#  state year value difference
#1     1 1980     4          1
#2     1 1981     5          3
#3     1 1982     4         -1
#4     2 1980     2         -1
#5     2 1981     3          1
#6     2 1982     4         -1

data

df <- structure(list(state = c(1L, 1L, 1L, 2L, 2L, 2L, 100L, 100L,
100L), year = c(1980L, 1981L, 1982L, 1980L, 1981L, 1982L, 1980L,
1981L, 1982L), value = c(4L, 5L, 4L, 2L, 3L, 4L, 3L, 2L, 5L)),
class = "data.frame", row.names = c(NA,
-9L))


问:
Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu. Problem is I need directories so what I have looks like
>/apples/oranges/test.ex< What I need is >/apples/oranges<
Not sure if Regex or just using str.replace() is better. As each line is different I would need to find the last / and remove it as well as everything up to <

Hopefully that makes sense.

答:
Here's way using the split and join methods:

```<code>s = '>/apples/oranges/test.ex<'
s = '/'.join(s.split('/')[:-1])+'<' # Splits s by '/', remove the last object, join them together, plus a '<'
print(s)
</code>```

Output:

```<code>>/apples/oranges<
</code>```

Title: Remove specific section of string

Body:
Here's way using the split and join methods:

s = '>/apples/oranges/test.ex<'
s = '/'.join(s.split('/')[:-1])+'<' # Splits s by '/', remove the last object, join them together, plus a '<'
print(s)

Output:

>/apples/oranges<


问:
How to avoid a "null" error when the List returned to ListView builder is empty?
```<code>Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  Future<List<Asset>> assets = dbHelper.getAssets();
  assets.then((value) => handleValue(value)).catchError((error) => handleError(error));
  return assets;
}
</code>```

"Asset" has 6 strings defined in it. When getAssets is executed with no records added (db table is empty) I get the following error.

"E/flutter (23529): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null."

Can someone elaborate what to write in the functions "handValue" and "HandleError" so I can avoid the exception on first launch of Listview when the DB table has no records.

```<code>Expanded(
            child: FutureBuilder<List<Asset>>(
              future: fetchAssetsFromDatabase(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: filterAssets.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: Text(filterAssets[index].name),
                          subtitle: Text(filterAssets[index].url),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => View(
                                  assets: Asset(
                                      id: filterAssets[index].id,
                                      name: filterAssets[index].name,
                                      username: filterAssets[index].username,
                                      password: filterAssets[index].password,
                                      url: filterAssets[index].url,
                                      notes: filterAssets[index].notes,
                                      other: filterAssets[index].other),
                                ),
                              ),
                            );
                          },
                        );
                      });
                } else if (snapshot.hasData == false) {
                  return new Text("No Data found", textAlign: TextAlign.center);
                }
                return new Container(
                  alignment: AlignmentDirectional.center,
                  child: new CircularProgressIndicator(),
                );
              },
            ),
          ),
</code>```

答:
Use ?. when accessing the getAssets() method. This null-aware operator will prevent your exception.

Example usage: Future<List<Asset>> assets = dbHelper?.getAssets();

Additionally, you can use the await keyword instead of your currently complex Future handling, which will simplify your code.

```<code>Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  List<Asset> assets = await dbHelper?.getAssets();
  return assets;
}
</code>```

And if you think it's necessary you can use a try-catch block to replace your catchError.

```<code>Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  List<Asset> assets;
  try {
    assets = await dbHelper?.getAssets();
  } catch(e) {
    print(e);
  }
  return assets;
}
</code>```

Body:
Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  Future<List<Asset>> assets = dbHelper.getAssets();
  assets.then((value) => handleValue(value)).catchError((error) => handleError(error));
  return assets;
}

"Asset" has 6 strings defined in it. When getAssets is executed with no records added (db table is empty) I get the following error.

"E/flutter (23529): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null."

Can someone elaborate what to write in the functions "handValue" and "HandleError" so I can avoid the exception on first launch of Listview when the DB table has no records.

Expanded(
            child: FutureBuilder<List<Asset>>(
              future: fetchAssetsFromDatabase(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: filterAssets.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: Text(filterAssets[index].name),
                          subtitle: Text(filterAssets[index].url),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => View(
                                  assets: Asset(
                                      id: filterAssets[index].id,
                                      name: filterAssets[index].name,
                                      username: filterAssets[index].username,
                                      password: filterAssets[index].password,
                                      url: filterAssets[index].url,
                                      notes: filterAssets[index].notes,
                                      other: filterAssets[index].other),
                                ),
                              ),
                            );
                          },
                        );
                      });
                } else if (snapshot.hasData == false) {
                  return new Text("No Data found", textAlign: TextAlign.center);
                }
                return new Container(
                  alignment: AlignmentDirectional.center,
                  child: new CircularProgressIndicator(),
                );
              },
            ),
          ),

Body:
Use ?. when accessing the getAssets() method. This null-aware operator will prevent your exception.

Example usage: Future<List<Asset>> assets = dbHelper?.getAssets();

Additionally, you can use the await keyword instead of your currently complex Future handling, which will simplify your code.

Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  List<Asset> assets = await dbHelper?.getAssets();
  return assets;
}

And if you think it's necessary you can use a try-catch block to replace your catchError.

Future<List<Asset>> fetchAssetsFromDatabase() async {
  var dbHelper = DBHelper();
  List<Asset> assets;
  try {
    assets = await dbHelper?.getAssets();
  } catch(e) {
    print(e);
  }
  return assets;
}


问:
aframe register componet add onclick attribute
I want to create dynamic componet using aframe
But I cannot add onclick on my component

this my code

```<code>AFRAME.registerComponent('cylinders', {
init: function(){
let el = this.el;
let sceneEl = document.getElementById('scene1');
let cyl = document.createElement('a-cylinder');
    cyl.setAttribute('position', '0 0 0');
    cyl.setAttribute('rotation', '0 0 0');
    cyl.setAttribute('scale', '0 0 0');
    cyl.setAttribute('radius', 1);
    cyl.setAttribute('height', 0.1);
    cyl.setAttribute('color', '#39BB82');
    cyl.setAttribute('checkpoint', '');
    cyl.setAttribute('class', 'clickable');
    cyl.setAttribute('onclick', 'myFunction()');
    sceneEl.appendChild(cyl);
       }
    }
});
</code>```

my code working fine, but I cannot set onlick. If i write like this bottom I can use onclick.

```<code><a-cylinder
class="clickable"
checkpoint=""
radius="1"
height="0.1"
position="0 0 0"
rotation="0 0 0"
scale="0 0 0"
onclick="myFunction()"
color="#39BB82">
</a-cylinder>
</code>```

答:
Read about a-cursor

//https://aframe.io/docs/1.0.0/guides/building-a-minecraft-demo.html#try-it-out```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<script src="https://unpkg.com/aframe-teleport-controls@0.2.x/dist/aframe-teleport-controls.min.js"></script>
<script src="https://unpkg.com/aframe-controller-cursor-component@0.2.x/dist/aframe-controller-cursor-component.min.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/random-color.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/snap.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/intersection-spawn.js"></script>

<body>
  <a-scene>
    <a-assets>
      <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
      <img id="skyTexture" src="https://cdn.aframe.io/a-painter/images/sky.jpg">
      <a-mixin id="voxel"
         geometry="primitive: box; height: 0.5; width: 0.5; depth: 0.5"
         material="shader: standard"
         random-color
         snap="offset: 0.25 0.25 0.25; snap: 0.5 0.5 0.5"
      ></a-mixin>
    </a-assets>

    <a-cylinder id="ground" src="#groundTexture" radius="30" height="0.1"></a-cylinder>

    <a-sky id="background" src="#skyTexture" theta-length="90" radius="30"></a-sky>

    <!-- Hands. -->
    <a-entity id="teleHand" hand-controls="left" teleport-controls="type: parabolic; collisionEntities: [mixin='voxel'], #ground"></a-entity>
    <a-entity id="blockHand" hand-controls="right" controller-cursor intersection-spawn="event: click; mixin: voxel"></a-entity>

    <!-- Camera. -->
    <a-camera>
      <a-cursor intersection-spawn="event: click; mixin: voxel"></a-cursor>
    </a-camera>
  </a-scene>
</body></code>```

Body:
I want to create dynamic componet using aframe
But I cannot add onclick on my component

this my code

AFRAME.registerComponent('cylinders', {
init: function(){
let el = this.el;
let sceneEl = document.getElementById('scene1');
let cyl = document.createElement('a-cylinder');
    cyl.setAttribute('position', '0 0 0');
    cyl.setAttribute('rotation', '0 0 0');
    cyl.setAttribute('scale', '0 0 0');
    cyl.setAttribute('radius', 1);
    cyl.setAttribute('height', 0.1);
    cyl.setAttribute('color', '#39BB82');
    cyl.setAttribute('checkpoint', '');
    cyl.setAttribute('class', 'clickable');
    cyl.setAttribute('onclick', 'myFunction()');
    sceneEl.appendChild(cyl);
       }
    }
});

my code working fine, but I cannot set onlick. If i write like this bottom I can use onclick.

Body:
Read about a-cursor

//https://aframe.io/docs/1.0.0/guides/building-a-minecraft-demo.html#try-it-out

<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<script src="https://unpkg.com/aframe-teleport-controls@0.2.x/dist/aframe-teleport-controls.min.js"></script>
<script src="https://unpkg.com/aframe-controller-cursor-component@0.2.x/dist/aframe-controller-cursor-component.min.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/random-color.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/snap.js"></script>
<script src="https://rawgit.com/ngokevin/kframe/csstricks/scenes/aincraft/components/intersection-spawn.js"></script>

<body>
  <a-scene>
    <a-assets>
      <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
      <img id="skyTexture" src="https://cdn.aframe.io/a-painter/images/sky.jpg">
      <a-mixin id="voxel"
         geometry="primitive: box; height: 0.5; width: 0.5; depth: 0.5"
         material="shader: standard"
         random-color
         snap="offset: 0.25 0.25 0.25; snap: 0.5 0.5 0.5"
      ></a-mixin>
    </a-assets>

    <a-cylinder id="ground" src="#groundTexture" radius="30" height="0.1"></a-cylinder>

    <a-sky id="background" src="#skyTexture" theta-length="90" radius="30"></a-sky>

    <!-- Hands. -->
    <a-entity id="teleHand" hand-controls="left" teleport-controls="type: parabolic; collisionEntities: [mixin='voxel'], #ground"></a-entity>
    <a-entity id="blockHand" hand-controls="right" controller-cursor intersection-spawn="event: click; mixin: voxel"></a-entity>

    <!-- Camera. -->
    <a-camera>
      <a-cursor intersection-spawn="event: click; mixin: voxel"></a-cursor>
    </a-camera>
  </a-scene>
</body>


问:
Shouldn't this fail without the use of locking? Simple producer consumer
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

```<code>    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}
</code>```

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)

答: Using Queue without locks is not thread safe indeed. But better than using locks you may try ConcurrentQueue. Google for "C# ConcurrentQueue" and you will find quite a lot of examples, e.g. this one compares the use and performance of Queue with a lock and ConcurrentQueue.</p>

Body:
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)


问:
× Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
This is a picture of the errorI think this error is because I'm calling the setState inside the function, but I'm not sure and i don't know how to fix it.

This is one of many tries trying to make a board for a mine sweeper game but I'm having a hard time, I'm getting this error every time i try anything to make the two dimensional array that makes the board into only one array, so I have it divided into cells.

This is the index.js file

```<code>import React, { useState } from "react";
import "./board.css";

function Board(props) {
  const [cells, setCells] = useState([]);

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());

  return (
    <div className="App">
      <h1>Board</h1>
    </div>
  );
}
</code>```

答:
Try useEffect hook to avoid re-renders. I recommend you read the documents in React's website.
The issue is you're changing the state directly in the render method, changing the state will re-render the component and you're changing it over and over again, that's the infinite loop.</p>

```<code>useEffect(() => {

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());
}, []);
</code>```

Body:
This is a picture of the errorI think this error is because I'm calling the setState inside the function, but I'm not sure and i don't know how to fix it.

This is one of many tries trying to make a board for a mine sweeper game but I'm having a hard time, I'm getting this error every time i try anything to make the two dimensional array that makes the board into only one array, so I have it divided into cells.

This is the index.js file

import React, { useState } from "react";
import "./board.css";

function Board(props) {
  const [cells, setCells] = useState([]);

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());

  return (

Board

  );
}

Body:
Try useEffect hook to avoid re-renders. I recommend you read the documents in React's website.
The issue is you're changing the state directly in the render method, changing the state will re-render the component and you're changing it over and over again, that's the infinite loop.

useEffect(() => {

  const createBoard = () => {
    let board = new Array(props.rows);
    for (let i = 0; i < board.length; i++) {
      board[i] = new Array(props.columns);
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        board[i][j] = {
          isMine: false,
          isOpen: false,
          isFlag: false,
          x: i,
          y: j,
        };
      }
    }

    for (let i = 0; i < props.mines; i++) {
      let randomRow = Math.floor(Math.random() * props.rows);
      let randomColumn = Math.floor(Math.random() * props.columns);
      board[randomRow][randomColumn].isMine = true;
    }

    for (let i = 0; i < props.rows; i++) {
      for (let j = 0; j < props.columns; j++) {
        setCells(cells.concat(board[i][j]));
      }
    }

    return board;
  };

  console.table(createBoard());
}, []);


问:
Django - Redirect page slug to detailview - shortening urls
Alright, I have a simple setup with pages which belong to certain categories.

In my urls I have

```<code>path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'),
path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'),
</code>```

So for example;

www.mywebsite.com/activities/cycling/

points to the correct detailview for a page about cycling.

Now I thought It would be nice if we could shorten the url like;

www.mywebsite.com/cycling/

So I wrote the following view;

```<code>def redirect_with_category(request, page_slug):
    '''
    This redirect view points to the canonical url
    '''
    page = get_object_or_404(Page, slug=page_slug)
    return redirect(page, permanent=True)
</code>```

The urls.py are like this;

```<code>path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'),
path('<slug:page_slug>/', views.redirect_with_category, name='page_detail_redirect'),
path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'),
</code>```

And now we get into trouble, even though the redirect works. Django stops trying to solve the category_slug if it can't find a match.

Somehow to get this to work, Django should try to resolve the next path it it does not find a match within category_slug.

Apparently Django throws an error according to the documentation; "or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view"

Is there anyway we can solve this? Can Django be forced to look for the next matching results if it doesn't find a matching slug in the first url?

So I want to redirect;

www.mywebsite.com/cycling/ TO: www.mywebsite.com/activities/cycling/

答:
The reason this happens is because the path('<slug:page_slug>/, …) will never "fire", since each request you make is "captured" by the path('<slug:category_slug>/, …) if you make fully overlapping paths, the last one will never be triggered. In general it is better to make paths that do not overlap at all, since that means that for the overlap, a certain path is not accessible and one might intend to make that accessible.

You thus should do the matching in the PageByCategoryView view, and if that gives a "hit", thus perform the redirect, you can do that for example by overriding the dispatch method (or get if you only wish to redirect GET requests).

```<code>from django.http import Http404
from django.shortcuts import get_object_or_404, redirect

class PageByCategoryView(ListView):

    # …

    def dispatch(self, *args, **kwargs):
        try:
            return super().dispatch(*args, **kwargs)
        except Http404:
            page = get_object_or_404(Page, <b>slug=self.kwargs['category_slug']</b>)
            return redirect(page)</code>```

We thus first aim to handle the request properly by calling the super().dispatch(*args, **kwargs) method. If that returns a 404, we try to find a Page with the slug being equal to the category_slug and redirect to there. If that fails as well, a 404 will be returned.

Body:
Alright, I have a simple setup with pages which belong to certain categories.

In my urls I have

path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'),
path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'),

So for example;

www.mywebsite.com/activities/cycling/

points to the correct detailview for a page about cycling.

Now I thought It would be nice if we could shorten the url like;

www.mywebsite.com/cycling/

So I wrote the following view;

def redirect_with_category(request, page_slug):
    '''
    This redirect view points to the canonical url
    '''
    page = get_object_or_404(Page, slug=page_slug)
    return redirect(page, permanent=True)

The urls.py are like this;

path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'),
path('<slug:page_slug>/', views.redirect_with_category, name='page_detail_redirect'),
path('<slug:category_slug>/<slug:page_slug>/', views.PageDetailView.as_view(), name='page_detail'),

And now we get into trouble, even though the redirect works. Django stops trying to solve the category_slug if it can't find a match.

Somehow to get this to work, Django should try to resolve the next path it it does not find a match within category_slug.

Apparently Django throws an error according to the documentation; "or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view"

Is there anyway we can solve this? Can Django be forced to look for the next matching results if it doesn't find a matching slug in the first url?

So I want to redirect;

www.mywebsite.com/cycling/ TO: www.mywebsite.com/activities/cycling/

Body:
The reason this happens is because the path('<slug:page_slug>/, …) will never "fire", since each request you make is "captured" by the path('<slug:category_slug>/, …) if you make fully overlapping paths, the last one will never be triggered. In general it is better to make paths that do not overlap at all, since that means that for the overlap, a certain path is not accessible and one might intend to make that accessible.

You thus should do the matching in the PageByCategoryView view, and if that gives a "hit", thus perform the redirect, you can do that for example by overriding the dispatch method (or get if you only wish to redirect GET requests).

from django.http import Http404
from django.shortcuts import get_object_or_404, redirect

class PageByCategoryView(ListView):

    # …

    def dispatch(self, *args, **kwargs):
        try:
            return super().dispatch(*args, **kwargs)
        except Http404:
            page = get_object_or_404(Page, slug=self.kwargs['category_slug'])
            return redirect(page)

We thus first aim to handle the request properly by calling the super().dispatch(*args, **kwargs) method. If that returns a 404, we try to find a Page with the slug being equal to the category_slug and redirect to there. If that fails as well, a 404 will be returned.


问:
Get configured "Order Size" of strategy
is it possible to get the configured "Order Size" of a strategy?
If so, how?

I would need it to do some DCA calculations.

Thank you already for your help!

答:
See strategy.position_size

Direction and size of the current market position.

  If the value is > 0, the market position is long.

  If the value is < 0, the market position is short.

  The absolute value is the number of contracts/shares/lots/units in trade (position size).

You can't get the Order size without having a position, but you could do something like this:

```<code>//@version=4
strategy("My Strategy", overlay=true)

var float posSize = na

if bar_index==0
    label.new(bar_index, high, "FirstBar")
    strategy.entry("Dummy entry", strategy.long, when=true)
if bar_index==1
    posSize  := strategy.position_size
    strategy.cancel("Dummy entry", when=true)

plot(posSize)
</code>```

Title: Get configured "Order Size" of strategy

Body:
See strategy.position_size

Direction and size of the current market position.

  If the value is > 0, the market position is long.

  If the value is < 0, the market position is short.

  The absolute value is the number of contracts/shares/lots/units in trade (position size).

You can't get the Order size without having a position, but you could do something like this:

//@version=4
strategy("My Strategy", overlay=true)

var float posSize = na

if bar_index==0
    label.new(bar_index, high, "FirstBar")
    strategy.entry("Dummy entry", strategy.long, when=true)
if bar_index==1
    posSize  := strategy.position_size
    strategy.cancel("Dummy entry", when=true)

plot(posSize)


问:
Compile headers for errors using cmake
Background

I have a number of headers as part of a library (call it A) and are also used externally from other libraries (call it C).

I'd like to compile as part A's compilation to ensure the headers are self-contained. (Currently, this involves compiling C and if there are issues, re-compile A & make a new release).

Question

What's the best way to compile headers and discard the results? I am only interested in their successful compilation.

I am thinking of copy and rename them as cpp files (it's a C++ project) and then create a library out of them to check errors. But is there a simpler solution?

My aim is to the command-line equivalent of

```<code>g++ [compile_flags] -c header.hpp
</code>```

and check for errors but not interested in the produced files.

I'd like something that works with cmake 3.13.5 (or older).

Thanks

答:
Since I ran into the same question recently, let me show the solution I went with:

When you list the header files in your target's sources and only use relative paths below the current path (i.e. no .. in the paths), you can use a function like the following to compile a separate cpp file for each hpp file.

```<code>function(check_headers target)
    # build object library used to "compile" the headers
    add_library(${target}_headers OBJECT)
    target_link_libraries(${target}_headers PRIVATE ${target})
    target_include_directories(${target}_headers PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
    # add a proxy source file for each header in the target source list
    get_target_property(TARGET_SOURCES ${target} SOURCES)
    foreach(TARGET_SOURCE ${TARGET_SOURCES})
        if ("${TARGET_SOURCE}" MATCHES ".*\.hpp$")
            set(HEADER_SOURCEFILE "${CMAKE_CURRENT_BINARY_DIR}/${TARGET_SOURCE}.cpp")
            file(WRITE "${HEADER_SOURCEFILE}" "#include \"${TARGET_SOURCE}\"")
            target_sources(${target}_headers PRIVATE "${HEADER_SOURCEFILE}")
        endif()
    endforeach()
endfunction()
</code>```

It adds an object library that compiles each header file in the given target.

Title: Compile headers for errors using cmake

Body:
Background

I have a number of headers as part of a library (call it A) and are also used externally from other libraries (call it C).

I'd like to compile as part A's compilation to ensure the headers are self-contained. (Currently, this involves compiling C and if there are issues, re-compile A & make a new release).

Question

What's the best way to compile headers and discard the results? I am only interested in their successful compilation.

I am thinking of copy and rename them as cpp files (it's a C++ project) and then create a library out of them to check errors. But is there a simpler solution?

My aim is to the command-line equivalent of

g++ [compile_flags] -c header.hpp

and check for errors but not interested in the produced files.

I'd like something that works with cmake 3.13.5 (or older).

Thanks

Body:
Since I ran into the same question recently, let me show the solution I went with:

When you list the header files in your target's sources and only use relative paths below the current path (i.e. no .. in the paths), you can use a function like the following to compile a separate cpp file for each hpp file.

function(check_headers target)
    # build object library used to "compile" the headers
    add_library(${target}_headers OBJECT)
    target_link_libraries(${target}_headers PRIVATE ${target})
    target_include_directories(${target}_headers PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
    # add a proxy source file for each header in the target source list
    get_target_property(TARGET_SOURCES ${target} SOURCES)
    foreach(TARGET_SOURCE ${TARGET_SOURCES})
        if ("${TARGET_SOURCE}" MATCHES ".*\.hpp$")
            set(HEADER_SOURCEFILE "${CMAKE_CURRENT_BINARY_DIR}/${TARGET_SOURCE}.cpp")
            file(WRITE "${HEADER_SOURCEFILE}" "#include \"${TARGET_SOURCE}\"")
            target_sources(${target}_headers PRIVATE "${HEADER_SOURCEFILE}")
        endif()
    endforeach()
endfunction()

It adds an object library that compiles each header file in the given target.


问:
filtering data in django rest framework with django-filter
i want to select all data with the same item in Product table.

```<code>class ProductViews(viewsets.ModelViewSet):
        permission_classes  =(permissions.IsAuthenticated, permissions.IsAdminUser)
        queryset = Generate.objects.all()
        serializer_class = GenerateSerializer

</code>```

Here is my modelViewSet. Any help ?

答:
I found the solution with django-filter

```<code>class ProductViews(viewsets.ModelViewSet):
        permission_classes  =(permissions.IsAuthenticated, permissions.IsAdminUser)
        queryset = Product.objects.all()
        serializer_class = ProductSerializer
        filter_backends = [DjangoFilterBackend]
        filterset_fields = ['desination']
</code>```

Now you can do : http://localhost.com/api/products/?desination=exemple

Body:
i want to select all data with the same item in Product table.

class ProductViews(viewsets.ModelViewSet):
        permission_classes  =(permissions.IsAuthenticated, permissions.IsAdminUser)
        queryset = Generate.objects.all()
        serializer_class = GenerateSerializer

Here is my modelViewSet. Any help ?

Body:
I found the solution with django-filter

class ProductViews(viewsets.ModelViewSet):
        permission_classes  =(permissions.IsAuthenticated, permissions.IsAdminUser)
        queryset = Product.objects.all()
        serializer_class = ProductSerializer
        filter_backends = [DjangoFilterBackend]
        filterset_fields = ['desination']

Now you can do : http://localhost.com/api/products/?desination=exemple