问:
Execute MathJax for custom tags without delimiters
I want to use mathjax on our page and i have a custom tag with the formulas <formula>.

However it works only when i use delimiters inside my custom tag, is it possible to get rich of the delimiter?

When i set inlineMath: [['', '']] the whole thing hangs up.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>title</title>
    <link rel="stylesheet" href="style.css">

hello world

this is a <formula>x^2 + y^2 = z^2</formula> formula x^2 + y^2 = z^2

this is a <formula>$x^2 + y^2 = z^2$</formula> formula x^2 + y^2 = z^2

```

答:
You can do something similar to the example given in the documentation that shows how to process the old v2-style

this is a <formula>x^2 + y^2 = z^2</formula> formula x^2 + y^2 = z^2
```

Note that this replaces the usual math-finding function with this one that looks for <formula> tags, so if you want to use the original delimiters as well, change the find: [10 to findTags: [9 so that the original will not be replaced and will run after your code runs.

Note also that this does not give you a means of distinguishing display-style math from in-line math (as the TeX delimiters do), so all the math is in in-line style.  You could, of course, modify the code to have two different tags, or allow an attribute on <formula> to specify display style.

Body:
You can do something similar to the example given in the documentation that shows how to process the old v2-style <script> tags that used to be used to hold the math.

Here is an example:

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script>
MathJax = {
  options: {
    renderActions: {
      find: [10, function (doc) {
        for (const node of document.querySelectorAll('formula')) {
          const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], false);
          const text = document.createTextNode('');
          node.parentNode.replaceChild(text, node);
          math.start = {node: text, delim: '', n: 0};
          math.end = {node: text, delim: '', n: 0};
          doc.math.push(math);
        }
      }, '']
    }
  }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<p>this is a <formula>x^2 + y^2 = z^2</formula> formula x^2 + y^2 = z^2</p>

Note that this replaces the usual math-finding function with this one that looks for <formula> tags, so if you want to use the original delimiters as well, change the find: [10 to findTags: [9 so that the original will not be replaced and will run after your code runs.

Note also that this does not give you a means of distinguishing display-style math from in-line math (as the TeX delimiters do), so all the math is in in-line style.  You could, of course, modify the code to have two different tags, or allow an attribute on <formula> to specify display style.


来源: stackexchange

问:
C++, = operator different options
I Wrote the following function for = operator:

```<code>Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

But, I wanted the following code to work as expected (without deleting current data):

```<code>Set s1,s2;
s1=s1;
</code>```

So I made the following changes:

```<code>Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

my question is:

1. Why this is correct:

```<code>    if (this == &s)
    {
        return *this;
    }
</code>```

while this is not:

```<code>    if (this == s)
    {
        return *this;
    }
</code>```

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

```<code>    if (*this == s)
    {
        return *this;
    }
</code>```

答:
this is a pointer that stores the address of an object, and s is a reference to some object.

This check:

```<code>if (this == &s)  // compares addresses
</code>```

is checking if the address of s is the same as the address of the object being assigned to. This is what you want, and is correct.

This check:

```<code>if (this == s)  // error, good
</code>```

compares a pointer and an object, which will give a compiler error.

This check:

```<code>if (*this == s)  // compares values
</code>```

compares the value of s with the object. This is incorrect, since 2 distinct objects can have the same value, while of course they have different addresses. This is not a case of self-assignment, and is incorrect.

ContentLicense: CC BY-SA 4.0

Title: C++, = operator different options

Body:
I Wrote the following function for = operator:

Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

But, I wanted the following code to work as expected (without deleting current data):

Set s1,s2;
s1=s1;

So I made the following changes:

Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

my question is:

1. Why this is correct:

    if (this == &s)
    {
        return *this;
    }

while this is not:

    if (this == s)
    {
        return *this;
    }

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

    if (*this == s)
    {
        return *this;
    }

Body:
this is a pointer that stores the address of an object, and s is a reference to some object.

This check:

if (this == &s)  // compares addresses

is checking if the address of s is the same as the address of the object being assigned to. This is what you want, and is correct.

This check:

if (this == s)  // error, good

compares a pointer and an object, which will give a compiler error.

This check:

if (*this == s)  // compares values

compares the value of s with the object. This is incorrect, since 2 distinct objects can have the same value, while of course they have different addresses. This is not a case of self-assignment, and is incorrect.


问:
How to add Typescript definitions to Express req & res
I have a set of controller functions for my REST API and I'm getting lots of the following

```<code>error TS7006: Parameter 'req' implicitly has an 'any' type.
</code>```

Likewise for res.  I've been playing around with typeings etc. but with no success. For example the Request type parameter below does NOT work.

Here is an example of the controller files. The reference path is correct.

```<code>/// <reference path="../../../typings/tsd.d.ts" />
/* globals require */
"use strict";
exports.test = (req : Request, res) => {
</code>```

I tried adding import * as express from "express"; into the file - I don't need it normally as these functions are exported and use by index.js which actually implements the routing.

And this is tsd.d.ts

```<code>/// <reference path="requirejs/require.d.ts" />
/// <reference path="express/express.d.ts" />
/// <reference path="mime/mime.d.ts" />
/// <reference path="node/node.d.ts" />
/// <reference path="serve-static/serve-static.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="mongoose/mongoose.d.ts" />
</code>```

答:
Rather than installing types(@types/express) you should also define request parameters. Since every parameter is string, interface should base on  dictionary.

Here is an inline route handler:

```<code>interface GetParams {
  [key: string]: string
  paramName: string
}

router.get<GetParams>('/:paramName', (req, res) => {
  res.send('Parameter is ' + req.params.paramName)
})

</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a set of controller functions for my REST API and I'm getting lots of the following

error TS7006: Parameter 'req' implicitly has an 'any' type.

Likewise for res.  I've been playing around with typeings etc. but with no success. For example the Request type parameter below does NOT work.

Here is an example of the controller files. The reference path is correct.

/// <reference path="../../../typings/tsd.d.ts" />
/* globals require */
"use strict";
exports.test = (req : Request, res) => {

I tried adding import * as express from "express"; into the file - I don't need it normally as these functions are exported and use by index.js which actually implements the routing.

And this is tsd.d.ts

/// <reference path="requirejs/require.d.ts" />
/// <reference path="express/express.d.ts" />
/// <reference path="mime/mime.d.ts" />
/// <reference path="node/node.d.ts" />
/// <reference path="serve-static/serve-static.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="mongoose/mongoose.d.ts" />

Body:
Rather than installing types(@types/express) you should also define request parameters. Since every parameter is string, interface should base on  dictionary.

Here is an inline route handler:

interface GetParams {
  [key: string]: string
  paramName: string
}

router.get<GetParams>('/:paramName', (req, res) => {
  res.send('Parameter is ' + req.params.paramName)
})


问:
Can't run Gradle Tasks on project
I'm trying to run a Gradle Task by double clicking it on Eclipse, but the task is greyed out and says "Cannot run tasks for included builds" if I right click it as you can see in the image below:

What's that supposed to mean? Suddenly I can't run tasks for no apparent reason when I was able a few hours ago.

My project is Liferay based. I'm under JDK 1.8 and Windows 10.

I tried restarting Eclipse, cleaning project, deleting .gradle folder, changing Gradle version to 4.10 and refreshing tasks but nothing changes.

答:
Posting this in case it helps anyone.  For me, this problem arose when I added a new Java project and manually converted it to gradle and then added it as a sub-project.

Doing so changed the following line in /.settings/org.eclipse.buildship.core.prefs  from this:

```<code>connection.project.dir=
</code>```

to this:

```<code>connection.project.dir=mynewproject
</code>```

Once I changed that line back, I could run all sub-project tasks again.

Title: Can't run Gradle Tasks on project

Body:
Posting this in case it helps anyone.  For me, this problem arose when I added a new Java project and manually converted it to gradle and then added it as a sub-project.

Doing so changed the following line in /.settings/org.eclipse.buildship.core.prefs  from this:

connection.project.dir=

to this:

connection.project.dir=mynewproject

Once I changed that line back, I could run all sub-project tasks again.


问:
Python Database that stays with the program
So mysql works great when you log into  your mysql database program on that device but what if you want to move the program to another device, the connected databases wont work...

Is there anyway to have the database somehow within the python file, so that when I move it to other devices it will act the same...Thank you!

答:
Assuming you want to store some simple information, Sqlite3 does exact what you're looking for. This is a sql database that is entirely run on a file on the hardrive that the application is running from. </p>

<p>But be careful what you put in this database. This is not meant to be a high performance database, and will crumble if you stress it too much. </p>

Body:
Assuming you want to store some simple information, Sqlite3 does exact what you're looking for. This is a sql database that is entirely run on a file on the hardrive that the application is running from.

But be careful what you put in this database. This is not meant to be a high performance database, and will crumble if you stress it too much.


问:
python3.7 subprocess failed to delete files for me
I have a python script using 'subprocess' running linux command to confirm my task is doing the right thing, and it worked well. But i found that at the same time it will generate some log files when running my task. So i added a clean up function to rm log files for me at the beginning. My script is:

```<code>def test_clean_up_logs(path_to_my_log):
    regex = path_to_my_log + ".*"   # i need this because log will append current date time when it's generated
    print(regex) # i can see it's correct
    result = subprocess.run(['rm', '-rf', regex])

def test_my_real_test():
      # This will run my real test and generate log files
</code>```

but it turns out it did not remove log files for me after i added first test, it still have more and more logs file in my build dir. I run it using:

```<code>Python3.7 -m pytest /path/to/mydir
</code>```

My question is:
1. Why did not it work? In my second test case, i am using 'subprocess' to run a linux command and it worked fine.

2. Is this correct way to clean up log files? i cannot think of a better way to do it automatically. Thanks!

答:
Why did not it work?

Because the arguments that you gave to your command is passed in quotes and wildcards like * does not work in quotes. Currently the executed command looks like this:

```<code>$ rm "-rf" "filename.*"
</code>```

Try this in your terminal and you will see that it will not remove the files that starts with filename..

You need to pass shell = True to execute the command in a shell interpreter and give your command as a single string.

```<code>subprocess.run(f'rm -rf {regex}', shell=True)
</code>```

Body:
I have a python script using 'subprocess' running linux command to confirm my task is doing the right thing, and it worked well. But i found that at the same time it will generate some log files when running my task. So i added a clean up function to rm log files for me at the beginning. My script is:

def test_clean_up_logs(path_to_my_log):
    regex = path_to_my_log + ".*"   # i need this because log will append current date time when it's generated
    print(regex) # i can see it's correct
    result = subprocess.run(['rm', '-rf', regex])

def test_my_real_test():
      # This will run my real test and generate log files

but it turns out it did not remove log files for me after i added first test, it still have more and more logs file in my build dir. I run it using:

Python3.7 -m pytest /path/to/mydir

My question is:
1. Why did not it work? In my second test case, i am using 'subprocess' to run a linux command and it worked fine.

2. Is this correct way to clean up log files? i cannot think of a better way to do it automatically. Thanks!

Body:
Why did not it work?

Because the arguments that you gave to your command is passed in quotes and wildcards like * does not work in quotes. Currently the executed command looks like this:

$ rm "-rf" "filename.*"

Try this in your terminal and you will see that it will not remove the files that starts with filename..

You need to pass shell = True to execute the command in a shell interpreter and give your command as a single string.

subprocess.run(f'rm -rf {regex}', shell=True)


问:
How to query from two collections in mongodb using aggregate?
I have the two following collections in my mongoDB:

PRODUCTS:

```<code>[
    {
        "_id": "5ebb0984e95e3e9e35aab3bf",
        "name": "Product 1",
        "brand": "ABC",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    },
    {
        "_id": "5ebdb9f3d943ae000a4a9714",
        "name": "Product 2",
        "brand": "DEF",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    }
]
</code>```

STOCK GOODS:

```<code>[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed058da75e4e01013f5779d",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04cede9e43cee79734b93",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    }
]
</code>```

I want to get the follow result:

```<code>[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    }
]
</code>```

My NodeJS and MongoDB aggregate look like this:

```<code>const mongoose = require("mongoose");
const StockGoods = mongoose.model("StockGoods");
ObjectId = require("mongodb").ObjectID;

exports.getProducts = async (companyId, branchId, inventoryId) => {
  const response = await StockGoods.aggregate([
    {
      $match: {
        companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
        inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new ObjectId(inventoryId)
        branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
      },
    },
    {
      $lookup: {
        from: "products",
        localField: "productId",
        foreignField: "_id",
        as: "inventory_docs",
      },
    },
    {
      $project: {
        data: "$inventory_docs",
      },
    },
    { $unwind: "$data" },
  ]);
  return response;
};
</code>```

This is the same database and the aggregate function described above, you can check this: https://mongoplayground.net/p/FRgAIfO2bwh.

But, this function aggregate does not working when I use nodejs.
My API returns nothing (empty array).

Whats wrong?

答:
[RESOLVED]

The problem was in the scheme:

```<code>companyId: {
    type: String,
    required: true,
},
</code>```

The correct is:

```<code>companyId: {
    type: Schema.Types.ObjectId,
    required: true,
},
</code>```

Body:
I have the two following collections in my mongoDB:

PRODUCTS:

[
    {
        "_id": "5ebb0984e95e3e9e35aab3bf",
        "name": "Product 1",
        "brand": "ABC",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    },
    {
        "_id": "5ebdb9f3d943ae000a4a9714",
        "name": "Product 2",
        "brand": "DEF",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    }
]

STOCK GOODS:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed058da75e4e01013f5779d",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04cede9e43cee79734b93",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    }
]

I want to get the follow result:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    }
]

My NodeJS and MongoDB aggregate look like this:

const mongoose = require("mongoose");
const StockGoods = mongoose.model("StockGoods");
ObjectId = require("mongodb").ObjectID;

exports.getProducts = async (companyId, branchId, inventoryId) => {
  const response = await StockGoods.aggregate([
    {
      $match: {
        companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
        inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new ObjectId(inventoryId)
        branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
      },
    },
    {
      $lookup: {
        from: "products",
        localField: "productId",
        foreignField: "_id",
        as: "inventory_docs",
      },
    },
    {
      $project: {
        data: "$inventory_docs",
      },
    },
    { $unwind: "$data" },
  ]);
  return response;
};

This is the same database and the aggregate function described above, you can check this: https://mongoplayground.net/p/FRgAIfO2bwh.

But, this function aggregate does not working when I use nodejs.
My API returns nothing (empty array).

Whats wrong?

Body:
[RESOLVED]

The problem was in the scheme:

companyId: {
    type: String,
    required: true,
},

The correct is:

companyId: {
    type: Schema.Types.ObjectId,
    required: true,
},


问:
openpyxl and iteration + alter specific cells question/seeking resource
Very new to python here. Need some help with using openpyxl, please! This is for a personal project on my self-learning journey. I'm looking for a resource to show me how to do the following thing in pip3 openpyxl:

I have a class that has a variable which acts as a unique identifier. This is the first column in my excel workbook. What I want to do:

I want to add new IDs to the spreadsheet. This means, first, I need to iterate over only the first column and make sure the new unique identifier isn't already present. I believe the following code does this iteration successfully:

```<code>for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):
</code>```

Then, if the unique identifier is not present, meaning the ID is not already contained within the dataset, I want to add that ID and its associated class values to the dataset in a new row. I think the following line does that, inserting a new row right under the header row:

```<code>sheet.insert_rows(idx=2)
</code>```

Then I write code below that to fill the rest of the cells in that row with the appropriate values.

Else if the unique identifier is already present, I want to use some of the data from the row containing that identifier and the associated class values, do some recalculations on those cells, and then update some of the other values/cells in the row, overwriting the old values. This is what I specifically need help with.

Based on something I saw elsewhere, this is my idea, putting everything together:

```<code>for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):
    if fin.fin != row:
