问:
Using reduce to remap an array with child arrays
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

```<code>var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})
</code>```

How do I remap the array as below and get my reduce function working?

```<code>var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]
</code>```

I would like the output to look like this:

```<code>var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]
</code>```

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.

答:
This will help</p>

```<code>    const variations= input.flatMap(obj => obj.productVariations.map(x => ({...x, linked:[{companyName: obj.companyName}]})))
    const final = variations.reduce((acc, curr) => {
        const obj = acc.find(x => x.variationName === curr.variationName)
        if(obj) {
            const uniqueOptions = [...new Set([...curr.variationOptions, ...obj.variationOptions].map(x => x.name))]
            obj.variationOptions = uniqueOptions.map(x => ({name: x}));
            obj.linked.push(...curr.linked)
        }
        else {
            acc.push(curr)
        }
        return acc;
    } ,[])
</code>```

Body:
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})

How do I remap the array as below and get my reduce function working?

var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]

I would like the output to look like this:

var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.

Body:
This will help

    const variations= input.flatMap(obj => obj.productVariations.map(x => ({...x, linked:[{companyName: obj.companyName}]})))
    const final = variations.reduce((acc, curr) => {
        const obj = acc.find(x => x.variationName === curr.variationName)
        if(obj) {
            const uniqueOptions = [...new Set([...curr.variationOptions, ...obj.variationOptions].map(x => x.name))]
            obj.variationOptions = uniqueOptions.map(x => ({name: x}));
            obj.linked.push(...curr.linked)
        }
        else {
            acc.push(curr)
        }
        return acc;
    } ,[])


来源: stackexchange

问:
Is it possible to change a part of text styling of ChoiceGroupOption (office-ui-fabric)?
I am using Office fabric Choice Group for my radio buttons. I would like to change the styling of part of text to bold, but the rest of text remains as normal font size. I am using onRenderField method but I have not successfully implemented yet.... I really appreciate any inputs!!

Final Goal for radio button text:

On: some additional explanation here

Example Code using onRenderField method:

```<code>options={[
  {
    key: 'On',
    text: 'On: some additional explanation here',
    onRenderField: (props, render) => {
      return (
        <span style={{fontWeight: 'bold'}}>
          {render!(props)}
        </span>
      );
    }
  }
]}
</code>```

The above code makes bold entire text like below:

On: some additional explanation here

答:
There's an option that doesn't appear to be well-documented called onRenderLabel that will do what you need.

Using it looks like:

```<code>{
  key: 'C',
  text: 'Option C',
  onRenderLabel: (p) => <span id={p.labelId} className="ms-ChoiceFieldLabel">Option C: only <strong>this part</strong> is bold</span>
}
</code>```

The p in the callback is of type IChoiceGroupOptionProps and may be of use, though it's more likely that defining the entire render inline is easier. ( https://learn.microsoft.com/en-us/javascript/api/office-ui-fabric-react/ichoicegroupoptionprops?view=office-ui-fabric-react-latest )

ContentLicense: CC BY-SA 4.0

Body:
I am using Office fabric Choice Group for my radio buttons. I would like to change the styling of part of text to bold, but the rest of text remains as normal font size. I am using onRenderField method but I have not successfully implemented yet.... I really appreciate any inputs!!

Final Goal for radio button text:

On: some additional explanation here

Example Code using onRenderField method:

options={[
  {
    key: 'On',
    text: 'On: some additional explanation here',
    onRenderField: (props, render) => {
      return (

          {render!(props)}

      );
    }
  }
]}

The above code makes bold entire text like below:

On: some additional explanation here

Body:
There's an option that doesn't appear to be well-documented called onRenderLabel that will do what you need.

Using it looks like:

{
  key: 'C',
  text: 'Option C',
  onRenderLabel: (p) => <span id={p.labelId} className="ms-ChoiceFieldLabel">Option C: only <strong>this part</strong> is bold</span>
}

The p in the callback is of type IChoiceGroupOptionProps and may be of use, though it's more likely that defining the entire render inline is easier. ( https://learn.microsoft.com/en-us/javascript/api/office-ui-fabric-react/ichoicegroupoptionprops?view=office-ui-fabric-react-latest )


问:
Palindrom checker with array function
my aim is to test for a palindrome (word is the same forwards and backwards) and the log and array containing only the palindromes, so far this is the most I could come with.

```<code>
const getAllPalindromes = (words) => {
 return words.filter((word) => {
  word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));

</code>```

To my understanding this should return an array containing the items that are true from the boolean, any pointers will help a newbie thanks a lot!

答:
You're not returning your filter conditional. You do the comparison, but then don't return it so the filter has an undefined as the return of the comparator, and thus it doesn't filter anything. Otherwise, the rest of your logic is correct!

const getAllPalindromes = (words) => words.filter((word) => word.split("").reverse().join("") === word);

console.log(getAllPalindromes(["hello", "noon"]));```
</div>
</div>
</p>

<p>Since you're using Arrow Functions we're going to use the implicit return in them to make things a little smaller especially since each function is really just a single statement. Here's the same code in a longer format for direct comparison</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const getAllPalindromes = function (words) {
 return words.filter(function (word) {
    return word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));</code>```

The differences between Arrow Functions and Functions was already answered a long time ago, so here it is for reference.

It might also help if you use an editor or code linter that can help you catch the problems early. A missed return statement is just as easy to make as an off by one error.

Off by One errors are as easy to make as a missed return statement undefined

Happy coding!

Title: Palindrom checker with array function

Body:
my aim is to test for a palindrome (word is the same forwards and backwards) and the log and array containing only the palindromes, so far this is the most I could come with.

const getAllPalindromes = (words) => {
 return words.filter((word) => {
  word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));

To my understanding this should return an array containing the items that are true from the boolean, any pointers will help a newbie thanks a lot!

Body:
You're not returning your filter conditional. You do the comparison, but then don't return it so the filter has an undefined as the return of the comparator, and thus it doesn't filter anything. Otherwise, the rest of your logic is correct!

const getAllPalindromes = (words) => words.filter((word) => word.split("").reverse().join("") === word);

console.log(getAllPalindromes(["hello", "noon"]));

Since you're using Arrow Functions we're going to use the implicit return in them to make things a little smaller especially since each function is really just a single statement. Here's the same code in a longer format for direct comparison

const getAllPalindromes = function (words) {
 return words.filter(function (word) {
    return word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));

The differences between Arrow Functions and Functions was already answered a long time ago, so here it is for reference.

It might also help if you use an editor or code linter that can help you catch the problems early. A missed return statement is just as easy to make as an off by one error.

Off by One errors are as easy to make as a missed return statement undefined

Happy coding!


问:
Unit test for webview
I'm building an application where I login via a webview.

To log in I use an external Html page which returns a token via querystring which I then use in my application

Everything works correctly for me.

Now I would like to create Unit Tests, but it is the first time for me.

Is it possible to create tests for the webview, going to write in the two fields of the html form and submit?

You can give me some suggestions, I'm doing some research but what I find about Unit Tests is not in my case, or maybe I'm wrong to look.

Thanks

答:
Looks like it is UI-test. For UI-testing you can use Espresso library https://developer.android.com/training/testing/espresso/web
Another great library for UI-testing is https://github.com/KasperskyLab/Kaspresso. This library offers you DSL for test readability and test stability</p>

Title: Unit test for webview


问:
Pandas groupby apply strange behavior when NaN's in group column
I'm encountering some unexpected Pandas groupby-apply results, and I can't figure out the exact cause.

Below I have to dataframes that are equal except the ordering of 2 values. df1 produces results as I expect them, but df2 produces a completely different result.

```<code>import numpy as np

df1 = pd.DataFrame({'group_col': [0.0, np.nan, 0.0, 0.0], 'value_col': [2,2,2,2]})
df2 = pd.DataFrame({'group_col': [np.nan, 0.0, 0.0, 0.0], 'value_col': [2,2,2,2]})
</code>```

df1:

```<code>   group_col  value_col
0        0.0          2
1        NaN          2
2        0.0          2
3        0.0          2
</code>```

df2:

```<code>   group_col  value_col
0        NaN          2
1        0.0          2
2        0.0          2
3        0.0          2
</code>```

When I groupby the group_col and do a value_counts of the value_col per group, including a reindex to include all possible values in the result I get the following for df1:

```<code>df1.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))

group_col
0.0        1    NaN
           2    3.0
           3    NaN
Name: value_col, dtype: float64

</code>```

It correctly finds 1 group and returns a multi-index series with the value_counts for each possible value. But when I run the same on df2, I get a completely different result:

```<code>0    NaN
1    NaN
2    3.0
3    NaN
Name: value_col, dtype: float64
</code>```

Here the result contains an index matching the original DataFrame instead of the multi-index I would expect. I thought it might have something to do with the group column starting with np.nan, but then I tried dropping the last row and I get the expected result again, so apparently the cause is something else.

```<code>df2.head(3).groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))

group_col
0.0        1    NaN
           2    2.0
           3    NaN
Name: value_col, dtype: float64

</code>```

What could be causing this?

答:
Let's begin with looking at some simple grouping calculations to understand how pandas works on it.

In the following case, grouping keys are used as index in the resulting Series object. The original index was dropped.

```<code>In [4]: df1.groupby('group_col')['value_col'] \
   ...: .apply(lambda x: {'sum': x.sum(), 'mean': x.mean()})
Out[4]:
group_col
0.0        sum     6.0
           mean    2.0
Name: value_col, dtype: float64

In [5]: df2.groupby('group_col')['value_col'] \
   ...: .apply(lambda x: {'sum': x.sum(), 'mean': x.mean()})
Out[5]:
group_col
0.0        sum     6.0
           mean    2.0
Name: value_col, dtype: float64
</code>```

In the next case, the index of the original DataFrame is preserved. Grouping keys are not contained in the result Series.

```<code>In [6]: df1.groupby('group_col')['value_col'].apply(lambda x: x / len(x))
Out[6]:
0    0.666667
1         NaN
2    0.666667
3    0.666667
Name: value_col, dtype: float64

In [7]: df2.groupby('group_col')['value_col'].apply(lambda x: x / len(x))
Out[7]:
0         NaN
1    0.666667
2    0.666667
3    0.666667
Name: value_col, dtype: float64
</code>```

What makes pandas behave differently when it produces the index of combined object?

Actually, this is based on whether the index was mutated by the aggregation or not. When the index is the same between the original object and the resulting object, it chooses to reuse the original index. On the other hand, when the index is different from the original object, it uses the group key in the index to form a MultiIndex.

Now, going back to the question, please notice that the index was changed for df1. For group key 0.0, the index of the original chunk was [0, 2, 3], whereas it is [1, 2, 3] after aggregation. However, for df2, the original index was [1, 2, 3], and accidentally, it was not changed by the aggregation.

Body:
I'm encountering some unexpected Pandas groupby-apply results, and I can't figure out the exact cause.

Below I have to dataframes that are equal except the ordering of 2 values. df1 produces results as I expect them, but df2 produces a completely different result.

import numpy as np

df1 = pd.DataFrame({'group_col': [0.0, np.nan, 0.0, 0.0], 'value_col': [2,2,2,2]})
df2 = pd.DataFrame({'group_col': [np.nan, 0.0, 0.0, 0.0], 'value_col': [2,2,2,2]})

df1:

   group_col  value_col
0        0.0          2
1        NaN          2
2        0.0          2
3        0.0          2

df2:

   group_col  value_col
0        NaN          2
1        0.0          2
2        0.0          2
3        0.0          2

When I groupby the group_col and do a value_counts of the value_col per group, including a reindex to include all possible values in the result I get the following for df1:

df1.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))

