问:
How to write Inner Query Programatically to fetch latest record based on condition
My use case is to find latest records( by date) based on some filter criteria from a SQL table.I had constructed the SQL query and ran it through the SQL IDE and it is working fine. I am using MS Sql Serve as my database.

But when i am trying to convert this query programatically using Spring-Data JPA/Criteria, i am not getting how to achieve that.

Here is my query to find latest record based on src_cc, src_nbr and isvariableWeight: -

```<code>    SELECT *
    FROM
    dcfin_test Tab1
    INNER JOIN (
        SELECT
            ibd_doc_nbr,
            ibd_doc_line_nbr,
            MAX(create_ts) AS max_Ts
        FROM
            dcfin_test
        WHERE
            src_cc = 'US'
            AND src_nbr = 6938
            AND isvariableWeight = 'Y'
        GROUP BY
            ibd_doc_nbr,
            ibd_doc_line_nbr) Tab2 ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr
    AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr
    AND Tab1.create_ts = Tab2.max_Ts;
</code>```

Here src_cc, src_nbr and isVaribaleWeight will be passed during runtime programatically. Above is shown for example purpose.

Here is my Entity Model looks like (other unwanted column has been removed) :-

```<code>import java.math.BigDecimal;
import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Entity
@Table(name = "dcfin_test")
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeightedAlertEntity {

@Id
@Column(name = "weightedAlertId")
private String weightedAlertId;

@Column(name = "src_cc")
private String sourceCC;

@Column(name = "src_nbr")
private int sourceNbr;

@Column(name = "isVaribaleWeight")
private String isVaribaleWeight;

@Column(name = "ibd_doc_nbr")
private String inboundDocNbr;

@Column(name = "ibd_doc_line_nbr")
private String inboundDocNbrLineNbr;

@Column(name = "item_nbr")
private String itemNbr;

@Column(name = "wac_percent_change")
private BigDecimal percentWacChange;

@Column(name = "waw_percent_change")
private BigDecimal percentWawChange;

@Column(name = "created_by")
private String createdBy;

@Column(name = "create_ts")
private Instant createTs;
</code>```

}

I tried doing it using native Query in spring Data JPA and it looks like as follows :-

```<code>@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data Tab1 "
        + "INNER JOIN ("
        + "SELECT ibd_doc_nbr,ibd_doc_line_nbr,MAX(create_ts) AS max_Ts FROM dcfin_weighted_alert_data"
        + " WHERE src_cc = ?1 AND src_nbr = ?2 AND weight_format_type = ?3 "
        + "GROUP BY ibd_doc_nbr, ibd_doc_line_nbr) Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public List<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType);
</code>```

}

And when i called above method from my service layer as below :-

```<code>List<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
        header.getFacilityCountryCode(),Integer.parseInt(header.getFacilityNum()),
        weightFormatType);
</code>```

Update on my Question :-

I have checked it thoroughly and found out that there was a mistake which leads to invalid column name as i used Tab2.create_ts in place of Tab2.max_Ts. Now i am able to get the results.

I need pagination support too as part of this query i.e. if user enters pageNum = 1 and pagesize = 10, i should be able to return 10 results if records are more.
and when user enters pageNum = 2, pageSize = 10, i should return next 10 records.

Can someone look into it and guide me how to achieve this using Spring Data Jpa / Criteria ?

答:
I have checked it thoroughly and found out that there was a mistake which leads to invalid column name (create_ts) as i used Tab2.create_ts in place of Tab2.max_Ts from inner Query. Now i am able to get the results.

Now when i tried to do pagination using Pageable like below :-

```<code>            Page<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
                header.getFacilityCountryCode(),
                Integer.parseInt(header.getFacilityNum()),
                weightFormatType, PageRequest.of(0, 10));
</code>```

this is my repository class looks like :-

```<code>@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data as Tab1 "
        + "INNER JOIN ("
        + "SELECT Tab3.ibd_doc_nbr,Tab3.ibd_doc_line_nbr,MAX(Tab3.create_ts) AS max_Ts FROM dcfin_weighted_alert_data as Tab3"
        + " WHERE Tab3.src_cc = ?1 AND Tab3.src_nbr = ?2 AND Tab3.weight_format_type = ?3 "
        + "GROUP BY Tab3.ibd_doc_nbr, Tab3.ibd_doc_line_nbr) as Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public Page<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType, Pageable pageable);
</code>```

}

I am getting this error:- The column 'ibd_doc_nbr' was specified multiple times for 'inner_query'.

Same query when i try using SQL IDE, it is working fine. Can someone help me where i am doing wrong.

Body:
My use case is to find latest records( by date) based on some filter criteria from a SQL table.I had constructed the SQL query and ran it through the SQL IDE and it is working fine. I am using MS Sql Serve as my database.

But when i am trying to convert this query programatically using Spring-Data JPA/Criteria, i am not getting how to achieve that.

Here is my query to find latest record based on src_cc, src_nbr and isvariableWeight: -

    SELECT *
    FROM
    dcfin_test Tab1
    INNER JOIN (
        SELECT
            ibd_doc_nbr,
            ibd_doc_line_nbr,
            MAX(create_ts) AS max_Ts
        FROM
            dcfin_test
        WHERE
            src_cc = 'US'
            AND src_nbr = 6938
            AND isvariableWeight = 'Y'
        GROUP BY
            ibd_doc_nbr,
            ibd_doc_line_nbr) Tab2 ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr
    AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr
    AND Tab1.create_ts = Tab2.max_Ts;

Here src_cc, src_nbr and isVaribaleWeight will be passed during runtime programatically. Above is shown for example purpose.

Here is my Entity Model looks like (other unwanted column has been removed) :-

import java.math.BigDecimal;
import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Entity
@Table(name = "dcfin_test")
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeightedAlertEntity {

@Id
@Column(name = "weightedAlertId")
private String weightedAlertId;

@Column(name = "src_cc")
private String sourceCC;

@Column(name = "src_nbr")
private int sourceNbr;

@Column(name = "isVaribaleWeight")
private String isVaribaleWeight;

@Column(name = "ibd_doc_nbr")
private String inboundDocNbr;

@Column(name = "ibd_doc_line_nbr")
private String inboundDocNbrLineNbr;

@Column(name = "item_nbr")
private String itemNbr;

@Column(name = "wac_percent_change")
private BigDecimal percentWacChange;

@Column(name = "waw_percent_change")
private BigDecimal percentWawChange;

@Column(name = "created_by")
private String createdBy;

@Column(name = "create_ts")
private Instant createTs;

}

I tried doing it using native Query in spring Data JPA and it looks like as follows :-

@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data Tab1 "
        + "INNER JOIN ("
        + "SELECT ibd_doc_nbr,ibd_doc_line_nbr,MAX(create_ts) AS max_Ts FROM dcfin_weighted_alert_data"
        + " WHERE src_cc = ?1 AND src_nbr = ?2 AND weight_format_type = ?3 "
        + "GROUP BY ibd_doc_nbr, ibd_doc_line_nbr) Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public List<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType);

}

And when i called above method from my service layer as below :-

List<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
        header.getFacilityCountryCode(),Integer.parseInt(header.getFacilityNum()),
        weightFormatType);

Update on my Question :-

I have checked it thoroughly and found out that there was a mistake which leads to invalid column name as i used Tab2.create_ts in place of Tab2.max_Ts. Now i am able to get the results.

I need pagination support too as part of this query i.e. if user enters pageNum = 1 and pagesize = 10, i should be able to return 10 results if records are more.
and when user enters pageNum = 2, pageSize = 10, i should return next 10 records.

Can someone look into it and guide me how to achieve this using Spring Data Jpa / Criteria ?

Body:
I have checked it thoroughly and found out that there was a mistake which leads to invalid column name (create_ts) as i used Tab2.create_ts in place of Tab2.max_Ts from inner Query. Now i am able to get the results.

Now when i tried to do pagination using Pageable like below :-

            Page<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
                header.getFacilityCountryCode(),
                Integer.parseInt(header.getFacilityNum()),
                weightFormatType, PageRequest.of(0, 10));

this is my repository class looks like :-

@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data as Tab1 "
        + "INNER JOIN ("
        + "SELECT Tab3.ibd_doc_nbr,Tab3.ibd_doc_line_nbr,MAX(Tab3.create_ts) AS max_Ts FROM dcfin_weighted_alert_data as Tab3"
        + " WHERE Tab3.src_cc = ?1 AND Tab3.src_nbr = ?2 AND Tab3.weight_format_type = ?3 "
        + "GROUP BY Tab3.ibd_doc_nbr, Tab3.ibd_doc_line_nbr) as Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public Page<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType, Pageable pageable);

}

I am getting this error:- The column 'ibd_doc_nbr' was specified multiple times for 'inner_query'.

Same query when i try using SQL IDE, it is working fine. Can someone help me where i am doing wrong.


来源: stackexchange

问:
how can I get some last objects from DB without reading all of the objects in Django?
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some last objects without reading all of data. For example something like this to get last 3 object:

last_three_objects = my_model.objects.get_last(count=3)
```

<p>PS: I know that I can get it in this way:</p>

<pre class="lang-py prettyprint-override"><code>last_three_objects = my_model.objects.all()[:3]
</code>```

or:

