问:
Extracting string of dates in a big query
I have used the below code  </p>

```<code>select --split( INDIVIDUAL_NAMES, '->') as Assigned_to_individual,

regexp_extract( split( INDIVIDUAL_NAMES, '->'),r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)') from [table name ]where _ID  in('071632')
</code>```

<p>Here we need to extract date and i have given it a try by using d so it gives me numeric fields but this is not giving me complete date. </p>

答:
Below is for BigQuery Standard SQL

#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_timestamp
FROM yourTable, UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item
-- ORDER BY 3
```

<p>above can be slightly simplified to remove redundant portions - for example as   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', date_as_string) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', date_as_string) AS date_as_timestamp
FROM yourTable,
  UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item,
  UNNEST([REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')]) AS date_as_string
-- ORDER BY 3
</code>```

Output is as below

id  name        date_as_string          date_as_datetime    date_as_timestamp
1   Start       null                    null                null
1   Akumar      01/06/2017 08:08:44 PM  2017-01-06T20:08:44 2017-01-06 20:08:44 UTC
1   Akumar      01/30/2017 10:34:33 AM  2017-01-30T10:34:33 2017-01-30 10:34:33 UTC
1   Akumar      03/15/2017 02:10:12 PM  2017-03-15T14:10:12 2017-03-15 14:10:12 UTC
1   Akumar      03/23/2017 12:42:52 PM  2017-03-23T12:42:52 2017-03-23 12:42:52 UTC
1   Akumar      06/20/2017 12:52:27 PM  2017-06-20T12:52:27 2017-06-20 12:52:27 UTC
1               06/27/2017 05:30:48 PM  2017-06-27T17:30:48 2017-06-27 17:30:48 UTC
1   Sneha Singh 06/28/2017 03:11:34 AM  2017-06-28T03:11:34 2017-06-28 03:11:34 UTC
1               11/11/2016 08:24:24 AM  2016-11-11T08:24:24 2016-11-11 08:24:24 UTC
1   Akumar      11/11/2016 11:15:33 AM  2016-11-11T11:15:33 2016-11-11 11:15:33 UTC
```

<blockquote>
  <p>would be really great if you can suggest a similar instance in legacy sql  </p>
</blockquote>

<p>You can try below for BigQuery Legacy SQL  </p>

<pre class="lang-sql prettyprint-override"><code>#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM yourTable
  ), item)
)
-- ORDER BY date_as_string
</code>```

You can test it with dummy data you provided as below

#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM (
      SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
    ) AS yourTable
  ), item)
)
ORDER BY date_as_string
```

Body:
I have used the below code

select --split( INDIVIDUAL_NAMES, '->') as Assigned_to_individual,

regexp_extract( split( INDIVIDUAL_NAMES, '->'),r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)') from [table name ]where _ID  in('071632')

Here we need to extract date and i have given it a try by using d so it gives me numeric fields but this is not giving me complete date.

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_timestamp
FROM yourTable, UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item
-- ORDER BY 3

above can be slightly simplified to remove redundant portions - for example as

#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', date_as_string) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', date_as_string) AS date_as_timestamp
FROM yourTable,
  UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item,
  UNNEST([REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')]) AS date_as_string
-- ORDER BY 3

Output is as below

id  name        date_as_string          date_as_datetime    date_as_timestamp
1   Start       null                    null                null
1   Akumar      01/06/2017 08:08:44 PM  2017-01-06T20:08:44 2017-01-06 20:08:44 UTC
1   Akumar      01/30/2017 10:34:33 AM  2017-01-30T10:34:33 2017-01-30 10:34:33 UTC
1   Akumar      03/15/2017 02:10:12 PM  2017-03-15T14:10:12 2017-03-15 14:10:12 UTC
1   Akumar      03/23/2017 12:42:52 PM  2017-03-23T12:42:52 2017-03-23 12:42:52 UTC
1   Akumar      06/20/2017 12:52:27 PM  2017-06-20T12:52:27 2017-06-20 12:52:27 UTC
1               06/27/2017 05:30:48 PM  2017-06-27T17:30:48 2017-06-27 17:30:48 UTC
1   Sneha Singh 06/28/2017 03:11:34 AM  2017-06-28T03:11:34 2017-06-28 03:11:34 UTC
1               11/11/2016 08:24:24 AM  2016-11-11T08:24:24 2016-11-11 08:24:24 UTC
1   Akumar      11/11/2016 11:15:33 AM  2016-11-11T11:15:33 2016-11-11 11:15:33 UTC

would be really great if you can suggest a similar instance in legacy sql

You can try below for BigQuery Legacy SQL

#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM yourTable
  ), item)
)
-- ORDER BY date_as_string

You can test it with dummy data you provided as below

#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM (
      SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
    ) AS yourTable
  ), item)
)
ORDER BY date_as_string


来源: stackexchange

问:
Group By vs. Join which one takes longer?
(This question is for self-study).

I have two tables.

A - a table containing the following columns: user, money

B - a table containing the following columns: user, number

money is the dollar amount that the user spent
number is the number of items that the user purchased

A is slightly bigger than B, and A contains all users that B contains while B is missing some users that A has, but A isn't much bigger than B either, like 1.1~1.2 times the size of B.

I wanna have create the table containing the following 3 columns: user, money, number

If the user is not present in table B, then we just use 0 as number.

There're two ways of doing it.

```<code>Select A.user, A.money, case when B.number is null then 0 else B.number end
as number from A left join B on A.user=B.user

Select user, max(money), max(number) from
((Select user, money, 0 as number from A)
union all (Select user, 0 as money, number from B))
group by user
</code>```

I was just curious about how to figure out which query would take less time and memory. Is there a good way to calculate it based on the size of tables A or B?

答:
The first query should be written as:

```<code>Select A.user, A.money,
       coalesce(B.number, 0) as number
from A left join
     B
     on A.user = B.user;
</code>```

With an index on B(user) or B(user, number) this should be the fastest way to do what you want. Without an index there is an "it depends".  You should try on your data.  But a reasonable database will probably do a hash-join for the join, and be faster than the equivalent aggregation.

In addition, doing the union all is probably going to preclude the use of indexes.  The resulting aggregation algorithm is going to be slower than a join using an index.

ContentLicense: CC BY-SA 3.0

Body:
(This question is for self-study).

I have two tables.

A - a table containing the following columns: user, money

B - a table containing the following columns: user, number

money is the dollar amount that the user spent
number is the number of items that the user purchased

A is slightly bigger than B, and A contains all users that B contains while B is missing some users that A has, but A isn't much bigger than B either, like 1.1~1.2 times the size of B.

I wanna have create the table containing the following 3 columns: user, money, number

If the user is not present in table B, then we just use 0 as number.

There're two ways of doing it.

Select A.user, A.money, case when B.number is null then 0 else B.number end
as number from A left join B on A.user=B.user

Select user, max(money), max(number) from
((Select user, money, 0 as number from A)
union all (Select user, 0 as money, number from B))
group by user

I was just curious about how to figure out which query would take less time and memory. Is there a good way to calculate it based on the size of tables A or B?

Body:
The first query should be written as:

Select A.user, A.money,
       coalesce(B.number, 0) as number
from A left join
     B
     on A.user = B.user;

With an index on B(user) or B(user, number) this should be the fastest way to do what you want. Without an index there is an "it depends".  You should try on your data.  But a reasonable database will probably do a hash-join for the join, and be faster than the equivalent aggregation.

In addition, doing the union all is probably going to preclude the use of indexes.  The resulting aggregation algorithm is going to be slower than a join using an index.


问:
common error page in ASP.NET
How to setup a common error page in ASP.NET website?
Also how to handel the error in Data Access Layer by common error page?</p>

答:
here i am explaining the way to implement a custom error page feature.

Step by step implementation

Creating Error Page : Develop an error page (the page that has to be displayed when error occurs)  in the root directory. Lets think that the name of the error page is ErrorPage.aspx

Configuring Web.Config :  write the following code in Web.Config

```<code> <configuration>
 <system.web>
 <customErrors mode="On" defaultRedirect="~\ErrorPage.aspx"/>
 </system.web>
 </configuration>
</code>```

Thats it!!! Now if any error occurs it will redirect to the error page. Now Sometimes we need to display the error. In that case we can write few lines of code in Global.asax

```<code>       void Application_Error(object sender, EventArgs e)
       {
            Exception ex = Server.GetLastError().GetBaseException();
            Session["LastException"] = ex.ToString();
       }
</code>```

As the exception has been captured and stored in the Session now we can show the message from the session. So we can write the following lines in ErrorPage.aspx.cs

```<code>            protected void Page_Load(object sender, EventArgs e)
            {
                 lblDisplayError.Text = Session["LastException"].ToString();

            }
