问:
Why would adding a simple field to select change the amount of returned rows SQL
I have a more complicated problem that I have tried to isolate down to it's components.

I have a simple query that returns all distinct customer emails (So every individual customer)

```<code>Select distinct
CustomerEmail

FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock) --I don't think the tables are relevant to the problem.
                LEFT JOIN (SELECT
                                ID.Company_Code
                                ,ID.Division_Code
                                ,ID.Invoice_Number
                                ,SUM (ID.Price* ID.Quantity) Total
                            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                            GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
                        ON I.Company_Code = ID.Company_Code
                        AND I.Division_Code = ID.Division_Code
                        AND I.Invoice_Number = ID.Invoice_Number
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[SpraygroundMagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

Where I.Company_Code ='09' AND I.Division_Code = '001'
AND I.Customer_Number = 'ECOM2X'
AND ISNUMERIC(SH.CUST_PO) <> 0
AND I.Date_Created BETWEEN DATEADD(month, -0, '6/1/2016') AND '1/1/2017'  -- Orders Base default is 12 months, options are 6,12, 18, and 24
</code>```

This returns 19,516 rows.

If however, I add a second simple select statement to my query,

```<code>Select distinct
Month(I.Date_Created) Month,
CustomerEmail
FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)...
</code>```

It now returns 20,452 rows.

Writing this question out, I think I understood the problem. It will duplicate the emails for different months. So if a customer placed an order on June and July, his email will appear twice, once for month 6 and once for month 7.

So this number should be more correct than the 19,516 number, right?

The way I calculate the TotalCustomers Number later in my more complex query is a simple Dense Rank statement

```<code>,DENSE_RANK() over (order by CustomerEmail asc)
+DENSE_RANK() over (order by CustomerEmail desc)
- 1 as TotalCustomersOverRange
</code>```

This returns me 19,516 because it doesn't count multiple purchases. But this is also technically correct, because over that date range, there are less unique customers. Only when you break it out by month do you get duplicate customers who are really them same.

What is the best way to fix this? Here is my full query:

```<code>--Calculate average amount of time between purchase
--Calculate percentage of quantity and total increase with each purchase.
--Return most valued customers.
--User defined base range
-- later on, more refined user defined customer base, so if the base range is 18 months and the customer range is 1 month, it will only check the data against customers that purchased orders within the last month.
-- over the customer range, we define who the customers are. We call this RANGE
-- over the orderes base range,  we define and how many times they ordered. We call this BASE.
-- First we filter by month, returning total new orders and total recurring orders
-- (FOR OTHER REPORT, filter by state and not month)
-- Then within the month, we drill down to calculate how many customers are one orders, two orders, three orders, etc total
-- For each order amount, we calculate average days between orders, total value, lifetime value, and quantity changes

SELECT DISTINCT --*
Month

,(DENSE_RANK() over (partition by Month order by CustomerEmail asc)
    +DENSE_RANK() over (partition by Month order by CustomerEmail desc))
    -1 as TotalCustomersThisMonth

,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and RangeOrderNumber = 1 then 1 else 0 end) over (partition by Month) NewCustomersOverRangeThisMonth --Some of those customers aren't really new, if we expand to the base.
,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer = 1 then 1 else 0 end) over (partition by Month) NewCustomersOverBaseThisMonth
,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer > 1 then 1 else 0 end)  over (partition by Month) RecurringCustomersOverBaseButNewInRangeThisMonth -- Customers in Base who are not in range.
,Sum(Case When AmountOrdersOverRangeByCustomer > 1 and RangeOrderNumber =1 then 1 else 0 end)  over (partition by Month) RecurringCustomerOverRangeThisMonth
,TTT.NewCustomersOverRange
,TTT.NewCustomersOverBase
,TTT.RecurringCustomersOverBaseButNewInRange
,TTT.RecurringCustomerOverRange
,TTT.TotalCustomersOverBase
,TTT.TotalCustomersOverRange

FROM --This table calculates new and recurring customers.
(
    SELECT
    *
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and RangeOrderNumber = 1 then 1 else 0 end) over () NewCustomersOverRange --Some of those customers aren't really new, if we expand to the base.
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer = 1 then 1 else 0 end) over () NewCustomersOverBase
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer > 1 then 1 else 0 end)  over () RecurringCustomersOverBaseButNewInRange -- Customers in Base who are not in range
    ,Sum(Case When AmountOrdersOverRangeByCustomer > 1 and RangeOrderNumber =1 then 1 else 0 end)  over () RecurringCustomerOverRange

    FROM -- This table gives you Order Numbers Per Customer
    (
        SELECT
            *
            ,ROW_NUMBER() over (partition by CustomerEmail order by Date_Created asc) RangeOrderNumber

            ,(DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
            +DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc))
            -1 as AmountOrdersOverRangeByCustomer

            ,Max(BaseOrderNumber) over (partition by CustomerEmail) AmountOrdersOverBaseByCustomer

            ,DENSE_RANK() over (order by CustomerEmail asc)
            +DENSE_RANK() over (order by CustomerEmail desc)
            - 1 as TotalCustomersOverRange

        FROM --This table gives you a line by line basis of every order
        (
            Select
             I.Date_Created
            ,I.Company_Code
            ,I.Division_Code
            ,I.Invoice_Number
            ,Sh.CUST_PO
            ,I.Total_Quantity
            ,ID.Total
            ,SH.Ship_City City
            ,CASE WHEN SH.Ship_Cntry <> 'US' THEN 'INT' ELSE SH.Ship_prov END State
            ,SH.Ship_Zip Zip
            ,SH.Ship_Cntry Country
            ,Month(I.Date_Created) Month
            ,S.CustomerEmail
            ,Count(*) over (partition by CustomerEmail order by Date_Created asc) BaseOrderNumber

            ,dense_rank() over (order by CustomerEmail)
            + dense_rank() over (order by CustomerEmail desc)
            - 1 as TotalCustomersOverBase
            --,Count(Distinct CustomerEmail) over () as TotalCustomersOverBase
            --,ROW_NUMBER() over (partition by S.CustomerEmail order by Date_Created asc) PurchaseCount --this goes somewhere else

            --,(DENSE_RANK() over (partition by Month(I.Date_Created) order by CustomerEmail asc)
            --+DENSE_RANK() over (partition by Month(I.Date_Created) order by CustomerEmail desc))
            ---1 as TotalCustomersThisMonth

            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)
                LEFT JOIN (SELECT
                                ID.Company_Code
                                ,ID.Division_Code
                                ,ID.Invoice_Number
                                ,SUM (ID.Price* ID.Quantity) Total
                            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                            GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
                        ON I.Company_Code = ID.Company_Code
                        AND I.Division_Code = ID.Division_Code
                        AND I.Invoice_Number = ID.Invoice_Number
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[SpraygroundMagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

            Where I.Company_Code ='09' AND I.Division_Code = '001'
            AND I.Customer_Number = 'ECOM2X'
            AND ISNUMERIC(SH.CUST_PO) <> 0
            AND I.Date_Created BETWEEN DATEADD(month, -12, '1/1/2017') AND '12/31/2016'  -- Orders Base default is 12 months, options are 6,12, 18, and 24
            --AND CustomerEmail is NULL
        )T
        Where  T.Date_Created BETWEEN '6/1/2016' AND '1/1/2017'-- Customer Range
    )TT

    --
    --Order By CustomerEmail, RangeOrderNumber asc
    --

)TTT

--Order By Date_Created desc
--Order By CustomerEmail, RangeOrderNumber asc
Order By Month
</code>```

答:
When using the DISTINCT operator, the dataset returned will only contain distinct rows. That means that if 2 or more rows that contain the same values for every column that row will only be returned once.

In your first statement you only display the value for CustomerEmail, so you will get a dataset for every distinct/unique value of CustomerEmail.

In the second statment, you have Month(I.Date_Created) and CustomerEmail, so you will get a row for every distinct/unique value of those 2 values combined. This means that in your first dataset that was more than 1 row with a specific value for CustomerEmail, and when you added Month(I.Date_Created) there were (at least) 2 different value for that expression.

In very simple terms, take the statement below:

```<code>WITH N AS(
    SELECT *
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N (N)),
Tally AS(
    SELECT LEFT(NEWID(),1) AS C,
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3, N N4, N N5)
SELECT DISTINCT C
FROM Tally;
</code>```

Despite the tally table creating 100,000 rows, you probably only received a dataset of 16 rows. Now, let's add both columns to the DISTINCT:

```<code>WITH N AS(
    SELECT *
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N (N)),
Tally AS(
    SELECT LEFT(NEWID(),1) AS C,
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3, N N4, N N5)
SELECT DISTINCT C,I
FROM Tally;
</code>```

Now you get 100,000 rows, despite the fact that the underlying data hasn't changed (well, it has as new values for NEWID would have been generated, but for the purposes of the example it works).

Body:
I have a more complicated problem that I have tried to isolate down to it's components.

I have a simple query that returns all distinct customer emails (So every individual customer)

Select distinct
CustomerEmail

FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock) --I don't think the tables are relevant to the problem.
                LEFT JOIN (SELECT
                                ID.Company_Code
                                ,ID.Division_Code
                                ,ID.Invoice_Number
                                ,SUM (ID.Price* ID.Quantity) Total
                            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                            GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
                        ON I.Company_Code = ID.Company_Code
                        AND I.Division_Code = ID.Division_Code
                        AND I.Invoice_Number = ID.Invoice_Number
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[SpraygroundMagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

Where I.Company_Code ='09' AND I.Division_Code = '001'
AND I.Customer_Number = 'ECOM2X'
AND ISNUMERIC(SH.CUST_PO) <> 0
AND I.Date_Created BETWEEN DATEADD(month, -0, '6/1/2016') AND '1/1/2017'  -- Orders Base default is 12 months, options are 6,12, 18, and 24

This returns 19,516 rows.

If however, I add a second simple select statement to my query,

Select distinct
Month(I.Date_Created) Month,
CustomerEmail
FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)...

It now returns 20,452 rows.

Writing this question out, I think I understood the problem. It will duplicate the emails for different months. So if a customer placed an order on June and July, his email will appear twice, once for month 6 and once for month 7.

So this number should be more correct than the 19,516 number, right?

The way I calculate the TotalCustomers Number later in my more complex query is a simple Dense Rank statement

,DENSE_RANK() over (order by CustomerEmail asc)
+DENSE_RANK() over (order by CustomerEmail desc)
- 1 as TotalCustomersOverRange

This returns me 19,516 because it doesn't count multiple purchases. But this is also technically correct, because over that date range, there are less unique customers. Only when you break it out by month do you get duplicate customers who are really them same.

What is the best way to fix this? Here is my full query:

--Calculate average amount of time between purchase
--Calculate percentage of quantity and total increase with each purchase.
--Return most valued customers.
--User defined base range
-- later on, more refined user defined customer base, so if the base range is 18 months and the customer range is 1 month, it will only check the data against customers that purchased orders within the last month.
-- over the customer range, we define who the customers are. We call this RANGE
-- over the orderes base range,  we define and how many times they ordered. We call this BASE.
-- First we filter by month, returning total new orders and total recurring orders
-- (FOR OTHER REPORT, filter by state and not month)
-- Then within the month, we drill down to calculate how many customers are one orders, two orders, three orders, etc total
-- For each order amount, we calculate average days between orders, total value, lifetime value, and quantity changes

SELECT DISTINCT --*
Month

,(DENSE_RANK() over (partition by Month order by CustomerEmail asc)
    +DENSE_RANK() over (partition by Month order by CustomerEmail desc))
    -1 as TotalCustomersThisMonth

,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and RangeOrderNumber = 1 then 1 else 0 end) over (partition by Month) NewCustomersOverRangeThisMonth --Some of those customers aren't really new, if we expand to the base.
,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer = 1 then 1 else 0 end) over (partition by Month) NewCustomersOverBaseThisMonth
,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer > 1 then 1 else 0 end)  over (partition by Month) RecurringCustomersOverBaseButNewInRangeThisMonth -- Customers in Base who are not in range.
,Sum(Case When AmountOrdersOverRangeByCustomer > 1 and RangeOrderNumber =1 then 1 else 0 end)  over (partition by Month) RecurringCustomerOverRangeThisMonth
,TTT.NewCustomersOverRange
,TTT.NewCustomersOverBase
,TTT.RecurringCustomersOverBaseButNewInRange
,TTT.RecurringCustomerOverRange
,TTT.TotalCustomersOverBase
,TTT.TotalCustomersOverRange

FROM --This table calculates new and recurring customers.
(
    SELECT
    *
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and RangeOrderNumber = 1 then 1 else 0 end) over () NewCustomersOverRange --Some of those customers aren't really new, if we expand to the base.
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer = 1 then 1 else 0 end) over () NewCustomersOverBase
    ,Sum(Case When AmountOrdersOverRangeByCustomer = 1 and AmountOrdersOverBaseByCustomer > 1 then 1 else 0 end)  over () RecurringCustomersOverBaseButNewInRange -- Customers in Base who are not in range
    ,Sum(Case When AmountOrdersOverRangeByCustomer > 1 and RangeOrderNumber =1 then 1 else 0 end)  over () RecurringCustomerOverRange

    FROM -- This table gives you Order Numbers Per Customer
    (
        SELECT
            *
            ,ROW_NUMBER() over (partition by CustomerEmail order by Date_Created asc) RangeOrderNumber

            ,(DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
            +DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc))
            -1 as AmountOrdersOverRangeByCustomer

            ,Max(BaseOrderNumber) over (partition by CustomerEmail) AmountOrdersOverBaseByCustomer

            ,DENSE_RANK() over (order by CustomerEmail asc)
            +DENSE_RANK() over (order by CustomerEmail desc)
            - 1 as TotalCustomersOverRange

        FROM --This table gives you a line by line basis of every order
        (
            Select
             I.Date_Created
            ,I.Company_Code
            ,I.Division_Code
            ,I.Invoice_Number
            ,Sh.CUST_PO
            ,I.Total_Quantity
            ,ID.Total
            ,SH.Ship_City City
            ,CASE WHEN SH.Ship_Cntry <> 'US' THEN 'INT' ELSE SH.Ship_prov END State
            ,SH.Ship_Zip Zip
            ,SH.Ship_Cntry Country
            ,Month(I.Date_Created) Month
            ,S.CustomerEmail
            ,Count(*) over (partition by CustomerEmail order by Date_Created asc) BaseOrderNumber

            ,dense_rank() over (order by CustomerEmail)
            + dense_rank() over (order by CustomerEmail desc)
            - 1 as TotalCustomersOverBase
            --,Count(Distinct CustomerEmail) over () as TotalCustomersOverBase
            --,ROW_NUMBER() over (partition by S.CustomerEmail order by Date_Created asc) PurchaseCount --this goes somewhere else

            --,(DENSE_RANK() over (partition by Month(I.Date_Created) order by CustomerEmail asc)
            --+DENSE_RANK() over (partition by Month(I.Date_Created) order by CustomerEmail desc))
            ---1 as TotalCustomersThisMonth

            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)
                LEFT JOIN (SELECT
                                ID.Company_Code
                                ,ID.Division_Code
                                ,ID.Invoice_Number
                                ,SUM (ID.Price* ID.Quantity) Total
                            FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                            GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
                        ON I.Company_Code = ID.Company_Code
                        AND I.Division_Code = ID.Division_Code
                        AND I.Invoice_Number = ID.Invoice_Number
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
                LEFT JOIN
                    [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[SpraygroundMagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

            Where I.Company_Code ='09' AND I.Division_Code = '001'
            AND I.Customer_Number = 'ECOM2X'
            AND ISNUMERIC(SH.CUST_PO) <> 0
            AND I.Date_Created BETWEEN DATEADD(month, -12, '1/1/2017') AND '12/31/2016'  -- Orders Base default is 12 months, options are 6,12, 18, and 24
            --AND CustomerEmail is NULL
        )T
        Where  T.Date_Created BETWEEN '6/1/2016' AND '1/1/2017'-- Customer Range
    )TT

    --
    --Order By CustomerEmail, RangeOrderNumber asc
    --

)TTT

--Order By Date_Created desc
--Order By CustomerEmail, RangeOrderNumber asc
Order By Month

Body:
When using the DISTINCT operator, the dataset returned will only contain distinct rows. That means that if 2 or more rows that contain the same values for every column that row will only be returned once.

In your first statement you only display the value for CustomerEmail, so you will get a dataset for every distinct/unique value of CustomerEmail.

In the second statment, you have Month(I.Date_Created) and CustomerEmail, so you will get a row for every distinct/unique value of those 2 values combined. This means that in your first dataset that was more than 1 row with a specific value for CustomerEmail, and when you added Month(I.Date_Created) there were (at least) 2 different value for that expression.

In very simple terms, take the statement below:

WITH N AS(
    SELECT *
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N (N)),
Tally AS(
    SELECT LEFT(NEWID(),1) AS C,
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3, N N4, N N5)
SELECT DISTINCT C
FROM Tally;

Despite the tally table creating 100,000 rows, you probably only received a dataset of 16 rows. Now, let's add both columns to the DISTINCT:

WITH N AS(
    SELECT *
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N (N)),
Tally AS(
    SELECT LEFT(NEWID(),1) AS C,
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3, N N4, N N5)
SELECT DISTINCT C,I
FROM Tally;

Now you get 100,000 rows, despite the fact that the underlying data hasn't changed (well, it has as new values for NEWID would have been generated, but for the purposes of the example it works).


来源: stackexchange

问:
Get 2nd parent directory of given file
I have a script which finds files containing certain strings.

Let's say my found file is:

```
C:\temp\drivers\etc\file.INF
```

I want to get the 2nd parent folder for that file.

For example if it's:

```
C:\temp\drivers\etc\file.INF
```

I want to have this path:

```
C:\temp\drivers
```

What makes the most sense to you in a situation like this?

I can make it work with:

```<code>$test = "C:\temp\drivers\etc\file.INF"
$first_parent = Split-path $test -Parent
$second_parent= $first_parent.Substring(0,$first_parent.LastIndexOf('\'))
$second_parent
</code>```

Output:

```
C:\temp\drivers
```

But is it optimal?

答:
Using split-path twice gets it done. Easiest way is piping it :

```<code>$test = "C:\temp\drivers\etc\file.INF"
Split-path $test | split-path
</code>```

Output:

```<code>C:\temp\drivers
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get 2nd parent directory of given file

Body:
I have a script which finds files containing certain strings.

Let's say my found file is:

C:\temp\drivers\etc\file.INF

I want to get the 2nd parent folder for that file.

For example if it's:

C:\temp\drivers\etc\file.INF

I want to have this path:

C:\temp\drivers

What makes the most sense to you in a situation like this?

I can make it work with:

$test = "C:\temp\drivers\etc\file.INF"
$first_parent = Split-path $test -Parent
$second_parent= $first_parent.Substring(0,$first_parent.LastIndexOf('\'))
$second_parent

Output:

C:\temp\drivers

But is it optimal?

Body:
Using split-path twice gets it done. Easiest way is piping it :

$test = "C:\temp\drivers\etc\file.INF"
Split-path $test | split-path

Output:

C:\temp\drivers


问:
Missing first document when loading multi-document yaml file in pandas dataframe
I tried to load a multi-document yaml file (i.e., a yaml file consting of multiple yaml documents separated by "---") into a Pandas dataframe. For some reason, the first document does not end up in the dataframe. If the output of yaml.safe_load_all is first materialized into a list (instead of feeding the iterator to pd.io.json.json_normalize),all documents end up in the dataframe. I could reproduce this with the example code below (on an entirely different yaml file).

import os
import yaml
import pandas as pd
import urllib.request

# public example of multi-document yaml
inputfilepath = os.path.expanduser("~/my_example.yaml")
url =  "https://raw.githubusercontent.com/kubernetes/examples/master/guestbook/all-in-one/guestbook-all-in-one.yaml"
urllib.request.urlretrieve(url, inputfilepath)

with open(inputfilepath, 'r') as stream:
     df1 = pd.io.json.json_normalize(yaml.safe_load_all(stream))

with open(inputfilepath, 'r') as stream:
     df2 = pd.io.json.json_normalize([ x for x in yaml.safe_load_all(stream)])

print(f'Output table shape with iterator: {df1.shape}')
print(f'Output table shape with iterator materialized as list: {df2.shape}')

```