last_three_objects = my_model.objects.all().order_by('-datetime')[:3]
```

But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

答:
But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

That is incorrect. QuerySets are lazy. That means that the .all() is not evaluated, unless you "consume" it, for example by iterating over it, or by calling len(…) or str(…) on it.

Even if you slice, it will not make a query immediately, you obtain a QuerySet that promises to make a query if you need it. So:

```<code>latest_three_objects = my_model.objects.all()[:3]</code>```

will not even make a query, unless you iterate over it, in which case, it will query with:

```<code>SELECT my_model.*
FROM my_model
<b>LIMIT 3</b></code>```

You can for example inspect the query by writing:

```<code><b>print(</b>my_model.objects.all()[:3]<b>.query)</b></code>```

in the Django shell for example.

This will however not return the latest three elements, it can return any three elements of your model. If you want the elements with the largest primary keys, you can use:

```<code>my_model.objects<b>.order_by('-pk')</b>[:3]</code>```

Furthermore ordering by a primary key is not a good idea, since you have no control how the primary keys are distributed, that is the responsibility of the database. You can better make a field that stores the timestamp:

```<code>class MyModel(models.Model):
    timestamp = models.DateTimeField(<b>auto_now_add=True, db_index=True</b>)</code>```

and then thus retrieve the elements by latest timestamp:

```<code>my_model.objects<b>.order_by('-timestamp')</b>[:3]</code>```

ContentLicense: CC BY-SA 4.0

Body:
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some last objects without reading all of data. For example something like this to get last 3 object:

last_three_objects = my_model.objects.get_last(count=3)

PS: I know that I can get it in this way:

last_three_objects = my_model.objects.all()[:3]

or:

last_three_objects = my_model.objects.all().order_by('-datetime')[:3]

But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

Body:
But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

That is incorrect. QuerySets are lazy. That means that the .all() is not evaluated, unless you "consume" it, for example by iterating over it, or by calling len(…) or str(…) on it.

Even if you slice, it will not make a query immediately, you obtain a QuerySet that promises to make a query if you need it. So:

latest_three_objects = my_model.objects.all()[:3]

will not even make a query, unless you iterate over it, in which case, it will query with:

SELECT my_model.*
FROM my_model
LIMIT 3

You can for example inspect the query by writing:

print(my_model.objects.all()[:3].query)

in the Django shell for example.

This will however not return the latest three elements, it can return any three elements of your model. If you want the elements with the largest primary keys, you can use:

my_model.objects.order_by('-pk')[:3]

Furthermore ordering by a primary key is not a good idea, since you have no control how the primary keys are distributed, that is the responsibility of the database. You can better make a field that stores the timestamp:

class MyModel(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True, db_index=True)

and then thus retrieve the elements by latest timestamp:

my_model.objects.order_by('-timestamp')[:3]


问:
import javax.validation.constraints.NotEmpty; not working
I currently have a java/spring-boot application where I changed the version (in code) from 2.1.4 to 2.3.0 but as a result I've come across the error error: package javax.validation.constraints does not exist when trying to run a clean build - this comes from a import javax.validation.constraints.NotEmpty; line I have in my code - does anyone know how to resolve this issue to the code compiles/builds successfully?

答:
The Validation Starter dependency is no longer included in the web starter dependencies. Therefore you need to add it manually to your gradle file:

```<code>  implementation 'org.springframework.boot:spring-boot-starter-validation'
</code>```

This is mentioned in the release notes:

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3.0-M1-Release-Notes#validation-starter-no-longer-included-in-web-starters

Body:
The Validation Starter dependency is no longer included in the web starter dependencies. Therefore you need to add it manually to your gradle file:

  implementation 'org.springframework.boot:spring-boot-starter-validation'

This is mentioned in the release notes:

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3.0-M1-Release-Notes#validation-starter-no-longer-included-in-web-starters


问:
Building and shifting numpy array
I have such a numpy array:

And I want to shift this array with N so I can get a new array, such that first 4 rows will be the first 4 rows from the beginning array, and the below rows will be the rows from the previous step.

I dont know how to explain it correctly, but look at the example where I shift with 1 (not the whole array, but I would like to do this for the whole array):

And when I shift with 2 (not the whole array, but I would like to do this for the whole array):

And if I shift with 3, I will have 12 zeros in first column, and 3 previous rows ..

And here's the code:

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

def shift_one(arr):
  arrT = arr.transpose()
  arrT_shape = arrT.shape[0]

  col1 = arrT[:, [0]]
  prev1 = numpy.zeros([arrT_shape, 1])
  x1 = numpy.vstack([col1, prev1])

  col2 = arrT[:, [1]]
  prev2 = arrT[:, [0]]
  x2 = numpy.vstack([col2, prev2])

  col3 = arrT[:, [2]]
  prev3 = arrT[:, [1]]
  x3 = numpy.vstack([col3, prev3])

  col4 = arrT[:, [3]]
  prev4 = arrT[:, [2]]
  x4 = numpy.vstack([col4, prev4])

  col5 = arrT[:, [4]]
  prev5 = arrT[:, [3]]
  x5 = numpy.vstack([col5, prev5])

  # ... and so on, until we have index [23] and [22] and x24

  res = numpy.hstack([x1, x2, x3, x4, x5])
  return res

def shift_two(arr):
    arrT = arr.transpose()
    arrT_shape = arrT.shape[0]
    new_size = 2 * arrT_shape

    col1 = arrT[:, [0]]
    prev1 = numpy.zeros([new_size, 1])
    x1 = numpy.vstack([col1, prev1])

    col22 = arrT[:, [1]]
    col21 = arrT[:, [0]]
    prev2 = numpy.zeros([arrT_shape, 1])
    x2 = numpy.vstack([col22, col21, prev2])

    col32 = arrT[:, [2]]
    col31 = arrT[:, [1]]
    col30 = arrT[:, [0]]
    x3 = numpy.vstack([col32, col31, col30])

    col42 = arrT[:, [3]]
    col41 = arrT[:, [2]]
    col40 = arrT[:, [1]]
    x4 = numpy.vstack([col42, col41, col40])

    col52 = arrT[:, [4]]
    col51 = arrT[:, [3]]
    col50 = arrT[:, [2]]
    x5 = numpy.vstack([col52, col51, col50])

    # ... and so on, until we have index [23], [22], [21] and x24

    res = numpy.hstack([x1, x2, x3, x4, x5])
    return res

arr1 = np.array([[0,   2,   0, 324],
        [1, 2, 0,324],
        [2, 2, 0, 324],
        [3, 2, 0, 324],
        [4, 2, 0, 324],
        [5, 2, 0, 324],
        [6, 2, 0, 324],
        [7, 2, 0, 324],
        [8, 2, 0, 324],
        [9, 2, 0, 324],
        [ 10, 2, 0, 324],
        [ 11, 2, 0, 324],
        [ 12, 2, 0, 324],
        [ 13, 2, 0, 324],
        [ 14, 2, 0, 324],
        [ 15, 2, 0, 324],
        [ 16, 2, 0, 324],
        [ 17, 2, 0, 324],
        [ 18, 2, 0, 324],
        [ 19, 2, 0, 324],
        [ 20, 2, 0, 324],
        [ 21, 2, 0, 324],
        [ 22, 2, 0, 324],
        [ 23, 2, 0, 324]])

print(arr1)

print('\n\n')
one = shift_one(arr1)
print(one)

print('\n\n')
two = shift_two(arr1)
print(two)
</code>```

Basically, I have a problem how to write a function, which will shift it with a given N ... I know how to write it step by step as I did, but I have a problem transforming it into something more usable. Thank you.

So again, an example for array with 5 columns (the original array has 24 columns):

答:
Looped

If you want to do this for the general case, you'll can start with a simple loop. If the input array has shape (M, N), the output will be (M * (delay + 1), N).

Stacking is one way to combine arrays. You can minimize the required number of stacks by always doubling the result:

```<code>def stagger(a, delay):
    m = a.shape[0]
    z = 1
    d = delay + 1
    while z < d:
        k = min(d - z, z)    # This will only kick in for the last iteration
        new = np.concatenate([np.zeros((m * k, z)), a[:m * k, :-z]], axis=1)
        a = np.concatenate([a, new], axis=0)
        z *= 2
    return a
</code>```

Vectorized

That being said, there is a fully vectorized way to do this using the monster that is np.lib.stride_tricks.asstrided. Imagine an array that is the first row of your original data padded on the left with delay + 1 zeros:

```<code>>>> d = delay + 1    # delay = 7
>>> row = np.concatenate([np.zeros(d), a[0]])
>>> row
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,
        8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.])
</code>```

You can view this array (without copying the data) as a staggered 2D buffer by adding a fake second dimension whose stride is one element shorter than it ought to be:

```<code>>>> m, n = a.shape
>>> staggered_row = np.lib.stride_tricks.as_strided(row[d:], shape=(d, n), strides=(-row.strides[0], row.strides[0]))
>>> staggered_row
array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.,
        12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.],
       [ 0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.,
        11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
       [ 0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,
        10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.],
       [ 0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,
         9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,
         8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,
         7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,
         6.,  7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16., 17.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,
         5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16.]])
</code>```

Here, the negative stride adds the elements of the zero padding into the array. Keep in mind that this is generally not safe and should be done with extreme care. The output will not be writable by default, because all the rows refer to largely the same memory locations.

Now imagine doing the same thing to your entire array: padding and adding a new dimension that lets you step back into the padding. If you order the dimensions carefully, a reshape of the view will create a new copy that looks exactly how you want in one step. Specifically, starting with shape (M, N), we pad to (D + M, N), create a view that is (D, M, N), and reshape to (D * M, N):

```<code>def staggerx(a, delay):
    d = delay + 1
    m, n = a.shape
    padded = np.concatenate([np.zeros((m, d)), a], axis=1)
    view = np.lib.stride_tricks.as_strided(padded[:, d:], shape=(d, m, n), strides=(-padded.strides[1], padded.strides[0], padded.strides[1]))
    result = view.reshape(-1, n)
    return result
</code>```

A reshape of a crazily strided array will always make a copy because the data is not contiguous by the way.

Title: Building and shifting numpy array

Body:
I have such a numpy array:

And I want to shift this array with N so I can get a new array, such that first 4 rows will be the first 4 rows from the beginning array, and the below rows will be the rows from the previous step.

I dont know how to explain it correctly, but look at the example where I shift with 1 (not the whole array, but I would like to do this for the whole array):

And when I shift with 2 (not the whole array, but I would like to do this for the whole array):

And if I shift with 3, I will have 12 zeros in first column, and 3 previous rows ..

And here's the code:

import numpy as np
import numpy

def shift_one(arr):
  arrT = arr.transpose()
  arrT_shape = arrT.shape[0]

  col1 = arrT[:, [0]]
  prev1 = numpy.zeros([arrT_shape, 1])
  x1 = numpy.vstack([col1, prev1])

  col2 = arrT[:, [1]]
  prev2 = arrT[:, [0]]
  x2 = numpy.vstack([col2, prev2])

  col3 = arrT[:, [2]]
  prev3 = arrT[:, [1]]
  x3 = numpy.vstack([col3, prev3])

  col4 = arrT[:, [3]]
  prev4 = arrT[:, [2]]
  x4 = numpy.vstack([col4, prev4])

  col5 = arrT[:, [4]]
  prev5 = arrT[:, [3]]
  x5 = numpy.vstack([col5, prev5])

  # ... and so on, until we have index [23] and [22] and x24

  res = numpy.hstack([x1, x2, x3, x4, x5])
  return res

def shift_two(arr):
    arrT = arr.transpose()
    arrT_shape = arrT.shape[0]
    new_size = 2 * arrT_shape

    col1 = arrT[:, [0]]
    prev1 = numpy.zeros([new_size, 1])
    x1 = numpy.vstack([col1, prev1])

    col22 = arrT[:, [1]]
    col21 = arrT[:, [0]]
    prev2 = numpy.zeros([arrT_shape, 1])
    x2 = numpy.vstack([col22, col21, prev2])

    col32 = arrT[:, [2]]
    col31 = arrT[:, [1]]
    col30 = arrT[:, [0]]
    x3 = numpy.vstack([col32, col31, col30])

    col42 = arrT[:, [3]]
    col41 = arrT[:, [2]]
    col40 = arrT[:, [1]]
    x4 = numpy.vstack([col42, col41, col40])

    col52 = arrT[:, [4]]
    col51 = arrT[:, [3]]
    col50 = arrT[:, [2]]
    x5 = numpy.vstack([col52, col51, col50])

    # ... and so on, until we have index [23], [22], [21] and x24

    res = numpy.hstack([x1, x2, x3, x4, x5])
    return res

arr1 = np.array([[0,   2,   0, 324],
        [1, 2, 0,324],
        [2, 2, 0, 324],
        [3, 2, 0, 324],
        [4, 2, 0, 324],
        [5, 2, 0, 324],
        [6, 2, 0, 324],
        [7, 2, 0, 324],
        [8, 2, 0, 324],
        [9, 2, 0, 324],
        [ 10, 2, 0, 324],
        [ 11, 2, 0, 324],
        [ 12, 2, 0, 324],
        [ 13, 2, 0, 324],
        [ 14, 2, 0, 324],
        [ 15, 2, 0, 324],
        [ 16, 2, 0, 324],
        [ 17, 2, 0, 324],
        [ 18, 2, 0, 324],
        [ 19, 2, 0, 324],
        [ 20, 2, 0, 324],
        [ 21, 2, 0, 324],
        [ 22, 2, 0, 324],
        [ 23, 2, 0, 324]])

print(arr1)

print('\n\n')
one = shift_one(arr1)
print(one)

print('\n\n')
two = shift_two(arr1)
print(two)

Basically, I have a problem how to write a function, which will shift it with a given N ... I know how to write it step by step as I did, but I have a problem transforming it into something more usable. Thank you.

So again, an example for array with 5 columns (the original array has 24 columns):

Body:
Looped

If you want to do this for the general case, you'll can start with a simple loop. If the input array has shape (M, N), the output will be (M * (delay + 1), N).

Stacking is one way to combine arrays. You can minimize the required number of stacks by always doubling the result:

def stagger(a, delay):
    m = a.shape[0]
    z = 1
    d = delay + 1
    while z < d:
        k = min(d - z, z)    # This will only kick in for the last iteration
        new = np.concatenate([np.zeros((m * k, z)), a[:m * k, :-z]], axis=1)
        a = np.concatenate([a, new], axis=0)
        z *= 2
    return a

Vectorized

That being said, there is a fully vectorized way to do this using the monster that is np.lib.stride_tricks.asstrided. Imagine an array that is the first row of your original data padded on the left with delay + 1 zeros:

>>> d = delay + 1    # delay = 7
>>> row = np.concatenate([np.zeros(d), a[0]])
>>> row
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,
        8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.])

You can view this array (without copying the data) as a staggered 2D buffer by adding a fake second dimension whose stride is one element shorter than it ought to be:

>>> m, n = a.shape
>>> staggered_row = np.lib.stride_tricks.as_strided(row[d:], shape=(d, n), strides=(-row.strides[0], row.strides[0]))
>>> staggered_row
array([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.,
        12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.],
       [ 0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.,
        11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
       [ 0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,
        10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.],
       [ 0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,
         9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,
         8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,  6.,
         7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16., 17., 18.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.,
         6.,  7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16., 17.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,
         5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16.]])

Here, the negative stride adds the elements of the zero padding into the array. Keep in mind that this is generally not safe and should be done with extreme care. The output will not be writable by default, because all the rows refer to largely the same memory locations.

Now imagine doing the same thing to your entire array: padding and adding a new dimension that lets you step back into the padding. If you order the dimensions carefully, a reshape of the view will create a new copy that looks exactly how you want in one step. Specifically, starting with shape (M, N), we pad to (D + M, N), create a view that is (D, M, N), and reshape to (D * M, N):

def staggerx(a, delay):
    d = delay + 1
    m, n = a.shape
    padded = np.concatenate([np.zeros((m, d)), a], axis=1)
    view = np.lib.stride_tricks.as_strided(padded[:, d:], shape=(d, m, n), strides=(-padded.strides[1], padded.strides[0], padded.strides[1]))
    result = view.reshape(-1, n)
    return result

A reshape of a crazily strided array will always make a copy because the data is not contiguous by the way.


问:
Connect to Oracle in remote server with .NET
In Visual Studio 2010 I select Add new connection and then I choose Oracle server. Then I choose Oracle provider for .Net, and this window comes.

I wonder what I should write in the Data Source text field if the Oracle database is at a server with name AZSSRV and IP address 172.117.17.1? Any help will be appreciated.

答:
Your entries from TNSNames.ora should appear here and you would select the one that you need to use.

Since the drop down does not seem to be working, it would indicate that VS2010 cannot find your Oracle home.

An easy solution to this is to create an environmental variable called

TNS_ADMIN

and place the path to the TNSNames.ora file you wish to you
as such

C:\app\MyDir\product\11.2.0\client_1\Network\Admin\

Close VS2010.  Make the environment variable changes, then reopen, the drop down should then show you the available ora connections you may want to use.

(you can look @ this thread for a bit more info: http://forums.oracle.com/forums/thread.jspa?threadID=2213359&tstart=0)

hth

ContentLicense: CC BY-SA 3.0


问:
Twilio : Retrieve a list of Room by UniqueName not working
https://www.twilio.com/docs/video/api/rooms-resource?code-sample=code-retrieve-a-list-of-rooms-by-uniquename&code-language=PHP&code-sdk-version=6.x

Based on the documentation above, I tried listing the detail of the room in twilio using uniqueName. My code looks simply like this

```<code>$twilio = new Client(config('services.twilio.sid'), config('services.twilio.token'));
$rooms = $twilio->video->v1->rooms->read(["uniqueName" => "3302"], 20);
dd($rooms);
</code>```

So, when I try to dd(); the $rooms, it's showing an empty array.

But when I go to my twilio room log, there is a list of the room

Is there something that I am missing? Thanks in advance

答: Nvm, fixed it. I used the wrong twilio key/secret. I have multiple twilio accounts.</p>

Body:
https://www.twilio.com/docs/video/api/rooms-resource?code-sample=code-retrieve-a-list-of-rooms-by-uniquename&code-language=PHP&code-sdk-version=6.x

Based on the documentation above, I tried listing the detail of the room in twilio using uniqueName. My code looks simply like this

$twilio = new Client(config('services.twilio.sid'), config('services.twilio.token'));
$rooms = $twilio->video->v1->rooms->read(["uniqueName" => "3302"], 20);
dd($rooms);

So, when I try to dd(); the $rooms, it's showing an empty array.

But when I go to my twilio room log, there is a list of the room

Is there something that I am missing? Thanks in advance


问:
Discord.js Error [TOKEN_INVALID]: An invalid token was provided
token collect all but can't run bot

Discord.js Version 12

I can't type my real token

```<code>client.login('')
</code>```

[ERROR] - Error [TOKEN_INVALID]: An invalid token was provided.

答: Try generating new token on Discord developer portal and use it instead</p>

Body:
token collect all but can't run bot

Discord.js Version 12

I can't type my real token

client.login('')

[ERROR] - Error [TOKEN_INVALID]: An invalid token was provided.


问:
Flutter app show grey screen in release mode but works fine in debug mode Instance of 'DiagnosticsProperty<void>'
I notice that the app works fine in debug mode but when I try the apk on my phone the app shows a grey screen after the loading screen.
when i used https and i adding all permission.

Httpclient not works in release mode (I/flutter (22182): Another exception was thrown: Instance of 'fr')

but works in debug mode in flutter android

答:
This issue has been existed for a period of time, here is the related issue.

I've come across this issue, but this depends on the code. For me, with CacheNetworkImage issue#404, I passed wrong imageUrl or null, that caused the grey screen. UI was working without grey screen even If I didn't handle properly until upgrading to 1.17.1 (previous flutter 1.12.13+hotfix.8), everything need to be more careful now.


问:
Assigning null/Nullable to DateTime in Ternary Operation
I have a statement like

```<code>DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);
</code>```

which I cannot compile. Reason is : null cannot be assigned to DateTime.

So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

I do not want to use if-statement and I want to do this in one line.

Also, Can I use operator ?? here.

答:
```<code>DateTime? dt = (string1 == string2) ? (DateTime?)null
                                    : DateTime.Parse(txtbox.Text);
</code>```

Body:
I have a statement like

DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);