group_col
0.0        1    NaN
           2    3.0
           3    NaN
Name: value_col, dtype: float64

It correctly finds 1 group and returns a multi-index series with the value_counts for each possible value. But when I run the same on df2, I get a completely different result:

0    NaN
1    NaN
2    3.0
3    NaN
Name: value_col, dtype: float64

Here the result contains an index matching the original DataFrame instead of the multi-index I would expect. I thought it might have something to do with the group column starting with np.nan, but then I tried dropping the last row and I get the expected result again, so apparently the cause is something else.

df2.head(3).groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))

group_col
0.0        1    NaN
           2    2.0
           3    NaN
Name: value_col, dtype: float64

What could be causing this?

Body:
Let's begin with looking at some simple grouping calculations to understand how pandas works on it.

In the following case, grouping keys are used as index in the resulting Series object. The original index was dropped.

In [4]: df1.groupby('group_col')['value_col'] \
   ...: .apply(lambda x: {'sum': x.sum(), 'mean': x.mean()})
Out[4]:
group_col
0.0        sum     6.0
           mean    2.0
Name: value_col, dtype: float64

In [5]: df2.groupby('group_col')['value_col'] \
   ...: .apply(lambda x: {'sum': x.sum(), 'mean': x.mean()})
Out[5]:
group_col
0.0        sum     6.0
           mean    2.0
Name: value_col, dtype: float64

In the next case, the index of the original DataFrame is preserved. Grouping keys are not contained in the result Series.

In [6]: df1.groupby('group_col')['value_col'].apply(lambda x: x / len(x))
Out[6]:
0    0.666667
1         NaN
2    0.666667
3    0.666667
Name: value_col, dtype: float64

In [7]: df2.groupby('group_col')['value_col'].apply(lambda x: x / len(x))
Out[7]:
0         NaN
1    0.666667
2    0.666667
3    0.666667
Name: value_col, dtype: float64

What makes pandas behave differently when it produces the index of combined object?

Actually, this is based on whether the index was mutated by the aggregation or not. When the index is the same between the original object and the resulting object, it chooses to reuse the original index. On the other hand, when the index is different from the original object, it uses the group key in the index to form a MultiIndex.

Now, going back to the question, please notice that the index was changed for df1. For group key 0.0, the index of the original chunk was [0, 2, 3], whereas it is [1, 2, 3] after aggregation. However, for df2, the original index was [1, 2, 3], and accidentally, it was not changed by the aggregation.


问:
Hive partition table query optimisation
I am new to hive,and hadoop ecosystem in general.From what I learnt of the basics of Hive you can create partitions on hive table based on certain attributes.And if a query has any mention of that attribute then it should supposedly get a performance boost as hive only scans that particular partition file instead of scanning the whole table.My question is suppose we have some hierarchical structure in the data.Say I partition a table based on unique state values and every time a query is based on state hive would only scan that particular state partition instead of scanning the whole table.However say every state also has unique district names.If I make a query based only on district values would hive scan the whole table?

If so then is there some way to change the query in such a way that I can manually instruct hive to query the particular state file to which the district belongs to.And then perform other operations only on that partition file,instead of scanning the whole table for matching district values.

答:
One of the strengths of Hive is that it has strong support for partitioning.  However, it cannot read your mind when you write queries.

If you have a partition on state, then you need state in the where clause for partition pruning.  So, if you query only on district, the whole table would be scanned.

If you have a partition on district, then you need the district.  A query on state would scan the whole table.

If you have a partition on both . . . well, then it is a little more complicated to declare, but your queries would read a minority of partitions with either state or district.

If you are just learning about partitions, I would advise you to start with date partitions.  These are the most common and a good way to get familiar with the concept.

Title: Hive partition table query optimisation


问:
Database connection pg_hba.conf
When i'm trying to my database in Azure from intelij i always getting this error:
PS Access in Azure is on

The specified database user/password combination is rejected: [28000] FATAL: no pg_hba.conf entry for host "37.140.21.90", user "xxx", database "xxx", SSL on

my pg_hba.conf:

host    all             all             ::1/128                 md5

host    replication     all             127.0.0.1/32            md5

host    replication     all             ::1/128                 md5

host    all             all            all                 md5

local   all             all                                     trust

答:
This is probably the result of SSL activated on your managed Azure DB.

To solve it there are two options:

1- Deactivate SSL on the Azure database side.

2- Add hostssl in your pg_hba.conf file so that host records match SSL connection attempts.

The line will be like:

```<code>hostssl database  user  address  auth-method  [auth-options]
</code>```

Title: Database connection pg_hba.conf

Body:
This is probably the result of SSL activated on your managed Azure DB.

To solve it there are two options:

1- Deactivate SSL on the Azure database side.

2- Add hostssl in your pg_hba.conf file so that host records match SSL connection attempts.

The line will be like:

hostssl database  user  address  auth-method  [auth-options]


问:
iPython/Jupyter %run magic appending .py to filename and causing error
I'm attempting to use the %run magic like so:

```<code>%run ../Tools/imports.ipynb
</code>```

I am running this code in two notebooks in the same directory, however, in one of them I get this error:

```<code>ERROR:root:File `'../Tools/imports.ipynb.py'` not found.
</code>```

I'm not sure what I'm missing here but I'm guessing there's some nuance as I did not write the first of the two notebooks. Anyone have any idea? Thanks.

答:
Turns out it's a pathing problem. It seems IPython automatically appends .py to the end of the filename which was confusing me, but there's a seperate pathing error.
Hopefully this helps someone.</p>

Body:
I'm attempting to use the %run magic like so:

%run ../Tools/imports.ipynb

I am running this code in two notebooks in the same directory, however, in one of them I get this error:

ERROR:root:File `'../Tools/imports.ipynb.py'` not found.

I'm not sure what I'm missing here but I'm guessing there's some nuance as I did not write the first of the two notebooks. Anyone have any idea? Thanks.


问:
Access Query form to two diferent tables. how to?
I have two different tables (Stock and Sales), that begin with 4 similar columns.

Similar Columns: Date, Store, Product_Number, Product_Descipt.

All of these columns have relationships to their masters tables (except for date).

Then i have in the 'Stock table' the Stock_quantity column and in 'sales table' Sales_Quantity column.

I need to create a query that gives me all the 'similar columns' and the stock_quantity and sales quantity if they exist in that day!

The problem is, by example, if date doesn't exist in one of the tables that 'row' doesn't appear in the query even if it exists in the other table!

How can i resolve this?

答:
You can utilize a Union Query like this: </p>

```<code>SELECT Date, Store, Product_Number, Product_Descipt, Stock_quantity as Quantity FROM Stock
UNION
SELECT Date, Store, Product_Number, Product_Descipt, Sales_quantity as Quantity FROM Sales
</code>```

<p>Edit:
Sales_quantity and Stock_quantity in the same line for the same product: </p>

```<code>SELECT Sales.Product_Number as Product_Number, Stock_quantity, Sales_quantity
FROM Sales FULL OUTER JOIN Stock ON Sales.Product_Number = Stock.Product_Number;
</code>```

Body:
You can utilize a Union Query like this:

SELECT Date, Store, Product_Number, Product_Descipt, Stock_quantity as Quantity FROM Stock
UNION
SELECT Date, Store, Product_Number, Product_Descipt, Sales_quantity as Quantity FROM Sales

Edit:
Sales_quantity and Stock_quantity in the same line for the same product:

SELECT Sales.Product_Number as Product_Number, Stock_quantity, Sales_quantity
FROM Sales FULL OUTER JOIN Stock ON Sales.Product_Number = Stock.Product_Number;


问:
Error:Server returned HTTP response code: 403 for URL: https://services.gradle.org/distributions/gradle-4.4-rc-3-all.zip
I changed my Gradle version to

