问:
sql query to get the max date for a particular element
I have a table

PEEVF

EFFECTIVE_START_DATE
EFFECTIVE_END_DATE
PERSON_ID
ELEMENT_NAME
VALUE

01-JAN-2021
10-JAN-2021
19
Bonus
9.1

11-JAN-2021
28-MAR-2021
19
Bonus
11

29-MAR-2021
10-APR-2021
19
Bonus
11.1

11-APR-2021
31-DEC-2021
19
Bonus
10

11-APR-2022
30-APR-2022
19
Bonus
12

19-APR-2022
30-MAY-2022
19
LTP
09

01-JAN-2019
30-APR-2019
8
Bonus
5

11-MAR-2021
10-JAN-2021
10
Bonus
11

11-JAN-2021
28-MAR-2021
10
Bonus
11.1

20-JAN-2019
08-MAR-2019
1
LTP
9

11-APR-2019
19-AUG-2019
1
LTP
9.8

I want to display the following output by using MAXand not use ROW_NUM.

LATEST_EFF_DT_BONUS
LATEST_EFF_DT_LTP
BONUS_VAL
LTP_VAL
PERSON_ID

11-APR-2022

12

19

19-APR-2022

09
19

01-JAN-2019

5

8

11-JAN-2021

11.1

10

11-APR-2019

9.8
1

When i am using the below statement, it is not giving correct value.

```<code>max(effective_start_Date)  over ( PARTITION BY ELEMENT_NAME,EFFECTIVE_START_DATE order by PERSON_ID )

</code>```

答:
Edit: Based on the downvote, I revised SQL. Now SQL returns the desired result.

SQL:

```<code>with b as (
  select
    person_id,
    element_name,
    max(effective_end_date) as msd
  from peevf
  group by person_id, element_name
) select
 case when b.element_name = 'Bonus' then to_char(a.EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end  as LATEST_EFF_DT_BONUS,
 case when b.element_name = 'LTP' then to_char(a.EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end as LATEST_EFF_DT_LTP,
 case when b.element_name = 'Bonus' then trim(trailing '.' from to_char(a.value,'fm99D9')) else ' ' end as BONUS_VAL,
 case when b.element_name = 'LTP' then trim(trailing '.' from to_char(a.value,'fm99D9')) else ' ' end as LTP_VAL,
 b.person_id as PERSON_ID
from b left join peevf a
on b.person_id = a.person_id
  and b.element_name = a.element_name
  and b.msd = a.EFFECTIVE_END_DATE
;
</code>```

SQL2:

Select using a max over by. You can get rid of the rowid if the order of the result does not matter or if there is another order.

```<code>select
  LATEST_EFF_DT_BONUS,
  LATEST_EFF_DT_LTP,
  BONUS_VAL,
  LTP_VAL,
  person_id
from (
 select
  case when element_name = 'Bonus' then to_char(EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end  as LATEST_EFF_DT_BONUS,
  case when element_name = 'LTP' then to_char(EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end as LATEST_EFF_DT_LTP,
  case when element_name = 'Bonus' then trim(trailing '.' from to_char(value,'fm99D9')) else ' ' end as BONUS_VAL,
  case when element_name = 'LTP' then trim(trailing '.' from to_char(value,'fm99D9')) else ' ' end as LTP_VAL,
  max(effective_end_date)    over ( PARTITION BY ELEMENT_NAME,PERSON_ID order by PERSON_ID) as mo,
  EFFECTIVE_END_DATE,
  rowid rn,
  person_id
 from peevf
) a
where
a.EFFECTIVE_END_DATE = a.mo
order by rn
;
</code>```

Output:

LATEST_EFF_DT_BONUS
LATEST_EFF_DT_LTP
BONUS_VAL
LTP_VAL
PERSON_ID

11-APR-2022

12

19

19-APR-2022

9
19

01-JAN-2019

5

8

11-JAN-2021

11.1

10

11-APR-2019

9.8
1

DDL:

```<code>CREATE TABLE PEEVF
    ("EFFECTIVE_START_DATE" timestamp, "EFFECTIVE_END_DATE" timestamp, "PERSON_ID" int, "ELEMENT_NAME" varchar2(5), "VALUE" number)
;

INSERT ALL
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('01-Jan-2021 12:00:00 AM', '10-Jan-2021 12:00:00 AM', 19, 'Bonus', 9.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Jan-2021 12:00:00 AM', '28-Mar-2021 12:00:00 AM', 19, 'Bonus', 11)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('29-Mar-2021 12:00:00 AM', '10-Apr-2021 12:00:00 AM', 19, 'Bonus', 11.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2021 12:00:00 AM', '31-Dec-2021 12:00:00 AM', 19, 'Bonus', 10)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2022 12:00:00 AM', '30-Apr-2022 12:00:00 AM', 19, 'Bonus', 12)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('19-Apr-2022 12:00:00 AM', '30-May-2022 12:00:00 AM', 19, 'LTP', 09)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('01-Jan-2019 12:00:00 AM', '30-Apr-2019 12:00:00 AM', 8, 'Bonus', 5)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Mar-2021 12:00:00 AM', '10-Jan-2021 12:00:00 AM', 10, 'Bonus', 11)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Jan-2021 12:00:00 AM', '28-Mar-2021 12:00:00 AM', 10, 'Bonus', 11.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('20-Jan-2019 12:00:00 AM', '08-Mar-2019 12:00:00 AM', 1, 'LTP', 9)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2019 12:00:00 AM', '19-Aug-2019 12:00:00 AM', 1, 'LTP', 9.8)
SELECT * FROM dual
;
</code>```

Body:
I have a table

PEEVF

EFFECTIVE_START_DATE
EFFECTIVE_END_DATE
PERSON_ID
ELEMENT_NAME
VALUE

01-JAN-2021
10-JAN-2021
19
Bonus
9.1

11-JAN-2021
28-MAR-2021
19
Bonus
11

29-MAR-2021
10-APR-2021
19
Bonus
11.1

11-APR-2021
31-DEC-2021
19
Bonus
10

11-APR-2022
30-APR-2022
19
Bonus
12

19-APR-2022
30-MAY-2022
19
LTP
09

01-JAN-2019
30-APR-2019
8
Bonus
5

11-MAR-2021
10-JAN-2021
10
Bonus
11

11-JAN-2021
28-MAR-2021
10
Bonus
11.1

20-JAN-2019
08-MAR-2019
1
LTP
9

11-APR-2019
19-AUG-2019
1
LTP
9.8

I want to display the following output by using MAXand not use ROW_NUM.

LATEST_EFF_DT_BONUS
LATEST_EFF_DT_LTP
BONUS_VAL
LTP_VAL
PERSON_ID

11-APR-2022

12

19

19-APR-2022

09
19

01-JAN-2019

5

8

11-JAN-2021

11.1

10

11-APR-2019

9.8
1

When i am using the below statement, it is not giving correct value.

max(effective_start_Date)  over ( PARTITION BY ELEMENT_NAME,EFFECTIVE_START_DATE order by PERSON_ID )

Body:
Edit: Based on the downvote, I revised SQL. Now SQL returns the desired result.

SQL:

with b as (
  select
    person_id,
    element_name,
    max(effective_end_date) as msd
  from peevf
  group by person_id, element_name
) select
 case when b.element_name = 'Bonus' then to_char(a.EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end  as LATEST_EFF_DT_BONUS,
 case when b.element_name = 'LTP' then to_char(a.EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end as LATEST_EFF_DT_LTP,
 case when b.element_name = 'Bonus' then trim(trailing '.' from to_char(a.value,'fm99D9')) else ' ' end as BONUS_VAL,
 case when b.element_name = 'LTP' then trim(trailing '.' from to_char(a.value,'fm99D9')) else ' ' end as LTP_VAL,
 b.person_id as PERSON_ID
from b left join peevf a
on b.person_id = a.person_id
  and b.element_name = a.element_name
  and b.msd = a.EFFECTIVE_END_DATE
;

SQL2:

Select using a max over by. You can get rid of the rowid if the order of the result does not matter or if there is another order.

select
  LATEST_EFF_DT_BONUS,
  LATEST_EFF_DT_LTP,
  BONUS_VAL,
  LTP_VAL,
  person_id
from (
 select
  case when element_name = 'Bonus' then to_char(EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end  as LATEST_EFF_DT_BONUS,
  case when element_name = 'LTP' then to_char(EFFECTIVE_START_DATE,'DD-MON-YYYY') else ' ' end as LATEST_EFF_DT_LTP,
  case when element_name = 'Bonus' then trim(trailing '.' from to_char(value,'fm99D9')) else ' ' end as BONUS_VAL,
  case when element_name = 'LTP' then trim(trailing '.' from to_char(value,'fm99D9')) else ' ' end as LTP_VAL,
  max(effective_end_date)    over ( PARTITION BY ELEMENT_NAME,PERSON_ID order by PERSON_ID) as mo,
  EFFECTIVE_END_DATE,
  rowid rn,
  person_id
 from peevf
) a
where
a.EFFECTIVE_END_DATE = a.mo
order by rn
;

Output:

LATEST_EFF_DT_BONUS
LATEST_EFF_DT_LTP
BONUS_VAL
LTP_VAL
PERSON_ID

11-APR-2022

12

19

19-APR-2022

9
19

01-JAN-2019

5

8

11-JAN-2021

11.1

10

11-APR-2019

9.8
1

DDL:

CREATE TABLE PEEVF
    ("EFFECTIVE_START_DATE" timestamp, "EFFECTIVE_END_DATE" timestamp, "PERSON_ID" int, "ELEMENT_NAME" varchar2(5), "VALUE" number)
;

INSERT ALL
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('01-Jan-2021 12:00:00 AM', '10-Jan-2021 12:00:00 AM', 19, 'Bonus', 9.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Jan-2021 12:00:00 AM', '28-Mar-2021 12:00:00 AM', 19, 'Bonus', 11)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('29-Mar-2021 12:00:00 AM', '10-Apr-2021 12:00:00 AM', 19, 'Bonus', 11.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2021 12:00:00 AM', '31-Dec-2021 12:00:00 AM', 19, 'Bonus', 10)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2022 12:00:00 AM', '30-Apr-2022 12:00:00 AM', 19, 'Bonus', 12)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('19-Apr-2022 12:00:00 AM', '30-May-2022 12:00:00 AM', 19, 'LTP', 09)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('01-Jan-2019 12:00:00 AM', '30-Apr-2019 12:00:00 AM', 8, 'Bonus', 5)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Mar-2021 12:00:00 AM', '10-Jan-2021 12:00:00 AM', 10, 'Bonus', 11)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Jan-2021 12:00:00 AM', '28-Mar-2021 12:00:00 AM', 10, 'Bonus', 11.1)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('20-Jan-2019 12:00:00 AM', '08-Mar-2019 12:00:00 AM', 1, 'LTP', 9)
    INTO PEEVF ("EFFECTIVE_START_DATE", "EFFECTIVE_END_DATE", "PERSON_ID", "ELEMENT_NAME", "VALUE")
         VALUES ('11-Apr-2019 12:00:00 AM', '19-Aug-2019 12:00:00 AM', 1, 'LTP', 9.8)
SELECT * FROM dual
;


来源: stackexchange

问:
How to read parquet file data partitioned on column from AWS S3 using python
I have saved the below table using pyspark to AWS S3, partitioned by column "channel_name". using below code.

```<code> df.write.option("header",True) \
                .partitionBy("channel_name") \
                .mode('append')\
                .parquet("s3://path")

</code>```

start_timestamp
channel_name
value

2020-11-02 08:51:50
velocity
1

2020-11-02 09:14:29
Temp
0

2020-11-02 09:18:32
velocity
0

2020-11-02 09:32:42
velocity
4

2020-11-03 13:06:03
Temp
2

2020-11-03 13:10:01
Temp
1

2020-11-03 13:54:38
Temp
5

2020-11-03 14:46:25
velocity
5

2020-11-03 14:57:31
Kilometer
6

2020-11-03 15:07:07
Kilometer
7

But i want to read same data which is partitoned on column "channel_name" using python, its not working, it is excluding that partitioned column "channel_name". below is code i tried with AWSwrangler.

```<code>import awswrangler as wr
df = wr.s3.read_parquet(path="s3://shreyasbigdata/Prod_test_item_id=V214944/")
</code>```

It looks like this, but i want that "channel_name" column also.

start_timestamp
value

2020-11-02 08:51:50
1

2020-11-02 09:14:29
0

2020-11-02 09:18:32
0

2020-11-02 09:32:42
4

2020-11-03 13:06:03
2

2020-11-03 13:10:01
1

2020-11-03 13:54:38
5

2020-11-03 14:46:25
5

2020-11-03 14:57:31
6

2020-11-03 15:07:07
7

I tried with different libraries but its not working.
Would be great if you help me to read all the columns including partitioned one.

答:
I got the Answer thank you

```<code>import s3fs
import pyarrow.parquet as pq
fs = s3fs.S3FileSystem()

bucket = 'bucket_name'
path = 'path_of_folder' #if its a directory omit the traling /
bucket_uri = f's3://{bucket}/{path}'

dataset = pq.ParquetDataset(bucket_uri, filesystem=fs)
table = dataset.read()
df = table.to_pandas()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have saved the below table using pyspark to AWS S3, partitioned by column "channel_name". using below code.

 df.write.option("header",True) \
                .partitionBy("channel_name") \
                .mode('append')\
                .parquet("s3://path")

start_timestamp
channel_name
value

2020-11-02 08:51:50
velocity
1

2020-11-02 09:14:29
Temp
0

2020-11-02 09:18:32
velocity
0

2020-11-02 09:32:42
velocity
4

2020-11-03 13:06:03
Temp
2

2020-11-03 13:10:01
Temp
1

2020-11-03 13:54:38
Temp
5

2020-11-03 14:46:25
velocity
5

2020-11-03 14:57:31
Kilometer
6

2020-11-03 15:07:07
Kilometer
7

But i want to read same data which is partitoned on column "channel_name" using python, its not working, it is excluding that partitioned column "channel_name". below is code i tried with AWSwrangler.

import awswrangler as wr
df = wr.s3.read_parquet(path="s3://shreyasbigdata/Prod_test_item_id=V214944/")

It looks like this, but i want that "channel_name" column also.

start_timestamp
value

2020-11-02 08:51:50
1

2020-11-02 09:14:29
0

2020-11-02 09:18:32
0

2020-11-02 09:32:42
4

2020-11-03 13:06:03
2

2020-11-03 13:10:01
1

2020-11-03 13:54:38
5

2020-11-03 14:46:25
5

2020-11-03 14:57:31
6

2020-11-03 15:07:07
7

I tried with different libraries but its not working.
Would be great if you help me to read all the columns including partitioned one.

Body:
I got the Answer thank you

import s3fs
import pyarrow.parquet as pq
fs = s3fs.S3FileSystem()

bucket = 'bucket_name'
path = 'path_of_folder' #if its a directory omit the traling /
bucket_uri = f's3://{bucket}/{path}'

dataset = pq.ParquetDataset(bucket_uri, filesystem=fs)
table = dataset.read()
df = table.to_pandas()


问:
query to find the second most common word in a table (oracle sql)
So I have a table employees as shown below

```<code>ID | name | department
---|------|-----------
1  | john | home
2  | alex | home
3  | ryan | tech
</code>```

I'm trying to group these by the department number and have the count displayed.  But I am trying to select the second most common, which in this case it should return (tech 1).  Any help on how to approach this is appreciated.

Edit:

By only using MINUS, I'm still not familiar with LIMIT when searching around online.

答:
We can use COUNT along with DENSE_RANK:

WITH cte AS (
    SELECT department, COUNT(*) AS cnt,
           DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) rnk
    FROM yourTable
    GROUP BY department
)

SELECT department, cnt
FROM cte
WHERE rnk = 2;
```
<p>As of Oracle 12c, you might find the following limit query satisfactory:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT department, COUNT(*) AS cnt
FROM yourTable
GROUP BY department
ORDER BY COUNT(*) DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;
</code>```

But this limit approach does not handle well the scenario where e.g. there might be 2 or more departments ties for first place.  DENSE_RANK does a better job of handling such edge cases.

Body:
So I have a table employees as shown below

ID | name | department
---|------|-----------
1  | john | home
2  | alex | home
3  | ryan | tech

I'm trying to group these by the department number and have the count displayed.  But I am trying to select the second most common, which in this case it should return (tech 1).  Any help on how to approach this is appreciated.

Edit:

By only using MINUS, I'm still not familiar with LIMIT when searching around online.

Body:
We can use COUNT along with DENSE_RANK:

WITH cte AS (
    SELECT department, COUNT(*) AS cnt,
           DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) rnk
    FROM yourTable
    GROUP BY department
)

SELECT department, cnt
FROM cte
WHERE rnk = 2;

As of Oracle 12c, you might find the following limit query satisfactory:

SELECT department, COUNT(*) AS cnt
FROM yourTable
GROUP BY department
ORDER BY COUNT(*) DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;

But this limit approach does not handle well the scenario where e.g. there might be 2 or more departments ties for first place.  DENSE_RANK does a better job of handling such edge cases.


问:
Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0
I just upgraded packages in an MVC 3 project (ASP.net 4), and now I am getting the following error message when accessing a page in that project:

Server Error in '/MyApplication' Application.

Could not load file or assembly 'System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
  one of its dependencies. The located assembly's manifest definition
  does not match the assembly reference. (Exception from HRESULT:
  0x80131040)  Description: An unhandled exception occurred during the
  execution of the current web request. Please review the stack trace
  for more information about the error and where it originated in the
  code.

Exception Details: System.IO.FileLoadException: Could not load file or
  assembly 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to
  determine why the assembly 'System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
  could not be loaded.

=== Pre-bind state information === LOG: User = IIS APPPOOL\ASP.NET v4.0 LOG: DisplayName = System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35  (Fully-specified)
  LOG: Appbase = file:///C:/.../ LOG: Initial PrivatePath = C:...\bin
  Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35.
  === LOG: This bind starts in default load context. LOG: Using application configuration file: C:...\web.config LOG: Using host
  configuration file:
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config LOG:
  Using machine configuration file from
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
  LOG: Post-policy reference: System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 LOG:
  Attempting download of new URL
  file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary
  ASP.NET Files/.../cb62a7b2/327a0353/System.Web.WebPages.Razor.DLL.
  LOG: Attempting download of new URL
  file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary
  ASP.NET
  Files/.../cb62a7b2/327a0353/System.Web.WebPages.Razor/System.Web.WebPages.Razor.DLL.
  LOG: Attempting download of new URL
  file:///C:/LeGroupeHtmSVN/.../UpDir.Web/bin/System.Web.WebPages.Razor.DLL.
  WRN: Comparing the assembly name resulted in the mismatch: Major
  Version ERR: Failed to complete setup of assembly (hr = 0x80131040).
  Probing terminated.

Stack Trace:

[FileLoadException: Could not load file or assembly
  'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)]

  Microsoft.Web.Helpers.PreApplicationStartCode.Start() +0

[InvalidOperationException: The pre-application start initialization
  method Start on type Microsoft.Web.Helpers.PreApplicationStartCode
  threw an exception with the following error message: Could not load
  file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040).]

  System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1
  methods) +11711966

  System.Web.Compilation.BuildManager.CallPreStartInitMethods() +465

  System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
  appManager, IApplicationHost appHost, IConfigMapPathFactory
  configMapPathFactory, HostingEnvironmentParameters hostingParameters,
  PolicyLevel policyLevel, Exception appDomainCreationException) +1167

[HttpException (0x80004005): The pre-application start initialization
  method Start on type Microsoft.Web.Helpers.PreApplicationStartCode
  threw an exception with the following error message: Could not load
  file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040).]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11700896
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +141    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +4869125

-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
  ASP.NET Version:4.0.30319.272

In my web.config file, and in my application, I am referencing System.Web.WebPages.Razor v1.0.0.0:

```<code>  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
  </dependentAssembly>
</code>```

I don't even know whether I could be using System.Web.WebPages.Razor v2.0.0.0 with .Net 4.

Now, how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?

答:
Fix Your Problem

Remove WebMatrix.Data and WebMatrix.WebData in the References of your Project

ContentLicense: CC BY-SA 3.0

Body:
I just upgraded packages in an MVC 3 project (ASP.net 4), and now I am getting the following error message when accessing a page in that project:

Server Error in '/MyApplication' Application.

Could not load file or assembly 'System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
  one of its dependencies. The located assembly's manifest definition
  does not match the assembly reference. (Exception from HRESULT:
  0x80131040)  Description: An unhandled exception occurred during the
  execution of the current web request. Please review the stack trace
  for more information about the error and where it originated in the
  code.

Exception Details: System.IO.FileLoadException: Could not load file or
  assembly 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to
  determine why the assembly 'System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
  could not be loaded.

=== Pre-bind state information === LOG: User = IIS APPPOOL\ASP.NET v4.0 LOG: DisplayName = System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35  (Fully-specified)
  LOG: Appbase = file:///C:/.../ LOG: Initial PrivatePath = C:...\bin
  Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35.
  === LOG: This bind starts in default load context. LOG: Using application configuration file: C:...\web.config LOG: Using host
  configuration file:
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config LOG:
  Using machine configuration file from
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
  LOG: Post-policy reference: System.Web.WebPages.Razor,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 LOG:
  Attempting download of new URL
  file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary
  ASP.NET Files/.../cb62a7b2/327a0353/System.Web.WebPages.Razor.DLL.
  LOG: Attempting download of new URL
  file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary
  ASP.NET
  Files/.../cb62a7b2/327a0353/System.Web.WebPages.Razor/System.Web.WebPages.Razor.DLL.
  LOG: Attempting download of new URL
  file:///C:/LeGroupeHtmSVN/.../UpDir.Web/bin/System.Web.WebPages.Razor.DLL.
  WRN: Comparing the assembly name resulted in the mismatch: Major
  Version ERR: Failed to complete setup of assembly (hr = 0x80131040).
  Probing terminated.

Stack Trace:

[FileLoadException: Could not load file or assembly
  'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)]

  Microsoft.Web.Helpers.PreApplicationStartCode.Start() +0

[InvalidOperationException: The pre-application start initialization
  method Start on type Microsoft.Web.Helpers.PreApplicationStartCode
  threw an exception with the following error message: Could not load
  file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040).]

  System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1
  methods) +11711966

  System.Web.Compilation.BuildManager.CallPreStartInitMethods() +465

  System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
  appManager, IApplicationHost appHost, IConfigMapPathFactory
  configMapPathFactory, HostingEnvironmentParameters hostingParameters,
  PolicyLevel policyLevel, Exception appDomainCreationException) +1167

[HttpException (0x80004005): The pre-application start initialization
  method Start on type Microsoft.Web.Helpers.PreApplicationStartCode
  threw an exception with the following error message: Could not load
  file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040).]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11700896
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +141    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +4869125

-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
  ASP.NET Version:4.0.30319.272

In my web.config file, and in my application, I am referencing System.Web.WebPages.Razor v1.0.0.0:

  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
  </dependentAssembly>

I don't even know whether I could be using System.Web.WebPages.Razor v2.0.0.0 with .Net 4.

Now, how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?


问:
dlopen failed: cannot open shared object file: No such file or directory
The problem is I use dlopen to load a library (the .so is written by me, it's not a system library), but I got the error shown in the title.

I have included dlfcn.h

in compiler, I used the -ldl command

What I want to load is just the source code folder, I tried to add -L., but it did not work.

答:
I would recommed dlerror to get the reason

```<code>void* handle = dlopen(SO_FILE, RTLD_NOW | RTLD_LOCAL | RTLD_DEEPBIND);
if(handle == NULL)
{
    printf(LOG_ERROR, "Error: %s\n",  dlerror());
    assert(0);
}
</code>```

this will report detailed reason for the error

Body:
I would recommed dlerror to get the reason

void* handle = dlopen(SO_FILE, RTLD_NOW | RTLD_LOCAL | RTLD_DEEPBIND);
if(handle == NULL)
{
    printf(LOG_ERROR, "Error: %s\n",  dlerror());
    assert(0);
}

this will report detailed reason for the error


问:
C# why LINQ string array Contains show false
my question is ABC006 is in testA, why Contains show false?
and testB  show true?</p>
```<code>public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}
</code>```

答:
You are using the Split function to the split the original string to an array.
The testA contains 2 elements after the split:

" ABC666"

"777"

If you call the Contains function on the array, it will check if any of the elements contains the exact match of the string given. Thanks the reason you are getting False.

You can use the Linq Any function to get the functionality you want:

```<code>Console.WriteLine(testA.Any( a=> a.Contains("ABC666")));
</code>```

This will call for Contains function of every string in the array.

Body:
my question is ABC006 is in testA, why Contains show false?
and testB  show true?

public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}

Body:
You are using the Split function to the split the original string to an array.
The testA contains 2 elements after the split:

" ABC666"

"777"

If you call the Contains function on the array, it will check if any of the elements contains the exact match of the string given. Thanks the reason you are getting False.

You can use the Linq Any function to get the functionality you want:

Console.WriteLine(testA.Any( a=> a.Contains("ABC666")));

This will call for Contains function of every string in the array.


问:
maps displayed wrong on mobile (using JQuery mobile)
I'm using jQuery mobile and I have to display some maps.
I'm using a function that create maps every time that I click on the specific link but after the generation of the first map, the others are displayed wrong.

Here an example,
First map:

Other maps:

I use a function like this:

```<code>function buildMap(div){

    var coord = new google.maps.LatLng(lat, lng);

    var options = {
        zoom: 13,
        scrollwheel: false,
        scaleControl: true,
        mapTypeControl: false,
        center: coord,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    var map = new google.maps.Map(div, options);

    return map;
}
</code>```

Can you help me?

Thank you!!

答:
Problem solved, you need to create the map on the "pageshow" event (an event of jQuery mobile):</p>

```<code>$('#map_page').live('pageshow',function(event, ui){
    buildResultMap('#map_canvas');
});
</code>```

Body:
I'm using jQuery mobile and I have to display some maps.
I'm using a function that create maps every time that I click on the specific link but after the generation of the first map, the others are displayed wrong.

Here an example,
First map:

Other maps:

I use a function like this:

function buildMap(div){

    var coord = new google.maps.LatLng(lat, lng);

    var options = {
        zoom: 13,
        scrollwheel: false,
        scaleControl: true,
        mapTypeControl: false,
        center: coord,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    var map = new google.maps.Map(div, options);

    return map;
}

Can you help me?

Thank you!!

Body:
Problem solved, you need to create the map on the "pageshow" event (an event of jQuery mobile):

$('#map_page').live('pageshow',function(event, ui){
    buildResultMap('#map_canvas');
});


问:
Remove certain fields from a YAML map object using yq
I have some tricky thing that I need to do for a yaml file, this is how it looks before

Before

```<code>apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      creationTimestamp: '2022-02-097T19:511:11Z'
      finalizers:
        - cuv.ssf.com
      generation: 1
      name: bar
      namespace: foo
      resourceVersion: '12236'
      uid: 0117657e8
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
    status:
      conditions:
        - lastTransitionTime: '2022-02-09T19:50:12Z'
          message: test
          observedGeneration: 1
          reason: Ready
          status: 'True'
          type: Ready
      lastOperation:
        description: test
        state: Succeeded
        type: Reconcile
</code>```

https://codebeautify.org/yaml-validator/y22fe4943

I need to remove all the fields under section metadata and the tricky part is to keep only the name and namespace
in addition to removing the status section at all, it should look like following

After

```<code>  apiVersion: v1
    items:
      - apiVersion: core.k8s.com/v1alpha1
        kind: Test
        metadata:
          name: bar
          namespace: foo
        spec:
          certificateIssuer:
            acme:
              email: myemail
          provider:
            credentials: dst
            type: foo
          domain: vst
          type: bar
</code>```

After link
https://codebeautify.org/yaml-validator/y220531ef

Using yq (https://github.com/mikefarah/yq/) version 4.19.1

答:
This should work using yq in the implementaion of https://github.com/kislyuk/yq (not https://github.com/mikefarah/yq), and the -y (or -Y) flag:

yq -y '.items[] |= (del(.status) | .metadata |= {name, namespace})'
```
```apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      name: bar
      namespace: foo
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
```

Body:
I have some tricky thing that I need to do for a yaml file, this is how it looks before

Before

apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      creationTimestamp: '2022-02-097T19:511:11Z'
      finalizers:
        - cuv.ssf.com
      generation: 1
      name: bar
      namespace: foo
      resourceVersion: '12236'
      uid: 0117657e8
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
    status:
      conditions:
        - lastTransitionTime: '2022-02-09T19:50:12Z'
          message: test
          observedGeneration: 1
          reason: Ready
          status: 'True'
          type: Ready
      lastOperation:
        description: test
        state: Succeeded
        type: Reconcile

https://codebeautify.org/yaml-validator/y22fe4943

I need to remove all the fields under section metadata and the tricky part is to keep only the name and namespace
in addition to removing the status section at all, it should look like following

After

  apiVersion: v1
    items:
      - apiVersion: core.k8s.com/v1alpha1
        kind: Test
        metadata:
          name: bar
          namespace: foo
        spec:
          certificateIssuer:
            acme:
              email: myemail
          provider:
            credentials: dst
            type: foo
          domain: vst
          type: bar

After link
https://codebeautify.org/yaml-validator/y220531ef

Using yq (https://github.com/mikefarah/yq/) version 4.19.1

Body:
This should work using yq in the implementaion of https://github.com/kislyuk/yq (not https://github.com/mikefarah/yq), and the -y (or -Y) flag:

yq -y '.items[] |= (del(.status) | .metadata |= {name, namespace})'

apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      name: bar
      namespace: foo
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar


问:
How to get Access Policies of the Azure KeyVault using Azure PowerShell
I'm working on an Azure Powershell script which compares the secrets and the access policies of two Azure KeyVaults.

For comparing the secrets of the Azure KeyVault I've used the command
Get-AzureKeyVaultSecret which worked fine,

but for the access policies seems like there is no any command like Get-AzKeyVaultAccessPolicy.

So, is there any way to retrieve the access policies from the KeyVault using Azure PowerShell?

答:
You could do it like this as well

$ az keyvault show --name <my-kv-name> --query "properties.accessPolicies"
```


问:
TypeError: this.canvasContainer is undefined in unit test Angular
I want to test my service in angular with karma and jasmine, I begin with unit tests and I don't found any solution for my case or because I don't know how I can fix the issue. I always have a problem with my fields which are often undefined I don't understand why. If you can explain me what is the real problem It will be very nice to be able to progress in my tests.

My service

```<code>import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CanvasElementService {

  public canvasContainer: HTMLDivElement;

  private scaleProperty: string = 'scale(1)';

  public updateScale(scale: number) {
    this.scaleProperty = `scale(${scale})`;
    this.update();
  }

  public update(): void {
    this.canvasContainer.style.transform = this.scaleProperty;
  }

}

</code>```

And my test

```<code>import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';

import { CanvasElementService } from './canvas-element.service';

fdescribe('CanvasElementService', () => {
  let service: CanvasElementService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(CanvasElementService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  describe("updateScale", () => {
    it("updatescale 2", () => {
      let scale = 3;
      spyOn(service, 'update').and.callThrough();
      service.updateScale(scale);
      expect(service['scaleProperty']).toBe('scale(3)');
    });

  });

});

</code>```

After run test I got :

thanks for help If you have any idea to fix it.

答:
Im not quite sure how to access a htmlElement in services. I think its only meant to be used by components (which have access to elements via @ViewChild() decorator).

You can try to achieve it by injecting your document into the service constructor and search for your element. Something like this:

```<code>constructor(@Inject(DOCUMENT) private document: HTMLDocument) {}
</code>```

But its really not recommend to use services to access your dom. Use components or directives for it.

https://medium.com/@smarth55/angular-bad-practices-patterns-service-that-touch-the-dom-57ea978dca92

Body:
I want to test my service in angular with karma and jasmine, I begin with unit tests and I don't found any solution for my case or because I don't know how I can fix the issue. I always have a problem with my fields which are often undefined I don't understand why. If you can explain me what is the real problem It will be very nice to be able to progress in my tests.

My service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CanvasElementService {

  public canvasContainer: HTMLDivElement;

  private scaleProperty: string = 'scale(1)';

  public updateScale(scale: number) {
    this.scaleProperty = `scale(${scale})`;
    this.update();
  }

  public update(): void {
    this.canvasContainer.style.transform = this.scaleProperty;
  }

}

And my test

import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';

import { CanvasElementService } from './canvas-element.service';

fdescribe('CanvasElementService', () => {
  let service: CanvasElementService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(CanvasElementService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  describe("updateScale", () => {
    it("updatescale 2", () => {
      let scale = 3;
      spyOn(service, 'update').and.callThrough();
      service.updateScale(scale);
      expect(service['scaleProperty']).toBe('scale(3)');
    });

  });

});

After run test I got :

thanks for help If you have any idea to fix it.

Body:
Im not quite sure how to access a htmlElement in services. I think its only meant to be used by components (which have access to elements via @ViewChild() decorator).

You can try to achieve it by injecting your document into the service constructor and search for your element. Something like this:

constructor(@Inject(DOCUMENT) private document: HTMLDocument) {}

But its really not recommend to use services to access your dom. Use components or directives for it.

https://medium.com/@smarth55/angular-bad-practices-patterns-service-that-touch-the-dom-57ea978dca92


问:
How to combine 2 results from SQL procedure
I wrote a SQL query, it is 300+ line and I made this as a procedure.

I want to run two times this procedure with different parameters and then want to see all result in one table.

For example:

```<code>exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1
// Returns 2 columns, number of rows can vary

exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1
// Returns 2 columns, number of rows can vary
</code>```

I run these together, then I hope to get a result of 4 columns

// 4 column,number of rows can vary

I tried openrowset but SQL blocked.

How can I do this, I would be very happy if you can help.

答:
Start with creating a table type than matches the output of your procedure.

For example:

```<code>CREATE TYPE XxxxxTblType AS TABLE(
 Col1 varchar(10) not null,
 Col2 decimal(8,2) not null
);
</code>```

This table type could also be used by your procedure.

Then use a variable with that table type to collect the results from the procedures. Then create a temporary table from that table variable.

```<code>declare @Xxxxx XxxxxTblType;
insert into @Xxxxx exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1;
insert into @Xxxxx exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1;

select * into #tmpXxxxx from @Xxxxx;
</code>```

Now you can query the temporary table.

```<code>select * from #tmpXxxxx;
</code>```

Body:
I wrote a SQL query, it is 300+ line and I made this as a procedure.

I want to run two times this procedure with different parameters and then want to see all result in one table.

For example:

exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1
// Returns 2 columns, number of rows can vary

exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1
// Returns 2 columns, number of rows can vary

I run these together, then I hope to get a result of 4 columns

// 4 column,number of rows can vary

I tried openrowset but SQL blocked.

How can I do this, I would be very happy if you can help.

Body:
Start with creating a table type than matches the output of your procedure.

For example:

CREATE TYPE XxxxxTblType AS TABLE(
 Col1 varchar(10) not null,
 Col2 decimal(8,2) not null
);

This table type could also be used by your procedure.

Then use a variable with that table type to collect the results from the procedures. Then create a temporary table from that table variable.

declare @Xxxxx XxxxxTblType;
insert into @Xxxxx exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1;
insert into @Xxxxx exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1;

select * into #tmpXxxxx from @Xxxxx;

Now you can query the temporary table.

select * from #tmpXxxxx;


问:
Remove empty P tags from HTML?
I am trying to strip empty
 tags from a block of HTML within a Shopify theme. For some reason the remove filter is not detecting whatever the space character is inside the tag. I've even tried copy/pasting from source code into my command and it's not working.

```<code>{{ article.content | remove: '<p> </p>' | remove: '<p> </p>' }}
</code>```

With this, it still remains:

Copy/paste of the pesky tag:

```<code><p> </p>
</code>```

答:
You can just hide all empty paragraphs with:</p>
```<code> p:empty {display: none;}
</code>```

Title: Remove empty P tags from HTML?

Body:
I am trying to strip empty
 tags from a block of HTML within a Shopify theme. For some reason the remove filter is not detecting whatever the space character is inside the tag. I've even tried copy/pasting from source code into my command and it's not working.

{{ article.content | remove: '

' | remove: '

' }}

With this, it still remains:

Copy/paste of the pesky tag:

Body:
You can just hide all empty paragraphs with:

 p:empty {display: none;}


问:
How to get time difference from ZoneDateTime in javascript
How can I get the time difference in seconds between two date-times one is from the backend in the form of ZoneDateTime and the other will be the current time at the frontend while response get received.

Response time from backend is -

```<code>callStartTime:{
chronology: {id: 'ISO', calendarType: 'iso8601'}
dayOfMonth: 8
dayOfWeek: "TUESDAY"
dayOfYear: 39
hour: 16
minute: 15
month: "FEBRUARY"
monthValue: 2
nano: 240000000
offset: {totalSeconds: 19800, id: '+05:30', rules: {…}}
second: 29
year: 2022
zone: {id: 'Asia/Calcutta', rules: {…}}
</code>```

From this How can I find the difference between current time and this time in seconds ?

答:
Calculate the equivalent ECMAScript time value from the data. Subtract that from the current time value and you have the difference in milliseconds, e.g.

function getTimeDiff(data, date = new Date()) {
  let utc = new Date(Date.UTC(
      data.year,
      data.monthValue - 1,
      data.dayOfMonth,
      data.hour,
      data.minute,
      data.second
  ) - data.offset.totalSeconds*1e3);
  return date - utc;
}

function msToTime(ms) {
  let days = ms / 8.64e7 | 0;
  let hrs = (ms%8.64e7) / 3.6e6 | 0;
  let mins = (ms%3.6e6) / 6e4 | 0;
  let secs = (ms%6e4) / 1e3 | 0;
  let z = n => (n<10? '0':'') + n;
  return `${days? days + ' day' + (days == 1? ' ' : 's ') : ''}${z(hrs)}:` +
         `${z(mins)}:${z(secs)}`;
}

let callStartTime = {
  chronology: {id: 'ISO', calendarType: 'iso8601'},
  dayOfMonth: 8,
  dayOfWeek: "TUESDAY",
  dayOfYear: 39,
  hour: 16,
  minute: 15,
  month: "FEBRUARY",
  monthValue: 2,
  nano: 240000000,
  offset: {totalSeconds: 19800, id: '+05:30', rules: {}},
  second: 29,
  year: 2022,
  zone: {id: 'Asia/Calcutta', rules: {}}
};

['2022-02-08T16:15:29+05:30', // 0
 null // now
].forEach(ts => {
  let data = callStartTime;
  let compDate = ts? new Date(ts) : new Date();
  let diffMs = getTimeDiff(data, compDate);
  console.log(`${ts || compDate.toISOString()} : ` +
              `${diffMs} ms (${msToTime(diffMs)})`
  );
});```

Body:
How can I get the time difference in seconds between two date-times one is from the backend in the form of ZoneDateTime and the other will be the current time at the frontend while response get received.

Response time from backend is -

callStartTime:{
chronology: {id: 'ISO', calendarType: 'iso8601'}
dayOfMonth: 8
dayOfWeek: "TUESDAY"
dayOfYear: 39
hour: 16
minute: 15
month: "FEBRUARY"
monthValue: 2
nano: 240000000
offset: {totalSeconds: 19800, id: '+05:30', rules: {…}}
second: 29
year: 2022
zone: {id: 'Asia/Calcutta', rules: {…}}

From this How can I find the difference between current time and this time in seconds ?


问:
Trying to limit the values that can be entered in a column based on the value of another column
I’m building a database using MS access, the purpose is to keep track of the researchs and the funds given to each research. The funding amount depends on what kind of funding program the research is registered to,and the employee shouldn’t be able to enter a value that exceeds the specified amount

(for example if the research is, registered to “small research projects” funding program, the funding amount will be 25,000 Saudi riyals max and could be less)

How can I apply this rule using MS access?

答:
Do the following.

Create a table for funding program,

Create a table for fund disbursements

Create a form for funding program

Create a  form for fund disbursements

Go to vba and add codes under the following

A. Disbursedamount after update
//This is to check if the amount been entered is more than the amount left to be spent on the program

B. Fundingprogram after update
This will use a function called dsum to update a field in the funding program form with the total spent till date.

Ensure you set the locked properties of the totalspent field in form view to "yes", this is to prevent any user from changing the value on this field.

Also take note of the areas i drew a blue line in the table of the fund disbursement and replicate exact same thing

I have attached images that shows the steps.


问:
Hugo with Asciidoctor
I'm trying to setup a blog with Hugo which basically works fine as long as I use Markdown. But since I also have some other website contents (docs) with antora in the repo I want to write all my texts with asciidoc. But I always run into this error, when I try to generate the website from adoc files. Markdown works, but Asciidoc gives this exception:

```<code>sebastian@kobol:~/work/repos/sommerfeld-io/website/blog$ hugo
Start building sites …
hugo v0.92.1-85E2E862 linux/amd64 BuildDate=2022-01-27T11:44:41Z VendorInfo=gohugoio
Error: Error building site: "/home/sebastian/work/repos/sommerfeld-io/website/blog/content/posts/my-second-post.adoc:1:1": access denied: "asciidoctor" is not whitelisted in policy "security.exec.allow"; the current security configuration is:

[security]
  enableInlineShortcodes = false
  [security.exec]
    allow = ['^dart-sass-embedded$', '^go$', '^npx$', '^postcss$']
    osEnv = ['(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$']

  [security.funcs]
    getenv = ['^HUGO_']

  [security.http]
    methods = ['(?i)GET|POST']
    urls = ['.*']

Total in 40 ms
</code>```

Can anyone give me a hint on how I can allow access to asciidoctor from hugo builds?

答:
That's the default Security Policy. You need to edit your config.toml file (or wherever you put your Hugo configuration files) and add a custom security policy.

As a minimum, the custom security policy will be a "cut & paste" of the default, with one or two additional regular expressions added.

For example:

```<code>[security]
enableInlineShortcodes = false

[security.exec]
allow = ["^dart-sass-embedded$", "^go$", "^npx$", "^postcss$", "^asciidoctor$"]
osEnv = ["(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM|RUBYLIB)$"]

[security.funcs]
getenv = ["^HUGO_"]

[security.http]
methods = ["(?i)GET|POST"]
urls = [".*"]
</code>```

I also added the RUBYLIB environment variable to tell Hugo to tell AsciiDoctor where its inline macro extensions live.

Title: Hugo with Asciidoctor

Body:
I'm trying to setup a blog with Hugo which basically works fine as long as I use Markdown. But since I also have some other website contents (docs) with antora in the repo I want to write all my texts with asciidoc. But I always run into this error, when I try to generate the website from adoc files. Markdown works, but Asciidoc gives this exception:

sebastian@kobol:~/work/repos/sommerfeld-io/website/blog$ hugo
Start building sites …
hugo v0.92.1-85E2E862 linux/amd64 BuildDate=2022-01-27T11:44:41Z VendorInfo=gohugoio
Error: Error building site: "/home/sebastian/work/repos/sommerfeld-io/website/blog/content/posts/my-second-post.adoc:1:1": access denied: "asciidoctor" is not whitelisted in policy "security.exec.allow"; the current security configuration is:

[security]
  enableInlineShortcodes = false
  [security.exec]
    allow = ['^dart-sass-embedded$', '^go$', '^npx$', '^postcss$']
    osEnv = ['(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$']

  [security.funcs]
    getenv = ['^HUGO_']

  [security.http]
    methods = ['(?i)GET|POST']
    urls = ['.*']

Total in 40 ms

Can anyone give me a hint on how I can allow access to asciidoctor from hugo builds?

Body:
That's the default Security Policy. You need to edit your config.toml file (or wherever you put your Hugo configuration files) and add a custom security policy.

As a minimum, the custom security policy will be a "cut & paste" of the default, with one or two additional regular expressions added.

For example:

[security]
enableInlineShortcodes = false

[security.exec]
allow = ["^dart-sass-embedded$", "^go$", "^npx$", "^postcss$", "^asciidoctor$"]
osEnv = ["(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM|RUBYLIB)$"]

[security.funcs]
getenv = ["^HUGO_"]

[security.http]
methods = ["(?i)GET|POST"]
urls = [".*"]

I also added the RUBYLIB environment variable to tell Hugo to tell AsciiDoctor where its inline macro extensions live.


问:
First three items of of NSArray into an NSString?
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

```<code>String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored
</code>```

答:
You could try the following (although it's completely untested as I'm away from my Mac)

```<code>int bandCount = 1;
NSString *bands;
for (NSString *band in bandArray) {
    if (bandCount > 3) break;
    if (bandCount == 1) {
        bands = [NSString stringWithFormat:@"%@", band];
    } else {
        bands = [NSString stringWithFormat:@"%@, %@", bands, band];
    }
    bandCount ++;
}
</code>```

Body:
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored

Body:
You could try the following (although it's completely untested as I'm away from my Mac)

int bandCount = 1;
NSString *bands;
for (NSString *band in bandArray) {
    if (bandCount > 3) break;
    if (bandCount == 1) {
        bands = [NSString stringWithFormat:@"%@", band];
    } else {
        bands = [NSString stringWithFormat:@"%@, %@", bands, band];
    }
    bandCount ++;
}


问:
boost:math:factorial2 throws an error while computing double factorial of -1?
The official documentation of boost library in C++ confirms that -1!! is defined. However, when I try to compute the double factorial of -1, it throws the following error
"Error in function boost::math::tgamma result of gamma is too large to represent". I can implement a code based on iteration to compute the same (if it comes to that), but would like to use optimized libraries wherever possible. Any suggestions on rectifying this issue?

```<code>#include <iostream>
#include  <boost/math/special_functions/factorials.hpp>

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}
</code>```

This is the minimal working example.

答:
The function is declared as

```<code>template <class T>
T double_factorial(unsigned i);
</code>```

and unsigned(-1) is a very large number.

Body:
The official documentation of boost library in C++ confirms that -1!! is defined. However, when I try to compute the double factorial of -1, it throws the following error
"Error in function boost::math::tgamma result of gamma is too large to represent". I can implement a code based on iteration to compute the same (if it comes to that), but would like to use optimized libraries wherever possible. Any suggestions on rectifying this issue?

#include <iostream>
#include  <boost/math/special_functions/factorials.hpp>

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}

This is the minimal working example.

Body:
The function is declared as

template <class T>
T double_factorial(unsigned i);

and unsigned(-1) is a very large number.


问:
How to update an existing meeting with Zoom API with restsharp
I am trying to update or reschedule a scheduled meeting or changing the date of a scheduled meeting to the next month in visual studio with restsharp.
This is the link of Zoom API version 2 docs:

https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/meetingUpdate

I can create meeting but I cannot update the meeting. Its not working. I am new so Kindly help me.
Below is my Code:

```<code>public ActionResult EmployeeUpdate(string employee)
    {
        var client = new RestClient("https://api.zoom.us/v2/meetings/{MeetingId}"); //long type
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("authorization", "Bearer " + "ZoomJWTToken");
        request.AddJsonBody(new
        {
            topic = "Future Meeting",
            type = 2,
            start_time = "2022-03-25T6:00:00",
            duration = 30,
            timezone = "Asia/Tashkent",
            password = "password"
        });
        IRestResponse response = client.Execute(request);
        HttpStatusCode statusCode = response.StatusCode;
        int numericStatusCode = (int)statusCode;
        Assert.Equal(204, numericStatusCode);
        return NoContent();
    }
</code>```

答:
This is a PATCH request. Changing the RestRequest should solve the problem. For more examples of how to use the API, see Postman.

Example request from Postman:

```<code>var client = new RestClient("https://api.zoom.us/v2/meetings/:meetingId?occurrence_id=<string>");
client.Timeout = -1;
var request = new RestRequest(Method.PATCH);
request.AlwaysMultipartFormData = true;
request.AddParameter("schedule_for", "<string>");
request.AddParameter("topic", "<string>");
request.AddParameter("type", "2");
request.AddParameter("start_time", "<dateTime>");
request.AddParameter("duration", "<integer>");
request.AddParameter("timezone", "<string>");
request.AddParameter("password", "<string>");
request.AddParameter("agenda", "<string>");
request.AddParameter("tracking_fields", "[{\"field\":\"<string>\",\"value\":\"<string>\"},{\"field\":\"<string>\",\"value\":\"<string>\"}]");
request.AddParameter("recurrence", "{\"type\":\"<integer>\",\"repeat_interval\":\"<integer>\",\"weekly_days\":\"1\",\"monthly_day\":1,\"monthly_week\":\"<integer>\",\"monthly_week_day\":\"<integer>\",\"end_times\":1,\"end_date_time\":\"<dateTime>\"}");
request.AddParameter("settings", "{\"host_video\":\"<boolean>\",\"participant_video\":\"<boolean>\",\"cn_meeting\":false,\"in_meeting\":false,\"join_before_host\":false,\"mute_upon_entry\":false,\"watermark\":false,\"use_pmi\":false,\"approval_type\":2,\"registration_type\":1,\"audio\":\"both\",\"auto_recording\":\"none\",\"enforce_login\":\"<boolean>\",\"enforce_login_domains\":\"<string>\",\"alternative_hosts\":\"<string>\",\"close_registration\":false,\"waiting_room\":false,\"global_dial_in_countries\":[\"<string>\",\"<string>\"],\"global_dial_in_numbers\":[{\"country\":\"<string>\",\"country_name\":\"<string>\",\"city\":\"<string>\",\"number\":\"<string>\",\"type\":\"<string>\"},{\"country\":\"<string>\",\"country_name\":\"<string>\",\"city\":\"<string>\",\"number\":\"<string>\",\"type\":\"<string>\"}],\"contact_name\":\"<string>\",\"contact_email\":\"<string>\",\"registrants_confirmation_email\":\"<boolean>\",\"registrants_email_notification\":\"<boolean>\",\"meeting_authentication\":\"<boolean>\",\"authentication_option\":\"<string>\",\"authentication_domains\":\"<string>\",\"authentication_name\":\"<string>\"}");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
</code>```

Body:
I am trying to update or reschedule a scheduled meeting or changing the date of a scheduled meeting to the next month in visual studio with restsharp.
This is the link of Zoom API version 2 docs:

https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/meetingUpdate

I can create meeting but I cannot update the meeting. Its not working. I am new so Kindly help me.
Below is my Code:

public ActionResult EmployeeUpdate(string employee)
    {
        var client = new RestClient("https://api.zoom.us/v2/meetings/{MeetingId}"); //long type
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("authorization", "Bearer " + "ZoomJWTToken");
        request.AddJsonBody(new
        {
            topic = "Future Meeting",
            type = 2,
            start_time = "2022-03-25T6:00:00",
            duration = 30,
            timezone = "Asia/Tashkent",
            password = "password"
        });
        IRestResponse response = client.Execute(request);
        HttpStatusCode statusCode = response.StatusCode;
        int numericStatusCode = (int)statusCode;
        Assert.Equal(204, numericStatusCode);
        return NoContent();
    }

Body:
This is a PATCH request. Changing the RestRequest should solve the problem. For more examples of how to use the API, see Postman.

Example request from Postman:

var client = new RestClient("https://api.zoom.us/v2/meetings/:meetingId?occurrence_id=<string>");
client.Timeout = -1;
var request = new RestRequest(Method.PATCH);
request.AlwaysMultipartFormData = true;
request.AddParameter("schedule_for", "<string>");
request.AddParameter("topic", "<string>");
request.AddParameter("type", "2");
request.AddParameter("start_time", "<dateTime>");
request.AddParameter("duration", "<integer>");
request.AddParameter("timezone", "<string>");
request.AddParameter("password", "<string>");
request.AddParameter("agenda", "<string>");
request.AddParameter("tracking_fields", "[{\"field\":\"<string>\",\"value\":\"<string>\"},{\"field\":\"<string>\",\"value\":\"<string>\"}]");
request.AddParameter("recurrence", "{\"type\":\"<integer>\",\"repeat_interval\":\"<integer>\",\"weekly_days\":\"1\",\"monthly_day\":1,\"monthly_week\":\"<integer>\",\"monthly_week_day\":\"<integer>\",\"end_times\":1,\"end_date_time\":\"<dateTime>\"}");
request.AddParameter("settings", "{\"host_video\":\"<boolean>\",\"participant_video\":\"<boolean>\",\"cn_meeting\":false,\"in_meeting\":false,\"join_before_host\":false,\"mute_upon_entry\":false,\"watermark\":false,\"use_pmi\":false,\"approval_type\":2,\"registration_type\":1,\"audio\":\"both\",\"auto_recording\":\"none\",\"enforce_login\":\"<boolean>\",\"enforce_login_domains\":\"<string>\",\"alternative_hosts\":\"<string>\",\"close_registration\":false,\"waiting_room\":false,\"global_dial_in_countries\":[\"<string>\",\"<string>\"],\"global_dial_in_numbers\":[{\"country\":\"<string>\",\"country_name\":\"<string>\",\"city\":\"<string>\",\"number\":\"<string>\",\"type\":\"<string>\"},{\"country\":\"<string>\",\"country_name\":\"<string>\",\"city\":\"<string>\",\"number\":\"<string>\",\"type\":\"<string>\"}],\"contact_name\":\"<string>\",\"contact_email\":\"<string>\",\"registrants_confirmation_email\":\"<boolean>\",\"registrants_email_notification\":\"<boolean>\",\"meeting_authentication\":\"<boolean>\",\"authentication_option\":\"<string>\",\"authentication_domains\":\"<string>\",\"authentication_name\":\"<string>\"}");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);


问:
useState Hook inside loop or conditional statement
I was reading the updated react docs whose link is here there is statement related to useState

If you want to useState in a condition or a loop, extract a new
component and put it there.

But what I know by the rules of hooks is that you cannot use hooks inside loops, conditions, or nested functions which is mentioned in the docs here

So can someone give an example of the first sentence, because they didn't gave an example or there.

My question is can we call hooks inside loops and conditional statements ?

答:
What they are saying is that if you want to have something with state in loop component:

```<code>const App = ()=>{
const fields = [someArray]
return(
<div>{fields.map((field)=>{
              const [value, setValue] = useState() //wrong usage!
              return (<input
                       onChange={(e)=>setValue(e)}
                       value={value}
                     />)})})

</div>
)}
</code>```

You need to specify component that you wanna loop in new Component and use hook there:

```<code>const Input = ()=>{
 const [value, setValue]= useState()
 return <input
             onChange={(e)=>setValue(e)}
             value={value}
      />
}
</code>```

and use it in loop

```<code>const App = ()=>{
 const fiels = [someArray];
 return (
  fields.map((field)=>
   <Input />
   )
  )
}

</code>```

Body:
What they are saying is that if you want to have something with state in loop component:

const App = ()=>{
const fields = [someArray]
return(
<div>{fields.map((field)=>{
              const [value, setValue] = useState() //wrong usage!
              return (<input
                       onChange={(e)=>setValue(e)}
                       value={value}
                     />)})})

</div>
)}

You need to specify component that you wanna loop in new Component and use hook there:

const Input = ()=>{
 const [value, setValue]= useState()
 return <input
             onChange={(e)=>setValue(e)}
             value={value}
      />
}

and use it in loop

const App = ()=>{
 const fiels = [someArray];
 return (
  fields.map((field)=>
   <Input />
   )
  )
}


问:
Google Sheets How to Sortn/Filter/Query Top 10 across multiple ranges broken at the rows?
I have data in A1:C10, and then more in A14:C20.  So there are some subtotal rows in between.
How can I get the top 10 across these ranges?  I'm actually just trying to show the C column.  I know I'm supposed to use the Array {}, but not sure how to do that exactly (gives me errors).

I'd also be happy to pull from just one range if I could somehow get top 12 EXCLUDING top 2 (because the top 2 would be the larger sum rows).

Here's what the sortn formula is that's not working:

```<code>=sortn({c1:C10,c14:c20},10,1,{c1:c10,c14:c20},False)
</code>```

This formula works when I only have one range.  But for one Department, I need to pull from two ranges.

I'd also tried query:

```<code>=query({a1:c10,a14:c20},"Select C Order by C Desc Limit 10")
</code>```

but that didn't work.

This is on a work spreadsheet, so I can't share it without doing some anonymizing.

答:
In addition to player0 answer, the reason why SORTN was returning #REF! Error was the size of the input array.
There are 2 issues in that formula:

SORTN input expects a “rectangular” range, meaning that the columns provided must have the same number of rows. Declaring the array as {RANGE1,RANGE2} will return two columns, c1:C10 have 10 rows and c14:c20 have 7 rows.

SORTN also expects that the sort column parameter to be a column index, a single row or a single column of values.

You can refer to the SORTN() function documentation here and documentation on the Array notation here

Body:
I have data in A1:C10, and then more in A14:C20.  So there are some subtotal rows in between.
How can I get the top 10 across these ranges?  I'm actually just trying to show the C column.  I know I'm supposed to use the Array {}, but not sure how to do that exactly (gives me errors).

I'd also be happy to pull from just one range if I could somehow get top 12 EXCLUDING top 2 (because the top 2 would be the larger sum rows).

Here's what the sortn formula is that's not working:

=sortn({c1:C10,c14:c20},10,1,{c1:c10,c14:c20},False)

This formula works when I only have one range.  But for one Department, I need to pull from two ranges.

I'd also tried query:

=query({a1:c10,a14:c20},"Select C Order by C Desc Limit 10")

but that didn't work.

This is on a work spreadsheet, so I can't share it without doing some anonymizing.


问:
Open-source radix/mtrie implementation in C?
I intend to use RADIX / MTRIE as my preferred data-structure for a routing implementation.

Is there a decent open source implementation available (apart from freebsd-net) which I can use for my purpose, or do I need to write one myself?

答:
There is a radix-tree implementation available under the GNU General Public License version 2, or (at your option) any later version:

http://www.gelato.unsw.edu.au/lxr/source/lib/radix-tree.c

OwnerDisplayName: harty

OwnerDisplayName: Andrew Johnson

ContentLicense: CC BY-SA 2.5


问:
How to model a n to m relation with an attribute in Entity framework without adding the extra table
I'm pretty new to the Entity framework and I'm modelling this simple structure:

With this model what I have is a Users class with a property UsersGroups (a collection of UserGroups objects).

I would like to have a Users class with a property like Groups with type Tuple or something like this (a new PriorizedGroup class, etc) that is much more related with the bussines.

Is this possible with the Entity framework?

Thanks in advance.

EDIT: If I were modeling the bussines objects I would create a User class with a Groups property that contained all the groups the user pertains with an extra property to store its priority (with a tuple, with an inherited class, as you wish). The thing is that I feel that the objects created by the Entity framework resemble the SQL structure, not the business structure.

答:
Not directly. EF can map the relation only in the way you see it at the moment but you can add your custom behavior to your partial part of the entity. The simple way is something like

```<code>public partial class Users
{
    public IEnumerable<PrioritizedGroup> Groups
    {
        get
        {
            return UserGroups.Select(ug => new PrioritizedGroup
                                                   {
                                                        Priority = ug.Priority,
                                                        Id = ug.Group.Id,
                                                        Name = ug.Group.Name,
                                                        Description = ug.Group.Description
                                                   })
                             .OrderBy(g => g.Priority);
        }
    }
}
</code>```

To make this happen directly in EF you need some advanced mapping technique which will require you to modify EDMX source code directly (either DefiningQuery or QueryView) and it will make the entity read only (you will need stored procedures for modification).

To make the collection exposed on Users updatable you would probably need to use ObservableCollection and transfer all modifications triggered by ObservableCollection back to original UserGroups collection. Once you have something like that implemented you can hide original collection.

Body:
Not directly. EF can map the relation only in the way you see it at the moment but you can add your custom behavior to your partial part of the entity. The simple way is something like

public partial class Users
{
    public IEnumerable<PrioritizedGroup> Groups
    {
        get
        {
            return UserGroups.Select(ug => new PrioritizedGroup
                                                   {
                                                        Priority = ug.Priority,
                                                        Id = ug.Group.Id,
                                                        Name = ug.Group.Name,
                                                        Description = ug.Group.Description
                                                   })
                             .OrderBy(g => g.Priority);
        }
    }
}

To make this happen directly in EF you need some advanced mapping technique which will require you to modify EDMX source code directly (either DefiningQuery or QueryView) and it will make the entity read only (you will need stored procedures for modification).

To make the collection exposed on Users updatable you would probably need to use ObservableCollection and transfer all modifications triggered by ObservableCollection back to original UserGroups collection. Once you have something like that implemented you can hide original collection.


问:
How do PUT, POST or PATCH request differ ultimately?
The data, being sent over a PUT/PATCH/POST request, ultimately ends up in the database.

Now whether we are inserting a new resource or updating or modifying an existing one - it all depends upon the database operation being carried out.

Even if we send a POST and ultimately perform just an update in the database, it does not impact anywhere at all, isn't it?!

Hence, do they actually differ - apart from a purely conceptual point of view?

答:
It is about the intent of the sender and from my perspective it has  a different behaviour on the server side.

in a nutshell:

POST : creates new data entry on the server (especially with REST)

PUT : updates full data entry on the server (REST) or it creates a new data entry (non REST). The difference to a POST request is that the client specifies the target location on the server.

PATCH : the client requests a partial update (Id and partial data of entry are given). The difference to PUT is that the client sends not the full data back to the server this can save bandwidth.

In general you can use any HTTP request to store data (GET, HEAD, DELETE...) but it is common practice to use POST, PUT, and PATCH for specific and standardized scenarios. Because every developer can understand it later


问:
Could not authenticate you from GoogleOauth2 because "Invalid credentials"
I params the Google subscription with the gem 'omniauth-google-oauth2' and I config the ui and provider + in the devise.rb I put this code config.omniauth :google_oauth2, ENV["GOOGLE_ID"], ENV["GOOGLE_SECRET"], scope: 'email', info_fields: 'email, first_name,last_name', image_size: 'large'

I enter the code in application.yml and I generate contacts APIs + Google + APIs but when I want to connect it like this :
the error message tells me that
Please could you tell what's wrong. Your help is appreciated.

I am a little bit lost.

答:
I was also having the same issue but with my Rails app. So I resolved it by upgrading the omniauth gems by running bundle update devise omniauth omniauth-google-oauth2 in terminal.
Original answer: https://stackoverflow.com/a/62572976/15751045</p>


问:
Why is the output of an adb command different when run from adb shell and run from Android Application?
I am relatively new to android and I just came across adb shell commands which provide a lot of useful things. My issue is that when I execute the command "top -bn1" using adb shell from terminal it gives me a bunch of processes with users - root, system and other users. But when I run the same command from an application using Runtime.getRuntime().exec("top -bn1") the ouput is totally different and only processes for a particular user are displayed.

Here is the adb output -

And here is the code in the app and its output -

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    process = Runtime.getRuntime().exec("top -bn1");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String msg = bufferedReader.lines().collect(Collectors.joining("\n"));
    Log.d("Data", msg);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Can somebody please explain -

Why is there a difference in the outputs as such?

How can I get the entire output by running the command from application?

What all requirements are there for the same?

答:
adb shell is member of a lot of groups so it has a lot of privileges. It is not root, but it is as close as it gets. You can see the list of groups that the shell user is added by running id command from the terminal or check out this answer. On the other hand, your application runs in a sandbox and have very limited privileges. That's why you see a limited info when you run a command from the app code.

If you want to have unlimited access to the system from within your application, you need to request root access. You can do that by running the su command in a rooted phone:

```<code>Runtime.getRuntime().exec("su");
</code>```

Body:
I am relatively new to android and I just came across adb shell commands which provide a lot of useful things. My issue is that when I execute the command "top -bn1" using adb shell from terminal it gives me a bunch of processes with users - root, system and other users. But when I run the same command from an application using Runtime.getRuntime().exec("top -bn1") the ouput is totally different and only processes for a particular user are displayed.

Here is the adb output -

And here is the code in the app and its output -

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    process = Runtime.getRuntime().exec("top -bn1");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String msg = bufferedReader.lines().collect(Collectors.joining("\n"));
    Log.d("Data", msg);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Can somebody please explain -

Why is there a difference in the outputs as such?

How can I get the entire output by running the command from application?

What all requirements are there for the same?

Body:
adb shell is member of a lot of groups so it has a lot of privileges. It is not root, but it is as close as it gets. You can see the list of groups that the shell user is added by running id command from the terminal or check out this answer. On the other hand, your application runs in a sandbox and have very limited privileges. That's why you see a limited info when you run a command from the app code.

If you want to have unlimited access to the system from within your application, you need to request root access. You can do that by running the su command in a rooted phone:

Runtime.getRuntime().exec("su");


问:
compiling 10000 of java project simultaneously
Any one know how to compiling and run huge no of java project in simultaneously(assume request comming every time) can i use for sun jdk for this situation. is there way to distributed compilation? </p>

答:
You can use the ToolProvider api to start a compilation programmatically. (see this tutorial for help)

With that as a starting point, you only need to create the proper abstraction to define what a project is (source folders, classpath etc.) and you have a thin frontend for compiling multiple projects.

I would probably use a ThreadPool to implement the actual compiling:

```<code>ExecutorService threadPool =
    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
</code>```

Or if you can't use threads, use a pool of compilers (or compiler holders) with a library like commons / pool.

Either way, you can have this workflow:

Request comes in

transform request to project definition

either request a free compiler or put the project in a queue

compile

return a handle to the compile job, so the client can poll the status asynchronously

Body:
You can use the ToolProvider api to start a compilation programmatically. (see this tutorial for help)

With that as a starting point, you only need to create the proper abstraction to define what a project is (source folders, classpath etc.) and you have a thin frontend for compiling multiple projects.

I would probably use a ThreadPool to implement the actual compiling:

ExecutorService threadPool =
    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

Or if you can't use threads, use a pool of compilers (or compiler holders) with a library like commons / pool.

Either way, you can have this workflow:

Request comes in

transform request to project definition

either request a free compiler or put the project in a queue

compile

return a handle to the compile job, so the client can poll the status asynchronously


问:
Java inheritance: What is the difference between method overriding and method hiding?
According to the documentation

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

While in case of static methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

So, I have tested the code example shown there with addition of more use cases:

The super class Animal:

public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
```
<p>The subclass <code>Cat</code>:</p>
<pre class="lang-java prettyprint-override"><code>public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal animal = new Animal();
        Animal.testClassMethod();
        Cat.testClassMethod();
        animal.testInstanceMethod();
        myAnimal.testInstanceMethod();
    }
}
</code>```

The output here is:

The static method in Animal

The static method in Cat

The instance method in Animal

The instance method in Cat

So, I still see no actual difference between overriding the superclass instance method with subclass instance method with the same signature and overriding (hiding) the superclass static (class) method with subclass static method with the same signature.

What am I missing here?

答: You can call super() in an object method (not static), but you can not call super in a static method because there is no "super" object to call to.</p>

Body:
According to the documentation

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

While in case of static methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

So, I have tested the code example shown there with addition of more use cases:

The super class Animal:

public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}

The subclass Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal animal = new Animal();
        Animal.testClassMethod();
        Cat.testClassMethod();
        animal.testInstanceMethod();
        myAnimal.testInstanceMethod();
    }
}