<p>I expect both results to be identical, but I get:</p>

```Output table shape with iterator: (5, 18)
Output table shape with iterator materialized as list: (6, 18)
```

Any ideas why these results differ?

答:
See this site for list comprehension vs. generator expressions.

df1 is missing the first row of data because you are passing a iterator instead of an iterable.

```<code>print(yaml.safe_load_all(stream))
#Output: <generator object load_all at 0x00000293E1697750>
</code>```

From the pandas docs, it is expecting a list:

data : dict or list of dicts

Update for more detail:

From looking into the normalize.py source file, the function json_normalize has this conditional check that's making it so your generator is treated like you passed in a nested structure:

```<code>if any([isinstance(x, dict)
    for x in compat.itervalues(y)] for y in data):
        # naive normalization, this is idempotent for flat records
        # and potentially will inflate the data considerably for
        # deeply nested structures:
        #  {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}
        #
        # TODO: handle record value which are lists, at least error
        #       reasonably
        data = nested_to_record(data, sep=sep)
    return DataFrame(data)
</code>```

Inside of the nested_to_record function:

```<code>new_d = copy.deepcopy(d)
for k, v in d.items():
    # each key gets renamed with prefix
    if not isinstance(k, compat.string_types):
        k = str(k)
    if level == 0:
        newkey = k
    else:
        newkey = prefix + sep + k

    # only dicts gets recurse-flattend
    # only at level>1 do we rename the rest of the keys
    if not isinstance(v, dict):
        if level != 0:  # so we skip copying for top level, common case
            v = new_d.pop(k)
            new_d[newkey] = v
        continue
    else:
        v = new_d.pop(k)
        new_d.update(nested_to_record(v, newkey, sep, level + 1))
new_ds.append(new_d)
</code>```

The line d.items() is where your generator is evaluated and inside the loop is where you can see they skip the first "level", which in your case is the first record.

Body:
I tried to load a multi-document yaml file (i.e., a yaml file consting of multiple yaml documents separated by "---") into a Pandas dataframe. For some reason, the first document does not end up in the dataframe. If the output of yaml.safe_load_all is first materialized into a list (instead of feeding the iterator to pd.io.json.json_normalize),all documents end up in the dataframe. I could reproduce this with the example code below (on an entirely different yaml file).

import os
import yaml
import pandas as pd
import urllib.request

# public example of multi-document yaml
inputfilepath = os.path.expanduser("~/my_example.yaml")
url =  "https://raw.githubusercontent.com/kubernetes/examples/master/guestbook/all-in-one/guestbook-all-in-one.yaml"
urllib.request.urlretrieve(url, inputfilepath)

with open(inputfilepath, 'r') as stream:
     df1 = pd.io.json.json_normalize(yaml.safe_load_all(stream))

with open(inputfilepath, 'r') as stream:
     df2 = pd.io.json.json_normalize([ x for x in yaml.safe_load_all(stream)])

print(f'Output table shape with iterator: {df1.shape}')
print(f'Output table shape with iterator materialized as list: {df2.shape}')

I expect both results to be identical, but I get:

Output table shape with iterator: (5, 18)
Output table shape with iterator materialized as list: (6, 18)

Any ideas why these results differ?

Body:
See this site for list comprehension vs. generator expressions.

df1 is missing the first row of data because you are passing a iterator instead of an iterable.

print(yaml.safe_load_all(stream))
#Output: <generator object load_all at 0x00000293E1697750>

From the pandas docs, it is expecting a list:

data : dict or list of dicts

Update for more detail:

From looking into the normalize.py source file, the function json_normalize has this conditional check that's making it so your generator is treated like you passed in a nested structure:

if any([isinstance(x, dict)
    for x in compat.itervalues(y)] for y in data):
        # naive normalization, this is idempotent for flat records
        # and potentially will inflate the data considerably for
        # deeply nested structures:
        #  {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}
        #
        # TODO: handle record value which are lists, at least error
        #       reasonably
        data = nested_to_record(data, sep=sep)
    return DataFrame(data)

Inside of the nested_to_record function:

new_d = copy.deepcopy(d)
for k, v in d.items():
    # each key gets renamed with prefix
    if not isinstance(k, compat.string_types):
        k = str(k)
    if level == 0:
        newkey = k
    else:
        newkey = prefix + sep + k

    # only dicts gets recurse-flattend
    # only at level>1 do we rename the rest of the keys
    if not isinstance(v, dict):
        if level != 0:  # so we skip copying for top level, common case
            v = new_d.pop(k)
            new_d[newkey] = v
        continue
    else:
        v = new_d.pop(k)
        new_d.update(nested_to_record(v, newkey, sep, level + 1))
new_ds.append(new_d)

The line d.items() is where your generator is evaluated and inside the loop is where you can see they skip the first "level", which in your case is the first record.


问:
getline() doesn't read accented characters correctly
I'm trying to get accented characters from user using getline() command, but it does not print them correctly.

I tried to include some libraries as locale, but it was in vain.

Here's my code:

```<code>#include <iostream>
#include <cstdlib>
#include <string>
#include <locale>

using namespace std;

class Pers {
public:
    string name;
    int age;
    string weapon;
};

int main()
{
    setlocale(LC_ALL, "");
    Pers pers;

    cout << "Say the name of your character: ";
    getline(cin, pers.name);
    cout << pers.name;
}
</code>```

When I type: Mark Coração, this is what I get:

How do I fix it?

答:
Actually, the problem does not come from getline().

std::cout (respectively std::cin) does not support special characters. For this, you have to use std::wcout (respectively std::wcin) which uses wide characters (the size of standard characters limits you to what you can find in the ascii table).
You need to use bigger characters to store the special characters too, that is the case of wide characters.
std::string handles standard characters, std::wstring handles wide characters.

A way to do this could be:

```<code>std::wstring a(L"Coração");
std::wcout << a << std::endl;
</code>```

Output:

Coração

To make it work with getline():

```<code>std::wstring a;
getline(std::wcin, a)
std::wcout << a << std::endl;
</code>```

I hope it can help.

Body:
I'm trying to get accented characters from user using getline() command, but it does not print them correctly.

I tried to include some libraries as locale, but it was in vain.

Here's my code:

#include <iostream>
#include <cstdlib>
#include <string>
#include <locale>

using namespace std;

class Pers {
public:
    string name;
    int age;
    string weapon;
};

int main()
{
    setlocale(LC_ALL, "");
    Pers pers;

    cout << "Say the name of your character: ";
    getline(cin, pers.name);
    cout << pers.name;
}

When I type: Mark Coração, this is what I get:

How do I fix it?

Body:
Actually, the problem does not come from getline().

std::cout (respectively std::cin) does not support special characters. For this, you have to use std::wcout (respectively std::wcin) which uses wide characters (the size of standard characters limits you to what you can find in the ascii table).
You need to use bigger characters to store the special characters too, that is the case of wide characters.
std::string handles standard characters, std::wstring handles wide characters.

A way to do this could be:

std::wstring a(L"Coração");
std::wcout << a << std::endl;

Output:

Coração

To make it work with getline():

std::wstring a;
getline(std::wcin, a)
std::wcout << a << std::endl;

I hope it can help.


问:
How to fix Uncaught TypeError in Phaser 3 for Game Development
I'm following a space shooter tutorial for a game I'm developing as I learn Javascript. The tutorial puts many of the classes in the same file stacked on top of each other, but I've read this isn't a good practice and all Classes should have their own separate file. The link for the tutorial is here...

https://yorkcs.com/2019/02/08/build-a-space-shooter-with-phaser-3-4/

I've made sure everything is typed properly, but whenever I run it in Chrome (and I've cleared my cache too), I get an error message that says...

Uncaught TypeError: Cannot read property 'getFirstTick' of null

It's throwing the error on line 21 of enemies.js for this line of code...

```<code>this.play( 'basicenemy' );
</code>```

I've tried several things because I've gotten different errors. I think I've made the mistake of following separate tutorials. I've tried adding the images to the files themselves instead of the sceneMain.js file where the first level is because at one point it was telling me that play() was undefined.

entities.js

```<code>class Entities extends Phaser.GameObjects.Sprite
{
  constructor(scene, x, y, key, type)
  {
    super(scene, x, y, key, type);
    this.scene = scene;
    this.scene.add.existing(this);
    this.scene.physics.world.enableBody(this, 0);
    this.setData("type", type);
    this.setData("isDead", false);
  }
}
</code>```

enemies.js

```<code>class BasicEnemy extends Entities
{
  constructor(scene, x, y)
  {
    super(scene, x, y, 'basicenemy', 'BasicEnemy');
    this.body.velocity.y = Phaser.Math.Between(50, 100);
    this.shootTimer = this.scene.time.addEvent({
        delay: 1000,
        callback: function() {
          var laser = new EnemyLaser(
            this.scene,
            this.x,
            this.y
          );
          laser.setScale(this.scaleX);
          this.scene.enemyLasers.add(laser);
        },
        callbackScope: this,
        loop: true
      });
    this.play( 'basicenemy' );
  }
}
</code>```

sceneMain.js

```<code>//The Bullet Group
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function() {
          var enemy = new BasicEnemy(
            this,
            Phaser.Math.Between(0, this.game.config.width),
            0
          );
          this.basicEnemy.add(enemy);
        },
        callbackScope: this,
        loop: true
      });
</code>```

In sceneMain.js I'm trying to get enemies to spawn from the top of the screen with this line...

```<code>this.basicEnemy.add(enemy);
</code>```