</code>```

fin is the unique ID which is the name given to each case and also an attribute stored in the class. I'm also wondering if != row will work here or if I need to index like row[0] or if row.value should be used?

```<code>        sheet.insert_rows(idx=2)
        sheet["A2"] = fin.fin     #setting cell A2 = unique id attribute of my class instance
        sheet["B2"] = fin.kgs     #setting cell B2 = kgs attribute of my class instance
        sheet["F2"] = fin.kgs_to_lbs() #setting cell F2 to module output converting kgs to lbs
    else:
        sheet['B{}'.format(row)] = fin.kgs.format(row) #if the id is not unique, change value in column B of that row
        sheet['F{}'].format(row) = fin.kgs_to_lbs.format(row) #if the id is not unique, change value in column F of that row
</code>```

Hopefully that's clear. Let me know if anything isn't. I'm looking either for some sample code or a reference to a resource that would be helpful, please!

答:
Some issues with your code there. Ath the momnet your code is iterating over the cells in column A and checking if a cell object is equal to your attribute fin.fin which I assume is either a string or an integer (?). Since they arent it will always be FALSE thus creating a new row above row 2.

So, the question you are trying to answer is in actuallity - Does fin.fin already exists in column A?. For that you can just take the list of values in column A and check if fin.fin is in it, we will use a list comprehension to build it:

```<code>known_identifiers = [cell.value for cell in ws['A']]  # Creating a list of all known identifiers from column A

if fin.fin is not in known_identifiers:
    # Special identifier is not in the Excel file add it and data

    sheet.insert_rows(idx=2)

    sheet["A2"] = fin.fin  # setting cell A2 = unique id attribute of my class instance
    sheet["B2"] = fin.kgs  # setting cell B2 = kgs attribute of my class instance
    sheet["F2"] = fin.kgs_to_lbs()  #setting cell F2 to module output converting kgs to lbs

else:
    # Identifier found, Change data in specific columns.

   row = known_identifiers.index(fin.fin)+1  # Row is the same as the item list index+1 (As lists start from 0 and rows from 1)
   sheet[f"B{row}"] = fin.kgs.format(row)  # Not sure why you need `format` here but it's your class
   sheet[f"F{row}"] = fin.kgs_to_lbs.format(row) # Same