The output here is:

The static method in Animal

The static method in Cat

The instance method in Animal

The instance method in Cat

So, I still see no actual difference between overriding the superclass instance method with subclass instance method with the same signature and overriding (hiding) the superclass static (class) method with subclass static method with the same signature.

What am I missing here?


问:
I am new to Python and I wonder what is wrong with this code
I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]  and not if name[1], but what else is wrong with it?

Code:

```<code>def make_list(number):
    names = []
    for item in number:
        names.append(input("Enter your name with a capital letter."))
        print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [1] == 'A':
        print("Name", name, "starts with A")

</code>```

Compiler says:

```<code>Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable
</code>```

答: for item in number: looks like you are attemping to repeat the loop number times. In python you do that like this: for item in range(0, number):. item will range from 0 to number-1

Body:
I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]  and not if name[1], but what else is wrong with it?

Code:

def make_list(number):
    names = []
    for item in number:
        names.append(input("Enter your name with a capital letter."))
        print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [1] == 'A':
        print("Name", name, "starts with A")

Compiler says:

Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable


问:
React/Jest - How to mock the behavior of event.preventDefault and event.stopPropagation
I have an input field as follows:

```<code><Input name="score" type="number" className={cx(['input-width'])} value={this.state.score} isIncomplete={false} isInvalid={this.state.isScoreInvalid} min="0" max="100" onKeyPress={this.handleInput} onChange={this.updateValue} onBlur={this.updateScoreInvalidState} />
</code>```