</code>```

And we will be able to see the error on the label of ErrorPage.
Hope it will work fine.

Thanks

Pritom Nandy

OwnerDisplayName: Chetan

ContentLicense: CC BY-SA 2.5

Title: common error page in ASP.NET

LastEditorDisplayName: ScarletGarden

Body:
here i am explaining the way to implement a custom error page feature.

Step by step implementation

Creating Error Page : Develop an error page (the page that has to be displayed when error occurs)  in the root directory. Lets think that the name of the error page is ErrorPage.aspx

Configuring Web.Config :  write the following code in Web.Config

 <configuration>
 <system.web>
 <customErrors mode="On" defaultRedirect="~\ErrorPage.aspx"/>
 </system.web>
 </configuration>

Thats it!!! Now if any error occurs it will redirect to the error page. Now Sometimes we need to display the error. In that case we can write few lines of code in Global.asax

       void Application_Error(object sender, EventArgs e)
       {
            Exception ex = Server.GetLastError().GetBaseException();
            Session["LastException"] = ex.ToString();
       }

As the exception has been captured and stored in the Session now we can show the message from the session. So we can write the following lines in ErrorPage.aspx.cs

            protected void Page_Load(object sender, EventArgs e)
            {
                 lblDisplayError.Text = Session["LastException"].ToString();

            }

And we will be able to see the error on the label of ErrorPage.
Hope it will work fine.

Thanks

Pritom Nandy


问:
How to install eZ Platform via composer
How do you install eZ Platform?

I'd like to get starting using it and I hear that the best way is to use composer. The problem for me is I've not used either before :\

Note: This is a first post to the new stackoverflow tag: ezplatform. We needed this tag to be created for future support needs and want to ask a good and common first time user question make it clear to future users that they can use the ezplatform tag here on stackoverflow to ask questions specific to eZ Platform (and not eZ Publish). I realize that this is a rather poor quality first question for the tag and for that I do apologize. Please try to understand.

答: Just a note here, you can also install eZ Platform with eZ Launchpad now https://ezsystems.github.io/launchpad/ (all on top of Docker)</p>

Title: How to install eZ Platform via composer


问:
VBA EXCEL Merging Rows in one Columns
So I have a column which lists through different modules, with some repeating for 5 rows, some for 20. I am trying to merge these through VBA however something is wrong with my code. Here is the Sub I am using for this, I have commented where the error comes after i debugged it line by line. Would appreciate any input on this error!

Thanks guys!

Notes:

i starts on 7 as that is the row where the module records start from.

```<code>Sub ReMergeECURowsMPNT()

Dim wsMPNT As Worksheet
Set wsMPNT = Worksheets("Module Part Number Tracker")

Dim lrowMPNT As Long
lrowMPNT = CRC.LastRowInMPNT

Dim i As Long
Dim j As Long

Dim sameRows As Boolean
sameRows = True

For i = 7 To lrowMPNT
    If StrComp(Cells(i, 3), Cells(i + 1, 3), vbTextCompare) Then

        sameRows = False

    End If

    If sameRows = False Then
        With wsMPNT
            .Range(Cells(i, 3), Cells(i + 1, 3)).Merge        '''Application defined error on this line
        End With
    End If

    sameRows = True
Next i
</code>```

End Sub

答:
Unless DisplayAlerts is set as False, you should typically get a prompt like "The selection contains multiple data values. Merging into one cell will keep the upper-left most data only.", and if clicked "Cancel" instead of "Ok", VBA will throw an "Application-defined or object-defined error".

Also, check the line lrowMPNT = CRC.LastRowInMPNT. If you are looking for merging "Column C", you may try something as simple as this:

```<code>Sub ReMergeECURowsMPNT()
    Application.DisplayAlerts = False
    Dim wsMPNT As Worksheet, lrowMPNT As Long, i As Long, j As Long
    Set wsMPNT = Worksheets("Module Part Number Tracker")
    wsMPNT.Select
    lrowMPNT = wsMPNT.UsedRange.Row - 1 + wsMPNT.UsedRange.Rows.Count
    For i = 7 To lrowMPNT
        If Cells(i, 3) = Cells(i + 1, 3) Then
            j = j + 1
        ElseIf j > 0 Then
            Range(Cells(i - j, 3), Cells(i, 3)).Merge
            j = 0
        End If
    Next i
    Application.DisplayAlerts = True
End Sub
</code>```

Title: VBA EXCEL Merging Rows in one Columns

Body:
So I have a column which lists through different modules, with some repeating for 5 rows, some for 20. I am trying to merge these through VBA however something is wrong with my code. Here is the Sub I am using for this, I have commented where the error comes after i debugged it line by line. Would appreciate any input on this error!

Thanks guys!

Notes:

i starts on 7 as that is the row where the module records start from.

Sub ReMergeECURowsMPNT()

Dim wsMPNT As Worksheet
Set wsMPNT = Worksheets("Module Part Number Tracker")

Dim lrowMPNT As Long
lrowMPNT = CRC.LastRowInMPNT

Dim i As Long
Dim j As Long

Dim sameRows As Boolean
sameRows = True

For i = 7 To lrowMPNT
    If StrComp(Cells(i, 3), Cells(i + 1, 3), vbTextCompare) Then

        sameRows = False

    End If

    If sameRows = False Then
        With wsMPNT
            .Range(Cells(i, 3), Cells(i + 1, 3)).Merge        '''Application defined error on this line
        End With
    End If

    sameRows = True
Next i

End Sub

Body:
Unless DisplayAlerts is set as False, you should typically get a prompt like "The selection contains multiple data values. Merging into one cell will keep the upper-left most data only.", and if clicked "Cancel" instead of "Ok", VBA will throw an "Application-defined or object-defined error".

Also, check the line lrowMPNT = CRC.LastRowInMPNT. If you are looking for merging "Column C", you may try something as simple as this:

Sub ReMergeECURowsMPNT()
    Application.DisplayAlerts = False
    Dim wsMPNT As Worksheet, lrowMPNT As Long, i As Long, j As Long
    Set wsMPNT = Worksheets("Module Part Number Tracker")
    wsMPNT.Select
    lrowMPNT = wsMPNT.UsedRange.Row - 1 + wsMPNT.UsedRange.Rows.Count
    For i = 7 To lrowMPNT
        If Cells(i, 3) = Cells(i + 1, 3) Then
            j = j + 1
        ElseIf j > 0 Then
            Range(Cells(i - j, 3), Cells(i, 3)).Merge
            j = 0
        End If
    Next i
    Application.DisplayAlerts = True
End Sub


问:
Why can I extend a class at runtime by initializing another class by ClassName.__init__(self)
I was wondering why can I extend a class at runtime using the following code:

```<code>class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"

test = ClassA()
print(dir(test))
</code>```

This gives me access to test.value and test.punk. But I don't understand why. Thanks.

答:
ClassB.__init__ doesn't make any use of self that assumes it is actually an instance of ClassB, so explicitly calling it on an instance of ClassA is legal, though a bit odd. It's not really any different than if you had written

```<code>class ClassA:
    def __init__(self):
        self.value = "1"
        punker(self)

def punker(obj):
    obj.punk = "Punk"
</code>```

punker isn't really much different than ClassB.__init__, a fact you can see even more readily by defining ClassB as

```<code>class ClassB:
    __init__ = punker
</code>```

Body:
I was wondering why can I extend a class at runtime using the following code:

class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"

test = ClassA()
print(dir(test))

This gives me access to test.value and test.punk. But I don't understand why. Thanks.

Body:
ClassB.__init__ doesn't make any use of self that assumes it is actually an instance of ClassB, so explicitly calling it on an instance of ClassA is legal, though a bit odd. It's not really any different than if you had written

class ClassA:
    def __init__(self):
        self.value = "1"
        punker(self)

def punker(obj):
    obj.punk = "Punk"

punker isn't really much different than ClassB.__init__, a fact you can see even more readily by defining ClassB as

class ClassB:
    __init__ = punker


问:
Identify the same user in Google Analytics when use a Webapp and a desktop client (with measurement protocol)
I have an mixed application, where a part is a WebApp and a part is a desktop client. I track the user with google analytics. On the desktop client, i do this with the measurement protocol.

Now, the problem is, that in Google analytics, I see the usage of both parts, but a user is identify not as the same, when it use the web app and the desktop client.

Is there an option, in the measurement protocol, to identify the user, that google analytics can match it to the webapp user and knows that it is the same user?

答:
You can enable the User ID in Google Analytics, however you'll need to do the detection yourself.

If your users have a sign-in of some kind, you can just use their ID and pass it to Google Analytics. If your users do not sign in, you will need to manage it via some kind of fingerprinting yourself and assign an ID.

Here is some more info from the GA documentation.

```<code>ga('create', 'UA-XXXXX-Y', 'auto', {
  userId: USER_ID
});
ga('send', 'pageview');
</code>```

I've never used this for cross-device user tracking, so I can't say how it will affect certain reports such as Device.

Body:
You can enable the User ID in Google Analytics, however you'll need to do the detection yourself.

If your users have a sign-in of some kind, you can just use their ID and pass it to Google Analytics. If your users do not sign in, you will need to manage it via some kind of fingerprinting yourself and assign an ID.

Here is some more info from the GA documentation.

ga('create', 'UA-XXXXX-Y', 'auto', {
  userId: USER_ID
});
ga('send', 'pageview');

I've never used this for cross-device user tracking, so I can't say how it will affect certain reports such as Device.


答:
You didn't extend ClassB, you just executed ClassB.__init__() method over your ClassA instance. Python doesn't prevent you from adding new properties to any object, case in point:

```<code>class ClassA:
    def __init__(self):
        self.value = "1"

test = ClassA()
test.punk = "Punk"
print(dir(test))
</code>```

But that's not extending - that property is available only to your test instance. Methods won't be inherited, for example.

```<code>class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"
    def foo(self):
        print("BAR!")

test = ClassA()
print(test.punk)  # OK
test.foo()  # ERR!
</code>```

Title: Why can I extend a class at runtime by initializing another class by ClassName.__init__(self)

Body:
You didn't extend ClassB, you just executed ClassB.__init__() method over your ClassA instance. Python doesn't prevent you from adding new properties to any object, case in point:

class ClassA:
    def __init__(self):
        self.value = "1"

test = ClassA()
test.punk = "Punk"
print(dir(test))

But that's not extending - that property is available only to your test instance. Methods won't be inherited, for example.

class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"
    def foo(self):
        print("BAR!")

test = ClassA()
print(test.punk)  # OK
test.foo()  # ERR!


问:
Creating dynamic array name in python numpy
There are already several similar questions on SO, for example How do I create a variable number of variables?. But I think my question is bit different one.