</code>```

Do notice that int(identifier) != str(identifier) so be sure you're checking variables of the same type, if needed convert one or the other. Also, I have used f-strings in my code as I think it generates a nicer cleaner code, you can read about those - Here.

Body:
Very new to python here. Need some help with using openpyxl, please! This is for a personal project on my self-learning journey. I'm looking for a resource to show me how to do the following thing in pip3 openpyxl:

I have a class that has a variable which acts as a unique identifier. This is the first column in my excel workbook. What I want to do:

I want to add new IDs to the spreadsheet. This means, first, I need to iterate over only the first column and make sure the new unique identifier isn't already present. I believe the following code does this iteration successfully:

for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):

Then, if the unique identifier is not present, meaning the ID is not already contained within the dataset, I want to add that ID and its associated class values to the dataset in a new row. I think the following line does that, inserting a new row right under the header row:

sheet.insert_rows(idx=2)

Then I write code below that to fill the rest of the cells in that row with the appropriate values.

Else if the unique identifier is already present, I want to use some of the data from the row containing that identifier and the associated class values, do some recalculations on those cells, and then update some of the other values/cells in the row, overwriting the old values. This is what I specifically need help with.

Based on something I saw elsewhere, this is my idea, putting everything together:

for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):
    if fin.fin != row:

fin is the unique ID which is the name given to each case and also an attribute stored in the class. I'm also wondering if != row will work here or if I need to index like row[0] or if row.value should be used?

        sheet.insert_rows(idx=2)
        sheet["A2"] = fin.fin     #setting cell A2 = unique id attribute of my class instance
        sheet["B2"] = fin.kgs     #setting cell B2 = kgs attribute of my class instance
        sheet["F2"] = fin.kgs_to_lbs() #setting cell F2 to module output converting kgs to lbs
    else:
        sheet['B{}'.format(row)] = fin.kgs.format(row) #if the id is not unique, change value in column B of that row
        sheet['F{}'].format(row) = fin.kgs_to_lbs.format(row) #if the id is not unique, change value in column F of that row

Hopefully that's clear. Let me know if anything isn't. I'm looking either for some sample code or a reference to a resource that would be helpful, please!

Body:
Some issues with your code there. Ath the momnet your code is iterating over the cells in column A and checking if a cell object is equal to your attribute fin.fin which I assume is either a string or an integer (?). Since they arent it will always be FALSE thus creating a new row above row 2.

So, the question you are trying to answer is in actuallity - Does fin.fin already exists in column A?. For that you can just take the list of values in column A and check if fin.fin is in it, we will use a list comprehension to build it:

known_identifiers = [cell.value for cell in ws['A']]  # Creating a list of all known identifiers from column A

if fin.fin is not in known_identifiers:
    # Special identifier is not in the Excel file add it and data

    sheet.insert_rows(idx=2)

    sheet["A2"] = fin.fin  # setting cell A2 = unique id attribute of my class instance
    sheet["B2"] = fin.kgs  # setting cell B2 = kgs attribute of my class instance
    sheet["F2"] = fin.kgs_to_lbs()  #setting cell F2 to module output converting kgs to lbs

else:
    # Identifier found, Change data in specific columns.

   row = known_identifiers.index(fin.fin)+1  # Row is the same as the item list index+1 (As lists start from 0 and rows from 1)
   sheet[f"B{row}"] = fin.kgs.format(row)  # Not sure why you need `format` here but it's your class
   sheet[f"F{row}"] = fin.kgs_to_lbs.format(row) # Same

Do notice that int(identifier) != str(identifier) so be sure you're checking variables of the same type, if needed convert one or the other. Also, I have used f-strings in my code as I think it generates a nicer cleaner code, you can read about those - Here.


问:
Select specific levels of factor in R
I imagine this is a relatively simple issue for this audience, at least it would be for me had I still been working with SAS...
I have a character factor ("Trap") with 15 levels and I only want 3 of those levels (Weka, Rat, Stoat) for a data frame I want to summarize/analyze.  I don't want to use droplevels and have to write-out every level I DON'T want in the data frame, but I can't seem to get the coding right to select just the levels I want.  Please help.  Here's what I've most recently tried, to no avail. Any help would be greatly appreciated.

```<code>CatchbySpecies <- CatchbySpecies [!CatchbySpecies$Trap == "Weka", "Rat", "Stoat"]
</code>```

答:
From your text, it seems like you want to keep only those three levels -- if that's so, then you want:

```<code>CatchbySpecies <- CatchbySpecies [CatchbySpecies$Trap %in% c("Weka", "Rat", "Stoat"), ]
</code>```

Key differences from your attempt:

No exclamation at the front, unless you want the other ones

Wrap the list of things you do want in the concatenate function, c()

Use %in% instead of ==, since you don't want to check whether the factors are equal to the whole vector of c("Weka", "Rat", "Stoat"), but rather whether the factor is one of those elements contained within

Add a comma at the end. You're imposing a condition on the rows, so use a comma to indicate when that's done, and demonstrate an empty column condition.

Let me know if you have questions!

EDIT: You mentioned not wanting to use droplevels() and I wasn't quite sure why, but Ben Bolker helpfully pointed out that you may want to use it after doing this operation unless you want to retain the discarded factors in this variable for some reason. You can just edit the line as

```<code>CatchbySpecies <-
  droplevels(CatchbySpecies [CatchbySpecies$Trap %in% c("Weka", "Rat", "Stoat"), ])