Below function gets called OnKeypress

```<code>handleInput(event) {
    const charCode = (typeof event.which === 'number') ? event.which : event.keyCode;

    if (charCode === 45 || charCode === 46) {
      console.log("Here-------------");
      event.preventDefault();
      event.stopPropagation();
    }
  }
</code>```

Below function gets called onChange

```<code>updateValue(event) {
    this.setState({ [event.target.name]: event.target.value });
}
</code>```

I want to test this behavior:
If invalid input: '-' OR '.'
Ignore the input and do not update state variable score.
Have the following test.

```<code>it('should render input field correctly with invalid character as input', () => {
    const wrapper = shallowWithIntl(<TestView {...testProps} />).first().shallow();
    const score = wrapper.find('Input[name="score"]');
    const onKeypressEvent = {
      preventDefault: jest.fn(),
      stopPropagation: jest.fn(),
      which: 45,
      target: { name: 'score', value: '-' },
    };
    const onChangeEvent = {
      target: { name: 'score', value: '-' },
    };

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);

    score.simulate('keypress', onKeypressEvent);
    score.simulate('change', onChangeEvent);
    wrapper.update();

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);
  });
</code>```

Test is not working as expected. It is not preventing the event.

How to test this functionality? Thanks!

答:
```<code>const event = {
    preventDefault: jest.fn(),
    clipboardData: {
      getData: () => pasteValue,
    },
  } as unknown as React.ClipboardEvent<HTMLInputElement>;
</code>```