```<code>classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
</code>```

from

```<code>classpath 'com.android.tools.build:gradle:3.1.0-alpha05'
</code>```

and started getting this error. I tried to clean and rebuild the project but it didn't work. Reverting back to alpha05 version is not working anymore.

appearently the problem is in my gradle-wrapper.properties

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-rc-3-all.zip
</code>```

答:
This answer will not solve the OP's problem, but I had exactly the same error, Google gave this SO URL, and my solution was slightly different

I replaced the http with https (note the 's') in the gradle.properties file.

Since others may find this SO question with a Google search, I am posting my answer here.

ContentLicense: CC BY-SA 3.0

Body:
I changed my Gradle version to

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

from

classpath 'com.android.tools.build:gradle:3.1.0-alpha05'

and started getting this error. I tried to clean and rebuild the project but it didn't work. Reverting back to alpha05 version is not working anymore.

appearently the problem is in my gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-rc-3-all.zip


问:
Hash Join vs. Nested Loop
I'm new to SQL and I have a question.

I have this SQL code:

```<code>DROP TABLE if exists students;
DROP TABLE if exists grades;

CREATE TABLE students(
    s_id integer NOT NULL PRIMARY KEY,
    s_name text,
    s_last_name text,
    curr_year integer
);

CREATE TABLE grades(
    s_id integer NOT NULL PRIMARY KEY,
    course text,
    c_year integer,
    grade integer,
    FOREIGN KEY (s_id) REFERENCES students
);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (1, 'A', 'S', 3);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (2, 'A', 'A', 2);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (3, 'V', 'B', 1);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (4, 'K', 'N', 2);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (1, 'DB', 2, 98);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (2, 'OS', 3, 90);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (3, 'DB', 2, 94);

EXPLAIN ANALYZE
    SELECT *
    FROM students s JOIN grades gr
    ON s.s_id = gr.s_id
    WHERE curr_year > 0;

CREATE INDEX student_details ON students(s_id, s_name, s_last_name);
CREATE INDEX student_courses ON grades(s_id, course);

EXPLAIN ANALYZE
    SELECT *
    FROM students s JOIN grades gr
    ON s.s_id = gr.s_id
    WHERE curr_year > 0;

DROP INDEX student_details;
DROP INDEX student_courses;
DROP TABLE students CASCADE;
DROP TABLE grades CASCADE;
</code>```

And I try to understand the explain outputs.
Before the INDEX creating I got hash merge. Here is the explain output:

```<code> Hash Join  (cost=23.50..51.74 rows=270 width=116) (actual time=0.039..0.050 rows=3 loops=1)
   Hash Cond: (gr.s_id = s.s_id)
   ->  Seq Scan on grades gr  (cost=0.00..21.30 rows=1130 width=44) (actual time=0.005..0.008 rows=3 loops=1)
   ->  Hash  (cost=20.12..20.12 rows=270 width=72) (actual time=0.021..0.021 rows=4 loops=1)
         Buckets: 1024  Batches: 1  Memory Usage: 9kB
         ->  Seq Scan on students s  (cost=0.00..20.12 rows=270 width=72) (actual time=0.006..0.011 rows=4 loops=1)
               Filter: (curr_year > 0)
 Planning time: 0.147 ms
 Execution time: 0.089 ms
(9 rows)
</code>```

And after the INDEX creating I get Nested Loop:

```<code>Nested Loop  (cost=0.00..2.12 rows=1 width=116) (actual time=0.031..0.116 rows=3 loops=1)
   Join Filter: (s.s_id = gr.s_id)
   Rows Removed by Join Filter: 9
   ->  Seq Scan on students s  (cost=0.00..1.05 rows=1 width=72) (actual time=0.012..0.018 rows=4 loops=1)
         Filter: (curr_year > 0)
   ->  Seq Scan on grades gr  (cost=0.00..1.03 rows=3 width=44) (actual time=0.003..0.009 rows=3 loops=4)
 Planning time: 0.396 ms
 Execution time: 0.170 ms
</code>```

But I can't figure out why? Why the indexing in my case made Nested Loop be preferred over Hash Join?
I'll be very happy to get an explanation for that.

Thanks a lot!

答:
No one seems to have answered this question.
Neither execution plan uses indexes, so why when you create the indexes does the planner change from using HJ to using NL.
My guess would be that the after creating the indexes there are better table and column stats available than before. I don't know if creating the indexes cause table stats to be populated or if the planner is using statistics on the indexes to choose the path. Would be interesting to trace the planner and find out. I'm an Oracle person and could do it there. I don't know off the top of my head how do do that analysis on PostgreSQL.

If you look for example at the sequential scan on

students
HJ rows estimate is 1130
NL rows estimate is 1
actual rows  is  4

grades
HJ rows estimate is 270
NL rows estimate is 3
actual rows  is  3

the NL stats are more accurate, so something has changed about the stats after you created the indexes.
Quick test is to drop the indexes and see what the planner does. If it still does NLs with same stats, the it must be a change in the stats on the tables. If it goes back to HJ with the HJ estimates it must be stats on the indexes.

Gets weirder.
So I drop the indexes, and it continues to use NL. Fine, makes sense. The create indexes must have updated table stats.
So I drop the tables, recreate and then instead of creating the indexes, I analyze the tables.
Guess what, it uses HJ
but ... the stats are accurate, like the were with the NL.
more questions ...
Guessing the create index must do some stats analysis different from simply running analyze.

Title: Hash Join vs. Nested Loop

Body:
I'm new to SQL and I have a question.

I have this SQL code:

DROP TABLE if exists students;
DROP TABLE if exists grades;

CREATE TABLE students(
    s_id integer NOT NULL PRIMARY KEY,
    s_name text,
    s_last_name text,
    curr_year integer
);

CREATE TABLE grades(
    s_id integer NOT NULL PRIMARY KEY,
    course text,
    c_year integer,
    grade integer,
    FOREIGN KEY (s_id) REFERENCES students
);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (1, 'A', 'S', 3);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (2, 'A', 'A', 2);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (3, 'V', 'B', 1);

INSERT INTO students (s_id, s_name, s_last_name, curr_year)
VALUES (4, 'K', 'N', 2);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (1, 'DB', 2, 98);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (2, 'OS', 3, 90);

INSERT INTO grades (s_id, course, c_year, grade)
VALUES (3, 'DB', 2, 94);

EXPLAIN ANALYZE
    SELECT *
    FROM students s JOIN grades gr
    ON s.s_id = gr.s_id
    WHERE curr_year > 0;

CREATE INDEX student_details ON students(s_id, s_name, s_last_name);
CREATE INDEX student_courses ON grades(s_id, course);

EXPLAIN ANALYZE
    SELECT *
    FROM students s JOIN grades gr
    ON s.s_id = gr.s_id
    WHERE curr_year > 0;

DROP INDEX student_details;
DROP INDEX student_courses;
DROP TABLE students CASCADE;
DROP TABLE grades CASCADE;

And I try to understand the explain outputs.
Before the INDEX creating I got hash merge. Here is the explain output:

 Hash Join  (cost=23.50..51.74 rows=270 width=116) (actual time=0.039..0.050 rows=3 loops=1)
   Hash Cond: (gr.s_id = s.s_id)
   ->  Seq Scan on grades gr  (cost=0.00..21.30 rows=1130 width=44) (actual time=0.005..0.008 rows=3 loops=1)
   ->  Hash  (cost=20.12..20.12 rows=270 width=72) (actual time=0.021..0.021 rows=4 loops=1)
         Buckets: 1024  Batches: 1  Memory Usage: 9kB
         ->  Seq Scan on students s  (cost=0.00..20.12 rows=270 width=72) (actual time=0.006..0.011 rows=4 loops=1)
               Filter: (curr_year > 0)
 Planning time: 0.147 ms
 Execution time: 0.089 ms
(9 rows)

And after the INDEX creating I get Nested Loop:

Nested Loop  (cost=0.00..2.12 rows=1 width=116) (actual time=0.031..0.116 rows=3 loops=1)
   Join Filter: (s.s_id = gr.s_id)
   Rows Removed by Join Filter: 9
   ->  Seq Scan on students s  (cost=0.00..1.05 rows=1 width=72) (actual time=0.012..0.018 rows=4 loops=1)
         Filter: (curr_year > 0)
   ->  Seq Scan on grades gr  (cost=0.00..1.03 rows=3 width=44) (actual time=0.003..0.009 rows=3 loops=4)
 Planning time: 0.396 ms
 Execution time: 0.170 ms

But I can't figure out why? Why the indexing in my case made Nested Loop be preferred over Hash Join?
I'll be very happy to get an explanation for that.

Thanks a lot!


问:
Reusable simpleType definition in SQL Server schema collection
I'm trying to create a reusable simpleType in an SQL Server XML schema collection but I'm getting an error. For example:

```<code><?xml version="1.0" encoding="UTF-16"?>
<xs:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="SomethingUnique"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:simpleType name="dateTimeOrEmpty">
        <xs:union memberTypes="xs:dateTime">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value=""/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>

    <xs:element name="Root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="SomeDate"/>
                    <xs:simpleType>
                        <xs:union memberTypes="xs:dateTime">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:enumeration value=""/>
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:union>
                    </xs:simpleType>
                <xs:element name="OtherDate" type="dateTimeOrEmpty" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

If I try to create an XML schema collection with this schema I get this error

Reference to an undefined name 'dateTimeOrEmpty'

Is it possible to reuse the named simpleType definition or do I have to retype the entire simpleType definition for each element I was to use it on?

答:
Looks like a namespace problem.  I think I understood this at one time, but now I just have to fiddle with it until it works.  EG</p>