Any help would be much appreciated.

答:
OMG I got it to work!!! I simply removed this.play() from enemies.js and added it to sceneMain.js. This is the new code that works! For some reason it didn't want to play from the Enemies class, but it plays in sceneMain. I figured I would just use the code that already worked to spawn three static enemies that didn't move and would use it to spawn the enemies that drop from the top that the tutorial shows. Now I have enemies that are stationary and enemies that spawn and shoot bullets!

```<code>//The Enemies and Bullet Group That Spawns from the Top
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function()
        {
          var enemy = new BasicEnemy( this, Phaser.Math.Between(0, this.game.config.width), 0 );
          this.basicEnemy = this.physics.add.sprite(enemy);
          this.basicEnemy.play( 'badfly', this);
        },
        callbackScope: this,
        loop: true
      });
</code>```

Body:
I'm following a space shooter tutorial for a game I'm developing as I learn Javascript. The tutorial puts many of the classes in the same file stacked on top of each other, but I've read this isn't a good practice and all Classes should have their own separate file. The link for the tutorial is here...

https://yorkcs.com/2019/02/08/build-a-space-shooter-with-phaser-3-4/

I've made sure everything is typed properly, but whenever I run it in Chrome (and I've cleared my cache too), I get an error message that says...

Uncaught TypeError: Cannot read property 'getFirstTick' of null

It's throwing the error on line 21 of enemies.js for this line of code...

this.play( 'basicenemy' );

I've tried several things because I've gotten different errors. I think I've made the mistake of following separate tutorials. I've tried adding the images to the files themselves instead of the sceneMain.js file where the first level is because at one point it was telling me that play() was undefined.

entities.js

class Entities extends Phaser.GameObjects.Sprite
{
  constructor(scene, x, y, key, type)
  {
    super(scene, x, y, key, type);
    this.scene = scene;
    this.scene.add.existing(this);
    this.scene.physics.world.enableBody(this, 0);
    this.setData("type", type);
    this.setData("isDead", false);
  }
}

enemies.js

class BasicEnemy extends Entities
{
  constructor(scene, x, y)
  {
    super(scene, x, y, 'basicenemy', 'BasicEnemy');
    this.body.velocity.y = Phaser.Math.Between(50, 100);
    this.shootTimer = this.scene.time.addEvent({
        delay: 1000,
        callback: function() {
          var laser = new EnemyLaser(
            this.scene,
            this.x,
            this.y
          );
          laser.setScale(this.scaleX);
          this.scene.enemyLasers.add(laser);
        },
        callbackScope: this,
        loop: true
      });
    this.play( 'basicenemy' );
  }
}

sceneMain.js

//The Bullet Group
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function() {
          var enemy = new BasicEnemy(
            this,
            Phaser.Math.Between(0, this.game.config.width),
            0
          );
          this.basicEnemy.add(enemy);
        },
        callbackScope: this,
        loop: true
      });

In sceneMain.js I'm trying to get enemies to spawn from the top of the screen with this line...

this.basicEnemy.add(enemy);

Any help would be much appreciated.

Body:
OMG I got it to work!!! I simply removed this.play() from enemies.js and added it to sceneMain.js. This is the new code that works! For some reason it didn't want to play from the Enemies class, but it plays in sceneMain. I figured I would just use the code that already worked to spawn three static enemies that didn't move and would use it to spawn the enemies that drop from the top that the tutorial shows. Now I have enemies that are stationary and enemies that spawn and shoot bullets!

//The Enemies and Bullet Group That Spawns from the Top
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function()
        {
          var enemy = new BasicEnemy( this, Phaser.Math.Between(0, this.game.config.width), 0 );
          this.basicEnemy = this.physics.add.sprite(enemy);
          this.basicEnemy.play( 'badfly', this);
        },
        callbackScope: this,
        loop: true
      });


问:
Monitoring instances in cloud
I usually use Munin as monitoring software, but this (as others software I presume) needs an IP to make the ICMP or whatever pings to collect data.

In Amazon EC2 instances are created on the fly, with IP's you don't know.

How can they be monitored ?

I was thinking about using amazon console commands to read the IP's of the instances up, and change the monit configuration file on the fly also , but it can be too complicated ... or not?

Any other solution / suggestion ?

Thank you

答:
Our instances are bootstrapped using chef recipes, so it's easier for me to provide IPs/hosts as they (= all members of my cluster) get entered into /etc/hosts on start-up. Generally, it doesn't hurt to use elastic IPs for a master server and allow all connections (in /etc/munin/munin.conf by default).

I'd solve the security 'question' on the security groups level. E.g. allow only instances with a certain security group to connect to the munin-node process (on port 4949). The question which remains is.

E.g., using ec2-authorize you can achieve

```<code>ec2-authorize mygroup -o monitorgroup -u <AWS-USER-ID>
</code>```

This means that all instances with group monitorgroup can access resources on instances with mygroup.

Let me know if this helps!

ContentLicense: CC BY-SA 2.5

Title: Monitoring instances in cloud

Body:
Our instances are bootstrapped using chef recipes, so it's easier for me to provide IPs/hosts as they (= all members of my cluster) get entered into /etc/hosts on start-up. Generally, it doesn't hurt to use elastic IPs for a master server and allow all connections (in /etc/munin/munin.conf by default).

I'd solve the security 'question' on the security groups level. E.g. allow only instances with a certain security group to connect to the munin-node process (on port 4949). The question which remains is.

E.g., using ec2-authorize you can achieve

ec2-authorize mygroup -o monitorgroup -u <AWS-USER-ID>

This means that all instances with group monitorgroup can access resources on instances with mygroup.

Let me know if this helps!

ContentLicense: CC BY-SA 3.0


问:
Android Studio gradle can't import groovy.swing.SwingBuilder
I'm using this technique to make release builds ask for keystore passwords, but lately the Android Studio editor for build.gradle complains:

```<code>Cannot resolve symbol 'groovy'
</code>```

for the line:

```<code>import groovy.swing.SwingBuilder
</code>```

It didn't used to complain. The command line build ./gradlew assembleRelease still works. It's only AS that can't import groovy.

This is with Android Studio 2.3.1, Gradle 3.3, Android Gradle plugin 2.3.1.

Is there some AS configuration to make it happy?

Amazingly enough, the import error doesn't keep AS from making debug builds, and build.gradle doesn't try to use Swing in a debug build.

答:
Swing is an alternative Java library for creating UI, and this is in contravention to the Core Android APIs. As such, Swing is not supported on Android.

This page has the list of available Java packages (from Java 8, or whatever Version you put in your build.gradle...) https://developer.android.com/reference/packages.html

Body:
I'm using this technique to make release builds ask for keystore passwords, but lately the Android Studio editor for build.gradle complains:

Cannot resolve symbol 'groovy'

for the line:

import groovy.swing.SwingBuilder

It didn't used to complain. The command line build ./gradlew assembleRelease still works. It's only AS that can't import groovy.

This is with Android Studio 2.3.1, Gradle 3.3, Android Gradle plugin 2.3.1.

Is there some AS configuration to make it happy?

Amazingly enough, the import error doesn't keep AS from making debug builds, and build.gradle doesn't try to use Swing in a debug build.


问:
Docker setting entrypoint when attaching volume -v
Previously, I was able to attach a folder on my desktop as a volume in my container like so:

```<code>docker run -it --rm -v /Users/me/Desktop/Jupyter:/home/jovyan/work -p 8888:8888 jupyter/all-spark-notebook
</code>```

However, when I run...

```<code>docker run -it -v /Users/me/Desktop/nfscripts:/usr nextflow/nextflow /bin/bash
</code>```

... I get the following error:

```<code>docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/usr/local/bin/entry.sh\": stat /usr/local/bin/entry.sh: no such file or directory": unknown.
</code>```

When I launch an interactive session and check the directory I get the base / and I can see usr directory.

```<code>$ docker run -it nextflow/nextflow /bin/bash
$ pwd
/
$ ls
bin  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
</code>```

I recognize /usr/local/bin/entry.sh from the Cmd and it definitely exists because I can cat it.

```<code>            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "ENTRYPOINT [\"/usr/local/bin/entry.sh\"]"
            ],
</code>```

Am I not allowed to mount :/usr because it's in the path of the entry point?

答:
You need to mount the specified entrypoint, which can be different from the directory your launch an interactive session into:</p>

```<code>docker run -it --rm -v /Users/me/Desktop/nfscripts:/usr/local/bin/entry nextflow/nextflow /bin/bash
</code>```

Body:
Previously, I was able to attach a folder on my desktop as a volume in my container like so:

docker run -it --rm -v /Users/me/Desktop/Jupyter:/home/jovyan/work -p 8888:8888 jupyter/all-spark-notebook

However, when I run...

docker run -it -v /Users/me/Desktop/nfscripts:/usr nextflow/nextflow /bin/bash

... I get the following error:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/usr/local/bin/entry.sh\": stat /usr/local/bin/entry.sh: no such file or directory": unknown.

When I launch an interactive session and check the directory I get the base / and I can see usr directory.

$ docker run -it nextflow/nextflow /bin/bash
$ pwd
/
$ ls
bin  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

I recognize /usr/local/bin/entry.sh from the Cmd and it definitely exists because I can cat it.

            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "ENTRYPOINT [\"/usr/local/bin/entry.sh\"]"
            ],

Am I not allowed to mount :/usr because it's in the path of the entry point?

Body:
You need to mount the specified entrypoint, which can be different from the directory your launch an interactive session into:

docker run -it --rm -v /Users/me/Desktop/nfscripts:/usr/local/bin/entry nextflow/nextflow /bin/bash


问:
What am I doing wrong? radius = radius + 25
```<code>Line 14: radius = radius + 25
</code>```

Error message:

```<code>UnboundLocalError: local variable 'radius' referenced before assignment on line 14
</code>```

I have no idea why this is throwing an error. as far as I'm aware the computer's just being dumb...