which I cannot compile. Reason is : null cannot be assigned to DateTime.

So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

I do not want to use if-statement and I want to do this in one line.

Also, Can I use operator ?? here.


问:
Temp directory using tcl/tk
Is there any way to find temp directory using tcl/tk?
Similar to the one in python-->
print tempfile.gettempdir() # prints the current temporary directory</p>

答:
There's no particular function to do that.  You can do:

```<code>set tmpdir {}
set tdlist {}
set dlist [list TMPDIR TEMP TMP]
foreach {d} $dlist {
  if { [info exists ::env($d)] } {
    lappend tdlist $::env($d)
  }
}
# add more locations to this list if needed
lappend tdlist C:/temp c:/tmp /tmp /var/tmp
foreach {d} $tdlist {
  if { [file exists $d] && [file isdirectory $d] } {
    set tmpdir $d
    break
  }
}
</code>```

If you just need a temporary file, there is the file tempfile function that
will return a file handle to be used.

Title: Temp directory using tcl/tk

Body:
There's no particular function to do that.  You can do:

set tmpdir {}
set tdlist {}
set dlist [list TMPDIR TEMP TMP]
foreach {d} $dlist {
  if { [info exists ::env($d)] } {
    lappend tdlist $::env($d)
  }
}
# add more locations to this list if needed
lappend tdlist C:/temp c:/tmp /tmp /var/tmp
foreach {d} $tdlist {
  if { [file exists $d] && [file isdirectory $d] } {
    set tmpdir $d
    break
  }
}

If you just need a temporary file, there is the file tempfile function that
will return a file handle to be used.


问:
Only return the highest value in each group oracle
Given a table:

```<code>NAME        DATE_OCCURRED
a           2020-05-14 23:48.07
a           2020-05-14 23:48.07
a           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.09
</code>```

I would like to return, for each NAME, the time at which the most records exist; and how many records exist at that time:

```<code>NAME       MAXCOUNT_PER_SECOND   DATE_OCCURRED
a          2                     2020-05-14 23:48.07
b          3                     2020-05-14 23:48.08
</code>```

I have found the SQL to group the count by DATE_OCCURRED and NAME:

SELECT COUNT(*) AS COUNT_PER_SECOND, NAME, DATE_OCCURRED FROM TABLE GROUP BY NAME, DATE_OCCURRED ORDER BY NAME ASC, COUNT_PER_SECOND DESC

but I now want to select again, picking just the max for each name. I have tried:

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME FROM (the above query) GROUP BY NAME; and that works to give me the MAXCOUNT_PER_SECOND and the NAME; but as soon as I try and also get which DATE_OCCURRED resulted in that MAXCOUNT_PER_SECOND value, I end up with grouping errors when running the SQL; or I don't get the results I expect.

i.e:

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME; -> Not a GROUP BY expression

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME, DATE_OCCURRED ; -> Runs, but gives me the results for all dates, instead of just the max.

答:
You can use aggreagation and window functions:

```<code>select name, date_occured, no_records
from (
    select
        name,
        date_occured,
        count(*) no_records,
        rank() over(partition by name order by count(*) desc) rn
    from mytable
    group by name, date_occured
) t
where rn = 1
</code>```

The subquery aggreagates by name and date_occured, counts the records per group, and ranks groups of records having the same name by descending count. Then the outer query filters on the top record per name. Since we use rank(), possible top ties will be included in the resultset (if you don't want that, use row_number() instead).

Body:
Given a table:

NAME        DATE_OCCURRED
a           2020-05-14 23:48.07
a           2020-05-14 23:48.07
a           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.08
b           2020-05-14 23:48.09

I would like to return, for each NAME, the time at which the most records exist; and how many records exist at that time:

NAME       MAXCOUNT_PER_SECOND   DATE_OCCURRED
a          2                     2020-05-14 23:48.07
b          3                     2020-05-14 23:48.08

I have found the SQL to group the count by DATE_OCCURRED and NAME:

SELECT COUNT(*) AS COUNT_PER_SECOND, NAME, DATE_OCCURRED FROM TABLE GROUP BY NAME, DATE_OCCURRED ORDER BY NAME ASC, COUNT_PER_SECOND DESC

but I now want to select again, picking just the max for each name. I have tried:

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME FROM (the above query) GROUP BY NAME; and that works to give me the MAXCOUNT_PER_SECOND and the NAME; but as soon as I try and also get which DATE_OCCURRED resulted in that MAXCOUNT_PER_SECOND value, I end up with grouping errors when running the SQL; or I don't get the results I expect.

i.e:

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME; -> Not a GROUP BY expression

SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME, DATE_OCCURRED ; -> Runs, but gives me the results for all dates, instead of just the max.

Body:
You can use aggreagation and window functions:

select name, date_occured, no_records
from (
    select
        name,
        date_occured,
        count(*) no_records,
        rank() over(partition by name order by count(*) desc) rn
    from mytable
    group by name, date_occured
) t
where rn = 1

The subquery aggreagates by name and date_occured, counts the records per group, and ranks groups of records having the same name by descending count. Then the outer query filters on the top record per name. Since we use rank(), possible top ties will be included in the resultset (if you don't want that, use row_number() instead).


问:
Can we push object value into $project using mongodb
```<code>db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
    }
  },
  {
    $lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $project: {
      name: 1,
      status: 1,
      price: 1,
      currency: 1,
      numberOfRecord: {
        $size: "$data"
      }
    }
  },
  {
    $sort: {
      numberOfRecord: 1
    }
  }
])
</code>```

how to push the currency into price object using project please guide thanks a lot, also eager to know what is difference between $addtoSet and $push, what is good option to opt it from project or fix it from $addField

https://mongoplayground.net/p/RiWnnRtksb4

Output should be like this:

```<code>[
  {
    "_id": ObjectId("5ebf891245aa27c290672325"),
    "currency": "USD",
    "name": "Menz",
    "numberOfRecord": 0,
    "price": {
      "numberDecimal": "20",
      "currency": "USD",
    },
    "status": true
  },
  {
    "_id": ObjectId("5c4ee7eea4affa32face874b"),
    "currency": "USD",
    "name": "Dave",
    "numberOfRecord": 2,
    "price": {
      "numberDecimal": "10",
     "currency": "USD"
    },
    "status": true
  }
]
</code>```

答:
You can insert a field into an object with project directly, like this (field price):

```<code>$project: {
      name: 1,
      status: 1,
      price: {
        numberDecimal: "$price.numberDecimal",
        currency: "$currency"
      },
      numberOfRecord: {
        $size: "$data"
      }
    }
</code>```

By doing it with project, there is no need to use $addField.

For the difference between $addToSet and $push, read this great answer.

Body:
db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: [
          ObjectId("5c4ee7eea4affa32face874b"),
          ObjectId("5ebf891245aa27c290672325")
        ]
      }
    }
  },
  {
    $lookup: {
      from: "site",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $project: {
      name: 1,
      status: 1,
      price: 1,
      currency: 1,
      numberOfRecord: {
        $size: "$data"
      }
    }
  },
  {
    $sort: {
      numberOfRecord: 1
    }
  }
])

how to push the currency into price object using project please guide thanks a lot, also eager to know what is difference between $addtoSet and $push, what is good option to opt it from project or fix it from $addField

https://mongoplayground.net/p/RiWnnRtksb4

Output should be like this:

[
  {
    "_id": ObjectId("5ebf891245aa27c290672325"),
    "currency": "USD",
    "name": "Menz",
    "numberOfRecord": 0,
    "price": {
      "numberDecimal": "20",
      "currency": "USD",
    },
    "status": true
  },
  {
    "_id": ObjectId("5c4ee7eea4affa32face874b"),
    "currency": "USD",
    "name": "Dave",
    "numberOfRecord": 2,
    "price": {
      "numberDecimal": "10",
     "currency": "USD"
    },
    "status": true
  }
]

Body:
You can insert a field into an object with project directly, like this (field price):

$project: {
      name: 1,
      status: 1,
      price: {
        numberDecimal: "$price.numberDecimal",
        currency: "$currency"
      },
      numberOfRecord: {
        $size: "$data"
      }
    }

By doing it with project, there is no need to use $addField.

For the difference between $addToSet and $push, read this great answer.


问:
My python IDE can not run my file. How can I fix it?
I am trying to run something on PyCharm but everything I get is this:</p>

```<code>Z:\Python\Python37-32\python.exe: can\'t open file 'C:\Users\zgofer\.PyCharmCE2019.1\config\scratches\exm_fnc_reader.py': [Errno 2] No such file or directory
</code>```

答: Try to run it by rightclicking on the file in the project structure (on the left) and selecting "Run" there. Just clicking the "Run" icon on the top right does not necessarily execute the file that is currently open.</p>

Body:
I am trying to run something on PyCharm but everything I get is this:

Z:\Python\Python37-32\python.exe: can\'t open file 'C:\Users\zgofer\.PyCharmCE2019.1\config\scratches\exm_fnc_reader.py': [Errno 2] No such file or directory


问:
php.ini wont work outside public_html directory
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