```<code>CREATE XML SCHEMA COLLECTION foo AS
N'<?xml version="1.0" encoding="UTF-16"?>
<xs:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="SomethingUnique"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:s="SomethingUnique"
    >

    <xs:simpleType name="dateTimeOrEmpty">
        <xs:union memberTypes="xs:dateTime">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value=""/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>

    <xs:complexType name="RootType">
        <xs:sequence>
                <xs:element name="SomeDate" type="s:dateTimeOrEmpty"/>
                <xs:element name="OtherDate" type="s:dateTimeOrEmpty" />
            </xs:sequence>
    </xs:complexType>

    <xs:element name="Root" type="s:RootType"/>

</xs:schema>'
</code>```

Body:
I'm trying to create a reusable simpleType in an SQL Server XML schema collection but I'm getting an error. For example:

<?xml version="1.0" encoding="UTF-16"?>
<xs:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="SomethingUnique"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:simpleType name="dateTimeOrEmpty">
        <xs:union memberTypes="xs:dateTime">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value=""/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>

    <xs:element name="Root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="SomeDate"/>
                    <xs:simpleType>
                        <xs:union memberTypes="xs:dateTime">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:enumeration value=""/>
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:union>
                    </xs:simpleType>
                <xs:element name="OtherDate" type="dateTimeOrEmpty" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

If I try to create an XML schema collection with this schema I get this error

Reference to an undefined name 'dateTimeOrEmpty'

Is it possible to reuse the named simpleType definition or do I have to retype the entire simpleType definition for each element I was to use it on?

Body:
Looks like a namespace problem.  I think I understood this at one time, but now I just have to fiddle with it until it works.  EG

CREATE XML SCHEMA COLLECTION foo AS
N'<?xml version="1.0" encoding="UTF-16"?>
<xs:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="SomethingUnique"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:s="SomethingUnique"
    >

    <xs:simpleType name="dateTimeOrEmpty">
        <xs:union memberTypes="xs:dateTime">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value=""/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>

    <xs:complexType name="RootType">
        <xs:sequence>
                <xs:element name="SomeDate" type="s:dateTimeOrEmpty"/>
                <xs:element name="OtherDate" type="s:dateTimeOrEmpty" />
            </xs:sequence>
    </xs:complexType>

    <xs:element name="Root" type="s:RootType"/>

</xs:schema>'


问:
Create maximum value for each group
I am trying to classify the temp variable into different classes in such a way that Dur>5.

Further, I want to find the maximum value for each group as shown in expected outcome.

```<code>Dur=c(2.75,0.25,13,0.25,45.25,0.25,0.25,4.25,0.25,0.25,14)
temp=c(2.54,5.08,0,2.54,0,5,2.54,0,2.54,0,2.54)
df=data.frame(Dur,temp)
</code>```

Expected Outcome:

```<code>group=c(1,1,1,2,2,3,3,3,3,3,3)
Colnew=c(5.08,5.08,5.08,2.54,2.54,5,5,5,5,5,5)
(output=data.frame(df,group,Colnew))
</code>```

答:
We create a grouping variable by taking the cumsum of logical vector, then get the max of 'temp'

```<code>library(dplyr)
df %>%
   group_by(group = as.integer(factor(lag(cumsum(Dur > 5), default = 0)))) %>%
   mutate(Max = max(temp))
# A tibble: 11 x 4
# Groups:   group [3]
#    Dur  temp group   Max
#   <dbl> <dbl> <int> <dbl>
# 1  2.75  2.54     1  5.08
# 2  0.25  5.08     1  5.08
# 3 13     0        1  5.08
# 4  0.25  2.54     2  2.54
# 5 45.2   0        2  2.54
# 6  0.25  5        3  5
# 7  0.25  2.54     3  5
# 8  4.25  0        3  5
# 9  0.25  2.54     3  5
#10  0.25  0        3  5
#11 14     2.54     3  5
</code>```

Title: Create maximum value for each group

Body:
I am trying to classify the temp variable into different classes in such a way that Dur>5.

Further, I want to find the maximum value for each group as shown in expected outcome.

Dur=c(2.75,0.25,13,0.25,45.25,0.25,0.25,4.25,0.25,0.25,14)
temp=c(2.54,5.08,0,2.54,0,5,2.54,0,2.54,0,2.54)
df=data.frame(Dur,temp)

Expected Outcome:

group=c(1,1,1,2,2,3,3,3,3,3,3)
Colnew=c(5.08,5.08,5.08,2.54,2.54,5,5,5,5,5,5)
(output=data.frame(df,group,Colnew))

Body:
We create a grouping variable by taking the cumsum of logical vector, then get the max of 'temp'

library(dplyr)
df %>%
   group_by(group = as.integer(factor(lag(cumsum(Dur > 5), default = 0)))) %>%
   mutate(Max = max(temp))
# A tibble: 11 x 4
# Groups:   group [3]
#    Dur  temp group   Max
#   <dbl> <dbl> <int> <dbl>
# 1  2.75  2.54     1  5.08
# 2  0.25  5.08     1  5.08
# 3 13     0        1  5.08
# 4  0.25  2.54     2  2.54
# 5 45.2   0        2  2.54
# 6  0.25  5        3  5
# 7  0.25  2.54     3  5
# 8  4.25  0        3  5
# 9  0.25  2.54     3  5
#10  0.25  0        3  5
#11 14     2.54     3  5


问:
How can I show a popup with description for fullcalendar
I am using fullcalendar and my goal is to have a simple pop up on the event click but for some reason I cannot get it to pull in the description in the alert. </p>

<p>Am I missing some JS to include or something? I tried to use the examples from their site but it was not working. I am sure it is something stupid I am missing. </p>

```<code><script src='../assets/calendar/packages/core/main.js'></script>
<script src='../assets/calendar/packages/interaction/main.js'></script>
<script src='../assets/calendar/packages/daygrid/main.js'></script>
<script src='../assets/calendar/packages/timegrid/main.js'></script>
<script src='../assets/calendar/packages/list/main.js'></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var d = new Date();
        var calendarEl = document.getElementById('calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
            height: 'parent',
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
            },
            defaultView: 'dayGridMonth',
            defaultDate: d,

            eventClick: function(info) {
                alert('Event: ' + info.description);
            },

            navLinks: true, // can click day/week names to navigate views
            editable: false,
            eventLimit: true, // allow "more" link when too many events
            events:
            [
                {
                    title: 'All Day Event<br>second line',
                    description: 'description for Long Event',
                    start: '2020-05-01'
                },
                {
                    title: 'Session',
                    start: '2020-05-12T10:30:00',
                    description: 'description for Long Event',
                    end: '2020-05-12T12:30:00'
                },
                {
                    title: 'Practical',
                    start: '2020-05-27T10:30:00',
                     description: 'description for Long Event',
                    end: '2020-05-27T12:30:00'
                }

            ]
        });

        calendar.render();
    });

</script>
</code>```

答:
You need to write

```<code>alert('Event: ' + info.event.extendedProps.description);
</code>```

because

1) the info object isn't the event, the event is a sub-property of that info object - this is described at https://fullcalendar.io/docs/eventClick

and

2) description is a non-standard field as far as fullCalendar is concerned, and all non-standard fields are placed inside the extendedProps sub-property of the event object which fullCalendar generates based on the data you provide it - this is described at https://fullcalendar.io/docs/event-parsing

Body:
I am using fullcalendar and my goal is to have a simple pop up on the event click but for some reason I cannot get it to pull in the description in the alert.

Am I missing some JS to include or something? I tried to use the examples from their site but it was not working. I am sure it is something stupid I am missing.

Body:
You need to write

alert('Event: ' + info.event.extendedProps.description);

because

1) the info object isn't the event, the event is a sub-property of that info object - this is described at https://fullcalendar.io/docs/eventClick

and

2) description is a non-standard field as far as fullCalendar is concerned, and all non-standard fields are placed inside the extendedProps sub-property of the event object which fullCalendar generates based on the data you provide it - this is described at https://fullcalendar.io/docs/event-parsing


问:
MySQL Filtering Results from a One-to-many Relationship
I have two tables. quotes_table and flags_table. The quotes_table has a one-to-many relationship with the flags_table - each quote can have multiple flags. flags_table.id_flag is a foreign key of quotes_table.id_flag.

Example Input

quotes_table

```<code>pk | quote_key   | id_flag
--------------------------
1  | 111         | 200
2  | 222         | 251
3  | 111         | 250
</code>```

flags_table

```<code>id_flag | name
---------------
200 | testing
251 | converted
250 | paid
</code>```

Expected Output

```<code>quote_key | id_flag | name
-------------------------------------
222       | 251     | converted
</code>```

In summary, I am trying to return all quotes that do not have a flag of "testing" even if other flags are present.

My current query is still returning quote_key record 111 because of the left join but I am not sure how to "filter" it out.

Current Query

```<code>SELECT q.quote_key, q.id_flag, f.name FROM quotes_table AS q
LEFT JOIN flags_table AS f ON q.id_flag = f.id_flag
WHERE  f.name != "testing"
</code>```

Example Diagram of the quotes_tableand flags_table:

Result of performing a LEFT JOIN between the quotes_table and flags_table.

The rows in red represent a quote, notice the shared quote_key. So I am trying to throw away the entries in red from my results so that I only get quotes without a flag of "testing".

SQL Fiddle Example

答:
Hope this helps.</p>

```<code>SELECT q.quote_key, q.id_flag, f.name FROM quotes_table AS q
INNER JOIN flags_table AS f ON q.id_flag = f.id_flag
WHERE f.name != "Testing"
AND q.quote_key not in (select quote_key from quotes_table q1, flags_table f1
where q1.id_flag = f1.id_flag and f1.name = 'Testing')
</code>```