Body:
I have an input field as follows:

<Input name="score" type="number" className={cx(['input-width'])} value={this.state.score} isIncomplete={false} isInvalid={this.state.isScoreInvalid} min="0" max="100" onKeyPress={this.handleInput} onChange={this.updateValue} onBlur={this.updateScoreInvalidState} />

Below function gets called OnKeypress

handleInput(event) {
    const charCode = (typeof event.which === 'number') ? event.which : event.keyCode;

    if (charCode === 45 || charCode === 46) {
      console.log("Here-------------");
      event.preventDefault();
      event.stopPropagation();
    }
  }

Below function gets called onChange

updateValue(event) {
    this.setState({ [event.target.name]: event.target.value });
}

I want to test this behavior:
If invalid input: '-' OR '.'
Ignore the input and do not update state variable score.
Have the following test.

it('should render input field correctly with invalid character as input', () => {
    const wrapper = shallowWithIntl(<TestView {...testProps} />).first().shallow();
    const score = wrapper.find('Input[name="score"]');
    const onKeypressEvent = {
      preventDefault: jest.fn(),
      stopPropagation: jest.fn(),
      which: 45,
      target: { name: 'score', value: '-' },
    };
    const onChangeEvent = {
      target: { name: 'score', value: '-' },
    };

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);

    score.simulate('keypress', onKeypressEvent);
    score.simulate('change', onChangeEvent);
    wrapper.update();

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);
  });