```<code><Files php.ini>
  Order allow,deny
  Deny from all
</Files>
</code>```

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions

答:
You can use the PHPRC environment variable...see the documentation:

http://www.php.net/manual/en/configuration.file.php

Body:
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

<Files php.ini>
  Order allow,deny
  Deny from all
</Files>

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions


问:
MYSQL How to make relation with no constrain
Hello i am trying to figure it out this one.

I have 2 Tables

```<code>Sessions
id_session

Session_Requests
id_session
id_request
url
</code>```

How can i make a relation between id_session that when i delete the session
the requests will still remain with that id_session

```<code>EX:
Session id : 0923jguj45g8342

Request
id_session = 0923jguj45g8342
id_request = 1
url = https://example.com
</code>```

When i delete the session with a relation i have a constraint that i cannot delete sessions anymore, or put null instead of session that is not good.

I want to have the relation so when i delete the Requests table will remain untouched.

Is this possible ?

答:
depending on your requirements, consider a "join table" (or "junction table", "reference table"). (aside:Does anyone use other terms for this relationship?)

Remove the "id_session" from the requests table and
include an additional table which should have two references - one points to the Sessions and the other points to the Session_Requests

```<code>T_Join_sessions_requests
  id_session  -- points to the session
  id_request  -- points to the request
</code>```

whenever you insert a new request that is joined to a session you must insert the corresponding join entry.
whenever you remove a session you must also remove the join-table entries for that session, and leave the request table alone

When you first hear of this approach it is counterintuitive, but it's the best way to represent a many-to-many (and none-to-many?) relationships in a relational database. And you will find that actually makes coding to it much easier.

Body:
Hello i am trying to figure it out this one.

I have 2 Tables

Sessions
id_session

Session_Requests
id_session
id_request
url

How can i make a relation between id_session that when i delete the session
the requests will still remain with that id_session

EX:
Session id : 0923jguj45g8342

Request
id_session = 0923jguj45g8342
id_request = 1
url = https://example.com

When i delete the session with a relation i have a constraint that i cannot delete sessions anymore, or put null instead of session that is not good.

I want to have the relation so when i delete the Requests table will remain untouched.

Is this possible ?

Body:
depending on your requirements, consider a "join table" (or "junction table", "reference table"). (aside:Does anyone use other terms for this relationship?)

Remove the "id_session" from the requests table and
include an additional table which should have two references - one points to the Sessions and the other points to the Session_Requests

T_Join_sessions_requests
  id_session  -- points to the session
  id_request  -- points to the request

whenever you insert a new request that is joined to a session you must insert the corresponding join entry.
whenever you remove a session you must also remove the join-table entries for that session, and leave the request table alone

When you first hear of this approach it is counterintuitive, but it's the best way to represent a many-to-many (and none-to-many?) relationships in a relational database. And you will find that actually makes coding to it much easier.


答:
You can just set the object structure while projecting, so in this case there's no need for either $push or $addToSet.

```<code>{
    $project: {
      name: "1",
      status: 1,
      price: {
        currency: "$currency",
        numberDecimal: "$price.numberDecimal"
      },
      currency: 1,
      numberOfRecord: {
        $size: "$data",

      }
    }
  }
</code>```

Now the difference between $push and $addToSet is pretty trivial and derived from the name, $push saves all items while $addToSet will just create a set of them, for example:

input:

```<code>[
    //doc1
    {
        item: 1
    },
    //doc2
    {
        item: 2
    },
    //doc3
    {
        item: 1
    }
]
</code>```

Now this:

```<code>{
    $group: {
        _id: null,
        items: {$push: "$item"}
    }
}
</code>```

Will result in:
{_id: null, items: [1, 2, 1]}

While:

```<code>{
    $group: {
        _id: null,
        items: {$addToSet: "$item"}
    }
}
</code>```

Will result in:
{_id: null, items: [1, 2]}

Title: Can we push object value into $project using mongodb

Body:
You can just set the object structure while projecting, so in this case there's no need for either $push or $addToSet.

{
    $project: {
      name: "1",
      status: 1,
      price: {
        currency: "$currency",
        numberDecimal: "$price.numberDecimal"
      },
      currency: 1,
      numberOfRecord: {
        $size: "$data",

      }
    }
  }

Now the difference between $push and $addToSet is pretty trivial and derived from the name, $push saves all items while $addToSet will just create a set of them, for example:

input:

[
    //doc1
    {
        item: 1
    },
    //doc2
    {
        item: 2
    },
    //doc3
    {
        item: 1
    }
]

Now this:

{
    $group: {
        _id: null,
        items: {$push: "$item"}
    }
}

Will result in:
{_id: null, items: [1, 2, 1]}

While:

{
    $group: {
        _id: null,
        items: {$addToSet: "$item"}
    }
}

Will result in:
{_id: null, items: [1, 2]}


问:
is compare_exchange_weak for std::shared_ptr broken in msvs 2013?
Look at the sample, please

```<code>std::atomic < std::shared_ptr < int > > a;

std::shared_ptr < int > b;
std::shared_ptr < int > c = std::make_shared < int > (10);

while(a.compare_exchange_weak(b, c));

assert(a.load() == c);
assert(a.load().use_count() == 2); // <- assertion is failed.
</code>```

What do you think? Is it compiler error?

Build with msvs 2013 in win32 mode

答:
The question is about C++11 but it worth pointing out that since C++20 the OP code is valid as there is a specialization for std::atomic for both shared_ptr and unique_ptr.

See: std::atomic<std::shared_ptr<T>> at cppreference

Also, the alternative of using std::atomic_compare_exchange was deprecated in C++20.

Body:
Look at the sample, please

std::atomic < std::shared_ptr < int > > a;

std::shared_ptr < int > b;
std::shared_ptr < int > c = std::make_shared < int > (10);

while(a.compare_exchange_weak(b, c));

assert(a.load() == c);
assert(a.load().use_count() == 2); // <- assertion is failed.

What do you think? Is it compiler error?

Build with msvs 2013 in win32 mode


问:
Error of 'self' used before 'self.init' call or assignment to 'self' on init in a different module
I have checked questions sharing the same topic but none address this weird behaviour I am experiencing:

Say I have a simple old school struct:

```<code>struct Person {
   var name: String
   var age: Int
}
</code>```

And I want to overload the init in an extension like this:

```<code>extension Person {
   init(name: String) {
       self.name = name
       self.age = 26
   }
}
</code>```

As you expected, this code would run just fine.

However, If I move the Person struct to a different module (a.k.a different framework) and expose it to my module like this:

```<code>public struct Person {
   public var name: String
   public var age: Int
}
</code>```

If I now overload the init in an extension locally in my module the compiler produces the following errors:

'self' used before 'self.init' call or assignment to 'self'

'self.init' isn't called on all paths before returning from initializer

The only way I found to avoid this problem is calling the original init inside the overloaded one like this:

```<code> extension Person {
    init(name: String) {
       self.init(name: name, age: 24)
    }
 }
</code>```

I personally find this behaviour to be pretty strange.

Am I missing something?

答: Actually this example works for me with only a warning saying Initializer for struct 'Person' must use "self.init(...)" or "self = ..." because it is not in module. As far as I know it was by design that struct initialisers were enforced to be defined within the scope of the struct definition module since Swift 4.2. Check the motivation section in 'https://github.com/apple/swift-evolution/blob/master/proposals/0189-restrict-cross-module-struct-initializers.md'.

Body:
I have checked questions sharing the same topic but none address this weird behaviour I am experiencing:

Say I have a simple old school struct:

struct Person {
   var name: String
   var age: Int
}

And I want to overload the init in an extension like this:

extension Person {
   init(name: String) {
       self.name = name
       self.age = 26
   }
}

As you expected, this code would run just fine.

However, If I move the Person struct to a different module (a.k.a different framework) and expose it to my module like this:

public struct Person {
   public var name: String
   public var age: Int
}

If I now overload the init in an extension locally in my module the compiler produces the following errors:

'self' used before 'self.init' call or assignment to 'self'

'self.init' isn't called on all paths before returning from initializer

The only way I found to avoid this problem is calling the original init inside the overloaded one like this:

 extension Person {
    init(name: String) {
       self.init(name: name, age: 24)
    }
 }

I personally find this behaviour to be pretty strange.

Am I missing something?


问:
Why am I not catching an exception in my async application?
I have been reading around a bit, such as here (Catch an exception thrown by an async void method) and I thought the behaviour of async Task methods was:

that you could try/catch them as normal when using await or Task.Wait e.g. try{ await X();}catch(Exception SqlException e){...}

if you let it 'bubble up' you will instead get AggregateException

But I am finding my application is just terminating without breaking on exceptions at all. My code looks like:

```<code>    internal async Task RunAsync()
    {
        var tasks = monitors.Select((p) => p.Value.MonitorAsync()).ToList();
        await Task.WhenAny(tasks);
        Console.WriteLine("ONE");
    }

    public static async Task Main(string[] args)
    {
        var app = new App();
        try
        {
            await app.RunAsync();
            Console.WriteLine("TWO");
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
    }
</code>```

Setting breakpoints on "ONE" and "TWO" I can see that tasks has at least one Task with status Faulted, and t has status RanToCompletion. So the fault state is lost and no exceptions.

Clearly I'm missing something obvious, what should I be doing differently?

BTW WhenAny is used to detect unusual termination, these tasks should only ever exit due to failure. This is more of a test-bed to understand catching exceptions.

答:
This is because of WhenAny.  Please check the documentation:

The returned task will complete when any of the supplied tasks has
  completed. The returned task will always end in the RanToCompletion
  state with its Result set to the first task to complete. This is true
  even if the first task to complete ended in the Canceled or Faulted
  state.
  (emphasis mine)