Body:
I have two tables. quotes_table and flags_table. The quotes_table has a one-to-many relationship with the flags_table - each quote can have multiple flags. flags_table.id_flag is a foreign key of quotes_table.id_flag.

Example Input

quotes_table

pk | quote_key   | id_flag
--------------------------
1  | 111         | 200
2  | 222         | 251
3  | 111         | 250

flags_table

id_flag | name
---------------
200 | testing
251 | converted
250 | paid

Expected Output

quote_key | id_flag | name
-------------------------------------
222       | 251     | converted

In summary, I am trying to return all quotes that do not have a flag of "testing" even if other flags are present.

My current query is still returning quote_key record 111 because of the left join but I am not sure how to "filter" it out.

Current Query

SELECT q.quote_key, q.id_flag, f.name FROM quotes_table AS q
LEFT JOIN flags_table AS f ON q.id_flag = f.id_flag
WHERE  f.name != "testing"

Example Diagram of the quotes_tableand flags_table:

Result of performing a LEFT JOIN between the quotes_table and flags_table.

The rows in red represent a quote, notice the shared quote_key. So I am trying to throw away the entries in red from my results so that I only get quotes without a flag of "testing".

SQL Fiddle Example

Body:
Hope this helps.

SELECT q.quote_key, q.id_flag, f.name FROM quotes_table AS q
INNER JOIN flags_table AS f ON q.id_flag = f.id_flag
WHERE f.name != "Testing"
AND q.quote_key not in (select quote_key from quotes_table q1, flags_table f1
where q1.id_flag = f1.id_flag and f1.name = 'Testing')


问:
How do you return created relationships using apoc.refactor.cloneNodes([nodes], true)?
The signature of apoc.refactor.cloneNodes() returns

"apoc.refactor.cloneNodes(nodes :: LIST? OF NODE?, withRelationships = false :: BOOLEAN?, skipProperties = [] :: LIST? OF STRING?) :: (input :: INTEGER?, output :: NODE?, error :: STRING?)"

The function only yields nodes for output. Is there a way to return relationships as well, or do you have to query these manually?

My current implementation looks like this, but I thought there might be a better way?

```<code>MATCH (n) WHERE n.id IN $ids
WITH collect(n) as nodes
CALL apoc.refactor.cloneNodes(nodes,true) yield output
MATCH (output)-[r]-()
SET output.id = apoc.create.uuid(), r.id = apoc.create.uuid()
WITH collect({source:startnode(r), edge:r, target:endnode(r) }) as edges, collect (distinct output) as nodes
RETURN *
</code>```

search tag: apoc.refactor.cloneNodesWithRelationships (deprecated)

Updated to avoid cartesian products, and clarify nodesToClone and nodes:

```<code>MATCH (n) WHERE n.id in $ids
WITH collect(n) as nodesToClone
CALL apoc.refactor.cloneNodes(nodesToClone,true) yield output
SET output.id = apoc.create.uuid()
WITH output
MATCH (output)-[r]-()
SET r.id = apoc.create.uuid()
WITH collect({source:startnode(r), edge:r, target:endnode(r) }) as edges, collect (distinct output) as nodes
RETURN *
</code>```

答:
Your approach looks pretty reasonable.

However, (this is a minor side issue) the query would set the id of an output multiple times if it has multiple relationships. If you want to avoid the unnecessary overhead, you can replace this:

```<code>...
MATCH (output)-[r]-()
SET output.id = apoc.create.uuid(), r.id = apoc.create.uuid()
...
</code>```

with this:

```<code>...
SET output.id = apoc.create.uuid()
WITH output
MATCH (output)-[r]-()
SET r.id = apoc.create.uuid()
...
</code>```

[UPDATE]

In your updated query, you can avoid using the DISTINCT option in collect (distinct output) this way:

```<code>MATCH (n) WHERE n.id in $ids
WITH COLLECT(n) AS nodesToClone
CALL apoc.refactor.cloneNodes(nodesToClone,true) YIELD output
SET output.id = apoc.create.uuid()
WITH COLLECT(output) AS nodes
UNWIND nodes AS node
MATCH (node)-[r]-()
SET r.id = apoc.create.uuid()
WITH COLLECT({source:startnode(r), edge:r, target:endnode(r) }) AS edges, nodes
RETURN *
</code>```

Body:
The signature of apoc.refactor.cloneNodes() returns

"apoc.refactor.cloneNodes(nodes :: LIST? OF NODE?, withRelationships = false :: BOOLEAN?, skipProperties = [] :: LIST? OF STRING?) :: (input :: INTEGER?, output :: NODE?, error :: STRING?)"

The function only yields nodes for output. Is there a way to return relationships as well, or do you have to query these manually?

My current implementation looks like this, but I thought there might be a better way?

MATCH (n) WHERE n.id IN $ids
WITH collect(n) as nodes
CALL apoc.refactor.cloneNodes(nodes,true) yield output
MATCH (output)-[r]-()
SET output.id = apoc.create.uuid(), r.id = apoc.create.uuid()
WITH collect({source:startnode(r), edge:r, target:endnode(r) }) as edges, collect (distinct output) as nodes
RETURN *

search tag: apoc.refactor.cloneNodesWithRelationships (deprecated)

Updated to avoid cartesian products, and clarify nodesToClone and nodes:

MATCH (n) WHERE n.id in $ids
WITH collect(n) as nodesToClone
CALL apoc.refactor.cloneNodes(nodesToClone,true) yield output
SET output.id = apoc.create.uuid()
WITH output
MATCH (output)-[r]-()
SET r.id = apoc.create.uuid()
WITH collect({source:startnode(r), edge:r, target:endnode(r) }) as edges, collect (distinct output) as nodes
RETURN *

Body:
Your approach looks pretty reasonable.

However, (this is a minor side issue) the query would set the id of an output multiple times if it has multiple relationships. If you want to avoid the unnecessary overhead, you can replace this:

...
MATCH (output)-[r]-()
SET output.id = apoc.create.uuid(), r.id = apoc.create.uuid()
...

with this:

...
SET output.id = apoc.create.uuid()
WITH output
MATCH (output)-[r]-()
SET r.id = apoc.create.uuid()
...

[UPDATE]

In your updated query, you can avoid using the DISTINCT option in collect (distinct output) this way:

MATCH (n) WHERE n.id in $ids
WITH COLLECT(n) AS nodesToClone
CALL apoc.refactor.cloneNodes(nodesToClone,true) YIELD output
SET output.id = apoc.create.uuid()
WITH COLLECT(output) AS nodes
UNWIND nodes AS node
MATCH (node)-[r]-()
SET r.id = apoc.create.uuid()
WITH COLLECT({source:startnode(r), edge:r, target:endnode(r) }) AS edges, nodes
RETURN *


问:
Running SQL script using C# code ASP.NET Core
```<code>    public class ClassApp
    {
        static string ServerName = "LAPTOP-xxxxxxRK\\SQLEXPRESS";
        static string DatabaseName = "NewDbInstance";
        private SqlConnection tmpConn;

        public void CreateDb()
        {
            SqlConnection tmpConn;
            string sqlCreateDBQuery;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "SERVER = " + ServerName + "; Trusted_Connection=True;";
            sqlCreateDBQuery = " CREATE DATABASE " + DatabaseName;

            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                tmpConn.Open();
                Console.WriteLine(sqlCreateDBQuery);
                var result = myCommand.ExecuteNonQuery();
                Console.WriteLine(result);
                Console.WriteLine("Database has been created successfully!");

                if (result == -1)
                {
                    RunScript(DatabaseName);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void RunScript(string dbName)
        {
            FileInfo file = new FileInfo("C:\\Users\\ADMIN\\script.sql");
            string script = file.OpenText().ReadToEnd();
            script = script.Replace("GO", "");

            SqlConnection tmpConn;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "Server=LAPTOP-xxxxxxRK\\SQLEXPRESS;" + "Database=" + dbName + "; Trusted_Connection=True;";
            tmpConn.Open();
            SqlCommand myCommandnew = new SqlCommand(script, tmpConn);
            var resultnew = myCommandnew.ExecuteNonQuery();   //Error comes here
            Console.WriteLine(resultnew);
            tmpConn.Close();
        }
</code>```

So I have two questions

When I run this SQL file using C# I got the error

'CREATE SCHEMA' must be the first statement in a query batch.

How to solve this problem?

How to modify code like if create database if it does not exists?

答:
The error is occurring because some SQL DDL commands must be executed as the first statement of a SQL Batch, which is separated by "GO" statements in SSMS.

To run a script with "GO" statements, instead of parsing them out and creating other errors, use the Microsoft.SqlServer.Smo library.  It will process the script as separate batches without you having the messy problem of removing "GO" from already existing scripts.

Your code would look very similar to:

```<code>using (SqlConnection connection = ...)
        {
            Server server = new Server(new ServerConnection(connection));

            try
            {
                server.ConnectionContext.ExecuteNonQuery(script);
            }
            catch (Exception e) {...}
</code>```