Test is not working as expected. It is not preventing the event.

How to test this functionality? Thanks!


问:
Debug your functions while running unit tests?
I am using Visual Studio 2022; when I click "Test -> Run All Tests," the breakpoints in the code that is actually being tested are not being hit. If I click "Test -> Debug All Tests," it debugs just the test method and not my actual code. I want to debug the actual code. Is there any way to do that? There is an answer that says I could do that using 'Tests in Current Context' option but I can't seem to find that.</p>

答: Do you have a breakpoint in your actual code? if you do, IDE will hit that point in your code while the test is running.</p>


答:
Hiding it means that you can't call super.method() in the sub class's implementation.

So for example

```<code>class Cat extends Animal {
    public static void testClassMethod() {
        super.testClassMethod(); //this is not possible
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        super.testInstanceMethod(); //this is fine
        System.out.println("The instance method in Cat");
    }

}
</code>```

Title: Java inheritance: What is the difference between method overriding and method hiding?

Body:
Hiding it means that you can't call super.method() in the sub class's implementation.

So for example

class Cat extends Animal {
    public static void testClassMethod() {
        super.testClassMethod(); //this is not possible
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        super.testInstanceMethod(); //this is fine
        System.out.println("The instance method in Cat");
    }

}


问:
angular nativeElement.value does not appear in html
I work with angular and have an autocomplete input in html