```<code>I have another question, and I am not waiting two days for an answer.
but a bit of backstory is necessary. I'm using CodeHS to learn Python. I'm on lesson 2.12.5, and this is my code.
`
global sidereal
sidereal=int(input("How large do you like your squares? (1-400)")
def squaretine():
    for i in range(4)
        pendown()
        forward(sidereal)
        left(90)
        penup()
squaretine()
`
And this is my error:
ParseError: bad input on line 3

I could't even tell you what's wrong, I personally don't see any errors...

</code>```

答:
Most likely, you are doing an operation on radius before the variable is created. You have to create it before as follows :</p>

```<code># x the value you want to give to radius
radius = x
radius = radius + 25
</code>```

Body:
Line 14: radius = radius + 25

Error message:

UnboundLocalError: local variable 'radius' referenced before assignment on line 14

I have no idea why this is throwing an error. as far as I'm aware the computer's just being dumb...

I have another question, and I am not waiting two days for an answer.
but a bit of backstory is necessary. I'm using CodeHS to learn Python. I'm on lesson 2.12.5, and this is my code.
`
global sidereal
sidereal=int(input("How large do you like your squares? (1-400)")
def squaretine():
    for i in range(4)
        pendown()
        forward(sidereal)
        left(90)
        penup()
squaretine()
`
And this is my error:
ParseError: bad input on line 3

I could't even tell you what's wrong, I personally don't see any errors...

Body:
Most likely, you are doing an operation on radius before the variable is created. You have to create it before as follows :

# x the value you want to give to radius
radius = x
radius = radius + 25


问:
Calculate price of radio button and drop-down list
I have a radio-button list and a drop-down list that are populated from a database:

```<code>  <ul id="radio" class="input-list">
  <?php
  $stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
  $stmt->execute();
  $stmt->bind_result($case_id, $case_name, $case_price);
  while($stmt->fetch()) {
  echo '<li>
 <input class="selectedoptions" id="'.$case_id.'" name="config-prod" value="'.$case_price.'" type="radio">
  <label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
 </li>';
 }
 $stmt->close();
 ?>
 </ul>

  <?php
  echo "<select class='form-control' id='plist' name='partlist'>";
  $type = "processors";

 $stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM parts WHERE type=?");
 $stmt2->bind_param("s", $type);
 $stmt2->execute();
 $stmt2->bind_result($cpu_id, $cpu_name, $cpu_price);
 while($stmt2->fetch()){
  echo "<option value='$cpu_price'>$cpu_name</option>";
 }
 $stmt2->close();
 echo "</select>";
 ?>
</code>```

I would like to be able to obtain the price of the selected item from the two lists. I have tried to do this with JS:

```<code><script>

    var buildcost = 25.00;

    function updateTotal() {
    var radios = document.getElementsByName('config-prod');
    var partcost;

    for (var i = 0, length = radios.length; i < length; i++) {
        if (radios[i].checked) {
                partcost = parseInt(radios[i].value);
            break;
        }
    }

    total_cost = buildcost + partcost;
    document.getElementById('total').innerHTML = total_cost;

}
</script>
</code>```

The total_cost should be output to this:

```<code><input name="buildTotal" id="total" type="text" class="transparentFieldy float-price" disabled="" />
</code>```

However, this does not output anything. How do I change this to be able to calculate the price based on the selected elements? Thanks!

答:
To set the content of input-elements you have to use the value-property instead of innerHTML. You should also consider using parseFloat if you are dealing with currency.

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

<br>
Total: <input id="total" type="text"><button id="update" onclick="updateTotal();">Update</button></code>```

Body:
I have a radio-button list and a drop-down list that are populated from a database:

  <?php
  $stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
  $stmt->execute();
  $stmt->bind_result($case_id, $case_name, $case_price);
  while($stmt->fetch()) {
  echo '

 <input class="selectedoptions" id="'.$case_id.'" name="config-prod" value="'.$case_price.'" type="radio">
  '.$case_name.'         [£'.$case_price.']

';
 }
 $stmt->close();
 ?>

  <?php
  echo "<select class='form-control' id='plist' name='partlist'>";
  $type = "processors";

 $stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM parts WHERE type=?");
 $stmt2->bind_param("s", $type);
 $stmt2->execute();
 $stmt2->bind_result($cpu_id, $cpu_name, $cpu_price);
 while($stmt2->fetch()){
  echo "<option value='$cpu_price'>$cpu_name</option>";
 }
 $stmt2->close();
 echo "</select>";
 ?>

I would like to be able to obtain the price of the selected item from the two lists. I have tried to do this with JS:

The total_cost should be output to this:

<input name="buildTotal" id="total" type="text" class="transparentFieldy float-price" disabled="" />

However, this does not output anything. How do I change this to be able to calculate the price based on the selected elements? Thanks!

Body:
To set the content of input-elements you have to use the value-property instead of innerHTML. You should also consider using parseFloat if you are dealing with currency.

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

<br>
Total: <input id="total" type="text"><button id="update" onclick="updateTotal();">Update</button>


问:
INSERT statement conflicted with the FOREIGN KEY constraint after first 1k insert
I am attempting to insert about 30k rows of data into a database.  The first thousand rows go through without any problem but after that I keep getting the error "INSERT statement conflicted with the FOREIGN KEY constraint"

I am inserting into one table first getting the identity and then using that as a fk for the other table.  Code looks like

```<code> insert into PYMT_HIST(PAR_NUM,BILL_NUM,RCPT_NUM,TAX_YR,TOT_AMT_DUE,TOT_PD,PD_DATE,PD_BY,MUNI_DIST_ID)
        values (@par_num,@BILL_NUM,@RCTP_NUM,@TAX_YR,@TOT_AMT_DUE,@TOT_PD,(Convert(datetime,@PD_DATE)),@PD_BY,@MUNI_DIST_ID);
    set @pymt_hist_id = @@identity

    IF  @REAL_ESTATE > 0

        insert into PYMT_HIST_DETL(PYMT_HIST_ID,AMT_PD,FIN_TXN_LN_TY_ID)
                values(@pymt_hist_id,@REAL_ESTATE,1);
</code>```

答: Try using Scope_Identity() function instead of @@Identity.  @@Identity has global scope and could be getting changed outside the scope of the work you are doing.</p>

Body:
I am attempting to insert about 30k rows of data into a database.  The first thousand rows go through without any problem but after that I keep getting the error "INSERT statement conflicted with the FOREIGN KEY constraint"

I am inserting into one table first getting the identity and then using that as a fk for the other table.  Code looks like

 insert into PYMT_HIST(PAR_NUM,BILL_NUM,RCPT_NUM,TAX_YR,TOT_AMT_DUE,TOT_PD,PD_DATE,PD_BY,MUNI_DIST_ID)
        values (@par_num,@BILL_NUM,@RCTP_NUM,@TAX_YR,@TOT_AMT_DUE,@TOT_PD,(Convert(datetime,@PD_DATE)),@PD_BY,@MUNI_DIST_ID);
    set @pymt_hist_id = @@identity

    IF  @REAL_ESTATE > 0

        insert into PYMT_HIST_DETL(PYMT_HIST_ID,AMT_PD,FIN_TXN_LN_TY_ID)
                values(@pymt_hist_id,@REAL_ESTATE,1);


问:
Filter top n largest groups in data.frame
For the example data:

```<code>set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3
</code>```

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

```<code>example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6
</code>```

The expected output is:

```<code>   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3
</code>```

答:
We can use tidyverse methods for this.  Create a frequency column with add_count, arrange by that column and filter the rows where the 'group' is in the last two unique 'group' values

```<code>library(dplyr)
example_data %>%
   add_count(group) %>%
   arrange(n) %>%
   filter(group %in% tail(unique(group), 2)) %>%
   select(-n)
# A tibble: 11 x 3
#    col1  col2 group
#  <int> <int> <int>
# 1     1    16     2
# 2     4    19     2
# 3    11    26     2
# 4    12    27     2
# 5    13    28     2
# 6     3    18     3
# 7     5    20     3
# 8     7    22     3
# 9     9    24     3
#10    14    29     3
#11    15    30     3
</code>```

Or using data.table

```<code>library(data.table)
setDT(example_data)[group %in% example_data[, .N, group][order(-N), head(group, 2)]]
</code>```

Body:
For the example data:

set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6

The expected output is:

   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3

Body:
We can use tidyverse methods for this.  Create a frequency column with add_count, arrange by that column and filter the rows where the 'group' is in the last two unique 'group' values

library(dplyr)
example_data %>%
   add_count(group) %>%
   arrange(n) %>%
   filter(group %in% tail(unique(group), 2)) %>%
   select(-n)
# A tibble: 11 x 3
#    col1  col2 group
#  <int> <int> <int>
# 1     1    16     2
# 2     4    19     2
# 3    11    26     2
# 4    12    27     2
# 5    13    28     2
# 6     3    18     3
# 7     5    20     3
# 8     7    22     3
# 9     9    24     3
#10    14    29     3
#11    15    30     3

Or using data.table

library(data.table)
setDT(example_data)[group %in% example_data[, .N, group][order(-N), head(group, 2)]]


问:
Using in-memory filesystem in `pyarrow` tests
I have some pyarrow Parquet dataset writing code. I want to have an integration test that ensures the file is written correctly. I'd like to do that by writing a small example data chunk to an in-memory filesystem. However, I'm struggling to find a pyarrow-compatible in-memory filesystem interface for Python.

You'll find a snippet of code that has a filesystem variable in it below. I'd like to replace the filesystem variable with an in-memory filesystem that I can later inspect in integration tests programmatically.

import pyarrow.parquet as pq
pq.write_to_dataset(
        score_table,
        root_path=AWS_ZEBRA_OUTPUT_S3_PREFIX,
        filesystem=filesystem,
        partition_cols=[
            EQF_SNAPSHOT_YEAR_PARTITION,
            EQF_SNAPSHOT_MONTH_PARTITION,
            EQF_SNAPSHOT_DAY_PARTITION,
            ZEBRA_COMPUTATION_TIMESTAMP
        ]
    )
```

答:
You can pass an in-memory file object to write_to_dataset if filesystem is None.

So your call might become:

```<code>from io import BytesIO
import pyarrow.parquet as pq

with BytesIO() as f:
    pq.write_to_dataset(
        score_table,
        root_path=f,
        filesystem=None,
        partition_cols=[
            EQF_SNAPSHOT_YEAR_PARTITION,
            EQF_SNAPSHOT_MONTH_PARTITION,
            EQF_SNAPSHOT_DAY_PARTITION,
            ZEBRA_COMPUTATION_TIMESTAMP
        ]
    )
</code>```

Relevant lines from pyarrow source:

```<code>def resolve_filesystem_and_path(where, filesystem=None):
    """
    Return filesystem from path which could be an HDFS URI, a local URI,
    or a plain filesystem path.
    """
    if not _is_path_like(where):
        if filesystem is not None:
            raise ValueError("filesystem passed but where is file-like, so"
                             " there is nothing to open with filesystem.")
        return filesystem, where
</code>```

https://github.com/apache/arrow/blob/207b3507be82e92ebf29ec7d6d3b0bb86091c09a/python/pyarrow/filesystem.py#L402-L411

Body:
You can pass an in-memory file object to write_to_dataset if filesystem is None.

So your call might become:

from io import BytesIO
import pyarrow.parquet as pq

with BytesIO() as f:
    pq.write_to_dataset(
        score_table,
        root_path=f,
        filesystem=None,
        partition_cols=[
            EQF_SNAPSHOT_YEAR_PARTITION,
            EQF_SNAPSHOT_MONTH_PARTITION,
            EQF_SNAPSHOT_DAY_PARTITION,
            ZEBRA_COMPUTATION_TIMESTAMP
        ]
    )

Relevant lines from pyarrow source:

def resolve_filesystem_and_path(where, filesystem=None):
    """
    Return filesystem from path which could be an HDFS URI, a local URI,
    or a plain filesystem path.
    """
    if not _is_path_like(where):
        if filesystem is not None:
            raise ValueError("filesystem passed but where is file-like, so"
                             " there is nothing to open with filesystem.")
        return filesystem, where

https://github.com/apache/arrow/blob/207b3507be82e92ebf29ec7d6d3b0bb86091c09a/python/pyarrow/filesystem.py#L402-L411


问:
Does aria-haspopup require a true/false value?
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

```<code><div role="combobox" aria-expanded="false" aria-owns="ex1-listbox" aria-haspopup="listbox" id="ex1-combobox">
    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">
</div>
</code>```

答:
W3 specifications

If the w3 spec says its value can be true or false, then that is what browsers will be implementing.

If the attribute accepts other values, its undefined behavior. Avoid this if possible.

Some times the values of accepted attributes will change over the different versions of the w3 specification.

Body:
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">


问:
Cannot pass params using navigate and multiple StackNavigators
```<code>  render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation("VideoPlayer", video);
              }}
              style={styles.text}
            >
              {title}
            </Text>
</code>```

Using seperate stackNavigators in a DrawerNavigator, in my component I use getParam, however, its empty, how can I pass props?

```<code>  render() {
    const { navigation } = this.props;
    const videoId = navigation.getParam("video", ''); // empty

    return (
</code>```

AppNavigator:

```<code>const config = {
    initialRouteName: "Home",
    contentOptions: {
        activeTintColor: "#e91e63",
        itemStyle: {
            flexDirection: "row-reverse"
        }
    },
    drawerWidth: 300,
    drawerPosition: "right"
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({ navigation, routeName, props }) => ({
                    header: props => <Header {...props} />
                })
            }
        },
        {
            transparentCard: true
        }
    );

const routes = {
    Home: {
        screen: withHeader(HomeScreen, "Home", BasicHeader)
    },
    Links: {
        screen: withHeader(LinksScreen, "Links", DrawerHeader)
    },
    Settings: {
        screen: withHeader(SettingsScreen, "Settings", DrawerHeader)
    },
    VideoEpisodes: {
        screen: withHeader(VideoEpisodesScreen, "Video Episodes", DrawerHeader)
    },
    VideoPlayer: {
        screen: withHeader(VideoPlayerScreen, "Video Player", DrawerHeader)
    },
    TestYourself: {
        screen: withHeader(TestYourselfScreen, "Test Yourself", DrawerHeader)
    },
    MyResults: {
        screen: withHeader(MyResultsScreen, "My Results", DrawerHeader)
    },
    BookmarkedVideos: {
        screen: withHeader(
            BookmarkedVideosScreen,
            "Bookmarked Videos",
            DrawerHeader
        )
    },
    Search: {
        screen: withHeader(SearchScreen, "Search", DrawerHeader)
    },
    About: {
        screen: withHeader(AboutScreen, "About", DrawerHeader)
    }
};

const AppNavigator = createDrawerNavigator(routes, config);

export default createAppContainer(AppNavigator);
</code>```

VideoPlayer:

```<code>    export default class VideoPlayerScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          video: this.props.navigation.state.params.video
        };
      }
      render() {
        console.log(this.state.video);

        return (
          <View style={styles.container}>
            <VideoPlayer {...this.props} />
          </View>
        );
      }

}
</code>```

Snack setup here

答:
If the video has the right value,

 render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation.navigate("VideoPlayer", {video: video });
              }}
              style={styles.text}
            >
              {title}
            </Text>