I want to create dynamic array names. MATLAB (and Octave) has built in data structure cell array that can do the job. For example code creates A{1} to A{10} variables dynamically. var1 is 'dynamic input' to program.

```<code>var1=10;
for j=1:1:var1
  A{j} = {}; %creating empty cell
end
%resizing empty cells using a loop, arrays can be of different size
</code>```

As answered in the first question, python has dictionary to do this task. However, I am working with huge amount of data stored in form of arrays, and need to use numpy array as they are faster than python built in lists. Any suggestions?

Update:
I want to create variable size arrays afterwards.

答:
You can use numpy.memmap to create those kind of arrays.

data = np.arange(12, dtype='float32')

data.resize((3,4))

numpy.memmap documentation here.

Body:
There are already several similar questions on SO, for example How do I create a variable number of variables?. But I think my question is bit different one.

I want to create dynamic array names. MATLAB (and Octave) has built in data structure cell array that can do the job. For example code creates A{1} to A{10} variables dynamically. var1 is 'dynamic input' to program.

var1=10;
for j=1:1:var1
  A{j} = {}; %creating empty cell
end
%resizing empty cells using a loop, arrays can be of different size

As answered in the first question, python has dictionary to do this task. However, I am working with huge amount of data stored in form of arrays, and need to use numpy array as they are faster than python built in lists. Any suggestions?

Update:
I want to create variable size arrays afterwards.


问:
convert base64 bytes to image asp.net
I am trying to convert base64 bytes to an image .

This is the code i am using :

```<code>    Private Function Base64ToImage(ByVal base64 As String) As System.Drawing.Image
    Dim img As System.Drawing.Image
    Dim ms As MemoryStream = New MemoryStream
    Dim b1 As String = base64.Replace("_", "/")
    Dim b2 As String = base64.Replace("-", "+")
    Dim b64 As String = b2.Replace(" ", "+")

    Dim bb As String = b64.Substring(0, b64.Length - 3)

    Dim b() As Byte
    b = Convert.FromBase64String(b64)
    ms = New System.IO.MemoryStream(b)
    img = System.Drawing.Image.FromStream(ms)

    Return img
End Function
</code>```

This is the error i get :

The input is not a valid Base-64 string as it contains a non-base 64
  character, more than two padding characters, or an illegal character
  among the padding characters.

where is the problem ??

答: Remove the "data:image/png;base64,"  (or whatever is in there before the long string) before you try to convert it.</p>

Title: convert base64 bytes to image asp.net

Body:
I am trying to convert base64 bytes to an image .

This is the code i am using :

    Private Function Base64ToImage(ByVal base64 As String) As System.Drawing.Image
    Dim img As System.Drawing.Image
    Dim ms As MemoryStream = New MemoryStream
    Dim b1 As String = base64.Replace("_", "/")
    Dim b2 As String = base64.Replace("-", "+")
    Dim b64 As String = b2.Replace(" ", "+")

    Dim bb As String = b64.Substring(0, b64.Length - 3)

    Dim b() As Byte
    b = Convert.FromBase64String(b64)
    ms = New System.IO.MemoryStream(b)
    img = System.Drawing.Image.FromStream(ms)

    Return img
End Function

This is the error i get :

The input is not a valid Base-64 string as it contains a non-base 64
  character, more than two padding characters, or an illegal character
  among the padding characters.

where is the problem ??


问:
schema validation with msxml in delphi
I'm trying to validate an XML file against the schemas it references. (Using Delphi and MSXML2_TLB.) The (relevant part of the) code looks something like this:

```<code>procedure TfrmMain.ValidateXMLFile;
var
    xml: IXMLDOMDocument2;
    err: IXMLDOMParseError;
    schemas: IXMLDOMSchemaCollection;
begin
    xml := ComsDOMDocument.Create;
    if xml.load('Data/file.xml') then
    begin
        schemas := xml.namespaces;
        if schemas.length > 0 then
        begin
            xml.schemas := schemas;
            err := xml.validate;
        end;
    end;
end;
</code>```

This has the result that cache is loaded (schemas.length > 0), but then the next assignment raises an exception: "only XMLSchemaCache-schemacollections can be used."

How should I go about this?

答:
I have previously validated XML documents using the following code:</p>

```<code>Uses
  Classes,
  XMLIntf,
  SysUtils;

Function ValidateXMLDoc(aXmlDoc: IXMLDocument): boolean;
var
  validateDoc: IXMLDocument;
begin
  validateDoc := TXMLDocument.Create(nil);

  validateDoc.ParseOptions := [poResolveExternals, poValidateOnParse];
  validateDoc.XML := aXmlDoc.XML;

  validateDoc.Active := true;
  Result := True;
end;
</code>```

OwnerDisplayName: Miel

Title: schema validation with msxml in delphi

Body:
I'm trying to validate an XML file against the schemas it references. (Using Delphi and MSXML2_TLB.) The (relevant part of the) code looks something like this:

procedure TfrmMain.ValidateXMLFile;
var
    xml: IXMLDOMDocument2;
    err: IXMLDOMParseError;
    schemas: IXMLDOMSchemaCollection;
begin
    xml := ComsDOMDocument.Create;
    if xml.load('Data/file.xml') then
    begin
        schemas := xml.namespaces;
        if schemas.length > 0 then
        begin
            xml.schemas := schemas;
            err := xml.validate;
        end;
    end;
end;

This has the result that cache is loaded (schemas.length > 0), but then the next assignment raises an exception: "only XMLSchemaCache-schemacollections can be used."

How should I go about this?

LastEditorDisplayName: Miel

Body:
I have previously validated XML documents using the following code:

Uses
  Classes,
  XMLIntf,
  SysUtils;

Function ValidateXMLDoc(aXmlDoc: IXMLDocument): boolean;
var
  validateDoc: IXMLDocument;
begin
  validateDoc := TXMLDocument.Create(nil);

  validateDoc.ParseOptions := [poResolveExternals, poValidateOnParse];
  validateDoc.XML := aXmlDoc.XML;

  validateDoc.Active := true;
  Result := True;
end;

OwnerDisplayName: BennyBechDk


问:
ansible playbook syntax error
Ansible playbook throwing a syntax error, however everything looks correct.
What can be the issue on the role?

ERROR:

```<code>The error appears to have been in '/home/Desktop/playbooks/xx.yml': line 6, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

roles:
    - role: chronos_task
      ^ here
</code>```

CODE

```<code>---
- hosts: localhost
  connection: local
  gather_facts: no
  roles:
    - role: chronos_task
      no_log: true
      chronos_url: 'http://{{ chronos_host }}:{{ chronos_port }}'
      chronos_tasks:
        - type: iso8601
</code>```

答:
What can be the issue on the role?

The issue might be that the chronos_task role is not present in roles' path.

This is the exact error message you get in such a situation.

Title: ansible playbook syntax error

Body:
Ansible playbook throwing a syntax error, however everything looks correct.
What can be the issue on the role?

ERROR:

The error appears to have been in '/home/Desktop/playbooks/xx.yml': line 6, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

roles:
    - role: chronos_task
      ^ here

CODE

---
- hosts: localhost
  connection: local
  gather_facts: no
  roles:
    - role: chronos_task
      no_log: true
      chronos_url: 'http://{{ chronos_host }}:{{ chronos_port }}'
      chronos_tasks:
        - type: iso8601


问:
SQL - Dividing data from the same dataset with matching values in specific columns
I'm trying to find the proportion of females in a dataset that meet certain criteria: company id, job category, gender, timeframe, state id, and state kind. In order to do this, I have to divide the total # of females that meet this criteria by the total number of males and females that meet the criteria.
I'm currently querying data to find the # females from company 20, in engineering, from all time, with kind and id = 0 and dividing it by the total # male and females that meet that criteria:

```<code>/* number of females in eng. jobs */
(SELECT 1.0*sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND dimension_value = 'Female'
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0) /
/* number of m+f in eng */
(SELECT sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND (dimension_value = 'Female'
  OR dimension_value = 'Male')
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0))
</code>```

The problem is that I want to calculate this for all the companies in the dataset across all job categories, kinds, and ids. I'm unsure of how to do this without specifying those myself, and was wondering if anyone could help. I am using SQLWorkbench which is a DBMS-independent, cross-platform SQL query tool. I would appreciate some help (I am not using TSQL or PL/pgSQL).

Apologies for the formatting as well.

答:
Just use conditional aggregation:</p>

```<code>SELECT AVG(CASE WHEN dimension_value = 'Female' THEN 1.0 ELSE 0.0 END) as female_proportion
FROM metrics m JOIN
     category c
     ON m.job_id = c.job_id
WHERE m.company_id = 20 AND
      c.standard_job_cat = 'Engineering' AND
      time_frame = 'ALLTIME' AND
      state_kind = 0 AND
      state_item_id = 0;
</code>```

Body:
I'm trying to find the proportion of females in a dataset that meet certain criteria: company id, job category, gender, timeframe, state id, and state kind. In order to do this, I have to divide the total # of females that meet this criteria by the total number of males and females that meet the criteria.
I'm currently querying data to find the # females from company 20, in engineering, from all time, with kind and id = 0 and dividing it by the total # male and females that meet that criteria:

/* number of females in eng. jobs */
(SELECT 1.0*sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND dimension_value = 'Female'
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0) /
/* number of m+f in eng */
(SELECT sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND (dimension_value = 'Female'
  OR dimension_value = 'Male')
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0))

The problem is that I want to calculate this for all the companies in the dataset across all job categories, kinds, and ids. I'm unsure of how to do this without specifying those myself, and was wondering if anyone could help. I am using SQLWorkbench which is a DBMS-independent, cross-platform SQL query tool. I would appreciate some help (I am not using TSQL or PL/pgSQL).

