问:
Google Cloud Logging Authentication / permissions
I am using the Golang library cloud.google.com/go/logging and want to send runtime logging.

Already have a GOOGLE_APPLICATION_CREDENTIALS .json file - and am using google storage and firebase - so I know the credentials are working.

With logging, I get an error "Error 403: The caller does not have permission, forbidden"

The account in the application credentials is a service account and I have been looking at the IAM permissions.  There is not an obvious permission for logging (there are other stackdriver permissions, for debug, trace etc but these don't seem to work).

So assuming I am in the right place so far - what permissions does the service account need in order to send logging data to stackdriver logging?

答:
According to the official documentation:

Using Stackdriver Logging library for Go requires the Cloud IAM Logs
  Writer role on Google Cloud. Most Google Cloud environments provide
  this role by default.

1.App Engine grants the Logs Writer role by default.

2.On Google Kubernetes Engine, you must add the logging.write access scope when creating the cluster:

3.When using Compute Engine VM instances, add the cloud-platform access scope to each instance.

4.To use the Stackdriver Logging library for Go outside of Google Cloud, including running the library on your own workstation, on your data center's computers, or on the VM instances of another cloud provider, you must supply your Google Cloud project ID and appropriate service account credentials directly to the Stackdriver Logging library for Go.

You can create and obtain service account credentials manually. When specifying the Role field, use the Logs Writer role. For more information on Cloud Identity and Access Management roles, go to Access control guide.

Setting Up Stackdriver Logging for Go

```<code>gcloud iam service-accounts list
gcloud projects add-iam-policy-binding my-project-123 \
--member serviceAccount:my-sa-123@my-project-123.iam.gserviceaccount.com \
--role roles/logging.logWriter
</code>```

Body:
According to the official documentation:

Using Stackdriver Logging library for Go requires the Cloud IAM Logs
  Writer role on Google Cloud. Most Google Cloud environments provide
  this role by default.

1.App Engine grants the Logs Writer role by default.

2.On Google Kubernetes Engine, you must add the logging.write access scope when creating the cluster:

3.When using Compute Engine VM instances, add the cloud-platform access scope to each instance.

4.To use the Stackdriver Logging library for Go outside of Google Cloud, including running the library on your own workstation, on your data center's computers, or on the VM instances of another cloud provider, you must supply your Google Cloud project ID and appropriate service account credentials directly to the Stackdriver Logging library for Go.

You can create and obtain service account credentials manually. When specifying the Role field, use the Logs Writer role. For more information on Cloud Identity and Access Management roles, go to Access control guide.

Setting Up Stackdriver Logging for Go

gcloud iam service-accounts list
gcloud projects add-iam-policy-binding my-project-123 \
--member serviceAccount:my-sa-123@my-project-123.iam.gserviceaccount.com \
--role roles/logging.logWriter


来源: stackexchange

答:
Just split the values by space:</p>

```<code>(ConvertFrom-Json $JSON).value.results | `
  % { $pair = $_ -split ' '; [PSCustomObject]@{Timestamp=$pair[0]; Value=$pair[1]}} `
  | ConvertTo-Csv -NoTypeInformation
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convert JSON to Csv columns in Powershell

Body:
I would like to convert my JSON into the below CSV output. I'm struggling to parse the "results" data into two columns.

CSV output:

TIMESTAMP, VALUE,
1581292800000, 270,
1581292860000, 347

My JSON output is as follows:

$JSON =
        {
        "value":  [
                      {
                          "fields":  [
                                         "@{label=DateTime; field=eventTimestamp; type=date; aggregation=series}",
                                         "@{label=Count; field=metrics.End User Response Time (ms); type=integer; aggregation=count}"
                                     ],
                          "results":  [
                                          "1581292800000 270",
                                          "1581292860000 347",
                                          "1581292920000 348",
                                          "1581292980000 401",
                                          "1581293040000 435",
                                          "1581293100000 413",
                                          "1581293160000 466",
                                          "1581293220000 445",
                                          "1581293280000 450",
                                          "1581293340000 488",
                                          "1581293400000 470",
                                          "1581293460000 450",
                                          "1581293520000 440",
                                          "1581293580000 435",
                                          "1581293640000 403",
                                          "1581293700000 472",
                                          "1581293760000 392",
                                          "1581293820000 398",
                                          "1581293880000 357",
                                          "1581293940000 356",
                                          "1581294000000 361",
                                          "1581294060000 339",
                                          "1581294120000 373",
                                          "1581294180000 340",
                                          "1581294240000 329",
                                          "1581294300000 327",
                                          "1581294360000 307",
                                          "1581294420000 282",
                                          "1581294480000 315"
                                      ],
                          "moreData":  false,
                          "schema":  "browserrecord"
                      }
                  ],
        "Count":  1
    }

The following code extracts the results, however the TIMESTAMP and VALUE are both in the same column.

$Output1 = ConvertTo-Json $JSON
$Output2 = ConvertFrom-Json $Outage2 | Select -ExpandProperty 'value' |  Select -ExpandProperty 'results'

Any help would be much appreciated.

Cheers!

Body:
Just split the values by space:

(ConvertFrom-Json $JSON).value.results | `
  % { $pair = $_ -split ' '; [PSCustomObject]@{Timestamp=$pair[0]; Value=$pair[1]}} `
  | ConvertTo-Csv -NoTypeInformation


问:
I cannot include config.h in gimp
I am new to gimp programming. I have installed the gimp and using it in Visual Studio 2010. The configuration is ok.

I was trying to compile the code from here:

 http://git.gnome.org/browse/gimp/tree/plug-ins/common/blur.c

The problem is that when including config.h, I am getting this:

fatal error C1189: #error : "config.h must be included prior to stdplugins-intl.h"

where is this config.h file located?

Also, I have problem with this code:

GimpRunMode run_mode; run_mode = param[0].data.d_int32;

it says a value of type gint32 cannot be assigned to an entity of type GimpRunMode.

答:
config.h is generated when you run ./configure in the root of the gimp directory. If you have run configure it should have ended up in the root of the gimp directory.

As to your other problem, try casting the value before assigning it:

```<code>GimpRunMode run_mode;
run_mode = (GimpRunMode)param[0].data.d_int32;
</code>```

ContentLicense: CC BY-SA 3.0

Title: I cannot include config.h in gimp

Body:
config.h is generated when you run ./configure in the root of the gimp directory. If you have run configure it should have ended up in the root of the gimp directory.

As to your other problem, try casting the value before assigning it:

GimpRunMode run_mode;
run_mode = (GimpRunMode)param[0].data.d_int32;


问:
Groovy - WARNING: An illegal reflective access operation has occurred
I am pretty much new to java and groovy. I have installed groovy 3.0 on my windows 10 laptop (64 bit) and when tried to run groovy getting following warning:

```<code>>groovy -v
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/C:/groovy-3.0.0-alpha-1/lib/groovy-3.0.0-alpha-1.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Groovy Version: 3.0.0-alpha-1 JVM: 9.0.1 Vendor: Oracle Corporation OS: Windows 10
</code>```

And the java version is:

```<code>java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
</code>```

Any help to resolve this.

答:
Use the Java 8, however, if the java version must be 9 or >, you need to update the groovy version too.

I was running groovy 2.2.1 and it only works until java version 8

Body:
I am pretty much new to java and groovy. I have installed groovy 3.0 on my windows 10 laptop (64 bit) and when tried to run groovy getting following warning:

>groovy -v
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/C:/groovy-3.0.0-alpha-1/lib/groovy-3.0.0-alpha-1.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Groovy Version: 3.0.0-alpha-1 JVM: 9.0.1 Vendor: Oracle Corporation OS: Windows 10

And the java version is:

java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

Any help to resolve this.


问:
Is it possible to fetch a public spotify playlist without user authorization?
I need to be able to get the tracks in a public spotify playlist without user authorization. I was reading through the official docs and wasn't able to find anything about public playlists. Do you have any idea if it is possible and if yes, how could I achieve this?</p>

答:
I am afraid the answer is no. You need a Client ID and Client Secret.
Please visit https://developer.spotify.com/documentation/general/guides/app-settings/


问:
Find column name based on search criteria
I have the following Excel spreadsheet:

```<code>        A        B         C              D              E          F
1     MFC2      MFC1      QFC      Search Criteria:     CW14
2     CW11                         Column Name:         MFC1
3               CW13
4               CW14
5                        CW17
6                        CW18
7                        CW19
8
9
</code>```

In Cells A1:C8 I have different calender weeks. All of them are unique!

In Cell E2 I want that the column name is displayed based on the value that is put in Cell E1.

In this case the search criteria is CW14 so the result should be column name MFC1.

I tried to modify the formula from this question but could not make it work:

```<code>E1 = INDEX($A$1:$C$1,MATCH(E$1,$A$2:$C$30,0))
</code>```

This formula gives me #NV as result.

What do I need to change to get the desried result?

Body:
I have the following Excel spreadsheet:

        A        B         C              D              E          F
1     MFC2      MFC1      QFC      Search Criteria:     CW14
2     CW11                         Column Name:         MFC1
3               CW13
4               CW14
5                        CW17
6                        CW18
7                        CW19
8
9

In Cells A1:C8 I have different calender weeks. All of them are unique!

In Cell E2 I want that the column name is displayed based on the value that is put in Cell E1.

In this case the search criteria is CW14 so the result should be column name MFC1.

I tried to modify the formula from this question but could not make it work:

E1 = INDEX($A$1:$C$1,MATCH(E$1,$A$2:$C$30,0))

This formula gives me #NV as result.

What do I need to change to get the desried result?

Body: =INDEX($A$1:$C$1,MAX(ISNUMBER(FIND(E1,$A$2:$C$7))*COLUMN($A$2:$C$7)))


问:
Return column name if result is true
I've got an Excel file that I need to manipulate in SQL. I've imported the file but need to show the primary key (MI_KEY) and the column name where the result is true/1.

My table is laid out like the below:

```<code>MI_KEY          TEST_1_FIELD          TEST_2_FIELD          TEST_3_FIELD          TEST_4_FIELD
123bg-fd23           1                     1                     0                     0
2873g-fht5           0                     0                     0                     0
23jdd-sd43           1                     0                     1                     1
23jfk-4kff           0                     1                     1                     1
</code>```

I want to return the MI_KEY and the column name where the result is true, for example;

```<code>  MI_KEY           ISSUE
123bg-fd23      TEST_1_FIELD
123bg-fd23      Test_2_FIELD
23jdd-sd43      TEST_1_FIELD
23jdd-sd43      TEST_3_FIELD
23jdd-sd43      TEST_4_FIELD
23jfk-4kff      TEST_2_FIELD
23jfk-4kff      TEST_3_FIELD
23jfk-4kff      TEST_4_FIELD
</code>```

It's probably important to let you know that this will need to be dynamic as different files could have different header names so I don't want to hard code if it can be helped.

答:
You can unpivot using apply and then filter:

```<code>select t.MI_KEY, v.which
from t cross apply
     (values ('TEST_1_FIELD', TEST_1_FIELD),
             ('TEST_2_FIELD', TEST_2_FIELD),
             ('TEST_3_FIELD', TEST_3_FIELD)
     ) v(which, val)
where val = 1;
</code>```

This assumes that "true" means the value is 1.

To make this dynamic, you will need to generate the list of columns for each table.  That requires dynamic SQL.

If this is the case, I would suggest that you have a problem with your data model.  You could instead be storing the base data as a single table with three columns, instead of tables with a variable number of columns.

Title: Return column name if result is true

Body:
I've got an Excel file that I need to manipulate in SQL. I've imported the file but need to show the primary key (MI_KEY) and the column name where the result is true/1.

My table is laid out like the below:

MI_KEY          TEST_1_FIELD          TEST_2_FIELD          TEST_3_FIELD          TEST_4_FIELD
123bg-fd23           1                     1                     0                     0
2873g-fht5           0                     0                     0                     0
23jdd-sd43           1                     0                     1                     1
23jfk-4kff           0                     1                     1                     1

I want to return the MI_KEY and the column name where the result is true, for example;

  MI_KEY           ISSUE
123bg-fd23      TEST_1_FIELD
123bg-fd23      Test_2_FIELD
23jdd-sd43      TEST_1_FIELD
23jdd-sd43      TEST_3_FIELD
23jdd-sd43      TEST_4_FIELD
23jfk-4kff      TEST_2_FIELD
23jfk-4kff      TEST_3_FIELD
23jfk-4kff      TEST_4_FIELD

It's probably important to let you know that this will need to be dynamic as different files could have different header names so I don't want to hard code if it can be helped.

Body:
You can unpivot using apply and then filter:

select t.MI_KEY, v.which
from t cross apply
     (values ('TEST_1_FIELD', TEST_1_FIELD),
             ('TEST_2_FIELD', TEST_2_FIELD),
             ('TEST_3_FIELD', TEST_3_FIELD)
     ) v(which, val)
where val = 1;

This assumes that "true" means the value is 1.

To make this dynamic, you will need to generate the list of columns for each table.  That requires dynamic SQL.

If this is the case, I would suggest that you have a problem with your data model.  You could instead be storing the base data as a single table with three columns, instead of tables with a variable number of columns.


问:
Communicating between Activities and Fragments when using Navigation Architecture Component
I want to let the host Activity know when something happens in a Fragment. Traditionally, I would have an interface with a callback that the Fragment can call, but now we are ofc using the navigation architecture component.

Is there a way to pass a reference to the host activity down to the fragments or how would I otherwise solve the "Communication between activities and fragments" situation?

Thanks!

答:
You can use the LiveData data holder class for such purposes.

Here is an article explaining both Fragment <--> Fragment communication and Activity <--> Fragment communication.


问:
Slurmdbd and ssl
I am trying to setup slurm with a remote mariadb database for accounting on Azure, using a mariadb database as service.

If ssl is disabled slurmdbd is perfectly working, it is able to contact the database and append new jobs.

If I enable ssl on the database, I got this error:

```<code>slurmdbd: debug2: Attempting to connect to mariadb.database.azure.com:3306
slurmdbd: error: mysql_real_connect failed: 9002 SSL connection is required. Please specify SSL options and retry.
</code>```

I am perfectly able to connect to the database using:

```<code>mysql --host=<host> --port=3306 --user=<user> --password=<password> --ssl --ssl-ca=./BaltimoreCyberTrustRoot.crt.pem
</code>```

I tried to add:

```<code>[client]
ssl_ca = /etc/mysql/ssl/BaltimoreCyberTrustRoot.crt.pem
</code>```

to /etc/my.cnf, in this way I am able to connect (with ssl enabled) using only:

```<code>mysql --host=<host> --port=3306 --user=<user> --password=<password>
</code>```

but slurmdbd gives me the same error.

Basically, I am not able to find the proper location for slurmdbd to read the ssl_ca.

Any ideas?

Thanks

答: i dont believe slurm has the ability to talk to an SSL Encrypted MySQL/MariaDB Server. You would need to set up a local MySQL Proxy which redirects the queries to the SSL connected one.</p>

Title: Slurmdbd and ssl

Body:
I am trying to setup slurm with a remote mariadb database for accounting on Azure, using a mariadb database as service.

If ssl is disabled slurmdbd is perfectly working, it is able to contact the database and append new jobs.

If I enable ssl on the database, I got this error:

slurmdbd: debug2: Attempting to connect to mariadb.database.azure.com:3306
slurmdbd: error: mysql_real_connect failed: 9002 SSL connection is required. Please specify SSL options and retry.

I am perfectly able to connect to the database using:

mysql --host=<host> --port=3306 --user=<user> --password=<password> --ssl --ssl-ca=./BaltimoreCyberTrustRoot.crt.pem

I tried to add:

[client]
ssl_ca = /etc/mysql/ssl/BaltimoreCyberTrustRoot.crt.pem

to /etc/my.cnf, in this way I am able to connect (with ssl enabled) using only:

mysql --host=<host> --port=3306 --user=<user> --password=<password>

but slurmdbd gives me the same error.

Basically, I am not able to find the proper location for slurmdbd to read the ssl_ca.

Any ideas?

Thanks


问:
Count the number of unique values appearing a set number of times in a range
I have a dataset in Excel that is structured as follows:

```<code>A    B            C
ID   Start_date   End_date
1    01/01/2000   05/01/2000
1    06/01/2000   15/05/2000
1    16/05/2000   07/04/2018
2    06/07/2016   09/10/2019
2    10/10/2019   14/12/2019
3    02/08/2000   06/08/2006
3    07/08/2006   15/02/2020
4    05/09/2012   09/11/2017
</code>```

I would like to create a time series of the number of unique values in the above dataset that occur more than 3 times in the 12 months prior to any month in the date range covered by the dataset (in this case 01/01/2000 - 15/02/2020). So, for example, the number of unique values appearing more than three times in the 12 months prior to January 2001 would be 1 (ID = 1).

I've tried this in Excel using the following formula:

```<code>{=SUM(--(FREQUENCY(IF(($B$2:$B$8<=EOMONTH('Time Series'!A2,0))*($C$2:$C$8>=EOMONTH('Time Series'!A2,-12),$A$2:$A$8),$A$2:$A$8)>0))}
</code>```

Where the value in 'Time Series'!A2 is January 2001.

However, this only returns the number of unique values that occur in the 12 months prior to January 2001, not how many unique values occur more than three times in the period.

Any help on this would be greatly appreciated - while I have been doing this in Excel so far, I would be open to performing the calculation in R if that would prove simpler.

Body:
I have a dataset in Excel that is structured as follows:

A    B            C
ID   Start_date   End_date
1    01/01/2000   05/01/2000
1    06/01/2000   15/05/2000
1    16/05/2000   07/04/2018
2    06/07/2016   09/10/2019
2    10/10/2019   14/12/2019
3    02/08/2000   06/08/2006
3    07/08/2006   15/02/2020
4    05/09/2012   09/11/2017

I would like to create a time series of the number of unique values in the above dataset that occur more than 3 times in the 12 months prior to any month in the date range covered by the dataset (in this case 01/01/2000 - 15/02/2020). So, for example, the number of unique values appearing more than three times in the 12 months prior to January 2001 would be 1 (ID = 1).

I've tried this in Excel using the following formula:

{=SUM(--(FREQUENCY(IF(($B$2:$B$8<=EOMONTH('Time Series'!A2,0))*($C$2:$C$8>=EOMONTH('Time Series'!A2,-12),$A$2:$A$8),$A$2:$A$8)>0))}

Where the value in 'Time Series'!A2 is January 2001.

However, this only returns the number of unique values that occur in the 12 months prior to January 2001, not how many unique values occur more than three times in the period.

Any help on this would be greatly appreciated - while I have been doing this in Excel so far, I would be open to performing the calculation in R if that would prove simpler.

Body:
I am not sure if I understood your question correctly:

1.Create minimal reproducible example:

df <-structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 4L),
               Start_date = c("01/01/2000", "06/01/2000", "16/05/2000", "06/07/2016", "10/10/2019", "02/08/2000", "07/08/2006", "05/09/2012"),
               End_date = c("05/01/2000", "15/05/2000","07/04/2018", "09/10/2019", "14/12/2019", "06/08/2006", "15/02/2020", "09/11/2017")),
          class = "data.frame", row.names = c(NA, -8L))

head(df)

Returns:

  ID Start_date   End_date
1  1 01/01/2000 05/01/2000
2  1 06/01/2000 15/05/2000
3  1 16/05/2000 07/04/2018
4  2 06/07/2016 09/10/2019
5  2 10/10/2019 14/12/2019
6  3 02/08/2000 06/08/2006

Suggested solution using dplyr

Format date columns as.Date:

library(dplyr)
df_formated <- df %>%
  mutate(Start_date = as.Date(Start_date, "%d/%m/%Y"),
         End_date = as.Date(End_date, "%d/%m/%Y"))

str(df)

Returns:

'data.frame':   8 obs. of  3 variables:
 $ ID        : int  1 1 1 2 2 3 3 4
 $ Start_date: chr  "01/01/2000" "06/01/2000" "16/05/2000" "06/07/2016" ...
 $ End_date  : chr  "05/01/2000" "15/05/2000" "07/04/2018" "09/10/2019" ...

Filter by cutoff_date and count occurences and filter by min_number_of_occurences:

cutoff_date <- as.Date("01/01/2001", "%d/%m/%Y")
min_number_of_occurences <- 3

df_formated %>%
  filter(Start_date < cutoff_date) %>%
  group_by(ID) %>%
  summarise(N = n()) %>%
  filter(N >= min_number_of_occurences)

Returns:

# A tibble: 1 x 2
     ID     N
  <int> <int>
1     1     3


问:
how can I point two different domains to one directory in apache centos 7
I have Two domains xyz.com and xyz.in. I need to point these two domains one directory. I have two different SSL certificates also. Can I do this ?</p>

答: you will have 2 diffrent certificates in one directory and in your apache configuration, you should add certificate and key file name.</p>


问:
How to display generated trx files in Jenkins WEB GUI?
I have a bunch of test result files (*.trx) after build is complete in directory TestResults.

Is it possible to display those test results in Jenkins? How?
I tried MSTest Jenkins plugin but it allows only one trx file per job :(

*.trx files are generated after each build and named with the date they are created: YYYY_MM_DD.HH_mm_ss.TRX thus names are constantly changing (after each re-build).

Any ideas how to display those test results in Jenkins?

答:
Use the xUnit plugin in conjunction with the MSTest plugin.  Sample usage -

```<code>xunit(
    [MSTest(deleteOutputFiles: true,
            failIfNotNew: true,
            pattern: '*.trx',
            skipNoTestFiles: false,
            stopProcessingIfError: true)
    ])
</code>```

Note, this expects that your trx files are in the root of your workspace.  If they aren't you'll need to copy them into there.

Body:
Use the xUnit plugin in conjunction with the MSTest plugin.  Sample usage -

xunit(
    [MSTest(deleteOutputFiles: true,
            failIfNotNew: true,
            pattern: '*.trx',
            skipNoTestFiles: false,
            stopProcessingIfError: true)
    ])

Note, this expects that your trx files are in the root of your workspace.  If they aren't you'll need to copy them into there.


问:
Reading data in a list from xml in python
```<code>   -<randomints count = 5>
       <ints>-2,-2,-2,-2,-2</ints>
       <ints>-2,-2,-1,-2,-2</ints>
       <ints>-2,-2,-2,-1,-2</ints>
    </randomints>
</code>```

I used xml.etree.ElementTree

```<code>Ints = []
for child in root.findall('randomints'):
    Ints = [l.text for l in child]
</code>```

I am getting output as ['-2,-2,-2,-2,-2','-2,-2,-1,-2,-2','-2,-2,-2,-1,-2']

But I need the output as [[-2,-2,-2,-2,-2],[-2,-2,-1,-2,-2],[-2,-2,-2,-1,-2]]

答:
Try this:

```<code>import xml.etree.ElementTree as ET

root = ET.parse("infile.xml")

for child in root.findall('randomints'):
    ints = [list(map(int, l.text.split(","))) for l in child]

print(ints)
</code>```

Output:

```<code>[[-2, -2, -2, -2, -2], [-2, -2, -1, -2, -2], [-2, -2, -2, -1, -2]]
</code>```

Body:
   -<randomints count = 5>
       <ints>-2,-2,-2,-2,-2</ints>
       <ints>-2,-2,-1,-2,-2</ints>
       <ints>-2,-2,-2,-1,-2</ints>
    </randomints>

I used xml.etree.ElementTree

Ints = []
for child in root.findall('randomints'):
    Ints = [l.text for l in child]

I am getting output as ['-2,-2,-2,-2,-2','-2,-2,-1,-2,-2','-2,-2,-2,-1,-2']

But I need the output as [[-2,-2,-2,-2,-2],[-2,-2,-1,-2,-2],[-2,-2,-2,-1,-2]]

Body:
Try this:

import xml.etree.ElementTree as ET

root = ET.parse("infile.xml")

for child in root.findall('randomints'):
    ints = [list(map(int, l.text.split(","))) for l in child]

print(ints)

Output:

[[-2, -2, -2, -2, -2], [-2, -2, -1, -2, -2], [-2, -2, -2, -1, -2]]


问:
How to count days in which a product's quantity on hand was 0 for a month? in Odoo
How to simply count days in which a product's quantity on hand was 0 for a month.
Any help would be appreciated! Thank you!

/i'm trying query. But it's too complicated ^^/

答:
You will first need to define "the day a product's quantity on hand is 0", becuase the quantity could change a lot during a day due to stock moves. It could be "the qty on hand is 0 in every minute of a day" or "the qty on hand is 0 at 23:59:59 of a day".

I think there are two approaches:

Calculate the qty on hand using stock.move across timeline and see how many 0s. This works well if you want to use computing power to replace disk storage usage and if you want to do the report now using existing data.

Create a new model to store qty on hand from stock.quant at a specific time point of a day. This is easier to code but only works for future reports and does not work well if you need to check multiple time points per day.

For the first approach, you can do SQL to get the quantity on hand at a specific time point calculated from stock.move.

If you don't care the location and just need the quantity on hand grouped by products:

```<code>WITH AGG AS
  (SELECT stock_move.product_id AS "PP",
          ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
   FROM stock_move
   LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
   LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
   LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id
   WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00'
     UNION
    ALL
     SELECT stock_move.product_id AS "PP",
            - ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
     FROM stock_move
     LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
     LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
     LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00' ),
     CALC AS
  (SELECT AGG."PP",
          sum(AGG."Base_Qty_Done") "Base QoH"
   FROM AGG
   GROUP BY AGG."PP")
SELECT product_product.default_code "Reference",
       CALC."Base QoH" "Qty Calculated From Stock Move",
       uom_category.name "Base UoM Of"
FROM CALC
LEFT OUTER JOIN product_product ON product_product.id = CALC."PP"
LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
LEFT OUTER JOIN uom_uom ON product_template.uom_id = uom_uom.id
LEFT OUTER JOIN uom_category ON uom_category.id = uom_uom.category_id
WHERE CALC."Base QoH" = 0
ORDER BY CALC."PP"
</code>```

If you need the quantity on hand per product per location:

```<code>WITH AGG AS
  (SELECT stock_move.product_id AS "PP",
          stock_move.location_dest_id AS "Loc",
          ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
   FROM stock_move
   LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
   LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
   LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id
   WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00'
     UNION
    ALL
     SELECT stock_move.product_id AS "PP",
            stock_move.location_id AS "Loc", - ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
     FROM stock_move
     LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
     LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
     LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00' ),
     CALC AS
  (SELECT AGG."PP",
          AGG."Loc",
          sum(AGG."Base_Qty_Done") "Base QoH"
   FROM AGG
   GROUP BY AGG."PP",
            AGG."Loc")
SELECT product_product.default_code "Reference",
       stock_location.name "Location",
       CALC."Base QoH" "Qty Calculated From Stock Move",
       uom_category.name "Base UoM Of"
FROM CALC
LEFT OUTER JOIN product_product ON product_product.id = CALC."PP"
LEFT OUTER JOIN stock_location ON stock_location.id = CALC."Loc"
LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
LEFT OUTER JOIN uom_uom ON product_template.uom_id = uom_uom.id
LEFT OUTER JOIN uom_category ON uom_category.id = uom_uom.category_id
WHERE CALC."Base QoH" = 0
ORDER BY CALC."PP"
</code>```

Change all '2020-01-01 07:00:00' in the query to your desired time point and repeat for all points on your timeline (if just one time thing, you may hand-craft the report with SQL and Excel, if not, write some code).

For the second approach, the query to get quantity on hand per product per location is easy.

```<code>SELECT stock_quant.product_id "PP ID",
       stock_quant.location_id "Location ID",
       Sum(stock_quant.quantity) "QoH"
FROM   stock_quant
GROUP  BY stock_quant.location_id,
          stock_quant.product_id
</code>```

You will need to write a new model with a schedueld task to store the data at pre-defined interval.

I'd recommend method 1, it's more work but uses less disk space and you can do reports on any time period including the past.

Body:
You will first need to define "the day a product's quantity on hand is 0", becuase the quantity could change a lot during a day due to stock moves. It could be "the qty on hand is 0 in every minute of a day" or "the qty on hand is 0 at 23:59:59 of a day".

I think there are two approaches:

Calculate the qty on hand using stock.move across timeline and see how many 0s. This works well if you want to use computing power to replace disk storage usage and if you want to do the report now using existing data.

Create a new model to store qty on hand from stock.quant at a specific time point of a day. This is easier to code but only works for future reports and does not work well if you need to check multiple time points per day.

For the first approach, you can do SQL to get the quantity on hand at a specific time point calculated from stock.move.

If you don't care the location and just need the quantity on hand grouped by products:

WITH AGG AS
  (SELECT stock_move.product_id AS "PP",
          ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
   FROM stock_move
   LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
   LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
   LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id
   WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00'
     UNION
    ALL
     SELECT stock_move.product_id AS "PP",
            - ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
     FROM stock_move
     LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
     LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
     LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00' ),
     CALC AS
  (SELECT AGG."PP",
          sum(AGG."Base_Qty_Done") "Base QoH"
   FROM AGG
   GROUP BY AGG."PP")
SELECT product_product.default_code "Reference",
       CALC."Base QoH" "Qty Calculated From Stock Move",
       uom_category.name "Base UoM Of"
FROM CALC
LEFT OUTER JOIN product_product ON product_product.id = CALC."PP"
LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
LEFT OUTER JOIN uom_uom ON product_template.uom_id = uom_uom.id
LEFT OUTER JOIN uom_category ON uom_category.id = uom_uom.category_id
WHERE CALC."Base QoH" = 0
ORDER BY CALC."PP"

If you need the quantity on hand per product per location:

WITH AGG AS
  (SELECT stock_move.product_id AS "PP",
          stock_move.location_dest_id AS "Loc",
          ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
   FROM stock_move
   LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
   LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
   LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id
   WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00'
     UNION
    ALL
     SELECT stock_move.product_id AS "PP",
            stock_move.location_id AS "Loc", - ROUND(stock_move.quantity_done / uom_uom.factor, 2) AS "Base_Qty_Done"
     FROM stock_move
     LEFT OUTER JOIN product_product ON product_product.id = stock_move.product_id
     LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
     LEFT OUTER JOIN uom_uom ON stock_move.product_uom = uom_uom.id WHERE product_template.type = 'product'
     AND stock_move.state = 'done'
     AND date <= '2020-01-01 07:00:00' ),
     CALC AS
  (SELECT AGG."PP",
          AGG."Loc",
          sum(AGG."Base_Qty_Done") "Base QoH"
   FROM AGG
   GROUP BY AGG."PP",
            AGG."Loc")
SELECT product_product.default_code "Reference",
       stock_location.name "Location",
       CALC."Base QoH" "Qty Calculated From Stock Move",
       uom_category.name "Base UoM Of"
FROM CALC
LEFT OUTER JOIN product_product ON product_product.id = CALC."PP"
LEFT OUTER JOIN stock_location ON stock_location.id = CALC."Loc"
LEFT OUTER JOIN product_template ON product_template.id = product_product.product_tmpl_id
LEFT OUTER JOIN uom_uom ON product_template.uom_id = uom_uom.id
LEFT OUTER JOIN uom_category ON uom_category.id = uom_uom.category_id
WHERE CALC."Base QoH" = 0
ORDER BY CALC."PP"

Change all '2020-01-01 07:00:00' in the query to your desired time point and repeat for all points on your timeline (if just one time thing, you may hand-craft the report with SQL and Excel, if not, write some code).

For the second approach, the query to get quantity on hand per product per location is easy.

SELECT stock_quant.product_id "PP ID",
       stock_quant.location_id "Location ID",
       Sum(stock_quant.quantity) "QoH"
FROM   stock_quant
GROUP  BY stock_quant.location_id,
          stock_quant.product_id

You will need to write a new model with a schedueld task to store the data at pre-defined interval.

I'd recommend method 1, it's more work but uses less disk space and you can do reports on any time period including the past.


问:
How exactly does Gitlab detect languages in a project?
I have been trying to understand how the languages chart (the one on the main page of a project as a line or in Repository > Charts as a circle) works.

It says "Measured in bytes of code. Excludes generated and vendored code." I played with it and this explanation seems inexact. Generated code is counted (at least in Java with @Generated), invalid JS in a .js file is not, comments and blank lines are, ...

Does anyone know how does it really work, or even better, know where I can find the corresponding code in Gitlab's source code so I can understand it myself ? I've looked but could not find it.

Thanks a lot !

答: Welcome to Stack Overflow. I think they're using GitHub Linguist https://github.com/github/linguist but it's not explicitly mentioned in their doc https://docs.gitlab.com/ee/user/project/repository/#repository-languages</p>


Body:
Split the results.  You can pipe that to export-csv.

'1581292800000 270',
'1581292860000 347',
'1581292920000 348' | foreach {
  $timestamp,$value = -split $_
  [pscustomobject]@{Timestamp = $timestamp
                        Value = $value}
}

Timestamp     Value
---------     -----
1581292800000 270
1581292860000 347
1581292920000 348


问:
What do the result codes in SVN mean?
What do the result codes in SVN mean? I need a quick reference.</p>

答:
You can always get a list by running:</p>

```<code>svn status --help
</code>```

Title: What do the result codes in SVN mean?

LastEditorDisplayName: ChanChan

Body:
You can always get a list by running:

svn status --help


问:
VueJs Watch per key of a model
I have an object (model), as an input field,for a search method, and I want that the watcher to detect changes per key, and not for all.

Right now ,if an input is changed, the watcher is called 10 times  (the number of inputs that I have).

```<code><b-form-input
        v-model="search[field.column]"
        type="search"
        id="filterInput"
        placeholder="search.."
></b-form-input>

watch:{
search: {
    handler(){
        // do somenthing
    },
    deep: true
}
}
</code>```

答:
You can watch a computed value that return the specific field that you want to watch.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    form: {
      name : '',
      lastname: ''
    }
  },
  computed: {
    formName() {
      return this.form.name;
    }
  },
  watch: {
    formName() {
      console.log("Name has changed")
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Name :
  <input v-model="form.name" />
  Lastname :
  <input v-model="form.lastname" />
</div></code>```

Title: VueJs Watch per key of a model

Body:
I have an object (model), as an input field,for a search method, and I want that the watcher to detect changes per key, and not for all.

Right now ,if an input is changed, the watcher is called 10 times  (the number of inputs that I have).

watch:{
search: {
    handler(){
        // do somenthing
    },
    deep: true
}
}

Body:
You can watch a computed value that return the specific field that you want to watch.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    form: {
      name : '',
      lastname: ''
    }
  },
  computed: {
    formName() {
      return this.form.name;
    }
  },
  watch: {
    formName() {
      console.log("Name has changed")
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  Name :
  <input v-model="form.name" />
  Lastname :
  <input v-model="form.lastname" />
</div>


问:
Keras model not training layers, validation accuracy always 0.5
My Keras CNN model (based on an implementation of AlexNet) always has training accuracy close to 0.5 (within +- 0.02) and the validation accuracy is always 0.5 exactly, no matter which epoch. It is a binary classification model where the train/val split is roughly 85/15 and within both those sets the images are split 50/50 for each class.

It doesn't seem to matter which model architecture I use, or whether I initalise with random or ImageNet weights, the validation accuracy is always 0.5. In fact, when I didn't have the images split 50/50 into their binary classifications, the validation accuracy would reflect this (so when I had significantly more images belonging to one class, the validation accuracy would always be 0.85).

Because of this last point, I have a suspicion the problem doesn't lie with the model or weight optimisation, but rather with my instantiation of the ImageDataGenerator class - although this is just an educated hunch at this stage.

I've included my code below, can anyone locate any blindingly obvious errors?

```<code>sz=224 # image width = height = 224
batch_size=64
train_data_dir = r"./crack_dataset/train"
validation_data_dir = r"./crack_dataset/validate"
nb_train_samples = 3416
nb_val_samples = 612

train_datagen = ImageDataGenerator(rescale=1./255)

validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_data_dir,
                                                    target_size = (sz, sz),
                                                    batch_size=batch_size,
                                                    class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
                                                              target_size = (sz, sz),
                                                              batch_size=batch_size,
                                                              class_mode='binary')

# Create Model
model = Sequential()

model.add(Conv2D(filters=96, input_shape=input_shape, kernel_size=(11,11), strides=(4,4), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=256, kernel_size=(11,11), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Flatten())
model.add(Dense(4096, input_shape=(256,), activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer=Adam(0.1), loss='binary_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator,
                    steps_per_epoch = nb_train_samples // batch_size,
                    epochs=30,
                    validation_data=validation_generator,
                    validation_steps=nb_val_samples // batch_size)
</code>```

答:
The problem is the learning rate of the optimizer, the value is way too big.
As suggested in the comment, it should be set to a low value, close to 0.

You can see how the learning rate might influence the classification accuracy in the image below:

Body:
My Keras CNN model (based on an implementation of AlexNet) always has training accuracy close to 0.5 (within +- 0.02) and the validation accuracy is always 0.5 exactly, no matter which epoch. It is a binary classification model where the train/val split is roughly 85/15 and within both those sets the images are split 50/50 for each class.

It doesn't seem to matter which model architecture I use, or whether I initalise with random or ImageNet weights, the validation accuracy is always 0.5. In fact, when I didn't have the images split 50/50 into their binary classifications, the validation accuracy would reflect this (so when I had significantly more images belonging to one class, the validation accuracy would always be 0.85).

Because of this last point, I have a suspicion the problem doesn't lie with the model or weight optimisation, but rather with my instantiation of the ImageDataGenerator class - although this is just an educated hunch at this stage.

I've included my code below, can anyone locate any blindingly obvious errors?

sz=224 # image width = height = 224
batch_size=64
train_data_dir = r"./crack_dataset/train"
validation_data_dir = r"./crack_dataset/validate"
nb_train_samples = 3416
nb_val_samples = 612

train_datagen = ImageDataGenerator(rescale=1./255)

validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_data_dir,
                                                    target_size = (sz, sz),
                                                    batch_size=batch_size,
                                                    class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
                                                              target_size = (sz, sz),
                                                              batch_size=batch_size,
                                                              class_mode='binary')

# Create Model
model = Sequential()

model.add(Conv2D(filters=96, input_shape=input_shape, kernel_size=(11,11), strides=(4,4), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=256, kernel_size=(11,11), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Flatten())
model.add(Dense(4096, input_shape=(256,), activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer=Adam(0.1), loss='binary_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator,
                    steps_per_epoch = nb_train_samples // batch_size,
                    epochs=30,
                    validation_data=validation_generator,
                    validation_steps=nb_val_samples // batch_size)


问:
I can't show data from a local API
I need to convert a PHP project to NodeJS, and I already have the API done without errors. The problem is when I want to fetch that data from the front-end, it returns me nothing than 404 errors. When I copy and paste the code in the browser console it works fine.

Server.js

```<code>const express = require("express");
const app = express();
const { Sequelize } = require('sequelize');
const path = require('path');

app.use(express.json());

// Conexion
const sequelize = new Sequelize('interaccion', 'carlos', 'CARLOSpsp1', {
    host: 'localhost',
    dialect: 'mysql'
});

app.get('/', (req,res) => {
    res.sendFile(path.join(`${__dirname}/client/index.html`));
});

app.get('/ejes', async (req, res) => {
    try {
        await sequelize.authenticate();
        console.log('Conexion exitosa');
        const [result, metadata] = await sequelize.query("SELECT * FROM ejes");
        return res.json(result);
    } catch (error) {
        console.error('Hubo un error: ', error);
    }
});

const puerto = process.env.PORT || 3000;

app.listen(puerto,() => console.log(`Servidor en el puerto: ${puerto}`));
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hola mundo desde index</h1>

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

    </div>

    <script src="main.js"></script>
</body>
</html>
</code>```

main.js

```<code>let container = document.getElementById("id");
let div = document.createElement("div");

const fetchData = async () => {
    try{
        const res = await fetch("http://localhost:3000/ejes");
        const roles = await res.json();
        console.log(roles);
        roles.forEach(rol => {
            console.log(rol);
        });
    }catch(e){
        console.log("Error", e);
    }
}

window.onload = fetchData;
</code>```

Response from the route /ejes

console outputs

答:
It shows a 404 error for main.js.

Your server has:

app.get('/', (req,res) => {

app.get('/ejes', async (req, res) => {

… there's no route for main.js so why do you expect it to provide anything but a 404 Not Found error?

The express documentation explains how to serve static files, or you can use the same pattern as your / route.

Title: I can't show data from a local API

Body:
I need to convert a PHP project to NodeJS, and I already have the API done without errors. The problem is when I want to fetch that data from the front-end, it returns me nothing than 404 errors. When I copy and paste the code in the browser console it works fine.

Server.js

const express = require("express");
const app = express();
const { Sequelize } = require('sequelize');
const path = require('path');

app.use(express.json());

// Conexion
const sequelize = new Sequelize('interaccion', 'carlos', 'CARLOSpsp1', {
    host: 'localhost',
    dialect: 'mysql'
});

app.get('/', (req,res) => {
    res.sendFile(path.join(`${__dirname}/client/index.html`));
});

app.get('/ejes', async (req, res) => {
    try {
        await sequelize.authenticate();
        console.log('Conexion exitosa');
        const [result, metadata] = await sequelize.query("SELECT * FROM ejes");
        return res.json(result);
    } catch (error) {
        console.error('Hubo un error: ', error);
    }
});

const puerto = process.env.PORT || 3000;

app.listen(puerto,() => console.log(`Servidor en el puerto: ${puerto}`));

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Hola mundo desde index

main.js

let container = document.getElementById("id");
let div = document.createElement("div");

const fetchData = async () => {
    try{
        const res = await fetch("http://localhost:3000/ejes");
        const roles = await res.json();
        console.log(roles);
        roles.forEach(rol => {
            console.log(rol);
        });
    }catch(e){
        console.log("Error", e);
    }
}

window.onload = fetchData;

Response from the route /ejes

console outputs


问:
How can overwrite objects that have the same key in updating State with state hooks
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

```<code> const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };
</code>```

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

```<code> const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };
</code>```

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!

答:
```<code>const handleChange = (filter, label, value) => {
    filterValues.map(el => {
      for (let keys in el) {
        if (keys === filter) {
          el[filter] = [label, value];
          setFilterValues([el]);
        } else {
          let newObj = { [filter]: [label, value] };
          let finalArr = [...filterValues, newObj];
          setFilterValues(finalArr);
        }
      }
    });
  };
</code>```

Body:
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

 const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

 const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!


问:
How can i transpose csv data using java spark
I am using java spark and i want to know if there is anyway i can transform the sample data given below

```<code>Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte
</code>```

into something like this.

```<code>Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte
</code>```

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.

答:
Note: This is the RDD way of doing things. It might be easier in Scala and Dataframe.

Use SparkContext to read the file

More specifically you need to use textFile() API which will give you RDD.

Once you have the RDD, you can tokenize each record based on the Comma ( this is done invoking map() API on RDD and passing the map function to it. In your case this function can be implemented as splitting comma delimited string into multiple tokens. You can use Tuple datastructure to emit the output.

You can choose the Tuple1 to Tuple22 based on number of fields you have. Refer here.

Step 3 should again give you back a RDD of Tuples. You run flatMap function on this RDD which will use the first field in the Tuple and concat it to the other required Tuple fields.

Once done, you can again put everything together back by concatenating all tuple fields with comma delimiter. ( This will be another map function)

In the end you call saveAsTextFile() to save the updated data.

Body:
I am using java spark and i want to know if there is anyway i can transform the sample data given below

Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte

into something like this.

Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.


问:
Get the default value of a property given its name
I have a property, (example shown below).

```<code> [DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }
</code>```

The situation I'm using this is to make sure it shows up as bold in the a PropertyGrid if the default value is not set.

I find it incredibly annoying that in my constructor, I have to set the initial value of my property, and hope that they match up.

Is it possible to have my constructor "discover" the default value of a given property, and set it accordingly?  Something like:

```<code>myctor()
{
   myVal = GetDefaultValueProperty<bool>("MyProperty");
}
</code>```

答:
Here's a generic extension method based on Paul Turner's answer. It will work for any member of any class.

```<code>public static bool TryGetDefaultValue<TSource, TResult>(this TSource _, Expression<Func<TSource, TResult>> expression, out TResult result)
{
    if (((MemberExpression)expression.Body).Member.GetCustomAttribute(typeof(DefaultValueAttribute)) is DefaultValueAttribute attribute)
    {
        result = (TResult)attribute.Value;
        return true;
    }

    result = default;
    return false;
}
</code>```

Alternatively, you're OK with the default value being returned if the attribute was not found, use this:

```<code>public static TResult GetDefaultValue<TSource, TResult>(this TSource _, Expression<Func<TSource, TResult>> expression)
{
    if (((MemberExpression)expression.Body).Member.GetCustomAttribute(typeof(DefaultValueAttribute)) is DefaultValueAttribute attribute)
    {
        return (TResult)attribute.Value;
    }

    return default;
}
</code>```

You could also modify it to throw an exception if the attribute wasn't found.

Body:
I have a property, (example shown below).

 [DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }

The situation I'm using this is to make sure it shows up as bold in the a PropertyGrid if the default value is not set.

I find it incredibly annoying that in my constructor, I have to set the initial value of my property, and hope that they match up.

Is it possible to have my constructor "discover" the default value of a given property, and set it accordingly?  Something like:

myctor()
{
   myVal = GetDefaultValueProperty<bool>("MyProperty");
}

Body:
Here's a generic extension method based on Paul Turner's answer. It will work for any member of any class.

public static bool TryGetDefaultValue<TSource, TResult>(this TSource _, Expression<Func<TSource, TResult>> expression, out TResult result)
{
    if (((MemberExpression)expression.Body).Member.GetCustomAttribute(typeof(DefaultValueAttribute)) is DefaultValueAttribute attribute)
    {
        result = (TResult)attribute.Value;
        return true;
    }

    result = default;
    return false;
}

Alternatively, you're OK with the default value being returned if the attribute was not found, use this:

public static TResult GetDefaultValue<TSource, TResult>(this TSource _, Expression<Func<TSource, TResult>> expression)
{
    if (((MemberExpression)expression.Body).Member.GetCustomAttribute(typeof(DefaultValueAttribute)) is DefaultValueAttribute attribute)
    {
        return (TResult)attribute.Value;
    }

    return default;
}

You could also modify it to throw an exception if the attribute wasn't found.


问:
Python Pandas Regex
I have a pandas dataframe like in the example below.
Column 0 has many HTML tags, from which I need to extract all URLs and add them as columns in this DataFrame, while respecting the row order.

In this case, column 2, row 0 would have the: "https://sco...". In reality, this column could have as many as 10 URLs, which should be added to individual columns of the Dataframe.
I've tried using Beautiful Soup, but I couldn't make it work accurately with a Dataframe like this.

I've tried extracting using the Regex below to extract all those URLs, but I couldn't plug it to the Dataframe.

```<code>postsOnlyURL = re.findall('"(http.*?)"',all_text,re.IGNORECASE|re.DOTALL)

                                                    0                                                  1
0   src="https://sco ...                               publicado a 23/10/2019Ident...
1   Ativo</div></div><div class="_7jwu">Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
2   Ativo</div></div><div class="_7jwu">Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
</code>```

Is there a way to make this work?

答:
Here is a potential solution

```import pandas as pd
import re
from bs4 import BeautifulSoup

# Create sample df
a = ["""Ativo

Começou a ser publicado a 23/10/2019

Identificação: 411753089755204

<button aria-pressed="false" data-testid="SUIAbstractMenu/button" type="button" aria-disabled="false" class="_271k _271l _1o4e _271m _1qjd _7tvm _7tv2 _7tv4" style="width: auto; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 12px; font-weight: bold; font-family: Arial, sans-serif; line-height: 26px; text-align: center; background-color: transparent; border-color: transparent; height: 28px; padding-left: 7px; padding-right: 7px; border-radius: 2px;">
Abrir menu pendente
</button>

imaginBank

Patrocinado

Parking, peajes, impuestos, gasolina... Al final termina siendo una pasta. ¿Te has planteado recortar estos gastos? No, no hablamos de abandonar la conducción. Hablamos de enchufarnos al futuro. Conoce todos los beneficios de tener un coche un eléctrico y lo fácil que es conseguirlo con un Préstamo Auto de imaginBank. #Enchúfate

 *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank

Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Ver Det""",
    """Ativo

Começou a ser publicado a 23/10/2019

Identificação: 712910935875237

<button aria-pressed="false" data-testid="SUIAbstractMenu/button" type="button" aria-disabled="false" class="_271k _271l _1o4e _271m _1qjd _7tvm _7tv2 _7tv4" style="width: auto; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 12px; font-weight: bold; font-family: Arial, sans-serif; line-height: 26px; text-align: center; background-color: transparent; border-color: transparent; height: 28px; padding-left: 7px; padding-right: 7px; border-radius: 2px;">
Abrir menu pendente
</button>

imaginBank

Patrocinado

Ya reciclas, vas con tu botella de agua para rellenar y has dejado de usar bolsas de plástico para hacer la compra. ¿Qué sigue? Un coche eléctrico. Entérate por qué molan tanto y #Enchúfate con un Préstamo Auto de imaginBank para hacerte con tu coche eléctrico o híbrido.

 *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank

Préstamo desde 3.000€ hasta 30.000€ ¡Solicítalo desde la app!

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app

<button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;">

Use App

</button>

Ver Det"""
    ]

b = [
    """AtivoComeçou a ser publicado a 23/10/2019Identificação: 411753089755204Abrir menu pendenteimaginBankPatrocinadoParking, peajes, impuestos, gasolina... Al final termina siendo una pasta. ¿Te has planteado recortar estos gastos? No, no hablamos de abandonar la conducción. Hablamos de enchufarnos al futuro. Conoce todos los beneficios de tener un coche un eléctrico y lo fácil que es conseguirlo con un Préstamo Auto de imaginBank. #Enchúfate *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse AppVer Det""",
    """AtivoComeçou a ser publicado a 23/10/2019Identificação: 712910935875237Abrir menu pendenteimaginBankPatrocinadoYa reciclas, vas con tu botella de agua para rellenar y has dejado de usar bolsas de plástico para hacer la compra. ¿Qué sigue? Un coche eléctrico. Entérate por qué molan tanto y #Enchúfate con un Préstamo Auto de imaginBank para hacerte con tu coche eléctrico o híbrido. *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank Préstamo desde 3.000€ hasta 30.000€ ¡Solicítalo desde la app!Use App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse AppVer Det"""
]

df = pd.DataFrame({0: a, 1: b})

def get_links(x):
    soup = BeautifulSoup(x, parser='html.parser')
    links = [i.get('href') for i in soup.findAll('a', attrs={'href': re.compile("^http")})]
    return links

df[0].apply(get_links)

```

<p><code>df[0].apply(get_links)</code> returns</p>

```0    [https://www.facebook.com/imaginBank/, http://...
1    [https://www.facebook.com/imaginBank/, http://...
Name: 0, dtype: object

```

<p><code>df[1].apply(get_links)</code> returns</p>

```0    []
1    []
Name: 1, dtype: object

```

Title: Python Pandas Regex

Body:
I have a pandas dataframe like in the example below.
Column 0 has many HTML tags, from which I need to extract all URLs and add them as columns in this DataFrame, while respecting the row order.

In this case, column 2, row 0 would have the: "https://sco...". In reality, this column could have as many as 10 URLs, which should be added to individual columns of the Dataframe.
I've tried using Beautiful Soup, but I couldn't make it work accurately with a Dataframe like this.

I've tried extracting using the Regex below to extract all those URLs, but I couldn't plug it to the Dataframe.

postsOnlyURL = re.findall('"(http.*?)"',all_text,re.IGNORECASE|re.DOTALL)

                                                    0                                                  1
0   src="https://sco ...                               publicado a 23/10/2019Ident...
1   Ativo

Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...
2   Ativo

Começou a ...  AtivoComeçou a ser publicado a 23/10/2019Ident...

Is there a way to make this work?

Body:
Here is a potential solution

import pandas as pd
import re
from bs4 import BeautifulSoup

# Create sample df
a = ["""Ativo</div></div><div class="_7jwu">Começou a ser publicado a <span>23/10/2019</span></div><div class="_8jox"><div aria-describedby="js_m" aria-haspopup="true" class="_4rhp" role="tooltip" tabindex="0">Identificação: 411753089755204</div></div></div><div class="_8k-_"><div class="_3qn7 _61-0 _2fyi _3qng" style="max-width: 120px;"><span data-hover="tooltip"><i class="_3-8_ img sp_-Fn2d835eMD sx_39e484" alt=""></i></span><span data-hover="tooltip"><i class="_3-8_ img sp_-Fn2d835eMD sx_f3b669" alt=""></i></span><span data-hover="tooltip"><i class="img sp_-Fn2d835eMD sx_e31062" alt=""></i></span></div></div></div><div class="_7jwv"><div style="display: inline-block; width: auto;"><button aria-pressed="false" data-testid="SUIAbstractMenu/button" type="button" aria-disabled="false" class="_271k _271l _1o4e _271m _1qjd _7tvm _7tv2 _7tv4" style="width: auto; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 12px; font-weight: bold; font-family: Arial, sans-serif; line-height: 26px; text-align: center; background-color: transparent; border-color: transparent; height: 28px; padding-left: 7px; padding-right: 7px; border-radius: 2px;"><div class="_43rl"><i aria-hidden="true" class="_271o img sp_6UxJZoFesmZ sx_e4448e" alt=""></i><span class="accessible_elem">Abrir menu pendente</span></div></button></div></div></div><div class="_7jwy"><div class="_7jyg _7jyh"><div class="_7k71"><div class="_8nsi _8nqp"><div class="_3qn7 _61-0 _2fyi _3qng" style="width: 100%;"><img alt="imaginBank" class="_8nqq img" src="https://scontent.flis8-1.fna.fbcdn.net/v/t1.6435-9/56757490_843111089374606_3751796641934344192_n.png?_nc_cat=105&amp;_nc_oc=AQn_sfVuUVpGuXh9Xew56gOSFzdktA5s1xfEWBMkYzLNQ6m8zdOZve6xFIzu7IOEJL0&amp;_nc_ht=scontent.flis8-1.fna&amp;oh=ce8b3a3feea1162bc0874c260ab2b308&amp;oe=5EC4B78C"><div class="_3qn7 _61-0 _2fyh _3qnf" style="width: 100%;"><div class="_8nqr _3qn7 _61-3 _2fyi _3qng"><span style="font-family: Arial, sans-serif; font-size: 12px; line-height: 16px; letter-spacing: normal; font-weight: bold; overflow-wrap: normal; text-align: left; color: rgb(28, 30, 33);"><a data-hovercard="/ajax/hovercard/hovercard.php?id=197438223941899" target="_blank" href="https://www.facebook.com/imaginBank/">imaginBank</a></span></div><div class="_8nrv"><div class="_4ik4 _4ik5" style="-webkit-line-clamp: 2;"><div><span class="_8jos">Patrocinado</span></div></div></div></div></div></div></div><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"><div>Parking, peajes, impuestos, gasolina... Al final termina siendo una pasta. ¿Te has planteado recortar estos gastos? No, no hablamos de abandonar la conducción. Hablamos de enchufarnos al futuro. Conoce todos los beneficios de tener un coche un eléctrico y lo fácil que es conseguirlo con un Préstamo Auto de imaginBank. #Enchúfate<br> <br> *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank</div></div></div></div><div maxchangeamount="1" currentselectedindex="0" class="_23n-"><div class="_4u-c"><div index="0" class="_a28"><div class="_a2e"><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-2.fna.fbcdn.net/v/t39.16868-6/s600x600/68872437_623249314832062_3424786237267902464_n.jpg?_nc_cat=107&amp;_nc_oc=AQnCOg6lOVmyYNmKW9TeJMIQqFnp__ENhA6b0IF9n6OOvKhuFdfBFFn5A-i6mv9Qs9A&amp;_nc_ht=scontent.flis8-2.fna&amp;_nc_tp=7&amp;oh=4c316693ef6d41f08a19c047bbef6ff5&amp;oe=5EC0B4DA" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-1.fna.fbcdn.net/v/t39.16868-6/s600x600/69107399_623249321498728_5143385648069083136_n.jpg?_nc_cat=110&amp;_nc_oc=AQlHwBVTCf9XcxXVP4VH0YnbwivUgg1PXA8uYOxShCkbr9woauh1CiNiQTJbguBYmbc&amp;_nc_ht=scontent.flis8-1.fna&amp;_nc_tp=7&amp;oh=e52db30189225e3525fbef0cec013c31&amp;oe=5EFC734A" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-1.fna.fbcdn.net/v/t39.16868-6/s600x600/68744822_623249324832061_2903488387056926720_n.jpg?_nc_cat=109&amp;_nc_oc=AQkQBwWIk_gZ3WxbsRYe6kyjcJk0HU4XjUHDUQEP1diakZkjkk5Ng8U38gF9L3ZWaTI&amp;_nc_ht=scontent.flis8-1.fna&amp;_nc_tp=7&amp;oh=ef1d597a68349654821b7f2a7c730287&amp;oe=5EF8CBA5" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div></div></div></div><a class="_32rk _32rh _1cy6" href="#"><div direction="forward" class="_10sf _5x5_"><div class="_5x6d"><div class="_3bwv _3bww"><div class="_3bwy"><div class="_3bwx"><i class="_3-8w img sp_JmF3rXGjoQG sx_77d801" alt=""></i></div></div></div></div></div></a></div></div></div><div class="_7kfi"><div class="_7kd5"></div><a class="_7kfh" data-testid="snapshot_footer_link" href="#"><span style="font-family: Arial, sans-serif; font-size: 13px; line-height: 17px; letter-spacing: normal; overflow-wrap: normal; text-align: left; color: rgb(24, 119, 242);">Ver Det""",
    """Ativo</div></div><div class="_7jwu">Começou a ser publicado a <span>23/10/2019</span></div><div class="_8jox"><div aria-describedby="js_p" aria-haspopup="true" class="_4rhp" role="tooltip" tabindex="0">Identificação: 712910935875237</div></div></div><div class="_8k-_"><div class="_3qn7 _61-0 _2fyi _3qng" style="max-width: 120px;"><span data-hover="tooltip"><i class="_3-8_ img sp_-Fn2d835eMD sx_39e484" alt=""></i></span><span data-hover="tooltip"><i class="_3-8_ img sp_-Fn2d835eMD sx_f3b669" alt=""></i></span><span data-hover="tooltip"><i class="img sp_-Fn2d835eMD sx_e31062" alt=""></i></span></div></div></div><div class="_7jwv"><div style="display: inline-block; width: auto;"><button aria-pressed="false" data-testid="SUIAbstractMenu/button" type="button" aria-disabled="false" class="_271k _271l _1o4e _271m _1qjd _7tvm _7tv2 _7tv4" style="width: auto; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 12px; font-weight: bold; font-family: Arial, sans-serif; line-height: 26px; text-align: center; background-color: transparent; border-color: transparent; height: 28px; padding-left: 7px; padding-right: 7px; border-radius: 2px;"><div class="_43rl"><i aria-hidden="true" class="_271o img sp_6UxJZoFesmZ sx_e4448e" alt=""></i><span class="accessible_elem">Abrir menu pendente</span></div></button></div></div></div><div class="_7jwy"><div class="_7jyg _7jyh"><div class="_7k71"><div class="_8nsi _8nqp"><div class="_3qn7 _61-0 _2fyi _3qng" style="width: 100%;"><img alt="imaginBank" class="_8nqq img" src="https://scontent.flis8-1.fna.fbcdn.net/v/t1.6435-9/56757490_843111089374606_3751796641934344192_n.png?_nc_cat=105&amp;_nc_oc=AQn_sfVuUVpGuXh9Xew56gOSFzdktA5s1xfEWBMkYzLNQ6m8zdOZve6xFIzu7IOEJL0&amp;_nc_ht=scontent.flis8-1.fna&amp;oh=ce8b3a3feea1162bc0874c260ab2b308&amp;oe=5EC4B78C"><div class="_3qn7 _61-0 _2fyh _3qnf" style="width: 100%;"><div class="_8nqr _3qn7 _61-3 _2fyi _3qng"><span style="font-family: Arial, sans-serif; font-size: 12px; line-height: 16px; letter-spacing: normal; font-weight: bold; overflow-wrap: normal; text-align: left; color: rgb(28, 30, 33);"><a data-hovercard="/ajax/hovercard/hovercard.php?id=197438223941899" target="_blank" href="https://www.facebook.com/imaginBank/">imaginBank</a></span></div><div class="_8nrv"><div class="_4ik4 _4ik5" style="-webkit-line-clamp: 2;"><div><span class="_8jos">Patrocinado</span></div></div></div></div></div></div></div><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"><div>Ya reciclas, vas con tu botella de agua para rellenar y has dejado de usar bolsas de plástico para hacer la compra. ¿Qué sigue? Un coche eléctrico. Entérate por qué molan tanto y #Enchúfate con un Préstamo Auto de imaginBank para hacerte con tu coche eléctrico o híbrido.<br> <br> *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank</div></div></div></div><div maxchangeamount="1" currentselectedindex="0" class="_23n-"><div class="_4u-c"><div index="0" class="_a28"><div class="_a2e"><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-1.fna.fbcdn.net/v/t39.16868-6/s600x600/69012922_678822735864357_7122692236617187328_n.jpg?_nc_cat=104&amp;_nc_oc=AQketjlSUFzRGTqej50cs1XsD1InX5WgLsjHTd4mL6OWT7-OhrJXFvcz8WyRuRBSsqM&amp;_nc_ht=scontent.flis8-1.fna&amp;_nc_tp=7&amp;oh=cbfe1cf2d19b5c37ede1b2dfdf674276&amp;oe=5EBC43D4" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€ ¡Solicítalo desde la app!</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-2.fna.fbcdn.net/v/t39.16868-6/s600x600/68897058_678822749197689_3660284254794809344_n.jpg?_nc_cat=102&amp;_nc_oc=AQnuGGaDQSJvqp6qWgRPMeQJ5mGectLDp8RrAPgACaUxLzaXjGrN6r0SaQUAWU7Io_g&amp;_nc_ht=scontent.flis8-2.fna&amp;_nc_tp=7&amp;oh=ab5a43134d95ebef545ff39420bf7f9c&amp;oe=5EBEB413" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div><div class="_2zgz"><div class="_7jy-"><div class="_7jyr"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 16px; max-height: 112px; -webkit-line-clamp: 7;"> </div></div></div><a target="_blank" class="_231w _231z _4yee" href="http://play.google.com/store/apps/details?id=com.imaginbank.app" style="color: rgb(33, 111, 219);"><img class="_7jys _7jyt img" src="https://scontent.flis8-2.fna.fbcdn.net/v/t39.16868-6/s600x600/68874914_678822752531022_5734270725913575424_n.jpg?_nc_cat=108&amp;_nc_oc=AQkv8fSf75LF4KE4JbneYEcjKyFRw7xil-Nq6Q_rhP_qvoe04zH3ZUa4SwRvS8Nq0XU&amp;_nc_ht=scontent.flis8-2.fna&amp;_nc_tp=7&amp;oh=c5ad235fa78dd110248f46bd3913f998&amp;oe=5EF66280" alt=""><div class="_8jgz _8jg_"><div class="_8jh1"><div class="_8jh2"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;">Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la app</div></div></div><div class="_8jh3"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 14px; max-height: 28px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh4"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div><div class="_8jh5"><div tabindex="0" role="button"><div class="_4ik4 _4ik5" style="line-height: 12px; max-height: 24px; -webkit-line-clamp: 2;"></div></div></div></div><div class="_8jh0"><button type="button" aria-disabled="false" class="_271k _271m _1qjd _3-9a" style="max-width: 80px; letter-spacing: normal; color: rgb(68, 73, 80); font-size: 11px; font-weight: normal; font-family: Arial, sans-serif; line-height: 16px; text-align: center; background-color: rgb(245, 246, 247); border-color: rgb(218, 221, 225); height: 18px; padding-left: 4px; padding-right: 4px; background-clip: padding-box;"><div class="_43rl"><div data-hover="tooltip" data-tooltip-display="overflow" class="_43rm">Use App</div></div></button></div></div></a></div></div></div></div></div><a class="_32rk _32rh _1cy6" href="#"><div direction="forward" class="_10sf _5x5_"><div class="_5x6d"><div class="_3bwv _3bww"><div class="_3bwy"><div class="_3bwx"><i class="_3-8w img sp_JmF3rXGjoQG sx_77d801" alt=""></i></div></div></div></div></div></a></div></div></div><div class="_7kfi"><div class="_7kd5"></div><a class="_7kfh" data-testid="snapshot_footer_link" href="#"><span style="font-family: Arial, sans-serif; font-size: 13px; line-height: 17px; letter-spacing: normal; overflow-wrap: normal; text-align: left; color: rgb(24, 119, 242);">Ver Det"""
    ]

b = [
    """AtivoComeçou a ser publicado a 23/10/2019Identificação: 411753089755204Abrir menu pendenteimaginBankPatrocinadoParking, peajes, impuestos, gasolina... Al final termina siendo una pasta. ¿Te has planteado recortar estos gastos? No, no hablamos de abandonar la conducción. Hablamos de enchufarnos al futuro. Conoce todos los beneficios de tener un coche un eléctrico y lo fácil que es conseguirlo con un Préstamo Auto de imaginBank. #Enchúfate *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse AppVer Det""",
    """AtivoComeçou a ser publicado a 23/10/2019Identificação: 712910935875237Abrir menu pendenteimaginBankPatrocinadoYa reciclas, vas con tu botella de agua para rellenar y has dejado de usar bolsas de plástico para hacer la compra. ¿Qué sigue? Un coche eléctrico. Entérate por qué molan tanto y #Enchúfate con un Préstamo Auto de imaginBank para hacerte con tu coche eléctrico o híbrido. *La concesión de la operación está sujeta al análisis de la solvencia y de la capacidad de devolución del solicitante, en función de las políticas de riesgo de la entidad. imaginBank de CaixaBank Préstamo desde 3.000€ hasta 30.000€ ¡Solicítalo desde la app!Use App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse App Préstamo desde 3.000€ hasta 30.000€. Solicita el tuyo
  desde la appUse AppVer Det"""
]

df = pd.DataFrame({0: a, 1: b})

def get_links(x):
    soup = BeautifulSoup(x, parser='html.parser')
    links = [i.get('href') for i in soup.findAll('a', attrs={'href': re.compile("^http")})]
    return links

df[0].apply(get_links)

df[0].apply(get_links) returns

0    [https://www.facebook.com/imaginBank/, http://...
1    [https://www.facebook.com/imaginBank/, http://...
Name: 0, dtype: object

df[1].apply(get_links) returns

0    []
1    []
Name: 1, dtype: object


问:
Wrong records when filtering date
I have strange problem when i filter in related models by date,
consider this code :

```<code>function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}
</code>```

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

答:
Sorry guys but i figure it out, this is what works for me for getting range:

```<code>  $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'))
            ->whereDate('created_at', '<=', $request->input('deposit_at_to'));
  })
</code>```

if you wonder the laravel ver is 5.6,

Thank you all :-))

Title: Wrong records when filtering date

Body:
I have strange problem when i filter in related models by date,
consider this code :

function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

Body:
Sorry guys but i figure it out, this is what works for me for getting range:

  $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'))
            ->whereDate('created_at', '<=', $request->input('deposit_at_to'));
  })

if you wonder the laravel ver is 5.6,

Thank you all :-))


问:
Sending an order to oanda
I want to send an order to oanda to make a transaction,I use ipython notebook to compile my code,this is my code:

```<code>import oandapy

trade_expire=datetime.now()+timedelta(days=1)
trade_expire=trade_expire.isoformat("T")+"Z"
oanda=oandapy.API(environment='practice',access_token='XXXX....')
account_id=xxxxxxx

response=oanda.create_order(account_id,instrument='USD_EUR',units=1000,side='buy',/
type='limit',price=1.105,expire=trade_expire)
</code>```

But the error is：

```<code>OandaError: OANDA API returned error code 4 (The access token provided does
            not allow this request to be made)
</code>```

How can I solve this problem?

答:
I had the same problem, but when sending orders via curl commands.

The problem has to do with which API you are using from which account.

I notice in your python it says "practice," so you'll want to make sure the API token you generated is from within your practice account. Live accounts and practice accounts each use their own API tokens, and your commands will need to match.

You might also look elsewhere in your python, where it actually pings OandA's server.

For example, when using curl, a live account uses

"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"

and a practice account uses

"https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders"

Using your API token generated on your live account in a practice account will produce the error you're asking about.

Title: Sending an order to oanda

Body:
I want to send an order to oanda to make a transaction,I use ipython notebook to compile my code,this is my code:

import oandapy

trade_expire=datetime.now()+timedelta(days=1)
trade_expire=trade_expire.isoformat("T")+"Z"
oanda=oandapy.API(environment='practice',access_token='XXXX....')
account_id=xxxxxxx

response=oanda.create_order(account_id,instrument='USD_EUR',units=1000,side='buy',/
type='limit',price=1.105,expire=trade_expire)

But the error is：

OandaError: OANDA API returned error code 4 (The access token provided does
            not allow this request to be made)

How can I solve this problem?