```

<blockquote>
  <p>VideoPlayer Screen:</p>
</blockquote>

<pre class="lang-js prettyprint-override"><code>constructor(props) {
    super(props);
    this.state = {
      video: this.props.navigation.state.params.video,
    };
  }
</code>```

Body:
  render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation("VideoPlayer", video);
              }}
              style={styles.text}
            >
              {title}
            </Text>

Using seperate stackNavigators in a DrawerNavigator, in my component I use getParam, however, its empty, how can I pass props?

  render() {
    const { navigation } = this.props;
    const videoId = navigation.getParam("video", ''); // empty

    return (

AppNavigator:

const config = {
    initialRouteName: "Home",
    contentOptions: {
        activeTintColor: "#e91e63",
        itemStyle: {
            flexDirection: "row-reverse"
        }
    },
    drawerWidth: 300,
    drawerPosition: "right"
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({ navigation, routeName, props }) => ({
                    header: props =>
                })
            }
        },
        {
            transparentCard: true
        }
    );

const routes = {
    Home: {
        screen: withHeader(HomeScreen, "Home", BasicHeader)
    },
    Links: {
        screen: withHeader(LinksScreen, "Links", DrawerHeader)
    },
    Settings: {
        screen: withHeader(SettingsScreen, "Settings", DrawerHeader)
    },
    VideoEpisodes: {
        screen: withHeader(VideoEpisodesScreen, "Video Episodes", DrawerHeader)
    },
    VideoPlayer: {
        screen: withHeader(VideoPlayerScreen, "Video Player", DrawerHeader)
    },
    TestYourself: {
        screen: withHeader(TestYourselfScreen, "Test Yourself", DrawerHeader)
    },
    MyResults: {
        screen: withHeader(MyResultsScreen, "My Results", DrawerHeader)
    },
    BookmarkedVideos: {
        screen: withHeader(
            BookmarkedVideosScreen,
            "Bookmarked Videos",
            DrawerHeader
        )
    },
    Search: {
        screen: withHeader(SearchScreen, "Search", DrawerHeader)
    },
    About: {
        screen: withHeader(AboutScreen, "About", DrawerHeader)
    }
};

const AppNavigator = createDrawerNavigator(routes, config);

export default createAppContainer(AppNavigator);

VideoPlayer:

    export default class VideoPlayerScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          video: this.props.navigation.state.params.video
        };
      }
      render() {
        console.log(this.state.video);

        return (
          <View style={styles.container}>
            <VideoPlayer {...this.props} />
          </View>
        );
      }

}

Snack setup here

Body:
If the video has the right value,

 render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation.navigate("VideoPlayer", {video: video });
              }}
              style={styles.text}
            >
              {title}
            </Text>

VideoPlayer Screen:

constructor(props) {
    super(props);
    this.state = {
      video: this.props.navigation.state.params.video,
    };
  }


问:
Where is the source code of dependencies in node_modules?
I'm a beginner in typescript and npm, so my question may look stupid.
I declared some dependencies in my package.json file, and I have run the npm install command. Many dependencies were installed into the node_modules directory. But I think there should be the source code and doc in every dependency like that in java. But when I check the dependencies in node_modules, I only see the class declarations in some packages:

```<code>import { PipeTransform } from '@angular/core';
import { JhiFilterPipe } from './filter.pipe';
export declare class JhiPureFilterPipe extends JhiFilterPipe implements PipeTransform {
    transform(input: Array<any>, filter: string, field: string): any;
}
</code>```

There is no source code, neither the doc. So I was wondering where is the source code or even the compiled js code in these typescript package?

In java, when I declare dependencies in pom, I would see the source code of the API and their doc, but not the case for packages in node_modules.

Am I doing sth wrong?

Give me some hints plz!

答:
All packages are different, but to find where the main code is, you need to look at the package.json file. Within that file you will find a main key which will tell you where the entry point is for that package (the path is relative to the package.json file):

```<code>{
  "name": "@angular/core",
  "version": "8.0.0-rc.0+354.sha-4809382.with-local-changes",
  "description": "Angular - the core framework",
  "main": "./bundles/core.umd.js"
}
</code>```

If you navigate to that file you will see the entry point source code for that package. For the package you provided, the source is here

Body:
I'm a beginner in typescript and npm, so my question may look stupid.
I declared some dependencies in my package.json file, and I have run the npm install command. Many dependencies were installed into the node_modules directory. But I think there should be the source code and doc in every dependency like that in java. But when I check the dependencies in node_modules, I only see the class declarations in some packages:

import { PipeTransform } from '@angular/core';
import { JhiFilterPipe } from './filter.pipe';
export declare class JhiPureFilterPipe extends JhiFilterPipe implements PipeTransform {
    transform(input: Array<any>, filter: string, field: string): any;
}