Apologies for the formatting as well.

Body:
Just use conditional aggregation:

SELECT AVG(CASE WHEN dimension_value = 'Female' THEN 1.0 ELSE 0.0 END) as female_proportion
FROM metrics m JOIN
     category c
     ON m.job_id = c.job_id
WHERE m.company_id = 20 AND
      c.standard_job_cat = 'Engineering' AND
      time_frame = 'ALLTIME' AND
      state_kind = 0 AND
      state_item_id = 0;


问:
Table and Chart with Javascript
by using NodeJS or Javascript only, I want to create a simple web page containing a chart and a data table for that chart. After that, I wanna save the table and chart in a PDF file.
IMPORTANT: My device, where the web page will keep running, is stand alone and once it's running it'll be connected to a network WITHOUT internet access. That is, it'll be necessary to install everything on device (no problem!), because it'll not be able to get access to external components ou resources.

How can I create the chart and table on web page and save to PDF file?

答:
You can use jsPDF located here  https://parall.ax/products/jspdf and below is a working example

var doc = new jsPDF()

doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script></code>```

var chart_data = {
  labels: ['Player1', 'Player2', 'Player3', 'Player4'],
  datasets: [{
    fillColor: "rgba(6, 118, 152, 0.71)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [20, 34, 15, 64, ]
  }]
}

//original canvas
var canvas = document.querySelector('#cool-canvas');
var context = canvas.getContext('2d');

new Chart(context).Line(chart_data);

//hidden canvas
var newCanvas = document.querySelector('#supercool-canvas');
newContext = newCanvas.getContext('2d');

var supercoolcanvas = new Chart(newContext).Line(chart_data);
supercoolcanvas.defaults.global = {
  scaleFontSize: 600
}

//add event listener to button
document.getElementById('download-pdf').addEventListener("click", downloadPDF);

//donwload pdf from original canvas
function downloadPDF() {
  var canvas = document.querySelector('#cool-canvas');
  //creates image
  var canvasImg = canvas.toDataURL("image/jpeg", 1.0);

  //creates PDF from img
  var doc = new jsPDF('landscape');
  doc.setFontSize(20);
  doc.text(15, 15, "Cool Chart");
  doc.addImage(canvasImg, 'JPEG', 10, 10, 280, 150);
  doc.save('canvas.pdf');
}

//add event listener to 2nd button
document.getElementById('download-pdf2').addEventListener("click", downloadPDF2);

//download pdf form hidden canvas
function downloadPDF2() {
  var newCanvas = document.querySelector('#supercool-canvas');

  //create image from dummy canvas
  var newCanvasImg = newCanvas.toDataURL("image/jpeg", 1.0);

  //creates PDF from img
  var doc = new jsPDF('landscape');
  doc.setFontSize(20);
  doc.text(15, 15, "Super Cool Chart");
  doc.addImage(newCanvasImg, 'JPEG', 10, 10, 280, 150);
  doc.save('new-canvas.pdf');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  margin-top: 30px;
  padding: 10px 20px;
  border-radius: 0;
}</code>```

  <canvas id="cool-canvas" width="600" height="300"></canvas>

  <canvas id="supercool-canvas" width="1200" height="600"></canvas>

<button type="button" id="download-pdf">
  Download PDF
</button>

<button type="button" id="download-pdf2">
  Download Higher Quality PDF
</button>```

Title: Table and Chart with Javascript

Body:
You can use jsPDF located here  https://parall.ax/products/jspdf and below is a working example

var doc = new jsPDF()

doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>

var chart_data = {
  labels: ['Player1', 'Player2', 'Player3', 'Player4'],
  datasets: [{
    fillColor: "rgba(6, 118, 152, 0.71)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [20, 34, 15, 64, ]
  }]
}

//original canvas
var canvas = document.querySelector('#cool-canvas');
var context = canvas.getContext('2d');

new Chart(context).Line(chart_data);

//hidden canvas
var newCanvas = document.querySelector('#supercool-canvas');
newContext = newCanvas.getContext('2d');

var supercoolcanvas = new Chart(newContext).Line(chart_data);
supercoolcanvas.defaults.global = {
  scaleFontSize: 600
}

//add event listener to button
document.getElementById('download-pdf').addEventListener("click", downloadPDF);

//donwload pdf from original canvas
function downloadPDF() {
  var canvas = document.querySelector('#cool-canvas');
  //creates image
  var canvasImg = canvas.toDataURL("image/jpeg", 1.0);

  //creates PDF from img
  var doc = new jsPDF('landscape');
  doc.setFontSize(20);
  doc.text(15, 15, "Cool Chart");
  doc.addImage(canvasImg, 'JPEG', 10, 10, 280, 150);
  doc.save('canvas.pdf');
}

//add event listener to 2nd button
document.getElementById('download-pdf2').addEventListener("click", downloadPDF2);

//download pdf form hidden canvas
function downloadPDF2() {
  var newCanvas = document.querySelector('#supercool-canvas');

  //create image from dummy canvas
  var newCanvasImg = newCanvas.toDataURL("image/jpeg", 1.0);

  //creates PDF from img
  var doc = new jsPDF('landscape');
  doc.setFontSize(20);
  doc.text(15, 15, "Super Cool Chart");
  doc.addImage(newCanvasImg, 'JPEG', 10, 10, 280, 150);
  doc.save('new-canvas.pdf');
}

button {
  margin-top: 30px;
  padding: 10px 20px;
  border-radius: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<div>
  <canvas id="cool-canvas" width="600" height="300"></canvas>
</div>

<div style="height:0; width:0; overflow:hidden;">
  <canvas id="supercool-canvas" width="1200" height="600"></canvas>
</div>

<button type="button" id="download-pdf">
  Download PDF
</button>

<button type="button" id="download-pdf2">
  Download Higher Quality PDF
</button>


问:
Robust selector to find all elements of class
How can I get all elements who have a class that begins with vd-? My code below works for most cases except for the following:

```<code>class="foo vd-bar"
</code>```

It works for these cases:

```<code>class="vd-bar foo"
</code>```

Here is my selector, will it work if the HTML markup uses single quotation marks? For eg; class='vd-foo'?

```<code>$('[class^="vd-"]', myElement).each(function(index, ele) {

});
</code>```

答:
Unfortunately, CSS Level 3 attribute selectors are very limited (and Level 4 in draft are not much better).

You will have to use a combination of infix-match and prefix-match attribute selectors to achieve a robust selection of all elements with a class that begins with vd-:

```<code>[class*=" vd-"], [class^="vd-"] {
    ...
}
</code>```

The first one will select elements with value of attribute class containing <space>vd- (cases like foo vd-...) and the second one will patch the corner case of vd- class being the first one (cases like vd-bar foo).

Performance

One might be tempted to use only infix (substring) selector, on account of assumed performance penalty incurred by usage of double attribute selectors (infix and prefix match), knowingly sacrificing the accuracy and accepting mismatches like yrivd-button for vd-button.

However, measurements show there is no statistically significant difference in performance between only infix match selector and the combined infix+prefix match selector (compare substringMatch and classPrefixSelector on jsperf.com test).

The combined selector is only 2% to 7% slower (depending on browser) than a single attribute value match selector.

If someone is concerned about that, she shouldn't use attribute selectors at all, but only class selectors .vd-name, which are 2 to 3 times faster than any of the attribute selectors (including the simplest one [attr], which only tests for attribute existence).

Body:
How can I get all elements who have a class that begins with vd-? My code below works for most cases except for the following:

class="foo vd-bar"

It works for these cases:

class="vd-bar foo"

Here is my selector, will it work if the HTML markup uses single quotation marks? For eg; class='vd-foo'?

$('[class^="vd-"]', myElement).each(function(index, ele) {

});

Body:
Unfortunately, CSS Level 3 attribute selectors are very limited (and Level 4 in draft are not much better).

You will have to use a combination of infix-match and prefix-match attribute selectors to achieve a robust selection of all elements with a class that begins with vd-:

[class*=" vd-"], [class^="vd-"] {
    ...
}

The first one will select elements with value of attribute class containing <space>vd- (cases like foo vd-...) and the second one will patch the corner case of vd- class being the first one (cases like vd-bar foo).

Performance

One might be tempted to use only infix (substring) selector, on account of assumed performance penalty incurred by usage of double attribute selectors (infix and prefix match), knowingly sacrificing the accuracy and accepting mismatches like yrivd-button for vd-button.

However, measurements show there is no statistically significant difference in performance between only infix match selector and the combined infix+prefix match selector (compare substringMatch and classPrefixSelector on jsperf.com test).

The combined selector is only 2% to 7% slower (depending on browser) than a single attribute value match selector.

If someone is concerned about that, she shouldn't use attribute selectors at all, but only class selectors .vd-name, which are 2 to 3 times faster than any of the attribute selectors (including the simplest one [attr], which only tests for attribute existence).


问:
CVS: Checkout single file from list of branches
I have the task to checkout a single file from a list of around 300 branches.

The filename and path is the  same on every branch.

Is there a cvs command to accomplish something like this?

答:
```<code>for branch in $branches
do
    cvs checkout -p -r $branch </path/to/file> > $branch/<file>