```<code>   <mat-form-field style="width: 100%;" class="example-full-width">
        <mat-label>Application *</mat-label>
        <input type="text"
               placeholder="Pick one"
               aria-label="Application *"
               matInput
               formControlName="application"
               [matAutocomplete]="autoApp"
               ngbTooltip="{{atleastnumbercharacters}}"
               #applicationRef>
        <mat-autocomplete #autoApp="matAutocomplete" [displayWith]="getApplication.bind(this)">
            <mat-option (onSelectionChange)="initializeEnvironments(app)" *ngFor="let app of applications" [value]="app.id">
                {{app.name}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
</code>```

In my component I reference the input by

```<code>@ViewChild("applicationRef") applicationRef: ElementRef;
</code>```

But when I set the value in the input

```<code>this.applicationRef.nativeElement.value = applicationDto.name;
</code>```

it does not appear in html. Could you help me ?

答:
I found the solution. I forgot to tell you that I set

```<code>this.applicationRef.nativeElement.value = applicationDto.name;
</code>```

in ngAfterViewInit

The solution is the following:

```<code>setTimeOut( () => {this.applicationRef.nativeElement.value = applicationDto.name;});
</code>```

Body:
I work with angular and have an autocomplete input in html

   <mat-form-field style="width: 100%;" class="example-full-width">
        <mat-label>Application *</mat-label>
        <input type="text"
               placeholder="Pick one"
               aria-label="Application *"
               matInput
               formControlName="application"
               [matAutocomplete]="autoApp"
               ngbTooltip="{{atleastnumbercharacters}}"
               #applicationRef>
        <mat-autocomplete #autoApp="matAutocomplete" [displayWith]="getApplication.bind(this)">
            <mat-option (onSelectionChange)="initializeEnvironments(app)" *ngFor="let app of applications" [value]="app.id">
                {{app.name}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>

In my component I reference the input by

@ViewChild("applicationRef") applicationRef: ElementRef;

But when I set the value in the input

this.applicationRef.nativeElement.value = applicationDto.name;

it does not appear in html. Could you help me ?

Body:
I found the solution. I forgot to tell you that I set

this.applicationRef.nativeElement.value = applicationDto.name;

in ngAfterViewInit

The solution is the following:

setTimeOut( () => {this.applicationRef.nativeElement.value = applicationDto.name;});


问:
What is the difference between duration and delay on Ranorex?
I would like to learn difference between Duration and Delay terms on Ranorex tool. Here is an image from my exercise :

Thanks in advance.

答:
Delay

A Delay is just a normal action in Ranorex. Other Actions are Mouse, Key Sequence, Validation, ...

It does what the name says. Once this action is executed, it simply delays the execution of the next action for an exact amount of time.

Duration

A Duration is a certain property that all Actions have. Other properties of Actions are Continue on fail, Enabled, ...

The tooltip of the Duration property in Ranorex Studio 10.1.2 says: "The amount of time the entire action takes to execute, including wait time before the next action starts. Does not influence how fast the action itself is performed in the AUT. Example: For a Mouse click action with 10s duration, the click performs in a few ms, but Ranorex Studio then waits the full 10s before it executes the next action, effectively adding a delay. 0ms performs the action and then immediately starts the next action (may cause issues if the AUT isn't highly responsive). Duration does NOT include effective timeout value of a repository item linked to the action.