Body:
    public class ClassApp
    {
        static string ServerName = "LAPTOP-xxxxxxRK\\SQLEXPRESS";
        static string DatabaseName = "NewDbInstance";
        private SqlConnection tmpConn;

        public void CreateDb()
        {
            SqlConnection tmpConn;
            string sqlCreateDBQuery;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "SERVER = " + ServerName + "; Trusted_Connection=True;";
            sqlCreateDBQuery = " CREATE DATABASE " + DatabaseName;

            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                tmpConn.Open();
                Console.WriteLine(sqlCreateDBQuery);
                var result = myCommand.ExecuteNonQuery();
                Console.WriteLine(result);
                Console.WriteLine("Database has been created successfully!");

                if (result == -1)
                {
                    RunScript(DatabaseName);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void RunScript(string dbName)
        {
            FileInfo file = new FileInfo("C:\\Users\\ADMIN\\script.sql");
            string script = file.OpenText().ReadToEnd();
            script = script.Replace("GO", "");

            SqlConnection tmpConn;
            tmpConn = new SqlConnection();
            tmpConn.ConnectionString = "Server=LAPTOP-xxxxxxRK\\SQLEXPRESS;" + "Database=" + dbName + "; Trusted_Connection=True;";
            tmpConn.Open();
            SqlCommand myCommandnew = new SqlCommand(script, tmpConn);
            var resultnew = myCommandnew.ExecuteNonQuery();   //Error comes here
            Console.WriteLine(resultnew);
            tmpConn.Close();
        }

So I have two questions

When I run this SQL file using C# I got the error

'CREATE SCHEMA' must be the first statement in a query batch.

How to solve this problem?

How to modify code like if create database if it does not exists?

Body:
The error is occurring because some SQL DDL commands must be executed as the first statement of a SQL Batch, which is separated by "GO" statements in SSMS.

To run a script with "GO" statements, instead of parsing them out and creating other errors, use the Microsoft.SqlServer.Smo library.  It will process the script as separate batches without you having the messy problem of removing "GO" from already existing scripts.

Your code would look very similar to:

using (SqlConnection connection = ...)
        {
            Server server = new Server(new ServerConnection(connection));

            try
            {
                server.ConnectionContext.ExecuteNonQuery(script);
            }
            catch (Exception e) {...}


问:
How do I print a specific value from API output?
I want to print the price from this API. How do I print the specific value of 'price' from the json output?</p>

```<code>import requests
import json

url = 'https://api.oilpriceapi.com/v1/prices/latest'
headers = {
  'Authorization': 'Token XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
}

response = requests.get(url = url, headers = headers)
data = response.json()
print(data)
{'status': 'success', 'data': {'price': 36.19, 'formatted': '$36.19', 'currency': 'USD', 'code': 'BRENT_CRUDE_USD', 'created_at': '2020-06-02T22:11:30.159Z', 'type': 'spot_price'}}
</code>```

答:
Like so:</p>

```<code>print(data['status']) // success
print(data['data']['price']) // 36.19
</code>```

Body:
I want to print the price from this API. How do I print the specific value of 'price' from the json output?

import requests
import json

url = 'https://api.oilpriceapi.com/v1/prices/latest'
headers = {
  'Authorization': 'Token XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
}

response = requests.get(url = url, headers = headers)
data = response.json()
print(data)
{'status': 'success', 'data': {'price': 36.19, 'formatted': '$36.19', 'currency': 'USD', 'code': 'BRENT_CRUDE_USD', 'created_at': '2020-06-02T22:11:30.159Z', 'type': 'spot_price'}}

Body:
Like so:

print(data['status']) // success
print(data['data']['price']) // 36.19


问:
How to display user's inputted text from textarea on the same page?
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Word Counter</title>
  </head>
  <body>
    <div id="input-text-page">
      <h1>Word Counter</h1>
      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>
        <br />
      </form>
      <button onclick="countPage()">COUNT</button>
    </div>
    <div id="count-page" style="display: none;">
      <h1>Your Text:</h1>
      <p id=display-user-text></p>
    </div>
  </body>
  <script src="app.js"></script>
</html>
</code>```

JavaScript:

```<code>const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};
</code>```

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

答:
Since you're only hidding the elements, you can still access to it's value.
So before you do countPage.style.display = "block";
should be this:

```<code>const inputUserText = document.getElementById("inputted-user-text");  // Get input text
document.getElementById("display-user-text").innerText = inputUserText.value  // Set text in the other page
</code>```

Body:
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

<!DOCTYPE html>

    <title>Word Counter</title>

Word Counter

      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>

      </form>
      <button onclick="countPage()">COUNT</button>

Your Text:

JavaScript:

const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

Body:
Since you're only hidding the elements, you can still access to it's value.
So before you do countPage.style.display = "block";
should be this:

const inputUserText = document.getElementById("inputted-user-text");  // Get input text
document.getElementById("display-user-text").innerText = inputUserText.value  // Set text in the other page


问:
Why do I need to use http.StripPrefix to access my static files?
main.go

```<code>package main

import (
    "net/http"
)

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    http.ListenAndServe(":8080", nil)
}
</code>```

Directory structure:

```<code>%GOPATH%/src/project_name/main.go
%GOPATH%/src/project_name/static/..files and folders ..
</code>```

Even after reading the documentation I have trouble understanding what exactly http.StripPrefix does here.

1) Why can't I access localhost:8080/static if I remove http.StripPrefix?

2) What URL maps to /static folder if I remove that function?

答:
For anyone having issues with subdirectories, you need to add a "." because it seems it treats the path as relative only if it's a folder in the root directory of the binary.

For example

```<code>s.router.PathPrefix("/logos/").Handler(
        http.StripPrefix("/logos/", http.FileServer(http.Dir("./uploads/logos/"))))
</code>```

Note the "." before "/uploads"

Body:
main.go

package main

import (
    "net/http"
)

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    http.ListenAndServe(":8080", nil)
}

Directory structure:

%GOPATH%/src/project_name/main.go
%GOPATH%/src/project_name/static/..files and folders ..

Even after reading the documentation I have trouble understanding what exactly http.StripPrefix does here.

1) Why can't I access localhost:8080/static if I remove http.StripPrefix?

2) What URL maps to /static folder if I remove that function?

Body:
For anyone having issues with subdirectories, you need to add a "." because it seems it treats the path as relative only if it's a folder in the root directory of the binary.

For example

s.router.PathPrefix("/logos/").Handler(
        http.StripPrefix("/logos/", http.FileServer(http.Dir("./uploads/logos/"))))

Note the "." before "/uploads"


问:
How would you use Codemirror documents to get multiple editors?
I'm trying to add tabs to the Codemirror editor to have multiple editors just by the switch of a tab.

I got this basic implementation working but couldn't make any progress https://codepen.io/mottox2/pen/wmGopW

The CodeMirror manual says to do this
https://codemirror.net/doc/manual.html#api_doc

```<code>CodeMirror.Doc(text: string, mode: Object, firstLineNumber: ?number, lineSeparator: ?string)
</code>```

But I have no idea where I'd put that line of code

答:
Not sure if this answers your question, is this what you're looking for?
CodePen Example

```<code>var editors = document.getElementsByClassName('editor');
for (var i = 0; i < editors.length; i++) {
  var self = editors[i];
  var editor = CodeMirror.fromTextArea(self, {
    mode: "javascript",
    lineNumbers: true,
    autoRefresh: true
  });
  editor.save();
}

var tabs = document.querySelectorAll('.tab');

for (var i = 0; i < tabs.length; i++) {
  var self = tabs[i];
  self.addEventListener('click', function() {
    var data = this.getAttribute('data-tab');
    document.querySelectorAll('.tab-pane.active')[0].classList.remove('active');
    document.querySelectorAll('.tab-pane[data-pane="'+data+'"]')[0].classList.add('active');
    document.querySelectorAll('.tab.active')[0].classList.remove('active');
    this.classList.add('active');
  });
}
</code>```

Define multiple editors using a loop, create some tabs to hide / show each editor.

Body:
I'm trying to add tabs to the Codemirror editor to have multiple editors just by the switch of a tab.

I got this basic implementation working but couldn't make any progress https://codepen.io/mottox2/pen/wmGopW

The CodeMirror manual says to do this
https://codemirror.net/doc/manual.html#api_doc

CodeMirror.Doc(text: string, mode: Object, firstLineNumber: ?number, lineSeparator: ?string)

But I have no idea where I'd put that line of code

Body:
Not sure if this answers your question, is this what you're looking for?
CodePen Example

var editors = document.getElementsByClassName('editor');
for (var i = 0; i < editors.length; i++) {
  var self = editors[i];
  var editor = CodeMirror.fromTextArea(self, {
    mode: "javascript",
    lineNumbers: true,
    autoRefresh: true
  });
  editor.save();
}

var tabs = document.querySelectorAll('.tab');

for (var i = 0; i < tabs.length; i++) {
  var self = tabs[i];
  self.addEventListener('click', function() {
    var data = this.getAttribute('data-tab');
    document.querySelectorAll('.tab-pane.active')[0].classList.remove('active');
    document.querySelectorAll('.tab-pane[data-pane="'+data+'"]')[0].classList.add('active');
    document.querySelectorAll('.tab.active')[0].classList.remove('active');
    this.classList.add('active');
  });
}

Define multiple editors using a loop, create some tabs to hide / show each editor.


问:
collectl says "system does not have lustre modules installed"
I want to use collectl (V4.1.0-1) to get lustre (version=2.12.2_178_ga0680fe_dirty) specific stats. But, it says "-sl disabled because this system does not have lustre modules installed"! But, system does have the necessary lustre modules. Can somebody help in resolving this issue.

```<code>root@dgx1:~# collectl -sL
Use of uninitialized value $strace in pattern match (m//) at /usr/share/collectl/formatit.ph line 178.
Use of uninitialized value $speed in numeric gt (>) at /usr/share/collectl/formatit.ph line 181.
-sl disabled because this system does not have lustre modules installed
Error: no subsystems selected
type 'collectl -h' for help
root@dgx1:~#

root@dgx1:~# collectl -sl
Error: invalid subsystem 'l'
type 'collectl -h' for help
root@dgx1:~#
</code>```

Following are the system details.

```<code>root@dgx1:~# uname -r
4.15.0-45-generic

root@dgx1:~# uname -a
Linux dgx1 4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

root@dgx1:~# lctl get_param version
version=2.12.2_178_ga0680fe_dirty

root@dgx1:~# lsmod | grep lustre
lustre                737280  2093
lmv                   180224  3 lustre
mdc                   237568  3 lustre
lov                   311296  1397 lustre
ptlrpc               1306624  8 fld,osc,fid,mgc,lov,mdc,lmv,lustre
obdclass             2158592  1421 fld,osc,fid,ptlrpc,mgc,lov,mdc,lmv,lustre
lnet                  557056  7 osc,ko2iblnd,obdclass,ptlrpc,mgc,lmv,lustre
libcfs                471040  12 fld,lnet,osc,fid,ko2iblnd,obdclass,ptlrpc,mgc,lov,mdc,lmv,lustre

root@dgx1:~# collectl --version
collectl V4.1.0-1 (zlib:2.074,HiRes:1.9741)
Copyright 2003-2016 Hewlett-Packard Development Company, L.P.
collectl may be copied only under the terms of either the Artistic License
or the GNU General Public License, which may be found in the source kit
</code>```

答:
collectl needs to be patched since version 2.10. Notice however that collectl is no longer maintained (see this post on collectl).

There are also some other nice and current alternatives listed on the Whamcloud's third party tools page.

Body:
I want to use collectl (V4.1.0-1) to get lustre (version=2.12.2_178_ga0680fe_dirty) specific stats. But, it says "-sl disabled because this system does not have lustre modules installed"! But, system does have the necessary lustre modules. Can somebody help in resolving this issue.

root@dgx1:~# collectl -sL
Use of uninitialized value $strace in pattern match (m//) at /usr/share/collectl/formatit.ph line 178.
Use of uninitialized value $speed in numeric gt (>) at /usr/share/collectl/formatit.ph line 181.
-sl disabled because this system does not have lustre modules installed
Error: no subsystems selected
type 'collectl -h' for help
root@dgx1:~#

root@dgx1:~# collectl -sl
Error: invalid subsystem 'l'
type 'collectl -h' for help
root@dgx1:~#

Following are the system details.

root@dgx1:~# uname -r
4.15.0-45-generic

root@dgx1:~# uname -a
Linux dgx1 4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

root@dgx1:~# lctl get_param version
version=2.12.2_178_ga0680fe_dirty

root@dgx1:~# lsmod | grep lustre
lustre                737280  2093
lmv                   180224  3 lustre
mdc                   237568  3 lustre
lov                   311296  1397 lustre
ptlrpc               1306624  8 fld,osc,fid,mgc,lov,mdc,lmv,lustre
obdclass             2158592  1421 fld,osc,fid,ptlrpc,mgc,lov,mdc,lmv,lustre
lnet                  557056  7 osc,ko2iblnd,obdclass,ptlrpc,mgc,lmv,lustre
libcfs                471040  12 fld,lnet,osc,fid,ko2iblnd,obdclass,ptlrpc,mgc,lov,mdc,lmv,lustre

root@dgx1:~# collectl --version
collectl V4.1.0-1 (zlib:2.074,HiRes:1.9741)
Copyright 2003-2016 Hewlett-Packard Development Company, L.P.
collectl may be copied only under the terms of either the Artistic License
or the GNU General Public License, which may be found in the source kit


问:
Contradictory reporting of total Process memory usage in C# Winforms app
EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

I have a memory leak in one of my C# Winforms programs, and I'd like to graph its memory usage over time to get a better understanding of what might be causing the leak. Problem is, none of the usual memory diagnostic commands match up with what the Task Manager is claiming as its consumed memory for that process. I assumed this was perhaps due to the app using unsafe/unmanaged code not being included in the total.

So to try and drill deeper, I created a new Winforms app, very simple, with just a timer to report the memory usage in realtime. I use 5 labels, each with various functions (mostly found from here): Environment.WorkingSet, GC.GetTotalMemory(false), GC.GetTotalMemory(true), Process.GetCurrentProcess().PrivateMemorySize64 and Process.GetCurrentProcess().WorkingSet64.

Surprisingly (or maybe not so, sigh), I still can't get any of these five numbers to match up with the Windows 10 Task Manager. Here's a screenshot:

So what I'm basically looking for is that 5.1MB number. How do I sneakily extract that hidden number from the .NET framework?

Here's the code I have in the Timer tick function:

```<code>private void timer1_Tick(object sender, EventArgs e)
{
    //Refresh();
    label1.Text = "Environment.WorkingSet: " +  Environment.WorkingSet ;
    label2.Text = "GC.GetTotalMemory(false): " +    GC.GetTotalMemory(false) ;
    label3.Text = "GC.GetTotalMemory(true): " + GC.GetTotalMemory(true) ;
    Process proc = Process.GetCurrentProcess();
    label4.Text = "proc.PrivateMemorySize64: " +    proc.PrivateMemorySize64 ;
    label5.Text = "proc.WorkingSet64: " +       proc.WorkingSet64 ;
    proc.Dispose();
}
</code>```

As might be evident, I tried with and without the Refresh() command to no avail.

EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

答:
The windows task manager is showing only the memory that actually on the RAM and the process memory is including the pages (on the disk )
that the reason the process memory can be bigger from the actual RAM on your machine </p>

Body:
EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.

I have a memory leak in one of my C# Winforms programs, and I'd like to graph its memory usage over time to get a better understanding of what might be causing the leak. Problem is, none of the usual memory diagnostic commands match up with what the Task Manager is claiming as its consumed memory for that process. I assumed this was perhaps due to the app using unsafe/unmanaged code not being included in the total.

So to try and drill deeper, I created a new Winforms app, very simple, with just a timer to report the memory usage in realtime. I use 5 labels, each with various functions (mostly found from here): Environment.WorkingSet, GC.GetTotalMemory(false), GC.GetTotalMemory(true), Process.GetCurrentProcess().PrivateMemorySize64 and Process.GetCurrentProcess().WorkingSet64.

Surprisingly (or maybe not so, sigh), I still can't get any of these five numbers to match up with the Windows 10 Task Manager. Here's a screenshot:

So what I'm basically looking for is that 5.1MB number. How do I sneakily extract that hidden number from the .NET framework?

Here's the code I have in the Timer tick function:

private void timer1_Tick(object sender, EventArgs e)
{
    //Refresh();
    label1.Text = "Environment.WorkingSet: " +  Environment.WorkingSet ;
    label2.Text = "GC.GetTotalMemory(false): " +    GC.GetTotalMemory(false) ;
    label3.Text = "GC.GetTotalMemory(true): " + GC.GetTotalMemory(true) ;
    Process proc = Process.GetCurrentProcess();
    label4.Text = "proc.PrivateMemorySize64: " +    proc.PrivateMemorySize64 ;
    label5.Text = "proc.WorkingSet64: " +       proc.WorkingSet64 ;
    proc.Dispose();
}

As might be evident, I tried with and without the Refresh() command to no avail.

EDIT: The bounty's expired, but if the community would like to award it to someone, then I choose Raful Chizkiyahu.


问:
Django - Spotify API authorisation
I have developed a simple Django app, using Spotify API and Spotipy Authorisation (authorisation flow). This runs a localhost server where I click a simple button which creates a playlist in Spotify.

My issue however is in setting this up for an alternative user to login via their credentials and gain authorisation.

Atm, I have set this app up using a hardcoded cid and client secret within the views.py module (in the backend). This uses the following code to gain auth.

```<code>token = util.prompt_for_user_token(username, scope, client_id= cid, client_secret= secret, redirect_uri=r_uri)
</code>```

My index.html file then links a button to this script so that when clicked, the playlist is created. I expect this index.html needs to be updated to allow the user to login to their own spotify account and to authorise their token. However I am unsure on how to update this or if I am on the right track.

Alternatively, I think I may need to restart the project using java to gain authorisation for another user or using Implicit Grant Auth method, if spotipy authorisation cannot be used.

答:
You won't be able to use prompt_for_user_token for this because it is a  helper meant to be used locally by a single user and will block the app if the signin process is not completed.

Have a look at this Flask python app and adapt it to make it work in Django.  https://github.com/plamere/spotipy/blob/master/examples/app.py

It does everything you need:

uses python and spotipy

allows user to login using a link

allows user to do any action by clicking another link

keeps client id and secret on the backend

Have fun!

Title: Django - Spotify API authorisation

Body:
I have developed a simple Django app, using Spotify API and Spotipy Authorisation (authorisation flow). This runs a localhost server where I click a simple button which creates a playlist in Spotify.

My issue however is in setting this up for an alternative user to login via their credentials and gain authorisation.

Atm, I have set this app up using a hardcoded cid and client secret within the views.py module (in the backend). This uses the following code to gain auth.

token = util.prompt_for_user_token(username, scope, client_id= cid, client_secret= secret, redirect_uri=r_uri)

My index.html file then links a button to this script so that when clicked, the playlist is created. I expect this index.html needs to be updated to allow the user to login to their own spotify account and to authorise their token. However I am unsure on how to update this or if I am on the right track.

Alternatively, I think I may need to restart the project using java to gain authorisation for another user or using Implicit Grant Auth method, if spotipy authorisation cannot be used.


问:
How do I save form response as an object in Django's database?
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

```<code>class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
</code>```

This is my view in views.py file.

```<code>@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')
</code>```

This is my HTML code for the form.

```<code>{% extends 'authmain.html' %}

{% block content %}
<h3> <p class="text-center"> Create a new Course Blockchain: </p> </h3>

<div class="card border-dark mb-3 mx-auto" align="center" style="width: 40rem;">
  <div class="card-body">
    <h5 class="card-title">
      <form method='POST'>
        {% csrf_token %}
        <label for="year">Year: </label>
        <input type="text" id="year" name="year" value=""><br>
        <label for="code">Course Code: </label>
        <input type="text" id="code" name="code" value=""><br>
        <label for="name">Course Name: </label>
        <input type="text" id="name" name="name" value=""><br>
        <label for="slot">Slot: </label>
        <input type="text" id="slot" name="slot" value=""><br>
        <label for="sem">Semester: </label>
        <input type="text" id="sem" name="sem" value=""><br>
        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>
    </h5>
    </div>
</div>

{% endblock %}
</code>```

This is my urls.py.

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]
</code>```

This is the view function for success.

```<code>
@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})
</code>```

答:
To save directly in the database in Django use Model.objects.create()

```<code>Chain.objects.create(user=request.user, name=name, year=year, sem=sem,
                      code=code, slot = slot)
</code>```

Body:
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

This is my view in views.py file.

@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')

This is my HTML code for the form.

{% extends 'authmain.html' %}

{% block content %}

 Create a new Course Blockchain:

      <form method='POST'>
        {% csrf_token %}
        Year:
        <input type="text" id="year" name="year" value="">

        Course Code:
        <input type="text" id="code" name="code" value="">

        Course Name:
        <input type="text" id="name" name="name" value="">

        Slot:
        <input type="text" id="slot" name="slot" value="">

        Semester:
        <input type="text" id="sem" name="sem" value="">

        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>

{% endblock %}

This is my urls.py.

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]

This is the view function for success.

@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})