done
</code>```

The -p option checks out to standard output. You can then redirect to a filename of your choice.

Body:
for branch in $branches
do
    cvs checkout -p -r $branch </path/to/file> > $branch/<file>
done

The -p option checks out to standard output. You can then redirect to a filename of your choice.


问:
How do you determine the size of an object in C++?
For example, say I have a class Temp:

```<code>class Temp
{
    public:
        int function1(int foo) { return 1; }
        void function2(int bar) { foobar = bar; }

    private:
        int foobar;
};
</code>```

When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )

答:
I've always wondered this sort of thing, so I decided to come up with a complete answer. It's about what you might expect, and it is predictable (yay)! Thus, with the information below, you ought to be able to predict the size of a class.

Using Visual Studio Community 2017 (Version 15.2), in Release mode with all optimizations disabled and RTTI (Run-time Type Information) off, I have determined the following:

Shortish answer:

First of all:

In 32 (x86) bit, <size of pointer> == 4 bytes

In 64 (x64) bit, <size of pointer> == 8 bytes

When I say "virtual class inheritance", I mean e.g.: class ChildClass: virtual public ParentClass

Now, my findings are that:

empty classes are 1 byte

inheritance of an empty class is still 1 byte

empty classes with functions are still 1 byte (?! see Note below for explanation)

inheritance of an empty class with a function is still 1 byte

adding a variable to an empty class is <size of variable> bytes

inheriting a class with a variable and adding another variable is <size of variables> bytes

inheriting a class and overriding its function adds a vtable (further explanation provided in Conclusions section) and is <size of pointer> bytes

simply declaring a function virtual also adds a vtable, making it <size of pointer> bytes

virtual class inheritance of an empty class (with or without a member function) also adds a vtable, and makes the class <size of pointer> bytes

virtual class inheritance of a non-empty class also adds a vtable, but it gets somewhat complicated: it adds <size of pointer> bytes to the total, wrapping all of the member variables in as many <size of pointer> bytes increments as is necessary to cover <total size of member variables> - yeah, you read that right... (see my guess as to what's going on in Conclusions...)

Note that I even tried having the function() cout some text, creating an instance of the class, and calling the function; it doesn't change the size of the function class (it's not an optimization)! I was somewhat surprised, but it actually makes sense: member functions don't change, so they can be stored external to the class itself.

Conclusions:

Empty classes are 1 byte, since that is the minimum required for it to have a presence in memory. Once data or vtable data is added, though, begin counting at 0 bytes.

Adding a (non-virtual) member function does nothing to the size, because the member function is stored externally.

Declaring a member function to be virtual (even if the class is not overridded!) or overriding a member function in a child class adds what is called a "vtable" or "virtual function table", which allows for Dynamic Dispatch (which is really super awesome to use though and I highly recommend using it). This vtable consumes <size of pointer> bytes, adding <size of pointer> bytes to said class. This vtable can only exist once per class (either it does or it doesn't), of course.

Adding a member variable increases the size of the class by that member variable, regardless of whether said member variable is in the parent or child class (the parent class remains its own size though, of course).

Virtual class inheritance is the only part that gets complicated... So... I think what's going on after a little experimentation is: the size of the class actually increments in <size of pointer> bytes at a time, even if it doesn't need to consume that much memory, I'm guessing because it's adding a vtable "helper block" for each <size of pointer> bytes of memory or something...

Long answer:

I determined all of this using this code:

```<code>#include <iostream>

using namespace std;

class TestA
{

};

class TestB: public TestA
{

};

class TestC: virtual public TestA
{

};

class TestD
{
    public:
        int i;
};

class TestE: public TestD
{
    public:
        int j;
};

class TestF: virtual public TestD
{
    public:
        int j;
};

class TestG
{
    public:
        void function()
        {

        }
};

class TestH: public TestG
{
    public:
        void function()
        {

        }
};

class TestI: virtual public TestG
{
    public:
        void function()
        {

        }
};

class TestJ
{
    public:
        virtual void function()
        {

        }
};

class TestK: public TestJ
{
    public:
        void function() override
        {

        }
};

class TestL: virtual public TestJ
{
    public:
        void function() override
        {

        }
};

void main()
{
    cout << "int:\t\t" << sizeof(int) << "\n";
    cout << "TestA:\t\t" << sizeof(TestA) << "\t(empty class)\n";
    cout << "TestB:\t\t" << sizeof(TestB) << "\t(inheriting empty class)\n";
    cout << "TestC:\t\t" << sizeof(TestC) << "\t(virtual inheriting empty class)\n";
    cout << "TestD:\t\t" << sizeof(TestD) << "\t(int class)\n";
    cout << "TestE:\t\t" << sizeof(TestE) << "\t(inheriting int + int class)\n";
    cout << "TestF:\t\t" << sizeof(TestF) << "\t(virtual inheriting int + int class)\n";
    cout << "TestG:\t\t" << sizeof(TestG) << "\t(function class)\n";
    cout << "TestH:\t\t" << sizeof(TestH) << "\t(inheriting function class)\n";
    cout << "TestI:\t\t" << sizeof(TestI) << "\t(virtual inheriting function class)\n";
    cout << "TestJ:\t\t" << sizeof(TestJ) << "\t(virtual function class)\n";
    cout << "TestK:\t\t" << sizeof(TestK) << "\t(inheriting overriding function class)\n";
    cout << "TestL:\t\t" << sizeof(TestL) << "\t(virtual inheriting overriding function class)\n";

    cout << "\n";
    system("pause");
}
</code>```

Output:

32 (x86) bits:

```<code>int:            4
TestA:          1       (empty class)
TestB:          1       (inheriting empty class)
TestC:          4       (virtual inheriting empty class)
TestD:          4       (int class)
TestE:          8       (inheriting int + int class)
TestF:          12      (virtual inheriting int + int class)
TestG:          1       (function class)
TestH:          1       (inheriting function class)
TestI:          4       (virtual inheriting function class)
TestJ:          4       (virtual function class)
TestK:          4       (inheriting overriding function class)
TestL:          8       (virtual inheriting overriding function class)
</code>```

64 (x64) bits:

```<code>int:            4
TestA:          1       (empty class)
TestB:          1       (inheriting empty class)
TestC:          8       (virtual inheriting empty class)
TestD:          4       (int class)
TestE:          8       (inheriting int + int class)
TestF:          24      (virtual inheriting int + int class)
TestG:          1       (function class)
TestH:          1       (inheriting function class)
TestI:          8       (virtual inheriting function class)
TestJ:          8       (virtual function class)
TestK:          8       (inheriting overriding function class)
TestL:          16      (virtual inheriting overriding function class)
</code>```

If you want information on multiple inheritance, go figure it out your darn self! -.-

Body:
For example, say I have a class Temp:

class Temp
{
    public:
        int function1(int foo) { return 1; }
        void function2(int bar) { foobar = bar; }

    private:
        int foobar;
};

When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )

Body:
I've always wondered this sort of thing, so I decided to come up with a complete answer. It's about what you might expect, and it is predictable (yay)! Thus, with the information below, you ought to be able to predict the size of a class.

Using Visual Studio Community 2017 (Version 15.2), in Release mode with all optimizations disabled and RTTI (Run-time Type Information) off, I have determined the following:

Shortish answer:

First of all:

In 32 (x86) bit, <size of pointer> == 4 bytes

In 64 (x64) bit, <size of pointer> == 8 bytes

When I say "virtual class inheritance", I mean e.g.: class ChildClass: virtual public ParentClass

Now, my findings are that:

empty classes are 1 byte

inheritance of an empty class is still 1 byte

empty classes with functions are still 1 byte (?! see Note below for explanation)

inheritance of an empty class with a function is still 1 byte

adding a variable to an empty class is <size of variable> bytes

inheriting a class with a variable and adding another variable is <size of variables> bytes

inheriting a class and overriding its function adds a vtable (further explanation provided in Conclusions section) and is <size of pointer> bytes

simply declaring a function virtual also adds a vtable, making it <size of pointer> bytes

virtual class inheritance of an empty class (with or without a member function) also adds a vtable, and makes the class <size of pointer> bytes

virtual class inheritance of a non-empty class also adds a vtable, but it gets somewhat complicated: it adds <size of pointer> bytes to the total, wrapping all of the member variables in as many <size of pointer> bytes increments as is necessary to cover <total size of member variables> - yeah, you read that right... (see my guess as to what's going on in Conclusions...)

Note that I even tried having the function() cout some text, creating an instance of the class, and calling the function; it doesn't change the size of the function class (it's not an optimization)! I was somewhat surprised, but it actually makes sense: member functions don't change, so they can be stored external to the class itself.

Conclusions:

Empty classes are 1 byte, since that is the minimum required for it to have a presence in memory. Once data or vtable data is added, though, begin counting at 0 bytes.

Adding a (non-virtual) member function does nothing to the size, because the member function is stored externally.

Declaring a member function to be virtual (even if the class is not overridded!) or overriding a member function in a child class adds what is called a "vtable" or "virtual function table", which allows for Dynamic Dispatch (which is really super awesome to use though and I highly recommend using it). This vtable consumes <size of pointer> bytes, adding <size of pointer> bytes to said class. This vtable can only exist once per class (either it does or it doesn't), of course.

Adding a member variable increases the size of the class by that member variable, regardless of whether said member variable is in the parent or child class (the parent class remains its own size though, of course).

Virtual class inheritance is the only part that gets complicated... So... I think what's going on after a little experimentation is: the size of the class actually increments in <size of pointer> bytes at a time, even if it doesn't need to consume that much memory, I'm guessing because it's adding a vtable "helper block" for each <size of pointer> bytes of memory or something...

Long answer:

I determined all of this using this code:

#include <iostream>

using namespace std;

class TestA
{

};

class TestB: public TestA
{

};

class TestC: virtual public TestA
{

};

class TestD
{
    public:
        int i;
};

class TestE: public TestD
{
    public:
        int j;
};

class TestF: virtual public TestD
{
    public:
        int j;
};

class TestG
{
    public:
        void function()
        {

        }
};

class TestH: public TestG
{
    public:
        void function()
        {

        }
};

class TestI: virtual public TestG
{
    public:
        void function()
        {

        }
};

class TestJ
{
    public:
        virtual void function()
        {

        }
};

class TestK: public TestJ
{
    public:
        void function() override
        {

        }
};

class TestL: virtual public TestJ
{
    public:
        void function() override
        {

        }
};

void main()
{
    cout << "int:\t\t" << sizeof(int) << "\n";
    cout << "TestA:\t\t" << sizeof(TestA) << "\t(empty class)\n";
    cout << "TestB:\t\t" << sizeof(TestB) << "\t(inheriting empty class)\n";
    cout << "TestC:\t\t" << sizeof(TestC) << "\t(virtual inheriting empty class)\n";
    cout << "TestD:\t\t" << sizeof(TestD) << "\t(int class)\n";
    cout << "TestE:\t\t" << sizeof(TestE) << "\t(inheriting int + int class)\n";
    cout << "TestF:\t\t" << sizeof(TestF) << "\t(virtual inheriting int + int class)\n";
    cout << "TestG:\t\t" << sizeof(TestG) << "\t(function class)\n";
    cout << "TestH:\t\t" << sizeof(TestH) << "\t(inheriting function class)\n";
    cout << "TestI:\t\t" << sizeof(TestI) << "\t(virtual inheriting function class)\n";
    cout << "TestJ:\t\t" << sizeof(TestJ) << "\t(virtual function class)\n";
    cout << "TestK:\t\t" << sizeof(TestK) << "\t(inheriting overriding function class)\n";
    cout << "TestL:\t\t" << sizeof(TestL) << "\t(virtual inheriting overriding function class)\n";

    cout << "\n";
    system("pause");
}

Output:

32 (x86) bits:

int:            4
TestA:          1       (empty class)
TestB:          1       (inheriting empty class)
TestC:          4       (virtual inheriting empty class)
TestD:          4       (int class)
TestE:          8       (inheriting int + int class)
TestF:          12      (virtual inheriting int + int class)
TestG:          1       (function class)
TestH:          1       (inheriting function class)
TestI:          4       (virtual inheriting function class)
TestJ:          4       (virtual function class)
TestK:          4       (inheriting overriding function class)
TestL:          8       (virtual inheriting overriding function class)

64 (x64) bits:

int:            4
TestA:          1       (empty class)
TestB:          1       (inheriting empty class)
TestC:          8       (virtual inheriting empty class)
TestD:          4       (int class)
TestE:          8       (inheriting int + int class)
TestF:          24      (virtual inheriting int + int class)
TestG:          1       (function class)
TestH:          1       (inheriting function class)
TestI:          8       (virtual inheriting function class)
TestJ:          8       (virtual function class)
TestK:          8       (inheriting overriding function class)
TestL:          16      (virtual inheriting overriding function class)

If you want information on multiple inheritance, go figure it out your darn self! -.-


问:
ASP.NET MVC Two models in ove view, code change
I had this code and it worked fine:

```<code>@model IEnumerable<Moviestore.Models.Movie>
@{
ViewBag.Title = "Index";
}

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Genre)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Author)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Year)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Author)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Year)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
    </td>