</code>```

Title: Select specific levels of factor in R

Body:
I imagine this is a relatively simple issue for this audience, at least it would be for me had I still been working with SAS...
I have a character factor ("Trap") with 15 levels and I only want 3 of those levels (Weka, Rat, Stoat) for a data frame I want to summarize/analyze.  I don't want to use droplevels and have to write-out every level I DON'T want in the data frame, but I can't seem to get the coding right to select just the levels I want.  Please help.  Here's what I've most recently tried, to no avail. Any help would be greatly appreciated.

CatchbySpecies <- CatchbySpecies [!CatchbySpecies$Trap == "Weka", "Rat", "Stoat"]

Body:
From your text, it seems like you want to keep only those three levels -- if that's so, then you want:

CatchbySpecies <- CatchbySpecies [CatchbySpecies$Trap %in% c("Weka", "Rat", "Stoat"), ]

Key differences from your attempt:

No exclamation at the front, unless you want the other ones

Wrap the list of things you do want in the concatenate function, c()

Use %in% instead of ==, since you don't want to check whether the factors are equal to the whole vector of c("Weka", "Rat", "Stoat"), but rather whether the factor is one of those elements contained within

Add a comma at the end. You're imposing a condition on the rows, so use a comma to indicate when that's done, and demonstrate an empty column condition.

Let me know if you have questions!

EDIT: You mentioned not wanting to use droplevels() and I wasn't quite sure why, but Ben Bolker helpfully pointed out that you may want to use it after doing this operation unless you want to retain the discarded factors in this variable for some reason. You can just edit the line as

CatchbySpecies <-
  droplevels(CatchbySpecies [CatchbySpecies$Trap %in% c("Weka", "Rat", "Stoat"), ])


问:
OpenID Connect: How to add custom claims data in the client credential flow
I'm setting up a client credential flow with my identity server to get an access token from a client. I'm able to get the access token with the following code,

Identity server configuration:

```<code> public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var corsPolicyService = new DefaultCorsPolicyService()
        {
            AllowAll = true
        };

        var idServerServiceFactory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get())
        .UseInMemoryUsers(Users.Get());

        var options = new IdentityServerOptions
        {
            Factory = idServerServiceFactory,
            SiteName = "Demo",
            IssuerUri = IdentityConstants.IssuerUri,
            PublicOrigin = IdentityConstants.STSOrigin,
            SigningCertificate = LoadCertificate()
        };

        idsrvApp.UseIdentityServer(options);
    });
}
</code>```

Identity Server - Client configuration:

```<code>public static class Clients
{
    public static IEnumerable<Client> Get()
    {
    return new[]
     {
        new Client
        {
             ClientId = "ClientSDK",
             ClientName = "Client SDK (Client Credentials)",
             Flow = Flows.ClientCredentials,
             AllowAccessToAllScopes = true,

            ClientSecrets = new List<Secret>()
            {
                new Secret(IdentityConstants.ClientSecret.Sha256())
            }
        }
     };
}
</code>```

}

MVC Client:

```<code>  var oAuth2Client = new TokenClient(
              IdentityConstants.STSTokenEndpoint,
              "ClientSDK",
                IdentityConstants.ClientSecret);

    var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("MyScope").Result;

    return tokenResponse.AccessToken;
</code>```

I'm able to get the access token(i.e. JWT). Can one please tell me how to add a unique key like (UserId) from my database, when the JWT is created with its claims data when the token is created.

答:
First, you need to create custom attribute "userId" on Azure Portal, and apply it for selected application. Then follow this example,
Update user using Graph API

If you are using built in user flows, then you need to select "userId" for your application.
If you are using custom policy, then following process.
JWT token shows only output claims of Azure AD B2C custom policy. It is a multi steps process to create and update custom policy. Here is link to read more about How to create custom attribute

Body:
I'm setting up a client credential flow with my identity server to get an access token from a client. I'm able to get the access token with the following code,

Identity server configuration:

 public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var corsPolicyService = new DefaultCorsPolicyService()
        {
            AllowAll = true
        };

        var idServerServiceFactory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get())
        .UseInMemoryUsers(Users.Get());

        var options = new IdentityServerOptions
        {
            Factory = idServerServiceFactory,
            SiteName = "Demo",
            IssuerUri = IdentityConstants.IssuerUri,
            PublicOrigin = IdentityConstants.STSOrigin,
            SigningCertificate = LoadCertificate()
        };

        idsrvApp.UseIdentityServer(options);
    });
}

Identity Server - Client configuration:

public static class Clients
{
    public static IEnumerable<Client> Get()
    {
    return new[]
     {
        new Client
        {
             ClientId = "ClientSDK",
             ClientName = "Client SDK (Client Credentials)",
             Flow = Flows.ClientCredentials,
             AllowAccessToAllScopes = true,

            ClientSecrets = new List<Secret>()
            {
                new Secret(IdentityConstants.ClientSecret.Sha256())
            }
        }
     };
}

}

MVC Client:

  var oAuth2Client = new TokenClient(
              IdentityConstants.STSTokenEndpoint,
              "ClientSDK",
                IdentityConstants.ClientSecret);

    var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("MyScope").Result;

    return tokenResponse.AccessToken;

I'm able to get the access token(i.e. JWT). Can one please tell me how to add a unique key like (UserId) from my database, when the JWT is created with its claims data when the token is created.


问:
why using xml files in form validation in server side?
what is the benefit from using xml files in server side validation, in struts, for example, XML files are used in validation, here's an example http://www.vaannila.com/struts-2/struts-2-example/struts-2-validation-using-xml-example-1.html, and other practise to put all forms specification into XML file and parse it once then cashe the resulted object in order to use it in another time without the need to parse XML file again "the concept of lazy initialization". I want to know why using XML??</p>

答:
1) It's a file that can be configured easily without recompiling the application much the same as an app.config file

2) Advantage over app.config is that this validation file is specific to a single task, reducing the risk that would be incurred if the main app.config was edited and updated.

So basically you can now if you like put a GUI editor in front of the xml file and provide a means for administrators to modify the contents in a live environment.

Storing the data in a database would give you similar benefits, but it's a rather heavy weight solution to the problem.


问:
How can I merge two strings of comma-separated numbers in MySQL?
For example, there are three rooms.

```<code>1|gold_room|1,2,3

2|silver_room|1,2,3

3|brown_room|2,4,6

4|brown_room|3

5|gold_room|4,5,6
</code>```

Then, I'd like to get

```<code>gold_room|1,2,3,4,5,6

brown_room|2,3,4,6

silver_room|1,2,3
</code>```

How can I achieve this?

I've tried: select * from room group by name; And it only prints the first row.  And I know CONCAT() can combine two string values.

答:
I'm not making an assumption that the lists don't have elements in common on separate rows.

First create a table of integers.

```<code>mysql> create table n (n int primary key);
mysql> insert into n values (1),(2),(3),(4),(5),(6);
</code>```

You can join this to your rooms table using the FIND_IN_SET() function. Note that this cannot be optimized. It will execute N full table scans. But it does create an interim set of rows.

```<code>mysql> select * from n inner join rooms on find_in_set(n.n, rooms.csv) order by rooms.room, n.n;
+---+----+-------------+-------+
| n | id | room        | csv   |
+---+----+-------------+-------+
| 2 |  3 | brown_room  | 2,4,6 |
| 3 |  4 | brown_room  | 3     |
| 4 |  3 | brown_room  | 2,4,6 |
| 6 |  3 | brown_room  | 2,4,6 |
| 1 |  1 | gold_room   | 1,2,3 |
| 2 |  1 | gold_room   | 1,2,3 |
| 3 |  1 | gold_room   | 1,2,3 |
| 4 |  5 | gold_room   | 4,5,6 |
| 5 |  5 | gold_room   | 4,5,6 |
| 6 |  5 | gold_room   | 4,5,6 |
| 1 |  2 | silver_room | 1,2,3 |
| 2 |  2 | silver_room | 1,2,3 |
| 3 |  2 | silver_room | 1,2,3 |
+---+----+-------------+-------+
</code>```

Use GROUP BY to reduce these rows to one row per room. Use GROUP_CONCAT() to put the integers together into a comma-separated list.

```<code>mysql> select room, group_concat(distinct n.n order by n.n) as csv
  from n inner join rooms on find_in_set(n.n, rooms.csv) group by rooms.room
+-------------+-------------+
| room        | csv         |
+-------------+-------------+
| brown_room  | 2,3,4,6     |
| gold_room   | 1,2,3,4,5,6 |
| silver_room | 1,2,3       |
+-------------+-------------+
</code>```

I think this is a lot of work, and impossible to optimize. I don't recommend it.

The problem is that you are storing comma-separated lists of numbers, and then you want to query it as if the elements in the list are discrete values. This is a problem for SQL.

It would be much better if you did not store your numbers in a comma-separated list. Store multiple rows per room, with one number per row. You can run a wider variety of queries if you do this, and it will be more flexible.

For example, the query you asked about, to produce a result with numbers in a comma-separated list is more simple, and you don't need the extra n table:

```<code>select room, group_concat(n order by n) as csv from rooms group by room
</code>```

See also my answer to Is storing a delimited list in a database column really that bad?

Body:
For example, there are three rooms.

1|gold_room|1,2,3

2|silver_room|1,2,3

3|brown_room|2,4,6

4|brown_room|3

5|gold_room|4,5,6

Then, I'd like to get

gold_room|1,2,3,4,5,6

brown_room|2,3,4,6

silver_room|1,2,3

How can I achieve this?

I've tried: select * from room group by name; And it only prints the first row.  And I know CONCAT() can combine two string values.

Body:
I'm not making an assumption that the lists don't have elements in common on separate rows.

First create a table of integers.

mysql> create table n (n int primary key);
mysql> insert into n values (1),(2),(3),(4),(5),(6);

You can join this to your rooms table using the FIND_IN_SET() function. Note that this cannot be optimized. It will execute N full table scans. But it does create an interim set of rows.

mysql> select * from n inner join rooms on find_in_set(n.n, rooms.csv) order by rooms.room, n.n;
+---+----+-------------+-------+
| n | id | room        | csv   |
+---+----+-------------+-------+
| 2 |  3 | brown_room  | 2,4,6 |
| 3 |  4 | brown_room  | 3     |
| 4 |  3 | brown_room  | 2,4,6 |
| 6 |  3 | brown_room  | 2,4,6 |
| 1 |  1 | gold_room   | 1,2,3 |
| 2 |  1 | gold_room   | 1,2,3 |
| 3 |  1 | gold_room   | 1,2,3 |
| 4 |  5 | gold_room   | 4,5,6 |
| 5 |  5 | gold_room   | 4,5,6 |
| 6 |  5 | gold_room   | 4,5,6 |
| 1 |  2 | silver_room | 1,2,3 |
| 2 |  2 | silver_room | 1,2,3 |
| 3 |  2 | silver_room | 1,2,3 |
+---+----+-------------+-------+

Use GROUP BY to reduce these rows to one row per room. Use GROUP_CONCAT() to put the integers together into a comma-separated list.

mysql> select room, group_concat(distinct n.n order by n.n) as csv
  from n inner join rooms on find_in_set(n.n, rooms.csv) group by rooms.room
+-------------+-------------+
| room        | csv         |
+-------------+-------------+
| brown_room  | 2,3,4,6     |
| gold_room   | 1,2,3,4,5,6 |
| silver_room | 1,2,3       |
+-------------+-------------+

I think this is a lot of work, and impossible to optimize. I don't recommend it.

The problem is that you are storing comma-separated lists of numbers, and then you want to query it as if the elements in the list are discrete values. This is a problem for SQL.

It would be much better if you did not store your numbers in a comma-separated list. Store multiple rows per room, with one number per row. You can run a wider variety of queries if you do this, and it will be more flexible.

For example, the query you asked about, to produce a result with numbers in a comma-separated list is more simple, and you don't need the extra n table:

select room, group_concat(n order by n) as csv from rooms group by room

See also my answer to Is storing a delimited list in a database column really that bad?


答:
s is a reference so it's a location on memory and there is no need to use &operator with it

Yes, s is a reference. But the fact that it is a location in memory is an implementation detail. Syntactically, it behaves like an object. You need to use & in front of it to get a usable address (although, yeah, obviously behind the scene the address is already there).

if (*this == s)

No, you shouldn't use this. Your operator== will compare whether two list are the same (same content) not whether they are the same list (same object). The reason for avoiding the copy is because the object would be modifying itself.

But, if your operator== is well defined, you'll be able to get away with this. When you assign two identical objects, it will simply do nothing. I'd advise against. You never know, in the future what subtleties there will be in comparing objects when they get more complex.

Title: C++, = operator different options

Body:
I Wrote the following function for = operator:

Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

But, I wanted the following code to work as expected (without deleting current data):

Set s1,s2;
s1=s1;

So I made the following changes:

Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

my question is:

1. Why this is correct:

    if (this == &s)
    {
        return *this;
    }

while this is not:

    if (this == s)
    {
        return *this;
    }

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

    if (*this == s)
    {
        return *this;
    }


问:
What's the most optimal way to find 4 consecutive equal chars in a multidimensional array?
The challenge is to find 4 consecutive equal characters in horizontal, vertical or diagonal direction with the most optimal algorithm possible.

For example, if we have this matrix:

[

['L','T','G','C','T','A'],

['X','A','G','T','G','A'],

['T','R','T','K','G','A'],

['A','T','A','M','G','A'],

['C','C','C','C','T','G'],

['V','C','D','C','T','W']

]

the algorithm should find AAAA (vertical), CCCC (horizontal) and TTTT (inverted diagonal).

How would you do it? Any programming language can be used.

Thanks in advance!

答:
This is a Boogle board problem modified with repeated strings.

I believe that you can solve in O(N*M) time where N: Number of columns and M: Number of rows.

The approach that you can do is a BFS with memory in already matched strings and mark as visited.

In this link you can see a implementation with dictionaries. You'll need to get a modification to get repeated strings o times: https://gist.github.com/davidreynolds/2865498


问:
Is JpaRepository's findAll() guaranteed to return a non-null result if an exception isn't thrown?
The documentation is woefully sparse on this point.</p>

答:
Well, the Package summary of org.springframework.data.repository says Non-Null APIS. That means that it is guaranteed to return non-null type of objects from the method.

@NonNullAPI tells that package with this annotation is null-safe and API usage need not look into handling the null-check scenario.


问:
Remove repetition from if-else statement
I have written an if...else statement which uses an array myArr and a string myStr as follows:

```<code>If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If
</code>```

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

答:
What you need is nested if</p>

```<code>If myArr.Length > 0 Then
  'Do stuff for non zero length
    If myArr(0) = "-1" Then
       'Do stuff for -1 and you already have checked for array length
    End If
End If
</code>```

Body:
I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Body:
What you need is nested if

If myArr.Length > 0 Then
  'Do stuff for non zero length
    If myArr(0) = "-1" Then
       'Do stuff for -1 and you already have checked for array length
    End If
End If


问:
Need to compare two columns and complete a third with data from one the sheets
I have to compare two columns from two sheets with some data. If the columns have the same data, i have to display the data of one the sheets (a third column).

I tried with a

If, Vlookup and Index

formula but its not working, at least for me.

On Sheet 1 i have the "G" Column (original data) and on Sheet 2 i have the "C" column. If both cells match, i need the data from the "A" column on Sheet 2 to be displayed.

Can anyone give me a hand?

Thanks!

答: =IF(G1==SHEET2!C1, SHEET2!A1, "Cells do not match")</p>


问:
Automatically create Kubernetes resources after namespace creation
I have 2 teams:

devs: they create a new Kubernetes namespace each time they deploy a branch/tag of their app

ops: they manage access control to the cluster with (cluster)roles and (cluster)rolebindings

The problem is that 'devs' cannot kubectl their namespaces until 'ops' have created RBAC resources. And 'devs' cannot create RBAC resources themselves as they don't have the list of subjects to put in the rolebinding resource (sharing the list is not an option).

I have read the official documentation about Admission webhooks but what I understood is that they only act on the resource that triggered the webhook.

Is there a native and/or simple way in Kubernetes to apply resources whenever a new namespace is created?

答:
It's kind of related to how the user is authenticated to the cluster and how they get a kubeconfig file.You can put a group in the client certificate or the bearer token that kubectl uses from the kubeconfig. Ahead of time you can define a clusterrole having a clusterrolebinding to that group which gives them permission to certain verbs on certain resources(for example ability to create namespace)

Additionally you can use an admission webhook to validate if the user is supposed to be part of that group or not.


问:
How to iterate over rows in a DataFrame in Pandas
I have a pandas dataframe, df:

   c1   c2
0  10  100
1  11  110
2  12  120
```
<p>How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example:</p>
<pre class="lang-py prettyprint-override"><code>for row in df.rows:
    print(row['c1'], row['c2'])
</code>```

I found a similar question, which suggests using either of these:

for date, row in df.T.iteritems():
```
</li>
<li>
<pre class="lang-py prettyprint-override"><code>for row in df.iterrows():
</code>```

But I do not understand what the row object is and how I can work with it.

答:
In short

Use vectorization if possible

If an operation can't be vectorized - use list comprehensions

If you need a single object representing the entire row - use itertuples

If the above is too slow - try swifter.apply

If it's still too slow - try a Cython routine

Benchmark

Body:
I have a pandas dataframe, df:

   c1   c2
0  10  100
1  11  110
2  12  120

How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example:

for row in df.rows:
    print(row['c1'], row['c2'])

I found a similar question, which suggests using either of these:

for date, row in df.T.iteritems():

for row in df.iterrows():

But I do not understand what the row object is and how I can work with it.


问:
How to print two Different Tables using jspdf-autotable
I want to print these two tables as pdf using jspdf autotable plugin. But the script that I wrote prints only second table. I think the problem lies in writing script. Will someone guide me how to print these two tables using jspdf-autotable.

```<code>        <button onclick="generate()">Print</button>

<table id="tbl1" border="2">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Marks</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>01</td>
                    <td>Johnson</td>
                    <td>UK</td>
                    <td>112</td>
                </tr>
                <tr>
                    <td>02</td>
                    <td>Jim</td>
                    <td>US</td>
                    <td>142</td>
                </tr>
                <tr>
                    <td>03</td>
                    <td>Johnson</td>
                    <td>UK</td>
                    <td>112</td>
                </tr>
                <tr>
                    <td>04</td>
                    <td>Jim</td>
                    <td>US</td>
                    <td>142</td>
                </tr>
            </tbody>
        </table>
        <table id="tbl2" border="2">
            <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Phone</th>
                <th>Remarks</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>Julia</td>
                <td>Anderson</td>
                <td>2312144</td>
                <td>Good</td>
            </tr>
            <tr>
                <td>Emma</td>
                <td>Watson</td>
                <td>24564456</td>
                <td>Excellent</td>
            </tr>
            <tr>
                <td>Jim</td>
                <td>Carry</td>
                <td>5645648</td>
                <td>Seperb</td>
            </tr>
            <tr>
                <td>Harry</td>
                <td>Potter</td>
                <td>544562310</td>
                <td>Ridiculous</td>
            </tr>
            </tbody>
        </table>
</code>```

this is script:

```<code><script>
    function generate() {
        var doc = new jsPDF('p', 'pt', 'A4');

        var res = doc.autoTableHtmlToJson(document.getElementById("tbl1"), true);
        doc.autoTable(res.columns, res.data, {margin: {top: 80}});

        var res2 = doc.autoTableHtmlToJson(document.getElementById("tbl2"), true);
        doc.autoTable(res2.columns, res2.data, {margin: {top: 80}});

        doc.save("test.pdf");

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

答:
If you use doc.autoTableHtmlToJson does not consider a head and duplicate one row.
That's works for me:

generate(){
    const doc = new jsPDF()

    doc.autoTable({
      theme: 'plain',
      headStyles: { fontSize: 10 },
      bodyStyles: { fontSize: 8, fontStyle: 'italic' },

      head:  [['ID', 'Name', 'Country']],
      body: [['1', 'Simon', 'Sweden'], ['2', 'Karl', 'Norway']],

    });

    doc.autoTable({
      theme: 'plain',
      headStyles: { fontSize: 10 },
      bodyStyles: { fontSize: 8, fontStyle: 'italic' },

      head:  [['ID', 'Name', 'Country']],
      body: [['1', 'Simon', 'Swedenddd'], ['2', 'Karl', 'Norway']],

    });

    // doc.save('table.pdf');
    doc.output('dataurlnewwindow'); //to check pdf generate
}
```

Body:
I want to print these two tables as pdf using jspdf autotable plugin. But the script that I wrote prints only second table. I think the problem lies in writing script. Will someone guide me how to print these two tables using jspdf-autotable.

        <button onclick="generate()">Print</button>

                    ID
                    Name
                    Address
                    Marks

                    01
                    Johnson
                    UK
                    112

                    02
                    Jim
                    US
                    142

                    03
                    Johnson
                    UK
                    112

                    04
                    Jim
                    US
                    142

                First Name
                Last Name
                Phone
                Remarks

                Julia
                Anderson
                2312144
                Good

                Emma
                Watson
                24564456
                Excellent

                Jim
                Carry
                5645648
                Seperb

                Harry
                Potter
                544562310
                Ridiculous

this is script:


问:
determine if an application is shutting down normally
is there a way to determing if a jvm is shutting down normally?  Shutdown hook can only spawn a thread, is there a way to determine if the JVM is existing normally or abnormally at that time?</p>

答: You could write a file on startup and delete it again on graceful exit. If the JVM is gone but the file is still there you know that it crashed or has otherwise exited in a unintended manner.</p>


问:
Creating percentiles of data set
I've tried using the quantile function but it doesn't do as intended.

I also used new function

```<code> percentile <- function(Df, percentile = 50)
   {
   Df_Names <- names(Df)
  percentile <- percentile/100
  f <- function(x, p) c(NA, x[-length(x)]) + p * c(NA, diff(x))
  while(length(which(!is.na(Df[[length(Df)]]))) > 1)
  {
Df <- cbind(Df, f(Df[[length(Df)]], percentile))
}
setNames(Df, c(Df_Names, paste0("v", 1:(length(df) - length(df_Names)))))
}

Output=data.frame(pecentile(df, percentile = 50))
</code>```

Assume we are finding the P50 where I mention percentiles. Note: I used excel to calculate the percentiles with the percentile function, but the results should be the same using R. In most instances there are thousands of data points per column and R would be more time efficient to calculate them.

an example data set would be

```<code>  Date           data
  2020-01-01      49.5
  2020-02-01      49.7
  2020-03-14      48.5
  2020-05-02      50.2
</code>```

I'm trying to have the script result in a percentile output using the column before it as a starting point. However columns after V1 their percentiles are calculated differently than V1. As shown here

V1 Calculation

Where 49.35 is the percentile calculation in excel using 48.5 and 50.2 in the red box and 49.1 is the result of using 49.7 and 48.5 in the blue box that overlaps the red box.

and V2 calculation

where 49.225 is the result of using 49.1 and 49.35 in the red box while 49.35 is the result of using 49.6, 49.1 and 49.35 in the blue box that overlaps the red box.

V2 calculation starts off the same, but the calculations above it include the adjacent cell plus the cells below the adjacent cells, which the script doesn't do.

The result from this script should be:

```<code>  Date           data    V1     V2      V3
  2020-01-01      49.5   49.6   49.35    49.2875
  2020-02-01      49.7   49.1   49.225
  2020-03-14      48.5   49.35
  2020-05-02      50.2
</code>```

Note2: The script purposes is to be in a loop until the script creates the final column in this instance the final column is V3. but in reality it may go up to V800 or more

Then when this is done bring down the results without altering the output, resulting in:

```<code>  Date           data    V1     V2      V3
  2020-01-01      49.5   NA     NA      NA
  2020-02-01      49.7   49.6   NA      NA
  2020-03-14      48.5   49.1   49.35   NA
  2020-05-02      50.2   49.35  49.225  49.2875
</code>```

NOTE: The function works well to calculate the P50 in V1 which is fine, but it drops the ball with V2, V3 etc.

答:
Calculating a percentile (or more generally, a quantile) is not as easy as it might at first seem.  There are many, many ways of doing so, mainly to do with how ties are handled.  Are you sure that you are handling ties in the way that you intend?  Is perhaps the difference in answers between R's quantile and Excel's method the way in which they handle ties.  [The R online help gives 9 different algorithms.]

I think there's a typo in your first line.  I think you merant to say "I've tried using the quantile function but it doesn't do as I intended.".  if there really were a problem with quantile() I think it might have been spotted by now...

Title: Creating percentiles of data set

Body:
I've tried using the quantile function but it doesn't do as intended.

I also used new function

 percentile <- function(Df, percentile = 50)
   {
   Df_Names <- names(Df)
  percentile <- percentile/100
  f <- function(x, p) c(NA, x[-length(x)]) + p * c(NA, diff(x))
  while(length(which(!is.na(Df[[length(Df)]]))) > 1)
  {
Df <- cbind(Df, f(Df[[length(Df)]], percentile))
}
setNames(Df, c(Df_Names, paste0("v", 1:(length(df) - length(df_Names)))))
}

Output=data.frame(pecentile(df, percentile = 50))

Assume we are finding the P50 where I mention percentiles. Note: I used excel to calculate the percentiles with the percentile function, but the results should be the same using R. In most instances there are thousands of data points per column and R would be more time efficient to calculate them.

an example data set would be

  Date           data
  2020-01-01      49.5
  2020-02-01      49.7
  2020-03-14      48.5
  2020-05-02      50.2

I'm trying to have the script result in a percentile output using the column before it as a starting point. However columns after V1 their percentiles are calculated differently than V1. As shown here

V1 Calculation

Where 49.35 is the percentile calculation in excel using 48.5 and 50.2 in the red box and 49.1 is the result of using 49.7 and 48.5 in the blue box that overlaps the red box.

and V2 calculation

where 49.225 is the result of using 49.1 and 49.35 in the red box while 49.35 is the result of using 49.6, 49.1 and 49.35 in the blue box that overlaps the red box.

V2 calculation starts off the same, but the calculations above it include the adjacent cell plus the cells below the adjacent cells, which the script doesn't do.

The result from this script should be:

  Date           data    V1     V2      V3
  2020-01-01      49.5   49.6   49.35    49.2875
  2020-02-01      49.7   49.1   49.225
  2020-03-14      48.5   49.35
  2020-05-02      50.2

Note2: The script purposes is to be in a loop until the script creates the final column in this instance the final column is V3. but in reality it may go up to V800 or more

Then when this is done bring down the results without altering the output, resulting in:

  Date           data    V1     V2      V3
  2020-01-01      49.5   NA     NA      NA
  2020-02-01      49.7   49.6   NA      NA
  2020-03-14      48.5   49.1   49.35   NA
  2020-05-02      50.2   49.35  49.225  49.2875

NOTE: The function works well to calculate the P50 in V1 which is fine, but it drops the ball with V2, V3 etc.


问:
Retrieve locale based on the Accept-Language in Spring Boot
I have a Spring Boot (2.1.3.RELEASE) application that uses Jersey to define the (RESTful) endpoints. I'm trying to read and propagate some messages based on the locale being sent by the user-agents.

I've configured these beans:

```<code>@Bean
public LocaleResolver localeResolver() {
  final AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
  resolver.setSupportedLocales(Arrays.asList(Locale.GERMANY, Locale.US));
  resolver.setDefaultLocale(Locale.ENGLISH);
  return resolver;
}

@Bean
public MessageSource messageSource() { // Not sure if this is needed
  final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
  messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
  messageSource.setBasenames("classpath:/messages");
  messageSource.setUseCodeAsDefaultMessage(true);
  messageSource.setCacheSeconds(5);
  return messageSource;
}
</code>```

...and also the bundles (inside ../src/main/resources/) like: messages.properties (fallback), messages_en_US.properties, messages_de_DE.properties, etc.

Now, the challenge is that I'm not sure how to "read" the locale sent by the user-agents in order to read the messages from the bundles appropriately. I'm injecting a MessageSource ms, and programmatically reading messages like:

```<code>final Locale locale = ???
ms.getMessage("message.duplicate-token", null, locale);
</code>```

Any clues?

I've tried LocaleContextHolder.getLocale() but it's always en_US. If I hardcode the corresponding locale for the getMessage call, I'm able to retrieve the correct message(s). So I know the setup/configuration works for the most part.

Clients are sending the locale using the Accept-Language header — and values like: de-DE, en-US, etc.

答:
Create a custom AcceptHeaderLocaleResolver

```<code>public class AcceptHeaderResolver extends AcceptHeaderLocaleResolver {

    List<Locale> LOCALES = Arrays.asList(new Locale("en"), new Locale("ar"));

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String headerLang = request.getHeader("Accept-Language");
        return headerLang == null || headerLang.isEmpty()
                ? Locale.getDefault()
                : Locale.lookup(Locale.LanguageRange.parse(headerLang), LOCALES);
    }

}
</code>```

And Don't forgot to use it in @Configuration file

```<code>@Bean
public LocaleResolver sessionLocaleResolver() {
    AcceptHeaderResolver localeResolver = new AcceptHeaderResolver();
    return localeResolver;
}
</code>```

Body:
I have a Spring Boot (2.1.3.RELEASE) application that uses Jersey to define the (RESTful) endpoints. I'm trying to read and propagate some messages based on the locale being sent by the user-agents.

I've configured these beans:

@Bean
public LocaleResolver localeResolver() {
  final AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
  resolver.setSupportedLocales(Arrays.asList(Locale.GERMANY, Locale.US));
  resolver.setDefaultLocale(Locale.ENGLISH);
  return resolver;
}

@Bean
public MessageSource messageSource() { // Not sure if this is needed
  final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
  messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
  messageSource.setBasenames("classpath:/messages");
  messageSource.setUseCodeAsDefaultMessage(true);
  messageSource.setCacheSeconds(5);
  return messageSource;
}

...and also the bundles (inside ../src/main/resources/) like: messages.properties (fallback), messages_en_US.properties, messages_de_DE.properties, etc.

Now, the challenge is that I'm not sure how to "read" the locale sent by the user-agents in order to read the messages from the bundles appropriately. I'm injecting a MessageSource ms, and programmatically reading messages like:

final Locale locale = ???
ms.getMessage("message.duplicate-token", null, locale);

Any clues?

I've tried LocaleContextHolder.getLocale() but it's always en_US. If I hardcode the corresponding locale for the getMessage call, I'm able to retrieve the correct message(s). So I know the setup/configuration works for the most part.

Clients are sending the locale using the Accept-Language header — and values like: de-DE, en-US, etc.

Body:
Create a custom AcceptHeaderLocaleResolver

public class AcceptHeaderResolver extends AcceptHeaderLocaleResolver {

    List<Locale> LOCALES = Arrays.asList(new Locale("en"), new Locale("ar"));

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String headerLang = request.getHeader("Accept-Language");
        return headerLang == null || headerLang.isEmpty()
                ? Locale.getDefault()
                : Locale.lookup(Locale.LanguageRange.parse(headerLang), LOCALES);
    }

}

And Don't forgot to use it in @Configuration file

@Bean
public LocaleResolver sessionLocaleResolver() {
    AcceptHeaderResolver localeResolver = new AcceptHeaderResolver();
    return localeResolver;
}


问:
How to properly list items from array after splice
I have some example code:

```<code>var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};
</code>```

Now array looks like

```<code>[Object{id=0}, Object{id=1}, Object{id=2}]
</code>```

I use splice:

```<code>array.splice(0,1);
</code>```

And we have:

```<code>[Object{id=1}, Object{id=2}]
</code>```

When I try for or for ... in length will be only 2 and I can't iterate it in normal way. Result of loop is:

```<code>undefined
Object{id:1}
</code>```

In first case (when we use for) I understand why it didn't work, but for ... in should return indexes 1 and 2 not 0 and 1...

Anybody can explain me what I am doing wrong?

答:
What did you try? If I issue

```<code>var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};
array.splice(0,1);
for (var i = 0, len = array.length; i < len; i++)
    console.log(i + ":", array[i]);