Body:
To save directly in the database in Django use Model.objects.create()

Chain.objects.create(user=request.user, name=name, year=year, sem=sem,
                      code=code, slot = slot)


问:
Only take first value from loop GOLANG
Does anyone know why it took first value when I call variable inside the loop ? I want to make palindrome but the code just like this, can someone explain me. I'm new in GO</p>

```<code>    package main

    import "fmt"

    func main() {
        var kata, kosong, kebalikan, katanya string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata) - 1
    for i := panjang; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(kebalikan)
    }
    fmt.Print("\n")
    for i := 0; i <= panjang; i++ {
        katanya = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(katanya)
    }
    fmt.Println(katanya)
    fmt.Println(kebalikan)
    if fmt.Sprint(katanya) == fmt.Sprint(kebalikan) {
        fmt.Println(true)
    } else {
        fmt.Println(false)
    }

}
</code>```

答:
i have my answer from my own question, here i mean</p>

```<code>var kata, kebalikan string

fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata) - 1
for i := panjang; i >= 0; i-- {
    kebalikan = kebalikan + fmt.Sprint(string(kata[i]))
}
if fmt.Sprint(kata) == fmt.Sprint(kebalikan) {
    fmt.Println(true)
} else {
    fmt.Println(false)
}
</code>```