</tr>
}
}
</table>
</code>```

But I needed to add one more model, I done that with Tuple In this way:

```<code>@using Moviestore.Models;
@model Tuple<Movie, User>

@{
ViewBag.Title = "Index";
}

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Title)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Genre)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Author)
    </th>
    <th>
        @Html.DisplayNameFor(tuple => tuple.Item1.Year)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Author)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Year)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
    </td>
</tr>
}
}
</table>
</code>```

But now I have problem with bottom half of code.
From @foreach

I don't know what I need to put instead of @foreach (var item in Model)

And will then @Html.DisplayFor(modelItem => item.Title) also need some changes.

Sorry for long post, I tried to explain the problem as best as I can.

答:
Hi here is the viewmodel for your requirement:

```<code>public class MovieUserViewModel
{
    public IEnumerable<Movie> Movie { get; set; }
    public IEnumerable<Users> Users { get; set; }
}
</code>```

With the above viewmodel  , you can easily access each class

```<code>@foreach (var item in Model.Movie)

@foreach (var item in Model.Users)
</code>```

Additional info : Understanding ViewModel in ASP.NET MVC

Thanks

Karthik

Body:
I had this code and it worked fine:

@model IEnumerable<Moviestore.Models.Movie>
@{
ViewBag.Title = "Index";
}

@Html.ActionLink("Create New", "Create")

        @Html.DisplayNameFor(model => model.Title)

        @Html.DisplayNameFor(model => model.Genre)

        @Html.DisplayNameFor(model => model.Author)

        @Html.DisplayNameFor(model => model.Year)

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.Genre)

        @Html.DisplayFor(modelItem => item.Author)

        @Html.DisplayFor(modelItem => item.Year)

        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })

}
}

But I needed to add one more model, I done that with Tuple In this way:

@using Moviestore.Models;
@model Tuple<Movie, User>

@{
ViewBag.Title = "Index";
}

    @Html.ActionLink("Create New", "Create")

        @Html.DisplayNameFor(tuple => tuple.Item1.Title)

        @Html.DisplayNameFor(tuple => tuple.Item1.Genre)

        @Html.DisplayNameFor(tuple => tuple.Item1.Author)

        @Html.DisplayNameFor(tuple => tuple.Item1.Year)

@foreach (var item in Model) {
if (item.IsDeleted == 0)
{

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.Genre)

        @Html.DisplayFor(modelItem => item.Author)

        @Html.DisplayFor(modelItem => item.Year)

        @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
        @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })

}
}

But now I have problem with bottom half of code.
From @foreach

I don't know what I need to put instead of @foreach (var item in Model)

And will then @Html.DisplayFor(modelItem => item.Title) also need some changes.

Sorry for long post, I tried to explain the problem as best as I can.

Body:
Hi here is the viewmodel for your requirement:

public class MovieUserViewModel
{
    public IEnumerable<Movie> Movie { get; set; }
    public IEnumerable<Users> Users { get; set; }
}

With the above viewmodel  , you can easily access each class

@foreach (var item in Model.Movie)

@foreach (var item in Model.Users)

Additional info : Understanding ViewModel in ASP.NET MVC

Thanks

Karthik


问:
How to change eZPlatform Backoffice SiteAccess?
I'm new to ezplatform and I have been just thrown in a project involving migration from ez legacy to ez platform.
One problem I've just bumped into is about siteaccess and images.

Example: users have custom images defined in a var directory, let's say var/news.
Unfortunately backoffice uses default siteaccess and I don't find a way to modify it without trigger a redirect from /ez#login to /login page.

I noticed that I can't change backoffice siteaccess in demo platform too.

So I was wondering either if there's a way to achieve this purpose or there's documentation that could help to address such subject?

答:
Just to be clear, you have one var directory per site access, that is the issue right? As /ez will use the default one, you have a problem.

I think there is no simple way to manage this use case right now, I think it will be possible to do it with 2.x (ask in Slack)

One complex solution would be to put everything in one var directory and replace in the DB the different paths... :(

(or wait 2.x)


问:
Socketio and cloudflare
So I've already done my research and figured out that socket.io only works with cloudflare if you use set ports found that here </p>

<p>So through that research I found that http and https can't use the same port. I'm coming here to as you guys how do you get a socketio server to listen on two ports? So it can support http and https with cloudflare </p>

答:
The common method is referred to as an SSL Termination Proxy (also called SSL off-loading). The proxy accepts incoming messages over HTTPS and passes the decrypted requests to another resource (another server, web service/API, etc.). This would allow your Node.js application utilizing socketio to handle all requests, no matter if the client made an HTTP or HTTPS request. Software like NGINX, Apache, and even Microsoft IIS are capable of providing this functionality.

Here are some links regarding this topic:

General Info: https://en.wikipedia.org/wiki/TLS_termination_proxy

NGINX: https://www.nginx.com/resources/admin-guide/nginx-ssl-termination/

NGINX: https://www.nginx.com/resources/admin-guide/nginx-tcp-ssl-termination/

HAProxy: https://www.digitalocean.com/community/tutorials/how-to-implement-ssl-termination-with-haproxy-on-ubuntu-14-04

IIS: https://blogs.iis.net/wonyoo/ssl-off-loading-in-application-request-routing

Title: Socketio and cloudflare

Body:
So I've already done my research and figured out that socket.io only works with cloudflare if you use set ports found that here

So through that research I found that http and https can't use the same port. I'm coming here to as you guys how do you get a socketio server to listen on two ports? So it can support http and https with cloudflare


问:
What is the point of nulling private variables in destructor?
I have spot the following pattern in code I'm working with: in some classes in destructor I have found private variable being nulled, in example:

```<code>public function __destruct()
{
    foreach($this->observers as $observer)
    {
        $observer = null;
    }
    $this->db_build = null;
}
</code>```

Is there any point in doing this when PHP has GC? Does it somehow improve performance of script?

答: first - it's a good programming tone, second - it makes script memory free. if right after invoking destructor php script terminates, i see no advantages.</p>

Body:
I have spot the following pattern in code I'm working with: in some classes in destructor I have found private variable being nulled, in example:

public function __destruct()
{
    foreach($this->observers as $observer)
    {
        $observer = null;
    }
    $this->db_build = null;
}

Is there any point in doing this when PHP has GC? Does it somehow improve performance of script?


问:
Object.keys returning as not equal
This is my first post, I have researched but I'm not sure I'm phrasing the question the right way in searches.

I am attempting to compare the keys of an object to the keys in another object (this is for freeCodeCamp algorithms). My code is below:

```<code>function whereAreYou(collection, source) {
  var arr = [];
  for (var i=0;i<collection.length;i++) {
    console.log("Object.keys(source)= " + Object.keys(source));
    console.log("Object.keys(collection[" +i + "]))= " + Object.keys(collection[i]));
    console.log("collection[" +i + "].hasOwnProperty(Object.keys(source))= " + collection[i].hasOwnProperty(Object.keys(source)));
    if (collection[i].hasOwnProperty(Object.keys(source))) {
      var prop = Object.keys(source);
      console.log("prop=" + prop);
      console.log("collection[" +i + "][prop]= " + collection[i][prop]);
      console.log("source[prop]= " + source[prop]);
      if (collection[i][prop] === source[prop]) {
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}
</code>```

When there are multiple keys in the source argument, the

```<code>if (collection[i].hasOwnProperty(Object.keys(source)))
</code>```

returns false even when collection[i] does contain the keys as per below.

```<code>whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

Object.keys(source)= a,b
Object.keys(collection[0]))= a,b
collection[0].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[1]))= a
collection[1].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[2]))= a,b,c
collection[2].hasOwnProperty(Object.keys(source))= false
[]
</code>```

My question is why aren't a,b and a,b equal? Thank you for your time!

答:
I'm not sure that hasOwnProperty is what you want. Check out the definition of hasOwnProperty:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

You need to compare the items within each array. For example, on the first iteration:

```<code>Object.keys(collection[i]).includes("a") // true
Object.keys(collection[i]).includes("b") // true
Object.keys(collection[i]).includes(Object.keys(source)[0]) // true
Object.keys(collection[i]).includes(Object.keys(source)[1]) // true
</code>```

You can either iterate over Object.keys(source) and compare it to Object.keys(collection[i]), or try something shorter, see:
Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

You can do something like this:

```<code>function whereAreYou(collection, source) {
    var arr = [];
    for (var i = 0; i < collection.length; i++) {
        for (var j = 0; j < Object.keys(source).length; j++) {
            if (Object.keys(collection[i]).includes(Object.keys(source)[j])) {
                // do your comparisons here
            }
        }
    }
    return arr;
}
</code>```

Title: Object.keys returning as not equal

Body:
This is my first post, I have researched but I'm not sure I'm phrasing the question the right way in searches.

I am attempting to compare the keys of an object to the keys in another object (this is for freeCodeCamp algorithms). My code is below:

function whereAreYou(collection, source) {
  var arr = [];
  for (var i=0;i<collection.length;i++) {
    console.log("Object.keys(source)= " + Object.keys(source));
    console.log("Object.keys(collection[" +i + "]))= " + Object.keys(collection[i]));
    console.log("collection[" +i + "].hasOwnProperty(Object.keys(source))= " + collection[i].hasOwnProperty(Object.keys(source)));
    if (collection[i].hasOwnProperty(Object.keys(source))) {
      var prop = Object.keys(source);
      console.log("prop=" + prop);
      console.log("collection[" +i + "][prop]= " + collection[i][prop]);
      console.log("source[prop]= " + source[prop]);
      if (collection[i][prop] === source[prop]) {
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}

When there are multiple keys in the source argument, the

if (collection[i].hasOwnProperty(Object.keys(source)))

returns false even when collection[i] does contain the keys as per below.

whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

Object.keys(source)= a,b
Object.keys(collection[0]))= a,b
collection[0].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[1]))= a
collection[1].hasOwnProperty(Object.keys(source))= false
Object.keys(source)= a,b
Object.keys(collection[2]))= a,b,c
collection[2].hasOwnProperty(Object.keys(source))= false
[]

My question is why aren't a,b and a,b equal? Thank you for your time!

Body:
I'm not sure that hasOwnProperty is what you want. Check out the definition of hasOwnProperty:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

You need to compare the items within each array. For example, on the first iteration:

Object.keys(collection[i]).includes("a") // true
Object.keys(collection[i]).includes("b") // true
Object.keys(collection[i]).includes(Object.keys(source)[0]) // true
Object.keys(collection[i]).includes(Object.keys(source)[1]) // true

You can either iterate over Object.keys(source) and compare it to Object.keys(collection[i]), or try something shorter, see:
Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

You can do something like this:

function whereAreYou(collection, source) {
    var arr = [];
    for (var i = 0; i < collection.length; i++) {
        for (var j = 0; j < Object.keys(source).length; j++) {
            if (Object.keys(collection[i]).includes(Object.keys(source)[j])) {
                // do your comparisons here
            }
        }
    }
    return arr;
}


问:
DataGrid with Dynamic Editable Columns
I have been trying to make a an editable DataGrid with dynamic columns in a WPF MVVM project. The dynamic columns would be the same type, i.e: decimal.

The aim is to collect department totals of shops with indefinite number of departments. I tried to demonstrate it below.

```<code>Day Dept1   Dept2   Dept3... TotalOfDepartments CashTotal CreditTotal
=====================================================================
1    100     200     50            350             50       300
2     75     100      0            175             25       150
</code>```

So, there are numerous shops with indefinite departments and my goal is to collect month

I want to make Department, CashTotal & CreditTotal Columns editable. I've had several approaches that I tried like:

populate dynamic datagrid column and binding with editable using mVVm

Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

How do I bind a WPF DataGrid to a variable number of columns?

This is my last try from the last approach. As follows:

Model:

```<code> public class DailyRevenues
    {
        public int ShopId { get; set; }
        public int Day { get; set; }
        public ObservableCollection<Department> DepartmentList { get; set; }

        public DailyRevenues()
        {
            this.DepartmentList = new ObservableCollection<Department>();
        }
    }

    public class Department
    {
        public string Name { get; set; }

        private decimal total;
        public decimal Total
        {
            get { return total; }
            set { total = value; }
        }
    }