This means that WhenAny will not raise an exception if any of the tasks faults.

This is contrary to WhenAll, which will raise an exception if any of the tasks it waits for faults with an unhandled exception.

Body:
I have been reading around a bit, such as here (Catch an exception thrown by an async void method) and I thought the behaviour of async Task methods was:

that you could try/catch them as normal when using await or Task.Wait e.g. try{ await X();}catch(Exception SqlException e){...}

if you let it 'bubble up' you will instead get AggregateException

But I am finding my application is just terminating without breaking on exceptions at all. My code looks like:

    internal async Task RunAsync()
    {
        var tasks = monitors.Select((p) => p.Value.MonitorAsync()).ToList();
        await Task.WhenAny(tasks);
        Console.WriteLine("ONE");
    }

    public static async Task Main(string[] args)
    {
        var app = new App();
        try
        {
            await app.RunAsync();
            Console.WriteLine("TWO");
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
    }

Setting breakpoints on "ONE" and "TWO" I can see that tasks has at least one Task with status Faulted, and t has status RanToCompletion. So the fault state is lost and no exceptions.

Clearly I'm missing something obvious, what should I be doing differently?

BTW WhenAny is used to detect unusual termination, these tasks should only ever exit due to failure. This is more of a test-bed to understand catching exceptions.


问:
How to remove the device's frame on Visual Studio Emulator?
I only need what's relevant for the development and testing. I don't need the huge "emulated" dumb bezel area mostly good for grabbing and relocating the emulator window. Even the real devices start to eliminate those bezels nowadays.

I don't need the directional clues about the device orientation it provides. Just small grabbing handle should be enough on the tool strip or in the main window.

It wastes screen real estate and makes tiling besides other useful windows hard or inefficient (even with my double monitor setup).

How can i hide or remove it?

答:
It no longer works: if I remove the properties (using the small trash button or leaving them empty), the manager will restore them. (My version: Xamarin.Android SDK 10.2.0.100)

But I've found another solution:

Open Android Device Manager from Visual Studio.

While your device is powered off, click the "..." in the top right corner

Select "Show in explorer"

Edit the file "config.ini"

Remove the skin.name and skin.path properties and save file

Start the device!


问:
Prop keeps returning undefined
I'm currently trying to create a table where each row has a checkbox that can be enabled or disabled.
I have created 3 files:

ChangeUserGroup.jsx - This is where the data is read from a json file

UserGroupForm.jsx - Starts the form and passes the this.prop.permissions on to the next file, which contains the table and the checkboxes.

TableShowPermissions.jsx - Contains the table and the problematic function + checkbox

I would like for the data in the ChangeUserGroup.jsx state(called groupDetails.permissions) to control if the checkbox for the given permission is initialized with "defaultChecked". But i am getting the following error:

The files contain the following:

ChangeUserGroup.jsx

```<code>import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

import { Container, Row, Col, Card, CardHeader, CardBody, Table, Button } from 'reactstrap';

import jsonData from '_testdata/userGroups';
import LoadingIcon from '_components/LoadingIcon';
import UserGroupForm from '_components/UserGroupForm';

class ChangeUserGroup extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isLoading: false,
            userGroupId: 0,
            groupDetails: []
        }

    }

    componentDidMount() {
        this.setState({ isLoading: true });

        const { userGroupId } = this.props.match.params

        this.setState({
            userGroupId: userGroupId
        });

        jsonData.userGroups.filter((a) => a.id.toString() === userGroupId).map((b) => this.setState({
            groupDetails: b,
            isLoading: false
        }));
    }

    render() {

        const { groupDetails, isLoading } = this.state;

        if (isLoading) {
            return <LoadingIcon />;
        }

        return (
            <>
                <Helmet>
                    <title>{global.siteName + " - Brugergrupper"}</title>
                </Helmet>

                <main>
                    <section className="section section-shaped section-lg">

                        <Container>
                            <Row className="justify-content-center">
                                <Col lg="12">
                                    <Card className="bg-secondary shadow border-0">
                                        <CardHeader className="bg-white">
                                            <h1 className="text-center">{groupDetails.name}</h1>

                                        </CardHeader>
                                        <CardBody className="px-lg-5 py-lg-5">

                                            <UserGroupForm
                                                id={groupDetails.id}
                                                groupName={groupDetails.name}
                                                position={groupDetails.position}
                                                permissions={groupDetails.permissions} />

                                        </CardBody>

                                    </Card>
                                </Col>
                            </Row>
                        </Container>
                    </section>
                </main>
            </>
        );
    }
}

export { ChangeUserGroup };
</code>```

UserGroupForm.jsx

```<code>import React, { Component } from 'react';

import { Form } from "reactstrap";

import CustomFormInput from '_components/FormStuff/CustomFormInput';
import TableShowPermissions from '_components/UserGroups/TableShowPermissions';

class UserGroupForm extends Component {

    render() {

        const { id, groupName, position, permissions } = this.props;

        return (
            <Form>
                <CustomFormInput pLabel="Gruppe navn" pIcon="fa-user" pType="text" pShowLabel="on" pValue={groupName} />
                <CustomFormInput pLabel="Gruppe position" pIcon="fa-user" pType="text" pShowLabel="on" pValue={position} />
                <hr />
                <TableShowPermissions
                    thePermissions={permissions} />
            </Form>

        );
    }
}

export default UserGroupForm;
</code>```

TableShowPermissions.jsx

```<code>import React, { Component } from 'react';

import jsonData from 'UserPermissions';

import { Table, Button } from "reactstrap";

class TableShowPermissions extends Component {

    constructor(props) {
        super(props);

        this.checkIfPermissionAdded = this.checkIfPermissionAdded.bind(this);
    }

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }

    render() {

        return (

            <Table className="align-items-center table-bordered" responsive>
                <thead className="thead-light">
                    <tr>
                        <th scope="col">Permission navn</th>
                        <th scope="col">Beskrivelse</th>
                        <th scope="col" />
                    </tr>
                </thead>
                <tbody>

                    {jsonData.permissions.map(perm => (
                        <tr key={perm.id}>
                            <th scope="row">
                                {perm.permission}
                            </th>

                            <td>
                                {perm.description}
                            </td>

                            <td className="text-right">
                                <label className="custom-toggle">
                                    <input type="checkbox" defaultChecked={this.checkIfPermissionAdded(perm.permission)} />
                                    <span className="custom-toggle-slider rounded-circle" />
                                </label>
                            </td>
                        </tr>
                    ))}

                </tbody>
            </Table>

        );
    }
}

export default TableShowPermissions;
</code>```

JSON DATA

```<code>{
    "userGroups": [
        {
            "id": 1,
            "name": "Administrator",
            "position": "Admin",
            "permissions": "ADMIN_ROOT|"
        },
        {
            "id": 2,
            "name": "Moderator",
            "position": "Mod",
            "permissions": "ADMIN_SETTINGS_GENERAL|ADMIN_CASES_SEEALL|ADMIN_SETTINGS_CATEGORIES"
        },
        {
            "id": 3,
            "name": "Supporters",
            "position": "Supporter",
            "permissions": "ADMIN_CASES_SEEALL|"
        }
    ]
}
</code>```

Any help would be appreciated! :)

答:
If after a few react renders you do have the value, it most likely means it just isn't there yet in the first renders (this can happen if you are getting the data from a request).

You can either add an if condition to only run the split when thePermissions exist or add a default value to it.

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        if (thePermissions) {
          thePermissions.split('|').map(permC => {
              //console.log(checkPerm + " -- " + permC)
              if (checkPerm === permC) {
                return true;
              }
          });
        }

        return false;
    }
```

<p>or</p>

<pre class="lang-js prettyprint-override"><code>    checkIfPermissionAdded(checkPerm) {
        const { thePermissions = '' } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }
</code>```

It is possible that none is what you desire in your code but it might help you out knowing why it is happening.

Title: Prop keeps returning undefined

Body:
I'm currently trying to create a table where each row has a checkbox that can be enabled or disabled.
I have created 3 files:

ChangeUserGroup.jsx - This is where the data is read from a json file

UserGroupForm.jsx - Starts the form and passes the this.prop.permissions on to the next file, which contains the table and the checkboxes.

TableShowPermissions.jsx - Contains the table and the problematic function + checkbox

I would like for the data in the ChangeUserGroup.jsx state(called groupDetails.permissions) to control if the checkbox for the given permission is initialized with "defaultChecked". But i am getting the following error:

The files contain the following:

ChangeUserGroup.jsx

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

import { Container, Row, Col, Card, CardHeader, CardBody, Table, Button } from 'reactstrap';

import jsonData from '_testdata/userGroups';
import LoadingIcon from '_components/LoadingIcon';
import UserGroupForm from '_components/UserGroupForm';

class ChangeUserGroup extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isLoading: false,
            userGroupId: 0,
            groupDetails: []
        }

    }

    componentDidMount() {
        this.setState({ isLoading: true });

        const { userGroupId } = this.props.match.params

        this.setState({
            userGroupId: userGroupId
        });

        jsonData.userGroups.filter((a) => a.id.toString() === userGroupId).map((b) => this.setState({
            groupDetails: b,
            isLoading: false
        }));
    }

    render() {

        const { groupDetails, isLoading } = this.state;

        if (isLoading) {
            return <LoadingIcon />;
        }

        return (
            <>
                <Helmet>
                    <title>{global.siteName + " - Brugergrupper"}</title>
                </Helmet>

                        <Container>
                            <Row className="justify-content-center">
                                <Col lg="12">
                                    <Card className="bg-secondary shadow border-0">
                                        <CardHeader className="bg-white">

{groupDetails.name}

                                        </CardHeader>
                                        <CardBody className="px-lg-5 py-lg-5">

                                            <UserGroupForm
                                                id={groupDetails.id}
                                                groupName={groupDetails.name}
                                                position={groupDetails.position}
                                                permissions={groupDetails.permissions} />

                                        </CardBody>

                                    </Card>
                                </Col>
                            </Row>
                        </Container>

            </>
        );
    }
}