</code>```

the engine correctly outputs

```<code>0: Object { id=1 }
1: Object { id=2 }
</code>```

(but the array indices change to 0 and 1, perhaps that is what confuses you; remember that Array.splice by default removes from element 0 onwards and shifts all remaining elements downwards).

Update: apart from the fact that you can always get the id property of the individual objects using array[i].id, you can delete array elements without shifting the other elements using the delete operator. After I replace array.splice(0,1) with

```<code>delete array[0];
</code>```

the output shows

```<code>0: undefined
1: Object { id=1 }
2: Object { id=2 }
</code>```

Body:
I have some example code:

var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};

Now array looks like

[Object{id=0}, Object{id=1}, Object{id=2}]

I use splice:

array.splice(0,1);

And we have:

[Object{id=1}, Object{id=2}]

When I try for or for ... in length will be only 2 and I can't iterate it in normal way. Result of loop is:

undefined
Object{id:1}

In first case (when we use for) I understand why it didn't work, but for ... in should return indexes 1 and 2 not 0 and 1...

Anybody can explain me what I am doing wrong?

Body:
What did you try? If I issue

var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};
array.splice(0,1);
for (var i = 0, len = array.length; i < len; i++)
    console.log(i + ":", array[i]);

the engine correctly outputs

0: Object { id=1 }
1: Object { id=2 }

(but the array indices change to 0 and 1, perhaps that is what confuses you; remember that Array.splice by default removes from element 0 onwards and shifts all remaining elements downwards).

Update: apart from the fact that you can always get the id property of the individual objects using array[i].id, you can delete array elements without shifting the other elements using the delete operator. After I replace array.splice(0,1) with

delete array[0];

the output shows

0: undefined
1: Object { id=1 }
2: Object { id=2 }


问:
Circular import dependency in Python
Let's say I have the following directory structure:

```<code>a\
    __init__.py
    b\
        __init__.py
        c\
            __init__.py
            c_file.py
        d\
            __init__.py
            d_file.py