</code>```

ViewModel:

```<code>public class DataItemViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public DataItemViewModel()
        {
            this.MonthlyRevenues = new ObservableCollection<DailyRevenues>();

            var d1 = new DailyRevenues() { ShopId = 1, Day = 1 };
            d1.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 100 });
            d1.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 200 });

            var d2 = new DailyRevenues() { ShopId = 1, Day = 2 };
            d2.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 75 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 150 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment3", Total = 100 });

            this.MonthlyRevenues.Add(d1);
            this.MonthlyRevenues.Add(d2);
        }

        private ObservableCollection<DailyRevenues> monthlyRevenues;
        public ObservableCollection<DailyRevenues> MonthlyRevenues
        {
            get { return monthlyRevenues; }
            set
            {
                if (monthlyRevenues != value)
                {
                    monthlyRevenues = value;
                    OnPropertyChanged(nameof(MonthlyRevenues));
                }
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
</code>```

And the XAML:

```<code><DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Day" Binding="{Binding Path=Day}" />
            <DataGridTextColumn Header="{Binding Path=MonthlyRevenues[0].DepartmentList[0].Name}" Binding="{Binding Path=DepartmentList[0].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="{Binding Path=DepartmentList[1].Name}" Binding="{Binding Path=DepartmentList[1].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="Department Total"/>
            <DataGridTextColumn Header="Cash Total" />
            <DataGridTextColumn Header="Credit Total" />
        </DataGrid.Columns>
    </DataGrid>
</code>```

Unfortunately, on this last try using the indexers on XAML does not help me on dynamic columns and I can not find a way to bind them any other way.

More info: The datagrid (and the data demonstration) above belongs to shop1 and I want to collect monthly revenues of it`s departments on a window/user control . Each shop has the same count of departments throughout the month, but this does not mean that every department should have revenues each day, it can be zero. The department may be closed for any day, so does not raise any revenue for the day. Shop2 might have entirely different departments for the same month, so I will not handle all shops in the same screen.

EDIT 1: More info about scenario added.

答:
There are a number of different approaches you could take, each with pluses and minuses.  Based on your more complete description of the problem, I have chosen the custom type descriptor approach.

Here we add a custom type descriptor to the daily revenues class...

```<code>public class DailyRevenues : ICustomTypeDescriptor
{
    public int ShopId { get; set; }
    public int Day { get; set; }
    public ObservableCollection<Department> DepartmentList { get; set; }

    public DailyRevenues()
    {
        this.DepartmentList = new ObservableCollection<Department>();
    }
    public decimal TotalOfDepartments { get;  }
    public decimal CashTotal { get;  }
    public decimal CreditTotal { get; }

    public AttributeCollection GetAttributes()
    {
        return new AttributeCollection();
    }

    public string GetClassName()
    {
        return "DailyRevenues";
    }

    public string GetComponentName()
    {
        return "";
    }

    public TypeConverter GetConverter()
    {
        return null;
    }

    public EventDescriptor GetDefaultEvent()
    {
        return null;
    }

    public PropertyDescriptor GetDefaultProperty()
    {
        return null;
    }

    public object GetEditor(Type editorBaseType)
    {
        return null;
    }

    public EventDescriptorCollection GetEvents()
    {
        return null;
    }

    public EventDescriptorCollection GetEvents(Attribute[] attributes)
    {
        return null;
    }

    public PropertyDescriptorCollection GetProperties()
    {
        PropertyDescriptorCollection pdc0 = TypeDescriptor.GetProperties(typeof(DailyRevenues));
        List<PropertyDescriptor> pdList = new List<PropertyDescriptor>();
        pdList.Add(pdc0["Day"]);
        for (int i = 0; i < DepartmentList.Count; ++i)
        {
            pdList.Add(new DailyRevenuesProperty(DepartmentList[i].Name, i));
        }
        pdList.Add(pdc0["TotalOfDepartments"]);
        pdList.Add(pdc0["CashTotal"]);
        pdList.Add(pdc0["CreditTotal"]);
        return new PropertyDescriptorCollection(pdList.ToArray());
    }

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        return GetProperties();
    }

    public object GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }
}
</code>```

The custom type descriptor allows us to "flatten" the data structure.  As the number of departments change, the number of properties on the object changes.  This requires a custom property descriptor for the daily revenues class...

```<code>public class DailyRevenuesProperty : PropertyDescriptor
{
    int _index;
    public DailyRevenuesProperty(string name, int index)
        : base(name, new Attribute[0])
    {
        _index = index;
    }
    public override Type ComponentType
    {
        get
        {
            return typeof(DailyRevenues);
        }
    }

    public override bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public override Type PropertyType
    {
        get
        {
            return typeof(decimal);
        }
    }

    public override bool CanResetValue(object component)
    {
        return false;
    }

    public override object GetValue(object component)
    {
        DailyRevenues dr = component as DailyRevenues;
        if(dr != null && _index >= 0 && _index < dr.DepartmentList.Count)
        {
            return dr.DepartmentList[_index].Total;
        }
        else
        {
            return (decimal)0;
        }
    }

    public override void ResetValue(object component)
    {
    }

    public override void SetValue(object component, object value)
    {
        DailyRevenues dr = component as DailyRevenues;
        if (dr != null && _index >= 0 && _index < dr.DepartmentList.Count && value is decimal)
        {
            dr.DepartmentList[_index].Total = (decimal)value;
        }
    }

    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }
}
</code>```

Now we need a typed list. This replaces the observable collection.

```<code>public class MonthlyRevenues : ObservableCollection<DailyRevenues>, ITypedList
{
    public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        if(Count > 0)
        {
            return TypeDescriptor.GetProperties(this[0]);
        }
        else
        {
            return TypeDescriptor.GetProperties(typeof(DailyRevenues));
        }
    }

    public string GetListName(PropertyDescriptor[] listAccessors)
    {
        return "Monthly Revenues";
    }
}
</code>```

When auto generating columns the data grid checks to see if the items collection is a typed list.  If it is, the data grid queries for the properties on the typed list.

Finally to wrap things up, here is the data grid...

```<code>    <DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="true" />
</code>```

And this is the resulting grid...

There are number of limitations to this approach.  First I am relying on the data grid to autogenerate the columns.  If I want to add things like spaces to the header text, I will need to do some more stuff.  Second I am counting on the department names to be valid property names and to not collide with other properties in the daily revenues class.  If not, then I will need to do some more stuff.  And so on.

Title: DataGrid with Dynamic Editable Columns

Body:
I have been trying to make a an editable DataGrid with dynamic columns in a WPF MVVM project. The dynamic columns would be the same type, i.e: decimal.

The aim is to collect department totals of shops with indefinite number of departments. I tried to demonstrate it below.

Day Dept1   Dept2   Dept3... TotalOfDepartments CashTotal CreditTotal
=====================================================================
1    100     200     50            350             50       300
2     75     100      0            175             25       150

So, there are numerous shops with indefinite departments and my goal is to collect month

I want to make Department, CashTotal & CreditTotal Columns editable. I've had several approaches that I tried like:

populate dynamic datagrid column and binding with editable using mVVm

Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

How do I bind a WPF DataGrid to a variable number of columns?

This is my last try from the last approach. As follows:

Model:

 public class DailyRevenues
    {
        public int ShopId { get; set; }
        public int Day { get; set; }
        public ObservableCollection<Department> DepartmentList { get; set; }

        public DailyRevenues()
        {
            this.DepartmentList = new ObservableCollection<Department>();
        }
    }

    public class Department
    {
        public string Name { get; set; }

        private decimal total;
        public decimal Total
        {
            get { return total; }
            set { total = value; }
        }
    }

ViewModel:

public class DataItemViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public DataItemViewModel()
        {
            this.MonthlyRevenues = new ObservableCollection<DailyRevenues>();

            var d1 = new DailyRevenues() { ShopId = 1, Day = 1 };
            d1.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 100 });
            d1.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 200 });

            var d2 = new DailyRevenues() { ShopId = 1, Day = 2 };
            d2.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 75 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 150 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment3", Total = 100 });

            this.MonthlyRevenues.Add(d1);
            this.MonthlyRevenues.Add(d2);
        }

        private ObservableCollection<DailyRevenues> monthlyRevenues;
        public ObservableCollection<DailyRevenues> MonthlyRevenues
        {
            get { return monthlyRevenues; }
            set
            {
                if (monthlyRevenues != value)
                {
                    monthlyRevenues = value;
                    OnPropertyChanged(nameof(MonthlyRevenues));
                }
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

And the XAML:

<DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Day" Binding="{Binding Path=Day}" />
            <DataGridTextColumn Header="{Binding Path=MonthlyRevenues[0].DepartmentList[0].Name}" Binding="{Binding Path=DepartmentList[0].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="{Binding Path=DepartmentList[1].Name}" Binding="{Binding Path=DepartmentList[1].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="Department Total"/>
            <DataGridTextColumn Header="Cash Total" />
            <DataGridTextColumn Header="Credit Total" />
        </DataGrid.Columns>
    </DataGrid>

Unfortunately, on this last try using the indexers on XAML does not help me on dynamic columns and I can not find a way to bind them any other way.

More info: The datagrid (and the data demonstration) above belongs to shop1 and I want to collect monthly revenues of it`s departments on a window/user control . Each shop has the same count of departments throughout the month, but this does not mean that every department should have revenues each day, it can be zero. The department may be closed for any day, so does not raise any revenue for the day. Shop2 might have entirely different departments for the same month, so I will not handle all shops in the same screen.

EDIT 1: More info about scenario added.

Body:
There are a number of different approaches you could take, each with pluses and minuses.  Based on your more complete description of the problem, I have chosen the custom type descriptor approach.

Here we add a custom type descriptor to the daily revenues class...

public class DailyRevenues : ICustomTypeDescriptor
{
    public int ShopId { get; set; }
    public int Day { get; set; }
    public ObservableCollection<Department> DepartmentList { get; set; }

    public DailyRevenues()
    {
        this.DepartmentList = new ObservableCollection<Department>();
    }
    public decimal TotalOfDepartments { get;  }
    public decimal CashTotal { get;  }
    public decimal CreditTotal { get; }

    public AttributeCollection GetAttributes()
    {
        return new AttributeCollection();
    }

    public string GetClassName()
    {
        return "DailyRevenues";
    }

    public string GetComponentName()
    {
        return "";
    }

    public TypeConverter GetConverter()
    {
        return null;
    }

    public EventDescriptor GetDefaultEvent()
    {
        return null;
    }

    public PropertyDescriptor GetDefaultProperty()
    {
        return null;
    }

    public object GetEditor(Type editorBaseType)
    {
        return null;
    }

    public EventDescriptorCollection GetEvents()
    {
        return null;
    }

    public EventDescriptorCollection GetEvents(Attribute[] attributes)
    {
        return null;
    }

    public PropertyDescriptorCollection GetProperties()
    {
        PropertyDescriptorCollection pdc0 = TypeDescriptor.GetProperties(typeof(DailyRevenues));
        List<PropertyDescriptor> pdList = new List<PropertyDescriptor>();
        pdList.Add(pdc0["Day"]);
        for (int i = 0; i < DepartmentList.Count; ++i)
        {
            pdList.Add(new DailyRevenuesProperty(DepartmentList[i].Name, i));
        }
        pdList.Add(pdc0["TotalOfDepartments"]);
        pdList.Add(pdc0["CashTotal"]);
        pdList.Add(pdc0["CreditTotal"]);
        return new PropertyDescriptorCollection(pdList.ToArray());
    }

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        return GetProperties();
    }

    public object GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }
}

The custom type descriptor allows us to "flatten" the data structure.  As the number of departments change, the number of properties on the object changes.  This requires a custom property descriptor for the daily revenues class...

public class DailyRevenuesProperty : PropertyDescriptor
{
    int _index;
    public DailyRevenuesProperty(string name, int index)
        : base(name, new Attribute[0])
    {
        _index = index;
    }
    public override Type ComponentType
    {
        get
        {
            return typeof(DailyRevenues);
        }
    }

    public override bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public override Type PropertyType
    {
        get
        {
            return typeof(decimal);
        }
    }

    public override bool CanResetValue(object component)
    {
        return false;
    }

    public override object GetValue(object component)
    {
        DailyRevenues dr = component as DailyRevenues;
        if(dr != null && _index >= 0 && _index < dr.DepartmentList.Count)
        {
            return dr.DepartmentList[_index].Total;
        }
        else
        {
            return (decimal)0;
        }
    }

    public override void ResetValue(object component)
    {
    }

    public override void SetValue(object component, object value)
    {
        DailyRevenues dr = component as DailyRevenues;
        if (dr != null && _index >= 0 && _index < dr.DepartmentList.Count && value is decimal)
        {
            dr.DepartmentList[_index].Total = (decimal)value;
        }
    }

    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }
}

Now we need a typed list. This replaces the observable collection.

public class MonthlyRevenues : ObservableCollection<DailyRevenues>, ITypedList
{
    public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        if(Count > 0)
        {
            return TypeDescriptor.GetProperties(this[0]);
        }
        else
        {
            return TypeDescriptor.GetProperties(typeof(DailyRevenues));
        }
    }

    public string GetListName(PropertyDescriptor[] listAccessors)
    {
        return "Monthly Revenues";
    }
}

When auto generating columns the data grid checks to see if the items collection is a typed list.  If it is, the data grid queries for the properties on the typed list.

Finally to wrap things up, here is the data grid...

    <DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="true" />

And this is the resulting grid...

There are number of limitations to this approach.  First I am relying on the data grid to autogenerate the columns.  If I want to add things like spaces to the header text, I will need to do some more stuff.  Second I am counting on the department names to be valid property names and to not collide with other properties in the daily revenues class.  If not, then I will need to do some more stuff.  And so on.