export { ChangeUserGroup };

UserGroupForm.jsx

import React, { Component } from 'react';

import { Form } from "reactstrap";

import CustomFormInput from '_components/FormStuff/CustomFormInput';
import TableShowPermissions from '_components/UserGroups/TableShowPermissions';

class UserGroupForm extends Component {

    render() {

        const { id, groupName, position, permissions } = this.props;

        return (
            <Form>
                <CustomFormInput pLabel="Gruppe navn" pIcon="fa-user" pType="text" pShowLabel="on" pValue={groupName} />
                <CustomFormInput pLabel="Gruppe position" pIcon="fa-user" pType="text" pShowLabel="on" pValue={position} />

                <TableShowPermissions
                    thePermissions={permissions} />
            </Form>

        );
    }
}

export default UserGroupForm;

TableShowPermissions.jsx

import React, { Component } from 'react';

import jsonData from 'UserPermissions';

import { Table, Button } from "reactstrap";

class TableShowPermissions extends Component {

    constructor(props) {
        super(props);

        this.checkIfPermissionAdded = this.checkIfPermissionAdded.bind(this);
    }

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }

    render() {

        return (

                        Permission navn
                        Beskrivelse

                    {jsonData.permissions.map(perm => (

                                {perm.permission}

                                {perm.description}

                                    <input type="checkbox" defaultChecked={this.checkIfPermissionAdded(perm.permission)} />

                    ))}

        );
    }
}

export default TableShowPermissions;

JSON DATA

{
    "userGroups": [
        {
            "id": 1,
            "name": "Administrator",
            "position": "Admin",
            "permissions": "ADMIN_ROOT|"
        },
        {
            "id": 2,
            "name": "Moderator",
            "position": "Mod",
            "permissions": "ADMIN_SETTINGS_GENERAL|ADMIN_CASES_SEEALL|ADMIN_SETTINGS_CATEGORIES"
        },
        {
            "id": 3,
            "name": "Supporters",
            "position": "Supporter",
            "permissions": "ADMIN_CASES_SEEALL|"
        }
    ]
}

Any help would be appreciated! :)

Body:
If after a few react renders you do have the value, it most likely means it just isn't there yet in the first renders (this can happen if you are getting the data from a request).

You can either add an if condition to only run the split when thePermissions exist or add a default value to it.

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        if (thePermissions) {
          thePermissions.split('|').map(permC => {
              //console.log(checkPerm + " -- " + permC)
              if (checkPerm === permC) {
                return true;
              }
          });
        }

        return false;
    }

or

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions = '' } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }

It is possible that none is what you desire in your code but it might help you out knowing why it is happening.


问:
Send AJAX data to Node.js
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

```<code><script type="text/javascript">
    $(document).ready(function(){
    var selectElement = document.getElementById('selectDetails');
    var selectValue='';
        $.ajax({
                 url: "http://localhost:8070/api/route1",
                 type: 'POST',
                 dataType:'json',

                 success: function(res) {
                     console.log(res);
                     console.log(res.content);
                     $.each(res.content, function(key,value) {
                        console.log(value);
                        selectElement.options[selectElement.options.length] = new Option(value.hostname+":"+value.port);
                    });
                    $("#myButton").click(function(){
                        var selectValue = document.getElementById("selectDetails").value;
                        console.log(selectValue);
                    });
                },
                data: { selectValue: selectValue}
            });
        });
</script>
</code>```

app.js

```<code>router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});
</code>```

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.

答:
In pseudocode, you need to do something like:</p>

```<code>
    $(document).ready(function () {

      $.ajax("http://localhost:5000/config", function (data) {
         // Get initial values
         // Render values to Select options

      })

      $("#myButton").click(function () {
        // get selected value on click
        var selectedValue = 'foo'
        $.ajax({
          url: "http://localhost:5000/setServer",
          type: "POST",
          dataType: "json",
          data: { selectedValue: selectValue },
          success: function (res) {
            // on success, do what you need to do after data to server has been set.

          },
        });
      });
    });

</code>```

Title: Send AJAX data to Node.js

Body:
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

app.js

router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.

Body:
In pseudocode, you need to do something like:

    $(document).ready(function () {

      $.ajax("http://localhost:5000/config", function (data) {
         // Get initial values
         // Render values to Select options

      })

      $("#myButton").click(function () {
        // get selected value on click
        var selectedValue = 'foo'
        $.ajax({
          url: "http://localhost:5000/setServer",
          type: "POST",
          dataType: "json",
          data: { selectedValue: selectValue },
          success: function (res) {
            // on success, do what you need to do after data to server has been set.

          },
        });
      });
    });


问:
Numpy - for each element X in array1 find index of first element greater than X in array2
I have two numpy arrays x and y

```<code>x = numpy.array([1,2,3,4,5])
y = numpy.array([1,3,5,7])

z = func(x,y) # z = [2,2,3,3,4]
</code>```

is there a function func that will return the above. E.g. the index of the first element in y that is greater than 1 (first element in x) is 2 so z[0]=2

Looking for a one liner vectorized way to do this if it exists. Something that is agnostic to the actual comparison function (less than, greater than, leq, geq, etc)

答:
Create array1 with 15 even numbers.

Create array2 with 15 odd numbers.

Exchange array1, array2.

Addition array1, array2 and put the result in array3.

Print all prime number where there are array3.

Apply AND, OR, XOR operations using first element in array1 with first element in array2.

Body:
I have two numpy arrays x and y

x = numpy.array([1,2,3,4,5])
y = numpy.array([1,3,5,7])

z = func(x,y) # z = [2,2,3,3,4]

is there a function func that will return the above. E.g. the index of the first element in y that is greater than 1 (first element in x) is 2 so z[0]=2

Looking for a one liner vectorized way to do this if it exists. Something that is agnostic to the actual comparison function (less than, greater than, leq, geq, etc)


问:
TypeError: 'NoneType' object is not callable CircleCI
I'm trying to make this bit of code in my config.yml file work through CircleCI:

```<code>cd backend
pip install pipenv
pipenv install
</code>```

When uploading to circleci, I get the following for this section, everything else passes:

```<code>Requirement already satisfied: pipenv in /usr/local/lib/python3.7/site-packages (2020.5.28)

Requirement already satisfied: virtualenv in /usr/local/lib/python3.7/site-packages (from pipenv) (20.0.21)

Requirement already satisfied: pip>=18.0 in /usr/local/lib/python3.7/site-packages (from pipenv) (20.1.1)

Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.7/site-packages (from pipenv) (46.4.0)

Requirement already satisfied: virtualenv-clone>=0.2.5 in /usr/local/lib/python3.7/site-packages (from pipenv) (0.5.4)

Requirement already satisfied: certifi in /usr/local/lib/python3.7/site-packages (from pipenv) (2020.4.5.1)

Requirement already satisfied: distlib<1,>=0.3.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (0.3.0)

Requirement already satisfied: importlib-metadata<2,>=0.12; python_version < "3.8" in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.1.3)

Requirement already satisfied: appdirs<2,>=1.4.3 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.4.4)

Requirement already satisfied: filelock<4,>=3.0.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (3.0.12)

Requirement already satisfied: six<2,>=1.9.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.15.0)

Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/site-packages (from importlib-metadata<2,>=0.12; python_version < "3.8"->virtualenv->pipenv) (3.1.0)

Creating a virtualenv for this project…

Pipfile: /home/circleci/cyber-dive/Cyber-Dive-App/backend/Pipfile

Using /usr/local/bin/python3 (3.7.7) to create virtualenv…

created virtual environment CPython3.7.7.final.0-64 in 506ms

    creator CPython3Posix(dest=/home/circleci/cyber-dive/Cyber-Dive-App/backend/.venv, clear=False, global=False)

  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/home/circleci/.local/share/virtualenv/seed-app-data/v1.0.1)

  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Virtualenv location: /home/circleci/cyber-dive/Cyber-Dive-App/backend/.venv

Installing dependencies from Pipfile.lock (9ef944)…

Traceback (most recent call last):

    File "/usr/local/bin/pipenv", line 8, in <module>

    sys.exit(cli())

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 764, in __call__

    return self.main(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 717, in main

    rv = self.invoke(ctx)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 1137, in invoke

    return _process_result(sub_ctx.command.invoke(sub_ctx))

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 956, in invoke

    return ctx.invoke(self.callback, **ctx.params)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke

    return callback(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 64, in new_func

    return ctx.invoke(f, obj, *args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke

    return callback(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 17, in new_func

    return f(get_current_context(), *args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install

    editable_packages=state.installstate.editables,

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1874, in do_install

    keep_outdated=keep_outdated

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init

    pypi_mirror=pypi_mirror,

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 809, in do_install_dependencies

    deps_list = list(lockfile.get_requirements(dev=dev, only=requirements))

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/lockfile.py", line 272, in get_requirements

    yield Requirement.from_pipfile(k, v)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 1183, in from_pipfile

    r = VCSRequirement.from_pipfile(name, pipfile)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 897, in from_pipfile

    return cls(**creation_args)

  File "<attrs generated init 3bab60f45f8eb7fe6e20ab91412def0e78d5dff6>", line 31, in __init__

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 706, in get_link

    extras=self.extras,

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/utils.py", line 100, in build_vcs_link

    return create_link(uri)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/utils.py", line 40, in create_link

    return Link(link)

TypeError: 'NoneType' object is not callable

Exited with code exit status 1

CircleCI received exit code 1
`