</code>```

In the a package's __init__.py, the c package is imported. But c_file.py imports a.b.d.

The program fails, saying b doesn't exist when c_file.py tries to import a.b.d. (And it really doesn't exist, because we were in the middle of importing it.)

How can this problem be remedied?

答:
Circular Dependencies due to Type Hints

With type hints, there are more opportunities for creating circular imports. Fortunately, there is a solution using the special constant: typing.TYPE_CHECKING.

The following example defines a Vertex class and an Edge class. An edge is defined by two vertices and a vertex maintains a list of the adjacent edges to which it belongs.

Without Type Hints, No Error

File: vertex.py

```<code>class Vertex:
    def __init__(self, label):
        self.label = label
        self.adjacency_list = []
</code>```

File: edge.py

```<code>class Edge:
    def __init__(self, v1, v2):
        self.v1 = v1
        self.v2 = v2
</code>```

Type Hints Cause ImportError

ImportError: cannot import name 'Edge' from partially initialized module 'edge' (most likely due to a circular import)

File: vertex.py

```<code>from typing import List
from edge import Edge

class Vertex:
    def __init__(self, label: str):
        self.label = label
        self.adjacency_list: List[Edge] = []
</code>```

File: edge.py

```<code>from vertex import Vertex

class Edge:
    def __init__(self, v1: Vertex, v2: Vertex):
        self.v1 = v1
        self.v2 = v2