There is no source code, neither the doc. So I was wondering where is the source code or even the compiled js code in these typescript package?

In java, when I declare dependencies in pom, I would see the source code of the API and their doc, but not the case for packages in node_modules.

Am I doing sth wrong?

Give me some hints plz!

Body:
All packages are different, but to find where the main code is, you need to look at the package.json file. Within that file you will find a main key which will tell you where the entry point is for that package (the path is relative to the package.json file):

{
  "name": "@angular/core",
  "version": "8.0.0-rc.0+354.sha-4809382.with-local-changes",
  "description": "Angular - the core framework",
  "main": "./bundles/core.umd.js"
}

If you navigate to that file you will see the entry point source code for that package. For the package you provided, the source is here


问:
overloaded method not seen in subclass

Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

```<code>class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};
</code>```

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

答:
A::f is hidden by B:f. Use using directive to overload base class method.

```<code>class B : public A {
    public:
        using A::f;
        void f(float a, int b){ }
};
</code>```

Title: overloaded method not seen in subclass

Body:
Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

Body:
A::f is hidden by B:f. Use using directive to overload base class method.

class B : public A {
    public:
        using A::f;
        void f(float a, int b){ }
};


问:
Mount ADLS Gen2 to Databricks when firewall is enabled
When I am trying to mount ADLS Gen2 to Databricks, I have this issue : "StatusDescription=This request is not authorized to perform this operation" if the ADLS Gen2 firewall is enabled. But the request works fine if the firewall is disabled.

Someone can help please ?

```<code>configs = {"fs.azure.account.auth.type": "OAuth",
               "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
               "fs.azure.account.oauth2.client.id": clientID,
               "fs.azure.account.oauth2.client.secret": keyID,
               "fs.azure.account.oauth2.client.endpoint": "https://login.microsoftonline.com/" + tenantID + "/oauth2/token"}

dbutils.fs.mount(
  source = "abfss://" + fileSystem + "@" + accountName + ".dfs.core.windows.net/",
  mount_point = "/mnt/adlsGen2",
  extra_configs = configs)

StatusCode=403
StatusDescription=This request is not authorized to perform this operation.
ErrorCode=
ErrorMessage=
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.services.AbfsRestOperation.execute(AbfsRestOperation.java:134)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.services.AbfsClient.getAclStatus(AbfsClient.java:498)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystemStore.getIsNamespaceEnabled(AzureBlobFileSystemStore.java:164)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystemStore.getFileStatus(AzureBlobFileSystemStore.java:445)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystem.getFileStatus(AzureBlobFileSystem.java:362)
    at com.databricks.backend.daemon.dbutils.DBUtilsCore.verifyAzureFileSystem(DBUtilsCore.scala:486)
    at com.databricks.backend.daemon.dbutils.DBUtilsCore.mount(DBUtilsCore.scala:435)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:295)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
If you enable the firewall on an Azure Data Lake Store Gen2 account, this configuration only works with Azure Databricks if you deploy Azure Databricks in your own virtual network. It does not work with workspaces deployed without vnet-injection feature.
On the storage account you have to enable access from the public-Databricks subnet.</p>

Body:
When I am trying to mount ADLS Gen2 to Databricks, I have this issue : "StatusDescription=This request is not authorized to perform this operation" if the ADLS Gen2 firewall is enabled. But the request works fine if the firewall is disabled.

Someone can help please ?

configs = {"fs.azure.account.auth.type": "OAuth",
               "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
               "fs.azure.account.oauth2.client.id": clientID,
               "fs.azure.account.oauth2.client.secret": keyID,
               "fs.azure.account.oauth2.client.endpoint": "https://login.microsoftonline.com/" + tenantID + "/oauth2/token"}

dbutils.fs.mount(
  source = "abfss://" + fileSystem + "@" + accountName + ".dfs.core.windows.net/",
  mount_point = "/mnt/adlsGen2",
  extra_configs = configs)

StatusCode=403
StatusDescription=This request is not authorized to perform this operation.
ErrorCode=
ErrorMessage=
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.services.AbfsRestOperation.execute(AbfsRestOperation.java:134)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.services.AbfsClient.getAclStatus(AbfsClient.java:498)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystemStore.getIsNamespaceEnabled(AzureBlobFileSystemStore.java:164)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystemStore.getFileStatus(AzureBlobFileSystemStore.java:445)
    at shaded.databricks.v20180920_b33d810.org.apache.hadoop.fs.azurebfs.AzureBlobFileSystem.getFileStatus(AzureBlobFileSystem.java:362)
    at com.databricks.backend.daemon.dbutils.DBUtilsCore.verifyAzureFileSystem(DBUtilsCore.scala:486)
    at com.databricks.backend.daemon.dbutils.DBUtilsCore.mount(DBUtilsCore.scala:435)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:295)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)


问:
Got error when creating instance of SBNotificationHub
I'm trying to implement push notification in my Xamarin app on iOS. Using example from docs, I have:

```<code>        if (_hub == null)
        {
            string connectionString = "Endpoint=<whatever>";
            string hubName = "<hub name>";
            _hub = new SBNotificationHub(connectionString, hubName);
        }