When trying to run these tasks locally, here is what I get in my terminal after pipenv install:
ValueError: Path not found or generated: WindowsPath('c:/program files/git/mingw64/bin')
</code>```

I have been googling my brains out with this and I've got nothing. The path it specifies in the ValueError does exist on my computer and I currently have Python 3.8.2. I also have 3.7.7 installed as listed in my programs. Please help because I am stumped.

答:
Ok found the issue, it appears that on 2020-05-28 was released a new version of pipenv that was causing this problem and circle still uses it, pipenv has released a new relase today, June 2nd 2020.6.2 which fixes the problem, I just added

```<code>pip install pipenv==2020.6.2
</code>```

to circle config and builds are working again

EDIT: if you use cache within circleci you must explicitely uninstall the version coming from the circle docker image first or it will still fail

```<code>pip uninstall pipenv -y
</code>```

Body:
I'm trying to make this bit of code in my config.yml file work through CircleCI:

cd backend
pip install pipenv
pipenv install

When uploading to circleci, I get the following for this section, everything else passes:

Requirement already satisfied: pipenv in /usr/local/lib/python3.7/site-packages (2020.5.28)

Requirement already satisfied: virtualenv in /usr/local/lib/python3.7/site-packages (from pipenv) (20.0.21)

Requirement already satisfied: pip>=18.0 in /usr/local/lib/python3.7/site-packages (from pipenv) (20.1.1)

Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.7/site-packages (from pipenv) (46.4.0)

Requirement already satisfied: virtualenv-clone>=0.2.5 in /usr/local/lib/python3.7/site-packages (from pipenv) (0.5.4)

Requirement already satisfied: certifi in /usr/local/lib/python3.7/site-packages (from pipenv) (2020.4.5.1)

Requirement already satisfied: distlib<1,>=0.3.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (0.3.0)

Requirement already satisfied: importlib-metadata<2,>=0.12; python_version < "3.8" in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.1.3)

Requirement already satisfied: appdirs<2,>=1.4.3 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.4.4)

Requirement already satisfied: filelock<4,>=3.0.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (3.0.12)

Requirement already satisfied: six<2,>=1.9.0 in /usr/local/lib/python3.7/site-packages (from virtualenv->pipenv) (1.15.0)

Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/site-packages (from importlib-metadata<2,>=0.12; python_version < "3.8"->virtualenv->pipenv) (3.1.0)

Creating a virtualenv for this project…

Pipfile: /home/circleci/cyber-dive/Cyber-Dive-App/backend/Pipfile

Using /usr/local/bin/python3 (3.7.7) to create virtualenv…

created virtual environment CPython3.7.7.final.0-64 in 506ms

    creator CPython3Posix(dest=/home/circleci/cyber-dive/Cyber-Dive-App/backend/.venv, clear=False, global=False)

  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/home/circleci/.local/share/virtualenv/seed-app-data/v1.0.1)

  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Virtualenv location: /home/circleci/cyber-dive/Cyber-Dive-App/backend/.venv

Installing dependencies from Pipfile.lock (9ef944)…

Traceback (most recent call last):

    File "/usr/local/bin/pipenv", line 8, in <module>

    sys.exit(cli())

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 764, in __call__

    return self.main(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 717, in main

    rv = self.invoke(ctx)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 1137, in invoke

    return _process_result(sub_ctx.command.invoke(sub_ctx))

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 956, in invoke

    return ctx.invoke(self.callback, **ctx.params)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke

    return callback(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 64, in new_func

    return ctx.invoke(f, obj, *args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke

    return callback(*args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 17, in new_func

    return f(get_current_context(), *args, **kwargs)

  File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install

    editable_packages=state.installstate.editables,

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1874, in do_install

    keep_outdated=keep_outdated

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init

    pypi_mirror=pypi_mirror,

  File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 809, in do_install_dependencies

    deps_list = list(lockfile.get_requirements(dev=dev, only=requirements))

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/lockfile.py", line 272, in get_requirements

    yield Requirement.from_pipfile(k, v)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 1183, in from_pipfile

    r = VCSRequirement.from_pipfile(name, pipfile)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 897, in from_pipfile

    return cls(**creation_args)

  File "<attrs generated init 3bab60f45f8eb7fe6e20ab91412def0e78d5dff6>", line 31, in __init__

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 706, in get_link

    extras=self.extras,

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/utils.py", line 100, in build_vcs_link

    return create_link(uri)

  File "/usr/local/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/utils.py", line 40, in create_link

    return Link(link)

TypeError: 'NoneType' object is not callable

Exited with code exit status 1

CircleCI received exit code 1
`

When trying to run these tasks locally, here is what I get in my terminal after pipenv install:
ValueError: Path not found or generated: WindowsPath('c:/program files/git/mingw64/bin')

I have been googling my brains out with this and I've got nothing. The path it specifies in the ValueError does exist on my computer and I currently have Python 3.8.2. I also have 3.7.7 installed as listed in my programs. Please help because I am stumped.

Body:
Ok found the issue, it appears that on 2020-05-28 was released a new version of pipenv that was causing this problem and circle still uses it, pipenv has released a new relase today, June 2nd 2020.6.2 which fixes the problem, I just added

pip install pipenv==2020.6.2

to circle config and builds are working again

EDIT: if you use cache within circleci you must explicitely uninstall the version coming from the circle docker image first or it will still fail

pip uninstall pipenv -y


问:
In jquery fullcalendar, can I add a new event without refreshing the whole month?
I am using jquery fullcalendar and it works great.  My events come in from an ajax call and get returned as json.

I am trying to figure out if there is a way to add events from the client side without refreshing the whole server.

I have the ability to add a new event in my code (which adds it to my database) but the only way i know how to refresh the UI to show this new event is to call refetchevents (but this reloads everything for the month back from the server.

Is there anyway I can stick in additional events all clientside to avoid a full month event refresh ?

I see i can remove events one by one by the removeEvents method (with an id filter) but i don't see the equivalent around adding an event.

Update:

I have a followup question given the answers below which both worked. (didn't make sense to create another question).  I wanted to see the recommended way to "refresh" a single event on the clientside.  I tried to simply call 'renderEvent' with an event with the same Id but that creates a new event on the calendar.

I see there is the: UpdateEvent method which I would assume would be the answer but it seems like this only works if you are inside an eventClick (you can't just create a new event object, set the Id and change a field and call update.

```<code> http://arshaw.com/fullcalendar/docs/event_data/updateEvent/
</code>```

Is there a recommended way of refreshing an event from the client side similar to the "Add Clientside" event logic below?

Right now I am just removing and readding in the event like this:

```<code>       $('#calendar').fullCalendar('removeEvents', data.Event.id);
       $('#calendar').fullCalendar('renderEvent', data.Event, true);
</code>```

答:
Initialize your calendar then add a click event :

```<code>document.addEventListener('DOMContentLoaded', function () {

     var calendarEl = document.getElementById('calendar');

     var calendar = new FullCalendar.Calendar(calendarEl, {/*OPIONS*/});

     calendar.render();

     calendar.on('dateClick', function(info) {

         addNew(info);
     });
});
</code>```

Add the event to the calendar :

```<code>function addNew(info){
     var myEvent = {
         title:"my new event",
         start: info.dateStr,
         end: info.dateStr
     };
     calendar.addEvent(myEvent);
}
</code>```

Body:
I am using jquery fullcalendar and it works great.  My events come in from an ajax call and get returned as json.

I am trying to figure out if there is a way to add events from the client side without refreshing the whole server.

I have the ability to add a new event in my code (which adds it to my database) but the only way i know how to refresh the UI to show this new event is to call refetchevents (but this reloads everything for the month back from the server.

Is there anyway I can stick in additional events all clientside to avoid a full month event refresh ?

I see i can remove events one by one by the removeEvents method (with an id filter) but i don't see the equivalent around adding an event.

Update:

I have a followup question given the answers below which both worked. (didn't make sense to create another question).  I wanted to see the recommended way to "refresh" a single event on the clientside.  I tried to simply call 'renderEvent' with an event with the same Id but that creates a new event on the calendar.

I see there is the: UpdateEvent method which I would assume would be the answer but it seems like this only works if you are inside an eventClick (you can't just create a new event object, set the Id and change a field and call update.

 http://arshaw.com/fullcalendar/docs/event_data/updateEvent/

Is there a recommended way of refreshing an event from the client side similar to the "Add Clientside" event logic below?

Right now I am just removing and readding in the event like this:

       $('#calendar').fullCalendar('removeEvents', data.Event.id);
       $('#calendar').fullCalendar('renderEvent', data.Event, true);

Body:
Initialize your calendar then add a click event :

document.addEventListener('DOMContentLoaded', function () {

     var calendarEl = document.getElementById('calendar');

     var calendar = new FullCalendar.Calendar(calendarEl, {/*OPIONS*/});

     calendar.render();

     calendar.on('dateClick', function(info) {

         addNew(info);
     });
});

Add the event to the calendar :

function addNew(info){
     var myEvent = {
         title:"my new event",
         start: info.dateStr,
         end: info.dateStr
     };
     calendar.addEvent(myEvent);
}


问:
Setting width and height
I'm trying out the example code for Chart.js given in the docs.

Width and height is specified inline on the canvas element at 400px/400px.

But when rendering the chart it's blown up to full page width, and cuts off the far right end.

How/where am I supposed to control the width/height of the chart?

答:
I cannot believe nobody talked about using a relative parent element.

Code:

```<code><div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="chart"></canvas>
</div>
</code>```

Sources: Official documentation

Title: Setting width and height

Body:
I cannot believe nobody talked about using a relative parent element.

Code:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="chart"></canvas>
</div>

Sources: Official documentation