</code>```

Solution using TYPE_CHECKING

File: vertex.py

```<code>from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    from edge import Edge

class Vertex:
    def __init__(self, label: str):
        self.label = label
        self.adjacency_list: List['Edge'] = []
</code>```

File: edge.py

```<code>from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from vertex import Vertex

class Edge:
    def __init__(self, v1: 'Vertex', v2: 'Vertex'):
        self.v1 = v1
        self.v2 = v2
</code>```

Quoted vs. Unquoted Type Hints

In versions of Python prior to 3.10, conditionally imported types must be enclosed in quotes, making them “forward references”, which hides them from the interpreter runtime.

In Python 3.7, 3.8, and 3.9, a workaround is to use the following special import.

```<code>from __future__ import annotations
</code>```

This enables using unquoted type hints combined with conditional imports.

Python 3.10 (See PEP 563 -- Postponed Evaluation of Annotations)

In Python 3.10, function and variable annotations will no longer be
evaluated at definition time. Instead, a string form will be preserved
in the respective annotations dictionary. Static type checkers
will see no difference in behavior, whereas tools using annotations at
runtime will have to perform postponed evaluation.

The string form is obtained from the AST during the compilation step,
which means that the string form might not preserve the exact
formatting of the source. Note: if an annotation was a string literal
already, it will still be wrapped in a string.

ContentLicense: CC BY-SA 2.5

Title: Circular import dependency in Python

Body:
Let's say I have the following directory structure:

a\
    __init__.py
    b\
        __init__.py
        c\
            __init__.py
            c_file.py
        d\
            __init__.py
            d_file.py

In the a package's __init__.py, the c package is imported. But c_file.py imports a.b.d.

The program fails, saying b doesn't exist when c_file.py tries to import a.b.d. (And it really doesn't exist, because we were in the middle of importing it.)

How can this problem be remedied?

Body:
Circular Dependencies due to Type Hints

With type hints, there are more opportunities for creating circular imports. Fortunately, there is a solution using the special constant: typing.TYPE_CHECKING.

The following example defines a Vertex class and an Edge class. An edge is defined by two vertices and a vertex maintains a list of the adjacent edges to which it belongs.

Without Type Hints, No Error

File: vertex.py

class Vertex:
    def __init__(self, label):
        self.label = label
        self.adjacency_list = []

File: edge.py

class Edge:
    def __init__(self, v1, v2):
        self.v1 = v1
        self.v2 = v2

Type Hints Cause ImportError

ImportError: cannot import name 'Edge' from partially initialized module 'edge' (most likely due to a circular import)

File: vertex.py

from typing import List
from edge import Edge

class Vertex:
    def __init__(self, label: str):
        self.label = label
        self.adjacency_list: List[Edge] = []

File: edge.py

from vertex import Vertex

class Edge:
    def __init__(self, v1: Vertex, v2: Vertex):
        self.v1 = v1
        self.v2 = v2

Solution using TYPE_CHECKING

File: vertex.py

from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    from edge import Edge

class Vertex:
    def __init__(self, label: str):
        self.label = label
        self.adjacency_list: List['Edge'] = []

File: edge.py

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from vertex import Vertex

class Edge:
    def __init__(self, v1: 'Vertex', v2: 'Vertex'):
        self.v1 = v1
        self.v2 = v2

Quoted vs. Unquoted Type Hints

In versions of Python prior to 3.10, conditionally imported types must be enclosed in quotes, making them “forward references”, which hides them from the interpreter runtime.

In Python 3.7, 3.8, and 3.9, a workaround is to use the following special import.

from __future__ import annotations

This enables using unquoted type hints combined with conditional imports.

Python 3.10 (See PEP 563 -- Postponed Evaluation of Annotations)

In Python 3.10, function and variable annotations will no longer be
evaluated at definition time. Instead, a string form will be preserved
in the respective annotations dictionary. Static type checkers
will see no difference in behavior, whereas tools using annotations at
runtime will have to perform postponed evaluation.

The string form is obtained from the AST during the compilation step,
which means that the string form might not preserve the exact
formatting of the source. Note: if an annotation was a string literal
already, it will still be wrapped in a string.


问:
Creating a Nested Structure Table
I want to create arrays of nested structure for my database

something like this :

```<code>array(row(item row(departmentNumber bigint, itemNumber bigint, shelfCapacity row(qty double, precision   bigint))

location row(zone varchar, aisle bigint)))
</code>```

Below error i am facing:

But it's giving me error like this:

```<code>Unknown type: ROW(departmentNumber bigint, itemNumber bigint,shelfCapacity ROW )
</code>```

I created a sample SQL

```<code>WITH dataset AS (
  SELECT ARRAY[
    CAST(ROW('departmentNumber', 'itemNumber', CAST(ROW('qty', 'precision') AS ROW(qty double, precision bigint))) AS ROW(departmentNumber bigint, itemNumber bigint,shelfCapacity ROW ))
  ] AS items
)
SELECT * FROM dataset
</code>```

答:
Not 100 percent sure why identifier like 'departmentNumber' gets duplicated in your syntax, but in BigQuery, the ROW is called STRUCT, your query could likely be rewritten as:

WITH dataset AS (
  SELECT ARRAY[
    STRUCT<departmentNumber int64, itemNumber int64,shelfCapacity STRUCT<qty float64, precision int64>> (
      1, 1, STRUCT(2.1, 100)),
      (2, 2, STRUCT(3.1, 200))
  ] AS items
)
SELECT * FROM dataset
```

Title: Creating a Nested Structure Table

Body:
I want to create arrays of nested structure for my database

something like this :

array(row(item row(departmentNumber bigint, itemNumber bigint, shelfCapacity row(qty double, precision   bigint))

location row(zone varchar, aisle bigint)))

Below error i am facing:

But it's giving me error like this:

Unknown type: ROW(departmentNumber bigint, itemNumber bigint,shelfCapacity ROW )

I created a sample SQL

WITH dataset AS (
  SELECT ARRAY[
    CAST(ROW('departmentNumber', 'itemNumber', CAST(ROW('qty', 'precision') AS ROW(qty double, precision bigint))) AS ROW(departmentNumber bigint, itemNumber bigint,shelfCapacity ROW ))
  ] AS items
)
SELECT * FROM dataset


问:
Vuex: Add Dynamic Property to Object without triggering Watchers on existing Properties
I have a Vuex store with an object:

```<code> state: {
    contents: {},
 }
</code>```

where I dynamically store contents by key:

```<code>mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}
</code>```

and get them using:

```<code>getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},
</code>```

Let's say I have a component like this:

```<code>export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}
</code>```

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.

答:
I'm trying to figure it out by checking the fiddle:  https://jsfiddle.net/ericskaliks/Ln0uws9m/15/ , and I have a possible reason to this behavior.

Getters and Computed properties are updated or reached when the observed objects or properties inside them are changed. In this case the content getter is "watching" the state.contents store property, so each time store.contents is updated, the content getter is called, then the computed property myContent() updates its value and increase the updated data property with this.update++.

So the components will always be updated if the state.contents property is updated, i.e. adding a new unrelated property.

Body:
I have a Vuex store with an object:

 state: {
    contents: {},
 }

where I dynamically store contents by key:

mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}

and get them using:

getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},

Let's say I have a component like this:

export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.


问:
GraphQL and Data Loader Using the graphql-java-kickstart library
I am attempting to use the DataLoader feature within the graphql-java-kickstart library:

https://github.com/graphql-java-kickstart

My application is a Spring Boot application using 2.3.0.RELEASE. And I using version 7.0.1 of the graphql-spring-boot-starter library.

The library is pretty easy to use and it works when I don't use the data loader. However, I am plagued by the N+1 SQL problem and as a result need to use the data loader to help alleviate this issue. When I execute a request, I end up getting this:

```<code>Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer
</code>```

I am sure I am missing something in the configuration but really don't know what that is.

Here is my graphql schema:

```<code>type Account {
  id: ID!
  accountNumber: String!
  customers: [Customer]
}

type Customer {
  id: ID!
  fullName: String
}
</code>```