Title: Only take first value from loop GOLANG

Body:
Does anyone know why it took first value when I call variable inside the loop ? I want to make palindrome but the code just like this, can someone explain me. I'm new in GO

    package main

    import "fmt"

    func main() {
        var kata, kosong, kebalikan, katanya string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata) - 1
    for i := panjang; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(kebalikan)
    }
    fmt.Print("\n")
    for i := 0; i <= panjang; i++ {
        katanya = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(katanya)
    }
    fmt.Println(katanya)
    fmt.Println(kebalikan)
    if fmt.Sprint(katanya) == fmt.Sprint(kebalikan) {
        fmt.Println(true)
    } else {
        fmt.Println(false)
    }

}

Body:
i have my answer from my own question, here i mean

var kata, kebalikan string

fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata) - 1
for i := panjang; i >= 0; i-- {
    kebalikan = kebalikan + fmt.Sprint(string(kata[i]))
}
if fmt.Sprint(kata) == fmt.Sprint(kebalikan) {
    fmt.Println(true)
} else {
    fmt.Println(false)
}


问:
printf() prints twice the same line after signal handling
I have this function (in a long program with semaphores, I'll attach any code if necessary):

```<code>void signalHandler(int signumber){
    /* for SIGINT */
    if(signumber == SIGINT){
        printf(" Pressed - Stop the timer & start cleaning process...\n");
        flag = 0; //relevant for the rest of the program
    }
}
</code>```

when I'm running the program and press CTRL+C to stop it, instead of getting this output:

```<code>^C Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....
</code>```

I get this output with double print:

```<code>^C Pressed - Stop the timer & start cleaning process...
 Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....
</code>```

This little thing very annoying, how can I fix it?
Thanks.

答:
In ISO C, a signal handler may only set a volatile atomic flag, or abort the program .  In POSIX it may also call some signal-safe functions, you will see that printf is not in the list.

So, basically, don't call printf from the signal handler.

Perhaps you could write to stdout, if going for POSIX conformance without ISO conformance. Or for the latter, set a flag in the signal handler and check that flag periodically from the main loop.

Body:
I have this function (in a long program with semaphores, I'll attach any code if necessary):

void signalHandler(int signumber){
    /* for SIGINT */
    if(signumber == SIGINT){
        printf(" Pressed - Stop the timer & start cleaning process...\n");
        flag = 0; //relevant for the rest of the program
    }
}

when I'm running the program and press CTRL+C to stop it, instead of getting this output:

^C Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....

I get this output with double print:

^C Pressed - Stop the timer & start cleaning process...
 Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....

This little thing very annoying, how can I fix it?
Thanks.


问:
Is it possible to build an android app that installs 3 apk, which are stored inside the app itself?
I'm new to android studio and I'm a beginner. I want to build an app that contains 2 or 3 apk files inside the app itself - not in device storage - and make a single button to prompt to install all of them. Is that possible?! </p>

答:
Use this to save file to storage after requesting necessary permission : Write_External_Storage

```<code>private void copyAsset(String filename){
    String dirPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
    File dir = new File(dirPath);
    if(!dir.exists()){
        dir.mkdirs();

    }

    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open( filename);
        File outFile = new File(dirPath, filename);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
    } catch (IOException e){
        e.printStackTrace();
        Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
    } finally {
        if (in != null){
            try{
                in.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        if (out != null){
            try{
                out.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);

    }
}
</code>```

And finally use this to install:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory().getAbsolutePath + "/MyFiles/" +
"appName.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code>```

Make sure to request permessions : REQUEST_INSTALL_PACKAGES and READ EXTERNAL STORAGE

Body:
Use this to save file to storage after requesting necessary permission : Write_External_Storage

private void copyAsset(String filename){
    String dirPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
    File dir = new File(dirPath);
    if(!dir.exists()){
        dir.mkdirs();

    }

    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open( filename);
        File outFile = new File(dirPath, filename);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
    } catch (IOException e){
        e.printStackTrace();
        Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
    } finally {
        if (in != null){
            try{
                in.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        if (out != null){
            try{
                out.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);

    }
}

And finally use this to install:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory().getAbsolutePath + "/MyFiles/" +
"appName.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Make sure to request permessions : REQUEST_INSTALL_PACKAGES and READ EXTERNAL STORAGE


问:
How to make a path from a string in starlark?
I'm writing some validation code for a bazel build rule and I need to do some path validation. I need to check that a certain file exists in the same directory as the BUILD file. I notice that there's a context attribute build_file_path which points to the BUILD file. I'd like to extract the parent directory from this.

It looks like I can't create a new path object - I don't see a constructor/initializer. It also seems like Starlark doesn't support os.path like python because imports aren't supported.

What's the canonical way to get the parent directory of a string object representing a path in Starlark?

答:
I can't answer your final question, but hopefully the following will help with the initial problem:

You could use the Label of the target for which this instance of the rule is being built and find its package. This will give you a string representing the parent directory of the BUILD file.

i.e. ctx.label.package


问:
Is there a parallelized version of scipy.optimize.minimize?
I am trying to minimize a cost function using scipy.optimize.minimize, but it is very slow. My function has close to 5000 variables, and so it is not surprising that scipy is slow. However, if there is a parallel version of scipy.optimize.minimize it might help a great deal.

I was wondering if such version of scipy.optimize.minimize exists or if there is any other scipy/numpy tool available for performing minimization of this magnitude. I really appreciate any and all help.

Thanks everybody for their comments. This is a constrained minimization using the SLSQP solver. I have already spent a lot of time making sure that the cost function calculation is optimized, so the problem must be in calculation of the gradient or due to constraints. In other words, the amount of time that is spent on function evaluations is a very small fraction of the total time spent on the minimization.

答:
We implemented a parallel version of scipy.optimize.minimize(method='L-BFGS-B') in the package optimparallel available on PyPI. It can speedup the optimization by evaluating the objective function and the (approximate) gradient in parallel. I have not tested it with 5000 parameters. But, with fewer parameters we observe good parallel scaling.

The Python package is a Python implementation of the R package optimParallel. The method is documented in this R journal article.

Here is an illustration of the possible parallel scaling:


问:
Angular 2: Form submission canceled because the form is not connected
I have a modal that contains a form, when the modal is destroyed I get the following error in the console:

Form submission canceled because the form is not connected

The modal is added to a <modal-placeholder> element which is a direct child to <app-root>, my top level element.

What's the correct way to removing a form from the DOM and getting rid of this error in Angular 2? I currently use componentRef.destroy();

答:
If you still want to maintain the functionality of the button to be of type "submit", then you should not be using the click event on that button. Instead you should use the ngSubmit event on the form.

Example:

```<code><form (ngSubmit)="destroyComponent()">
<button type="submit">submit</button>
</form>
</code>```

Body:
If you still want to maintain the functionality of the button to be of type "submit", then you should not be using the click event on that button. Instead you should use the ngSubmit event on the form.

Example:

<form (ngSubmit)="destroyComponent()">
<button type="submit">submit</button>
</form>