</code>```

For some reason I got an exception: "Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: *** -[__NSDictionaryM setObject:forKey:]: key cannot be nil Native stack trace:"

Any ideas or direction where to look are appreciated. More about error:

```<code>    1   libobjc.A.dylib                     0x00000001988ea9f8 objc_exception_throw + 56
2   CoreFoundation                      0x0000000199688f8c _CFArgv + 0
3   CoreFoundation                      0x00000001995fe2b4 <redacted> + 904
4   TennisUmpireXamariniOS              0x0000000102355038 -[SBLocalStorage readContent] + 508
5   TennisUmpireXamariniOS              0x000000010235472c -[SBLocalStorage initWithNotificationHubPath:] + 296
6   TennisUmpireXamariniOS              0x000000010234dbe4 -[SBNotificationHub initWithConnectionString:notificationHubPath:] + 420
7   TennisUmpireXamariniOS              0x0000000104530a7c wrapper_managed_to_native_ApiDefinition_Messaging_IntPtr_objc_msgSend_IntPtr_IntPtr_intptr_intptr_intptr_intptr + 236
8   TennisUmpireXamariniOS              0x0000000104521038 WindowsAzure_Messaging_SBNotificationHub__ctor_string_string + 792
9   TennisUmpireXamariniOS              0x0000000102418a00 TennisUmpireXamarin_iOS_AppDelegate_RegisteredForRemoteNotifications_UIKit_UIApplication_Foundation_NSData + 480
10  TennisUmpireXamariniOS              0x000000010271d998 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 248
11  TennisUmpireXamariniOS              0x0000000104d30e80 mono_jit_runtime_invoke + 948
12  TennisUmpireXamariniOS              0x0000000104db54e8 mono_runtime_invoke_checked + 144
13  TennisUmpireXamariniOS              0x0000000104db8d90 mono_runtime_invoke + 80
14  TennisUmpireXamariniOS              0x00000001023ccf3c _ZL31native_to_managed_trampoline_23P11objc_objectP13objc_selectorPP11_MonoMethodP13UIApplicationP6NSDataj + 680
15  TennisUmpireXamariniOS              0x00000001023ccc88 -[AppDelegate application:didRegisterForRemoteNotificationsWithDeviceToken:] + 64
16  libdispatch.dylib                   0x000000019914fa38 <redacted> + 24
17  libdispatch.dylib                   0x00000001991507d4 <redacted> + 16
18  libdispatch.dylib                   0x00000001990fe004 <redacted> + 1068
19  CoreFoundation                      0x00000001996a0ec0 <redacted> + 12
20  CoreFoundation                      0x000000019969bdf8 <redacted> + 1924
21  CoreFoundation                      0x000000019969b354 CFRunLoopRunSpecific + 436
22  GraphicsServices                    0x000000019b89b79c GSEventRunModal + 104
23  UIKitCore                           0x00000001c5897b68 UIApplicationMain + 212
24  TennisUmpireXamariniOS              0x00000001031962c8 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 328
25  TennisUmpireXamariniOS              0x00000001030f723c UIKit_UIApplication_Main_string___intptr_intptr + 44
26  TennisUmpireXamariniOS              0x00000001030f71fc UIKit_UIApplication_Main_string___string_string + 172
27  TennisUmpireXamariniOS              0x00000001024178c0 TennisUmpireXamarin_iOS_Application_Main_string__ + 128
28  TennisUmpireXamariniOS              0x000000010271d998 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 248
29  TennisUmpireXamariniOS              0x0000000104d30e80 mono_jit_runtime_invoke + 948
30  TennisUmpireXamariniOS              0x0000000104db54e8 mono_runtime_invoke_checked + 144
31  TennisUmpireXamariniOS              0x0000000104dbb320 mono_runtime_exec_main_checked + 120
32  TennisUmpireXamariniOS              0x0000000104d1141c mono_jit_exec + 268
33  TennisUmpireXamariniOS              0x0000000104ea94d4 xamarin_main + 2184
34  TennisUmpireXamariniOS              0x00000001024177b8 main + 96
35  libdyld.dylib                       0x00000001991618e0 <redacted> + 4
</code>```

答:
Nobody seems to encounter this problem, but I think I figured out what was happening and want to put it in writing.

SBNotificationHub component preserves the state in the storage. When constructor is called, this state is restored. And my parameters to constructor were just fine, the first call went without any errors.

However, when I tried to call RegisterTemplate method, I passed invalid parameters, which resulted in 400 error from the notification hub. The problem is that even with this invalid parameters, the state was updated.

The next call to SBNotificationHub constructor tried to restore this inconsistent state and threw the error I posted in my question.

Now I would be stuck until app removed. This is with version https://www.nuget.org/packages/Xamarin.Azure.NotificationHubs.iOS/ (1.2.5.2). The problem is that I used package https://www.nuget.org/packages/Xamarin.Azure.NotificationHubs.iOS-updated/, which is forked version that stores state in KeyChain. As we know, even if app is uninstalled, the values in KeyChain remain, so even after I re-installed my app, I got stuck, until I actually wiped out device.

So, I switched to version 1.2.5.2 to at least be able to have clean start after uninstalling the app, and then troubleshooted what was wrong with my RegisterTemplate call.

The proper behavior, I think, would be to not update state if RegisterTemplate call wasn't successful. In addition to that, it would be nice to be able to clear the state in storage (Keychain or not) if it's corrupted. Or, why constructor even need to restore the state?

Body:
I'm trying to implement push notification in my Xamarin app on iOS. Using example from docs, I have:

        if (_hub == null)
        {
            string connectionString = "Endpoint=<whatever>";
            string hubName = "<hub name>";
            _hub = new SBNotificationHub(connectionString, hubName);
        }

For some reason I got an exception: "Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: *** -[__NSDictionaryM setObject:forKey:]: key cannot be nil Native stack trace:"

Any ideas or direction where to look are appreciated. More about error:

    1   libobjc.A.dylib                     0x00000001988ea9f8 objc_exception_throw + 56
2   CoreFoundation                      0x0000000199688f8c _CFArgv + 0
3   CoreFoundation                      0x00000001995fe2b4 <redacted> + 904
4   TennisUmpireXamariniOS              0x0000000102355038 -[SBLocalStorage readContent] + 508
5   TennisUmpireXamariniOS              0x000000010235472c -[SBLocalStorage initWithNotificationHubPath:] + 296
6   TennisUmpireXamariniOS              0x000000010234dbe4 -[SBNotificationHub initWithConnectionString:notificationHubPath:] + 420
7   TennisUmpireXamariniOS              0x0000000104530a7c wrapper_managed_to_native_ApiDefinition_Messaging_IntPtr_objc_msgSend_IntPtr_IntPtr_intptr_intptr_intptr_intptr + 236
8   TennisUmpireXamariniOS              0x0000000104521038 WindowsAzure_Messaging_SBNotificationHub__ctor_string_string + 792
9   TennisUmpireXamariniOS              0x0000000102418a00 TennisUmpireXamarin_iOS_AppDelegate_RegisteredForRemoteNotifications_UIKit_UIApplication_Foundation_NSData + 480
10  TennisUmpireXamariniOS              0x000000010271d998 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 248
11  TennisUmpireXamariniOS              0x0000000104d30e80 mono_jit_runtime_invoke + 948
12  TennisUmpireXamariniOS              0x0000000104db54e8 mono_runtime_invoke_checked + 144
13  TennisUmpireXamariniOS              0x0000000104db8d90 mono_runtime_invoke + 80
14  TennisUmpireXamariniOS              0x00000001023ccf3c _ZL31native_to_managed_trampoline_23P11objc_objectP13objc_selectorPP11_MonoMethodP13UIApplicationP6NSDataj + 680
15  TennisUmpireXamariniOS              0x00000001023ccc88 -[AppDelegate application:didRegisterForRemoteNotificationsWithDeviceToken:] + 64
16  libdispatch.dylib                   0x000000019914fa38 <redacted> + 24
17  libdispatch.dylib                   0x00000001991507d4 <redacted> + 16
18  libdispatch.dylib                   0x00000001990fe004 <redacted> + 1068
19  CoreFoundation                      0x00000001996a0ec0 <redacted> + 12
20  CoreFoundation                      0x000000019969bdf8 <redacted> + 1924
21  CoreFoundation                      0x000000019969b354 CFRunLoopRunSpecific + 436
22  GraphicsServices                    0x000000019b89b79c GSEventRunModal + 104
23  UIKitCore                           0x00000001c5897b68 UIApplicationMain + 212
24  TennisUmpireXamariniOS              0x00000001031962c8 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 328
25  TennisUmpireXamariniOS              0x00000001030f723c UIKit_UIApplication_Main_string___intptr_intptr + 44
26  TennisUmpireXamariniOS              0x00000001030f71fc UIKit_UIApplication_Main_string___string_string + 172
27  TennisUmpireXamariniOS              0x00000001024178c0 TennisUmpireXamarin_iOS_Application_Main_string__ + 128
28  TennisUmpireXamariniOS              0x000000010271d998 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 248
29  TennisUmpireXamariniOS              0x0000000104d30e80 mono_jit_runtime_invoke + 948
30  TennisUmpireXamariniOS              0x0000000104db54e8 mono_runtime_invoke_checked + 144
31  TennisUmpireXamariniOS              0x0000000104dbb320 mono_runtime_exec_main_checked + 120
32  TennisUmpireXamariniOS              0x0000000104d1141c mono_jit_exec + 268
33  TennisUmpireXamariniOS              0x0000000104ea94d4 xamarin_main + 2184
34  TennisUmpireXamariniOS              0x00000001024177b8 main + 96
35  libdyld.dylib                       0x00000001991618e0 <redacted> + 4


答: You are doing it inside a function, and since you are modifying it, python thinks you are refering to a local variable. Add global radius to the beginning of your function

Title: What am I doing wrong? radius = radius + 25

Body:
Line 14: radius = radius + 25

Error message:

UnboundLocalError: local variable 'radius' referenced before assignment on line 14

I have no idea why this is throwing an error. as far as I'm aware the computer's just being dumb...

I have another question, and I am not waiting two days for an answer.
but a bit of backstory is necessary. I'm using CodeHS to learn Python. I'm on lesson 2.12.5, and this is my code.
`
global sidereal
sidereal=int(input("How large do you like your squares? (1-400)")
def squaretine():
    for i in range(4)
        pendown()
        forward(sidereal)
        left(90)
        penup()
squaretine()
`
And this is my error:
ParseError: bad input on line 3

I could't even tell you what's wrong, I personally don't see any errors...


问:
How do I remove horizontal lines from Mime Message?
Noob, creating his first dynamic webpage, where a user can enter a message, along with their first and last name, email and phone number. I care most about the message, which I intend to forward via email, along with the other information, if provided. I have written a simple python script (site will be Flask, python and HTML), but it is inserting an unwanted horizontal line between each output, i.e.

Dear Bob

Message contents go here

first name

My goal is to have the outgoing message resemble an actual email, i.e. like above, but without the horizontal lines. I found most of the below code online, which is largely working. Simple answers that I can understand are preferred to clever ones I cannot (I'm a Noob).

```<code>def to_mail(first, last, phone, email, User_Complaint, addressed_to):
    # E mail account details
    my_sending_email = 'testing@gmail.com'
    sending_email_password = 'pass'

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(my_sending_email, sending_email_password)

    msg = MIMEMultipart()

    msg['Subject'] = 'Reporting an Issue With the Courts'
    msg['From'] = my_sending_email
    msg['To'] = addressed_to

    # Body of Email
    intro = MIMEText("Dear Leader")
    message_contents = MIMEText(User_Complaint)

    # use of .attach appears to insert the horizontal line
    msg.attach(intro)
    msg.attach(message_contents)

    # Party's Contact Info to append at bottom of email
    msg.attach(MIMEText(first + last))
    msg.attach(MIMEText(phone))
    msg.attach(MIMEText(email))

    s.send_message(msg)
    del msg

    s.quit()
</code>```

I just want to generate normal looking email content in the message body, i.e.

"Dear Leader,

I really like your hair. I'm your biggest fan.

(each biographic entry following should be on its own newline, but this automatically puts it on one line)
Stan Lee\n
stan@lee.com\n
647-647-1234"

答:
Thanks Assili, I was able to fix my code based on your suggestion with the following small tweaks.</p>

```<code>#Body of Email

text = intro + '\n' + '\n'  + message_contents + '\n' + '\n' + first + '' + last + '\n' + phone + '\n' + email

msg.attach(MIMEText(text))
</code>```

Body:
Noob, creating his first dynamic webpage, where a user can enter a message, along with their first and last name, email and phone number. I care most about the message, which I intend to forward via email, along with the other information, if provided. I have written a simple python script (site will be Flask, python and HTML), but it is inserting an unwanted horizontal line between each output, i.e.

Dear Bob

Message contents go here

first name

My goal is to have the outgoing message resemble an actual email, i.e. like above, but without the horizontal lines. I found most of the below code online, which is largely working. Simple answers that I can understand are preferred to clever ones I cannot (I'm a Noob).

def to_mail(first, last, phone, email, User_Complaint, addressed_to):
    # E mail account details
    my_sending_email = 'testing@gmail.com'
    sending_email_password = 'pass'

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(my_sending_email, sending_email_password)

    msg = MIMEMultipart()

    msg['Subject'] = 'Reporting an Issue With the Courts'
    msg['From'] = my_sending_email
    msg['To'] = addressed_to

    # Body of Email
    intro = MIMEText("Dear Leader")
    message_contents = MIMEText(User_Complaint)

    # use of .attach appears to insert the horizontal line
    msg.attach(intro)
    msg.attach(message_contents)

    # Party's Contact Info to append at bottom of email
    msg.attach(MIMEText(first + last))
    msg.attach(MIMEText(phone))
    msg.attach(MIMEText(email))

    s.send_message(msg)
    del msg

    s.quit()

I just want to generate normal looking email content in the message body, i.e.

"Dear Leader,

I really like your hair. I'm your biggest fan.

(each biographic entry following should be on its own newline, but this automatically puts it on one line)
Stan Lee\n
stan@lee.com\n
647-647-1234"

Body:
Thanks Assili, I was able to fix my code based on your suggestion with the following small tweaks.

#Body of Email

text = intro + '\n' + '\n'  + message_contents + '\n' + '\n' + first + '' + last + '\n' + phone + '\n' + email

msg.attach(MIMEText(text))


答:
try this.

```<code>radius = 0
def something():
    global radius
    radius = radius + 25
    return radius
</code>```

The reason this happens is that you can only access global variables from a def function so you have to declare it as global beforehand. You also have to declare the variable before you modify it using itself.

Body:
try this.

radius = 0
def something():
    global radius
    radius = radius + 25
    return radius

The reason this happens is that you can only access global variables from a def function so you have to declare it as global beforehand. You also have to declare the variable before you modify it using itself.