I have created a CustomGraphQLContextBuilder:

```<code>@Component
public class CustomGraphQLContextBuilder implements GraphQLServletContextBuilder {

    private final CustomerRepository customerRepository;

    public CustomGraphQLContextBuilder(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public GraphQLContext build(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return DefaultGraphQLServletContext.createServletContext(buildDataLoaderRegistry(), null).with(httpServletRequest).with(httpServletResponse).build();
    }

    @Override
    public GraphQLContext build(Session session, HandshakeRequest handshakeRequest) {
        return DefaultGraphQLWebSocketContext.createWebSocketContext(buildDataLoaderRegistry(), null).with(session).with(handshakeRequest).build();
    }

    @Override
    public GraphQLContext build() {
        return new DefaultGraphQLContext(buildDataLoaderRegistry(), null);
    }

    private DataLoaderRegistry buildDataLoaderRegistry() {
        DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry();

        dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, Customer>(accountIds ->
                        CompletableFuture.supplyAsync(() ->
                                customerRepository.findCustomersByAccountIds(accountIds), new SyncTaskExecutor())));

        return dataLoaderRegistry;
    }
}
</code>```

I also have create an AccountResolver:

```<code>public CompletableFuture<List<Customer>> customers(Account account, DataFetchingEnvironment dfe) {
    final DataLoader<Long, List<Customer>> dataloader = ((GraphQLContext) dfe.getContext())
            .getDataLoaderRegistry().get()
            .getDataLoader("customerDataLoader");

     return dataloader.load(account.getId());
}
</code>```

And here is the Customer Repository:

```<code>public List<Customer> findCustomersByAccountIds(List<Long> accountIds) {

    Instant begin = Instant.now();

    MapSqlParameterSource namedParameters = new MapSqlParameterSource();
    String inClause = getInClauseParamFromList(accountIds, namedParameters);

    String sql = StringUtils.replace(SQL_FIND_CUSTOMERS_BY_ACCOUNT_IDS,"__ACCOUNT_IDS__", inClause);

    List<Customer> customers = jdbcTemplate.query(sql, namedParameters, new CustomerRowMapper());

    Instant end = Instant.now();

    LOGGER.info("Total Time in Millis to Execute findCustomersByAccountIds: " + Duration.between(begin, end).toMillis());

    return customers;
}
</code>```

I can put a break point in the Customer Repository and see the SQL execute and it returns a List of Customer objects. You can also see that the schema wants an array of customers. If I remove the code above and put in the resolver to get the customers one by one....it works....but is really slow.

What am I missing in the configuration that would cause this?

```<code>Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer
</code>```

Thanks for your help!

Dan

答:
Thanks, @Bms bharadwaj! The issue was on my side in understanding how the data is returned in the dataloader. I ended up using a MappedBatchLoader to bring the data in a map. The key in the map being the accountId.

```<code>private DataLoader<Long, List<Customer>> getCustomerDataLoader() {
    MappedBatchLoader<Long, List<Customer>> customerMappedBatchLoader = accountIds -> CompletableFuture.supplyAsync(() -> {
        List<Customer> customers = customerRepository.findCustomersByAccountId(accountIds);
        Map<Long, List<Customer>> groupByAccountId = customers.stream().collect(Collectors.groupingBy(cust -> cust.getAccountId()));
        return groupByAaccountId;
    });
//    }, new SyncTaskExecutor());

    return DataLoader.newMappedDataLoader(customerMappedBatchLoader);
}
</code>```

This seems to have done the trick because before I was issuing hundreds of SQL statement and now down to 2 (one for the driver SQL...accounts and one for the customers).

Body:
I am attempting to use the DataLoader feature within the graphql-java-kickstart library:

https://github.com/graphql-java-kickstart

My application is a Spring Boot application using 2.3.0.RELEASE. And I using version 7.0.1 of the graphql-spring-boot-starter library.

The library is pretty easy to use and it works when I don't use the data loader. However, I am plagued by the N+1 SQL problem and as a result need to use the data loader to help alleviate this issue. When I execute a request, I end up getting this:

Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer

I am sure I am missing something in the configuration but really don't know what that is.

Here is my graphql schema:

type Account {
  id: ID!
  accountNumber: String!
  customers: [Customer]
}

type Customer {
  id: ID!
  fullName: String
}

I have created a CustomGraphQLContextBuilder:

@Component
public class CustomGraphQLContextBuilder implements GraphQLServletContextBuilder {

    private final CustomerRepository customerRepository;

    public CustomGraphQLContextBuilder(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public GraphQLContext build(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return DefaultGraphQLServletContext.createServletContext(buildDataLoaderRegistry(), null).with(httpServletRequest).with(httpServletResponse).build();
    }

    @Override
    public GraphQLContext build(Session session, HandshakeRequest handshakeRequest) {
        return DefaultGraphQLWebSocketContext.createWebSocketContext(buildDataLoaderRegistry(), null).with(session).with(handshakeRequest).build();
    }

    @Override
    public GraphQLContext build() {
        return new DefaultGraphQLContext(buildDataLoaderRegistry(), null);
    }

    private DataLoaderRegistry buildDataLoaderRegistry() {
        DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry();

        dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, Customer>(accountIds ->
                        CompletableFuture.supplyAsync(() ->
                                customerRepository.findCustomersByAccountIds(accountIds), new SyncTaskExecutor())));

        return dataLoaderRegistry;
    }
}

I also have create an AccountResolver:

public CompletableFuture<List<Customer>> customers(Account account, DataFetchingEnvironment dfe) {
    final DataLoader<Long, List<Customer>> dataloader = ((GraphQLContext) dfe.getContext())
            .getDataLoaderRegistry().get()
            .getDataLoader("customerDataLoader");

     return dataloader.load(account.getId());
}

And here is the Customer Repository:

public List<Customer> findCustomersByAccountIds(List<Long> accountIds) {

    Instant begin = Instant.now();

    MapSqlParameterSource namedParameters = new MapSqlParameterSource();
    String inClause = getInClauseParamFromList(accountIds, namedParameters);

    String sql = StringUtils.replace(SQL_FIND_CUSTOMERS_BY_ACCOUNT_IDS,"__ACCOUNT_IDS__", inClause);

    List<Customer> customers = jdbcTemplate.query(sql, namedParameters, new CustomerRowMapper());

    Instant end = Instant.now();

    LOGGER.info("Total Time in Millis to Execute findCustomersByAccountIds: " + Duration.between(begin, end).toMillis());

    return customers;
}

I can put a break point in the Customer Repository and see the SQL execute and it returns a List of Customer objects. You can also see that the schema wants an array of customers. If I remove the code above and put in the resolver to get the customers one by one....it works....but is really slow.

What am I missing in the configuration that would cause this?

Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer

Thanks for your help!

Dan

Body:
Thanks, @Bms bharadwaj! The issue was on my side in understanding how the data is returned in the dataloader. I ended up using a MappedBatchLoader to bring the data in a map. The key in the map being the accountId.

private DataLoader<Long, List<Customer>> getCustomerDataLoader() {
    MappedBatchLoader<Long, List<Customer>> customerMappedBatchLoader = accountIds -> CompletableFuture.supplyAsync(() -> {
        List<Customer> customers = customerRepository.findCustomersByAccountId(accountIds);
        Map<Long, List<Customer>> groupByAccountId = customers.stream().collect(Collectors.groupingBy(cust -> cust.getAccountId()));
        return groupByAaccountId;
    });
//    }, new SyncTaskExecutor());

    return DataLoader.newMappedDataLoader(customerMappedBatchLoader);
}

This seems to have done the trick because before I was issuing hundreds of SQL statement and now down to 2 (one for the driver SQL...accounts and one for the customers).


问:
Call to undefined function showfeeddialog() for FB.Connect.showFeedDialog
I am developing an Facebook application in fb:iframe. I do not want to use feed_publishUserAction as it requires a session key. Hence trying to use FB.Connect.showFeedDialog.

Is it OK to use the latter?

Can any one suggest example to use it as I am getting an error saying Call to undefined function showfeeddialog().

Should I update my library?
Any other suggestions?

答:
First of all, you need to make sure the client library is being included:

```<code><script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
</code>```

This should not be in the  of the HTML page but in the body. From the docs:

Note: You must include the

OwnerDisplayName: Kartikkowligi

LastEditorDisplayName: Neil N

Body:
First of all, you need to make sure the client library is being included:

<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

This should not be in the  of the HTML page but in the body. From the docs:

Note: You must include the <script> tag that loads the FeatureLoader at the
  beginning of your <body> element. The FeatureLoader may write body elements directly > to the document, which, if it happens within the <head> element, is reported as an
  error by some browsers.

How are you calling the function? It should look something like:

FB.Connect.showFeedDialog(123456789, data);

(the numbers being the template id of the template you want to publish in, created in facebook or registered with the api. "data" should be the json you will populate said template with).

On thing to be aware of is that you need to make sure client library is ready to rock before you call any functions from it:

FB.ensureInit(function () {
    // -- now library is officially ready
});

or check out the Waitable class.

Remember: you do have to have logged in via Facebook connect to use the showFeedDialog form. Also, having worked with the Connect API all week...it's still very beta and requires numerous workarounds. You should post some of your code so we can help further.

OwnerDisplayName: TypeOneError


答:
You might be able to get rid of multiple checks against myArr.Length by using nested If statements, but this makes the code less clear.

A clear approach (i.e. one that can be understood easily) is one that allows you to read a code fragment without having to remember the context in which the code is executed. By nesting If statements, more information must be kept in the readers working memory  (or short term memory) to deduce the meaning of he code.

Title: Remove repetition from if-else statement