问:
Flutter: There should be exactly one item with [DropdownButton]'s value
I am trying to create a dropdown button in Flutter. I am getting a List from my database then I pass the list to my dropdownButton everything works the data is shown as intended but when I choose an element from it I get this error:

```<code>There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
          items.where((DropdownMenuItem<T> item) {
            return item.value == value;
          }).length == 1'
</code>```

I tried setting DropdownButton value to null it works but then I can't see the chosen element.

Here is my code:

```<code>FutureBuilder<List<Tag>>(
    future: _tagDatabaseHelper.getTagList(),
    builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return ListView(
        children: <Widget>[
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.2,
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: MediaQuery.of(context).size.width * 0.07),
            child: Theme(
              data: ThemeData(canvasColor: Color(0xFF525A71)),
              child: DropdownButton<Tag>(
                value: _selectedTag,
                isExpanded: true,
                icon: Icon(
                  Icons.arrow_drop_down,
                  size: 24,
                ),
                hint: Text(
                  "Select tags",
                  style: TextStyle(color: Color(0xFF9F9F9F)),
                ),
                onChanged: (value) {
                  setState(() {
                    _selectedTag = value;
                  });
                },
                items: snapshot.data.map((Tag tag) {
                  return DropdownMenuItem<Tag>(
                    value: tag,
                    child: Text(
                      tag.tagTitle,
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                }).toList(),
                value: _selectedTag,
              ),
            ),
          ),
</code>```

I used futureBuilder to get my List from database.

答:
Code of my dropdown

```<code>child: DropdownButton(
      items: _currencies.map((String value) {
        return DropdownMenuItem<String>(
          child: Text(value),
          value: value,
        );
      }).toList(),
      value: 'Rupees',
      onChanged: (String newValueSelected) {
        // Your code to execute, when a menu item is selected from
        dropdown
      },
))
var _currencies = ['Rupee','Dollar','Pound'];
</code>```

I faced same error because the value in the dropdown code block is not matching with any of the fields in _currencies

Body:
I am trying to create a dropdown button in Flutter. I am getting a List from my database then I pass the list to my dropdownButton everything works the data is shown as intended but when I choose an element from it I get this error:

There should be exactly one item with [DropdownButton]'s value: Instance of 'Tag'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 805 pos 15: 'items == null || items.isEmpty || value == null ||
          items.where((DropdownMenuItem<T> item) {
            return item.value == value;
          }).length == 1'

I tried setting DropdownButton value to null it works but then I can't see the chosen element.

Here is my code:

FutureBuilder<List<Tag>>(
    future: _tagDatabaseHelper.getTagList(),
    builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return ListView(
        children: <Widget>[
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.2,
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: MediaQuery.of(context).size.width * 0.07),
            child: Theme(
              data: ThemeData(canvasColor: Color(0xFF525A71)),
              child: DropdownButton<Tag>(
                value: _selectedTag,
                isExpanded: true,
                icon: Icon(
                  Icons.arrow_drop_down,
                  size: 24,
                ),
                hint: Text(
                  "Select tags",
                  style: TextStyle(color: Color(0xFF9F9F9F)),
                ),
                onChanged: (value) {
                  setState(() {
                    _selectedTag = value;
                  });
                },
                items: snapshot.data.map((Tag tag) {
                  return DropdownMenuItem<Tag>(
                    value: tag,
                    child: Text(
                      tag.tagTitle,
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                }).toList(),
                value: _selectedTag,
              ),
            ),
          ),

I used futureBuilder to get my List from database.

Body:
Code of my dropdown

child: DropdownButton(
      items: _currencies.map((String value) {
        return DropdownMenuItem<String>(
          child: Text(value),
          value: value,
        );
      }).toList(),
      value: 'Rupees',
      onChanged: (String newValueSelected) {
        // Your code to execute, when a menu item is selected from
        dropdown
      },
))
var _currencies = ['Rupee','Dollar','Pound'];

I faced same error because the value in the dropdown code block is not matching with any of the fields in _currencies


来源: stackexchange

问:
When Player Image Scrolling Left, Enemy Mob Scrolls?
I have a problem with my enemy where when my player scrolls left the enemy scrolls with the player is there anyway to fix this even Video my full code is below its to long to fit here though

what I was trying to do is make my enemy not to change its position when my window is scrolling its doing the same for right and left keeps following the player

```<code>
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
  [...]
# I did the same for my players key movement  this part suppose to not make my player scroll
if playerman.y < 250:
        playerman.y += 1
        for platform in platforms:
            platform.y += playerman.speed
        for enemys in enemying:
            enemys.y += playerman.speed
</code>```

my enemy class

```<code>class enemy:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.walking_index = 0
        self.rect = pygame.Rect(x,y,height,width)
       def draw(self,window):
       self.move()
       if self.Walking_index + 1 >= 33:
           self.Walking_index = 0
       if self.vel > 0:
           window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       else:
           window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       def move(self):
       if self.vel > 0:
           if self.x + self.vel < self.path[1]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0
       else:
           if self.x - self.vel >  self.path[0]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0

</code>```

where I defined the enemy class

```<code>black = (0,0,0)
enemys1 = enemy(550,436,50,50,300)
enemys = [enemys1]
</code>```

my full code its to long to fit here  script

答:
It is not sufficient to scroll the position of the enemy. The path of the enemy is limited by an interval (self.path). When the x coordinate of the enemy reaches self.path[0] or self.path[1], then the enemy turns:

if self.vel > 0:
   if self.x + self.vel < self.path[1]:
       self.x += self.vel
   else:
       self.vel = self.vel * -1
       self.Walking_index = 0
else:
   if self.x - self.vel >  self.path[0]:
       self.x += self.vel
   else:
       self.vel = self.vel * -1
       self.Walking_index = 0
```
</blockquote>

<p>If you scroll the enemy, the you have to scroll the path, too.</p>

<p>Add a method <code>scroll</code> to the class <code>enemys</code>. Change the position and the start and end of the path:</p>

<pre class="lang-py prettyprint-override"><code>class enemys:
    # [...]

    def scroll(self, sx, sy):
        self.x += sx
        self.y += sy
        self.path[0] += sx
        self.path[1] += sx
</code>```

Use the method to scroll the enemy:

runninggame = True
while runninggame:
    # [...]

    if playerman.y < 250:
        playerman.y += 1

        # [...]
        for enemys in enemying:
            enemys.scroll(0, playerman.speed)

    if playerman.y > 450:
        playerman.y -= playerman.fall

        # [...]
        for enemys in enemying:
            enemys.scroll(0, -playerman.fall)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        playerman.x -= playerman.speed
        playerman.direction = "left"
        # camera controll for left
        if playerman.x < 100:

            # [...]
            for enemys in enemying:
                enemys.scroll(playerman.speed, 0)

    elif keys[pygame.K_d]:
        playerman.x += playerman.speed
        playerman.direction = "right"
        # camera for right:
        if playerman.x > 400:
            playerman.x -= playerman.speed

            # [...]
            for enemys in enemying:
                enemys.scroll(-playerman.speed, 0)
```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with my enemy where when my player scrolls left the enemy scrolls with the player is there anyway to fix this even Video my full code is below its to long to fit here though

what I was trying to do is make my enemy not to change its position when my window is scrolling its doing the same for right and left keeps following the player

while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
  [...]
# I did the same for my players key movement  this part suppose to not make my player scroll
if playerman.y < 250:
        playerman.y += 1
        for platform in platforms:
            platform.y += playerman.speed
        for enemys in enemying:
            enemys.y += playerman.speed

my enemy class

class enemy:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.walking_index = 0
        self.rect = pygame.Rect(x,y,height,width)
       def draw(self,window):
       self.move()
       if self.Walking_index + 1 >= 33:
           self.Walking_index = 0
       if self.vel > 0:
           window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       else:
           window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       def move(self):
       if self.vel > 0:
           if self.x + self.vel < self.path[1]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0
       else:
           if self.x - self.vel >  self.path[0]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0

where I defined the enemy class

black = (0,0,0)
enemys1 = enemy(550,436,50,50,300)
enemys = [enemys1]

my full code its to long to fit here  script

Body:
It is not sufficient to scroll the position of the enemy. The path of the enemy is limited by an interval (self.path). When the x coordinate of the enemy reaches self.path[0] or self.path[1], then the enemy turns:

if self.vel > 0:
   if self.x + self.vel < self.path[1]:
       self.x += self.vel
   else:
       self.vel = self.vel * -1
       self.Walking_index = 0
else:
   if self.x - self.vel >  self.path[0]:
       self.x += self.vel
   else:
       self.vel = self.vel * -1
       self.Walking_index = 0

If you scroll the enemy, the you have to scroll the path, too.

Add a method scroll to the class enemys. Change the position and the start and end of the path:

class enemys:
    # [...]

    def scroll(self, sx, sy):
        self.x += sx
        self.y += sy
        self.path[0] += sx
        self.path[1] += sx

Use the method to scroll the enemy:

runninggame = True
while runninggame:
    # [...]

    if playerman.y < 250:
        playerman.y += 1

        # [...]
        for enemys in enemying:
            enemys.scroll(0, playerman.speed)

    if playerman.y > 450:
        playerman.y -= playerman.fall

        # [...]
        for enemys in enemying:
            enemys.scroll(0, -playerman.fall)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        playerman.x -= playerman.speed
        playerman.direction = "left"
        # camera controll for left
        if playerman.x < 100:

            # [...]
            for enemys in enemying:
                enemys.scroll(playerman.speed, 0)

    elif keys[pygame.K_d]:
        playerman.x += playerman.speed
        playerman.direction = "right"
        # camera for right:
        if playerman.x > 400:
            playerman.x -= playerman.speed

            # [...]
            for enemys in enemying:
                enemys.scroll(-playerman.speed, 0)


问:
Working with performance on requests Parse SDK
I'm having some performance issues with my Parse queries, using Parse SDK.

On some requests, I have to get a ressources related to another one. E.g. :

I get all elements from ClassA

foreach ClassA elements, I have to find all ClassB and ClassC elements which contain a pointer to the relevant entry in ClassA.

Right now, to sum up:

I query all my ClassA elements

I loop on the results, and create a Promise (Parse query) to get ClassB elements and another one (Parse query) to get ClassC elements foreach result

My issue is that solution makes a lot of Parse Query, so a lot of Promise that I have to wait for. The real issue is that on my local env, all is working fine, the whole request makes 1s or less (it's quite heavy, but it does 45 parse query in the current case - based on my Class entries).
On my production server, same code, same data, same Node version, the same request makes 30s or more (=> timeout).

This is the relevant part of the code (it's old and messy) :

```<code>router.get('/:userId/company/customers', (req, res, next) => {
  if('company' in req.jwtData.data) {
    const company = req.jwtData.data.company;
    const query = new Parse.Query('Cards');
    const Companies = Parse.Object.extend('Companies');
    const currentCompany = new Companies({id: company.objectId});
    query.equalTo('company', currentCompany).find().then((cards) => {
      if(cards.length){
        const customersArrayId = cards.map(card => card.toJSON().user.objectId);
        const usersQuery = new Parse.Query('_User').containedIn('objectId', customersArrayId).find({ useMasterKey: true });
        usersQuery.then(customersResponse => {
          const customers = [];
          const customersPromises = [];
          if(customersResponse.length) {
            for (let index = 0; index < customersResponse.length; index++) {
              let customer = {
                ...customersResponse[index].toJSON(),
                ...customersResponse[index].attributes
              };
              const customerPromises = [];
              const customerId = customer.objectId;
              const stamps = new Parse.Query('Stamps').equalTo('user', new UserModel({objectId: customerId})).equalTo('company', currentCompany).limit(CONSTANTS.QUERY_MAX_LIMIT).find().then((stamps) => {
                return stamps;
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
              const cards = new Parse.Query('Cards').equalTo('user', new UserModel({objectId: customerId})).equalTo('company', currentCompany).limit(CONSTANTS.QUERY_MAX_LIMIT).find().then((cards) => {
                return cards;
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
              customers.push(customer);
              customerPromises.push(stamps);
              customerPromises.push(cards);
              customersPromises.push(customerPromises);
            }
            if(customersPromises.length) {
              const allPromises = customersPromises.map(customerP => Promise.all(customerP));
              Promise.all(allPromises).then((customerPromiseResponses) => {
                console.log('allPromises done, mapping all users data...');
                for (let index = 0; index < customerPromiseResponses.length; index++) {
                  const customerResponseData = customerPromiseResponses[index];
                  const stamps = customerResponseData[0];
                  const cards = customerResponseData[1];
                  const companyEmailAllowed = () => {
                    let check = false;
                    if(customers[index].hasOwnProperty('companiesNewsletterAgreements')) {
                      check = customers[index].companiesNewsletterAgreements.indexOf(company.objectId) > -1;
                    }
                    return check;
                  };
                  customers[index] = {
                    ...customers[index],
                    email: companyEmailAllowed() ? customers[index].email : null,
                    stamps,
                    cards,
                  }
                }
                res.json({
                  success: true,
                  data: customers
                });
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
            }
            else {
              res.json({
                success: true,
                data: customers
              });
            }

          } else {
            res.json({
              success: true,
              data: customers
            });
          }

        });
      } else {
        res.json({
          success: true,
          data: []
        });
      }

    });
  } else {
    res.json({
      success: false,
      error: "No company found."
    });
  }
});
</code>```

My question is: is it possible to get the same data in a more performant way (less Parse queries, less Promises)?

答:
I actually found a solution. Instead of starting Parse query for each result I found, I request the whole set of elements I need in the first place, using containedIn.

Then, I filter the results to assign the elements to their customer.

Body:
I'm having some performance issues with my Parse queries, using Parse SDK.

On some requests, I have to get a ressources related to another one. E.g. :

I get all elements from ClassA

foreach ClassA elements, I have to find all ClassB and ClassC elements which contain a pointer to the relevant entry in ClassA.

Right now, to sum up:

I query all my ClassA elements

I loop on the results, and create a Promise (Parse query) to get ClassB elements and another one (Parse query) to get ClassC elements foreach result

My issue is that solution makes a lot of Parse Query, so a lot of Promise that I have to wait for. The real issue is that on my local env, all is working fine, the whole request makes 1s or less (it's quite heavy, but it does 45 parse query in the current case - based on my Class entries).
On my production server, same code, same data, same Node version, the same request makes 30s or more (=> timeout).

This is the relevant part of the code (it's old and messy) :

router.get('/:userId/company/customers', (req, res, next) => {
  if('company' in req.jwtData.data) {
    const company = req.jwtData.data.company;
    const query = new Parse.Query('Cards');
    const Companies = Parse.Object.extend('Companies');
    const currentCompany = new Companies({id: company.objectId});
    query.equalTo('company', currentCompany).find().then((cards) => {
      if(cards.length){
        const customersArrayId = cards.map(card => card.toJSON().user.objectId);
        const usersQuery = new Parse.Query('_User').containedIn('objectId', customersArrayId).find({ useMasterKey: true });
        usersQuery.then(customersResponse => {
          const customers = [];
          const customersPromises = [];
          if(customersResponse.length) {
            for (let index = 0; index < customersResponse.length; index++) {
              let customer = {
                ...customersResponse[index].toJSON(),
                ...customersResponse[index].attributes
              };
              const customerPromises = [];
              const customerId = customer.objectId;
              const stamps = new Parse.Query('Stamps').equalTo('user', new UserModel({objectId: customerId})).equalTo('company', currentCompany).limit(CONSTANTS.QUERY_MAX_LIMIT).find().then((stamps) => {
                return stamps;
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
              const cards = new Parse.Query('Cards').equalTo('user', new UserModel({objectId: customerId})).equalTo('company', currentCompany).limit(CONSTANTS.QUERY_MAX_LIMIT).find().then((cards) => {
                return cards;
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
              customers.push(customer);
              customerPromises.push(stamps);
              customerPromises.push(cards);
              customersPromises.push(customerPromises);
            }
            if(customersPromises.length) {
              const allPromises = customersPromises.map(customerP => Promise.all(customerP));
              Promise.all(allPromises).then((customerPromiseResponses) => {
                console.log('allPromises done, mapping all users data...');
                for (let index = 0; index < customerPromiseResponses.length; index++) {
                  const customerResponseData = customerPromiseResponses[index];
                  const stamps = customerResponseData[0];
                  const cards = customerResponseData[1];
                  const companyEmailAllowed = () => {
                    let check = false;
                    if(customers[index].hasOwnProperty('companiesNewsletterAgreements')) {
                      check = customers[index].companiesNewsletterAgreements.indexOf(company.objectId) > -1;
                    }
                    return check;
                  };
                  customers[index] = {
                    ...customers[index],
                    email: companyEmailAllowed() ? customers[index].email : null,
                    stamps,
                    cards,
                  }
                }
                res.json({
                  success: true,
                  data: customers
                });
              }).catch(error => {
                res.json({
                  success: false,
                  error
                });
              });
            }
            else {
              res.json({
                success: true,
                data: customers
              });
            }

          } else {
            res.json({
              success: true,
              data: customers
            });
          }

        });
      } else {
        res.json({
          success: true,
          data: []
        });
      }

    });
  } else {
    res.json({
      success: false,
      error: "No company found."
    });
  }
});

My question is: is it possible to get the same data in a more performant way (less Parse queries, less Promises)?


问:
How to split a string on multiple delimiters stored in a list?
I have a list of delimiters like

```<code>List<String> delimiters= Arrays.asList(",",".");
</code>```

If I have a string like "a.b,c".

How to split on all the delimiters?

答:
You can do a regular expression.</p>

```<code>@Test
public void test() {
    List<String> delimiters = Arrays.asList(",", ".", "?");
    String str = "a.b,c?dr";

    StringBuilder regex = new StringBuilder();
    regex.append("[");
    delimiters.stream().forEach(delimiter -> regex.append(delimiter + "/"));
    regex.append("]");

    String[] result = str.split(regex.toString());
}
</code>```

Body:
I have a list of delimiters like

List<String> delimiters= Arrays.asList(",",".");

If I have a string like "a.b,c".

How to split on all the delimiters?

Body:
You can do a regular expression.

@Test
public void test() {
    List<String> delimiters = Arrays.asList(",", ".", "?");
    String str = "a.b,c?dr";

    StringBuilder regex = new StringBuilder();
    regex.append("[");
    delimiters.stream().forEach(delimiter -> regex.append(delimiter + "/"));
    regex.append("]");

    String[] result = str.split(regex.toString());
}


问:
The compiler doesnt show errors but I get no output. Whats wrong?
I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?

```<code>#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

bool PerfectCheck(int x) {

    int t; // divisor

    int sum; //  sum of divisors

    for (t = 0; t <= x; t++ ) {
        if (x%t == 0) {
            sum = sum + t;
        }
    }
    if (sum == x)
        return true;
    else
        return false;
}

int main() {

    srand(time(NULL));

    int x = rand()%(100-2+1)+2;

    if (PerfectCheck(x) == true )
        cout << x << "is a perfect number.";
    else
        cout << x << "is not a perfect number.";
    return 0;
}
</code>```

答:
There are three problems in your PerfectCheck function. First, you don't initialize the sum variable, so it can start off with any value whatsoever; you should set it to zero explicitly in the declaration.

Second, your for loop starts with t as zero, and you check x % t. The modulo operator implicitly involves a division, so using a left-hand value of zero has the same issue as trying to divide by zero, which will cause a crash.

Third, when checking for a perfect number, don't use that number itself in the sum; so, stop your loop with t < x instead of t <= x.

Also, as mentioned in the comments, you can simplify the return statement. The code below works, in the tests I have performed:

bool PerfectCheck(int x)
{
    int sum = 0; //  sum of divisors - MUST BE INITIALIZED (to zero)
    for (int t = 1; t < x; t++) { // DO NOT INCLUDE X ITSELF!!
        if (x % t == 0) {
            sum += t;
        }
    }
    return (sum == x); // This will already give a "true" or "false" bool value.
}
```

You could actually make the code a tiny bit more 'efficient', by initializing sum to 1 and then starting the loop from t = 2 (all numbers divide by 1, after all).

Feel free to ask for further clarification and/or explanation.

Body:
I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

bool PerfectCheck(int x) {

    int t; // divisor

    int sum; //  sum of divisors

    for (t = 0; t <= x; t++ ) {
        if (x%t == 0) {
            sum = sum + t;
        }
    }
    if (sum == x)
        return true;
    else
        return false;
}

int main() {

    srand(time(NULL));

    int x = rand()%(100-2+1)+2;

    if (PerfectCheck(x) == true )
        cout << x << "is a perfect number.";
    else
        cout << x << "is not a perfect number.";
    return 0;
}

Body:
There are three problems in your PerfectCheck function. First, you don't initialize the sum variable, so it can start off with any value whatsoever; you should set it to zero explicitly in the declaration.

Second, your for loop starts with t as zero, and you check x % t. The modulo operator implicitly involves a division, so using a left-hand value of zero has the same issue as trying to divide by zero, which will cause a crash.

Third, when checking for a perfect number, don't use that number itself in the sum; so, stop your loop with t < x instead of t <= x.

Also, as mentioned in the comments, you can simplify the return statement. The code below works, in the tests I have performed:

bool PerfectCheck(int x)
{
    int sum = 0; //  sum of divisors - MUST BE INITIALIZED (to zero)
    for (int t = 1; t < x; t++) { // DO NOT INCLUDE X ITSELF!!
        if (x % t == 0) {
            sum += t;
        }
    }
    return (sum == x); // This will already give a "true" or "false" bool value.
}

You could actually make the code a tiny bit more 'efficient', by initializing sum to 1 and then starting the loop from t = 2 (all numbers divide by 1, after all).

Feel free to ask for further clarification and/or explanation.


问:
Scatterplot function that can change based on variables for axes
I am trying to write a function that seems like it should be very simple but I am having problems with it. I want to write a function that takes in three arguements: a dataframe, x-axis variable and y-axis variable. Based on these, I want it to return a scatterplot in which the x-axis variable and y-axis variable can be changed. This is the very basic function I wrote:

```<code>scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = x_input, y = y_input),
    )
}
</code>```

For reproducibility, consider the dataset midwest that is in the ggplot2 package. The code I wrote does not produce errors when I run it, but when I try to pass arguments into it, such as

```<code>scatter_plot(midwest, percollege, percpovertyknown)
</code>```

the function returns

"Error in FUN(X[[i]], ...) : object 'percollege' not found"

It seems like it does not recognize the variables in the argument, but I have been playing around with the function for quite some time and I can't seem to figure it out. Can someone help me with how to fix this so my function works correctly?

答:
tidyverse uses non standard evaluation (NSE), which makes using its facilities in functions slightly more complicated than you expect.  Here's a version of your function that works for me.

```<code>scatter_plot <- function(dataframe, x_input, y_input) {
  qX <- enquo(x_input)
  qY <- enquo(y_input)
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = !! qX, y = !! qY),
    )
  return(plot)
}
</code>```

As you've assigned your plot to an object, I've added a return statement.

See here for more information on NSE.

Body:
I am trying to write a function that seems like it should be very simple but I am having problems with it. I want to write a function that takes in three arguements: a dataframe, x-axis variable and y-axis variable. Based on these, I want it to return a scatterplot in which the x-axis variable and y-axis variable can be changed. This is the very basic function I wrote:

scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = x_input, y = y_input),
    )
}

For reproducibility, consider the dataset midwest that is in the ggplot2 package. The code I wrote does not produce errors when I run it, but when I try to pass arguments into it, such as

scatter_plot(midwest, percollege, percpovertyknown)

the function returns

"Error in FUN(X[[i]], ...) : object 'percollege' not found"

It seems like it does not recognize the variables in the argument, but I have been playing around with the function for quite some time and I can't seem to figure it out. Can someone help me with how to fix this so my function works correctly?

Body:
tidyverse uses non standard evaluation (NSE), which makes using its facilities in functions slightly more complicated than you expect.  Here's a version of your function that works for me.

scatter_plot <- function(dataframe, x_input, y_input) {
  qX <- enquo(x_input)
  qY <- enquo(y_input)
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = !! qX, y = !! qY),
    )
  return(plot)
}

As you've assigned your plot to an object, I've added a return statement.

See here for more information on NSE.


答:
Please check below code whether it solves your problem:</p>

```<code>List<String> delimiters = Arrays.asList(",", ".", "?", ":");

for (String delimiter : delimiters) {
  text = text.replace(delimiter, " "); //replace all delimiter occurrence with space
}

String[] output = text.split(" "); //split using space
</code>```

Title: How to split a string on multiple delimiters stored in a list?

Body:
Please check below code whether it solves your problem:

List<String> delimiters = Arrays.asList(",", ".", "?", ":");

for (String delimiter : delimiters) {
  text = text.replace(delimiter, " "); //replace all delimiter occurrence with space
}

String[] output = text.split(" "); //split using space


问:
React - add one more property to state
So I populate the state for 'Sources' by fetching a list of sources from an api with axios. The resulting state of sources is an array of objects with some properties (see the screenshotp below;

```<code>const [articles, setArticles] = useState([]);
const [sources, setSources] = useState([]);
const [EndPoint, setEndPoint] = useState({
    headlines_url: 'top-headlines?',
    sources_url: 'sources?language=en&'
});

useEffect(() => {
        axios.all([
            axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
            axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
        ])
        .then(res => {
            const newArticles = res[0].data.articles;
            const newSources = res[1].data.sources;
            setArticles(newArticles);
            setSources(newSources);
        })
    }, [EndPoint]);
</code>```

What I'll be trying to do is to add checkboxes next to sources to indicate which sources to take articles from. First, however, I'd need one more property on the sources (Eg. active: true/false) to keep track of which source has been selected.
Would it be better to add one more property to the existing 'sources' object or create a completely new object referencing the sources id property? and how would I do it?

Thanks

答:
if you are certain about Source id to be unique you can do what you're desire in two ways:

1- first as you said you can add another state which keeps for example selectedSources which is an array of selected source ids and you can add a source based on its checkbox to this array

for example something like this:

```<code>  const [selectedSources, setSelectedSources] = useState([]);

  const handleAddSelectSource = (id) => {
    setSelectedSources(value => [...value, id]);
  }

  const handleRemoveSelectSource = (id) => {
    setSelectedSources(value => value.filter(eachId => eachId != id))
  }

  const handleSelectSource = (id) => {
    if(selectedSources.find(source => source === id)){
      handleRemoveSelectSource(id);
    }else{
      handleAddSelectSource(id);
    }
  }

</code>```

2- you can add a new property which will indicate if a source has been selected or not which you can do it this way:

```<code>
useEffect(() => {
    axios
      .all([
        axios.get(
          `http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`
        ),
        axios.get(
          `http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`
        )
      ])
      .then(res => {
        const newArticles = res[0].data.articles;
        const newSources = res[1].data.sources;
        setArticles(newArticles);
        setSources(newSources.map(source => ({
          ...source,
          active: false
        })));
      });
  }, [EndPoint]);

  const handleSelectSource = (id) => {
    setSources(oldSources => oldSources.map(source => {
      if(source.id === id){
        return {
          ...source,
          active: !source.active,
        }
      }else{
        return source;
      }
    }))
  }
</code>```

Title: React - add one more property to state

Body:
So I populate the state for 'Sources' by fetching a list of sources from an api with axios. The resulting state of sources is an array of objects with some properties (see the screenshotp below;

const [articles, setArticles] = useState([]);
const [sources, setSources] = useState([]);
const [EndPoint, setEndPoint] = useState({
    headlines_url: 'top-headlines?',
    sources_url: 'sources?language=en&'
});

useEffect(() => {
        axios.all([
            axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
            axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
        ])
        .then(res => {
            const newArticles = res[0].data.articles;
            const newSources = res[1].data.sources;
            setArticles(newArticles);
            setSources(newSources);
        })
    }, [EndPoint]);

What I'll be trying to do is to add checkboxes next to sources to indicate which sources to take articles from. First, however, I'd need one more property on the sources (Eg. active: true/false) to keep track of which source has been selected.
Would it be better to add one more property to the existing 'sources' object or create a completely new object referencing the sources id property? and how would I do it?

Thanks

Body:
if you are certain about Source id to be unique you can do what you're desire in two ways:

1- first as you said you can add another state which keeps for example selectedSources which is an array of selected source ids and you can add a source based on its checkbox to this array

for example something like this:

  const [selectedSources, setSelectedSources] = useState([]);

  const handleAddSelectSource = (id) => {
    setSelectedSources(value => [...value, id]);
  }

  const handleRemoveSelectSource = (id) => {
    setSelectedSources(value => value.filter(eachId => eachId != id))
  }

  const handleSelectSource = (id) => {
    if(selectedSources.find(source => source === id)){
      handleRemoveSelectSource(id);
    }else{
      handleAddSelectSource(id);
    }
  }

2- you can add a new property which will indicate if a source has been selected or not which you can do it this way:

useEffect(() => {
    axios
      .all([
        axios.get(
          `http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`
        ),
        axios.get(
          `http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`
        )
      ])
      .then(res => {
        const newArticles = res[0].data.articles;
        const newSources = res[1].data.sources;
        setArticles(newArticles);
        setSources(newSources.map(source => ({
          ...source,
          active: false
        })));
      });
  }, [EndPoint]);

  const handleSelectSource = (id) => {
    setSources(oldSources => oldSources.map(source => {
      if(source.id === id){
        return {
          ...source,
          active: !source.active,
        }
      }else{
        return source;
      }
    }))
  }


问:
Why does the recommended dispose pattern adds a disposed field at each level of the hierarchy?
The Dispose pattern is notoriously complicated to get right, especially when we have a hierarchy of classes that needs to dispose things at different levels. The recommended implementation is as follow, took from Implement a Dispose method - Microsoft Docs.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass() => Dispose(false);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        _disposed = true;
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // To detect redundant calls
    private bool _disposed = false;

    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        _disposed = true;

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
```

<p>What I don't get in this implementation is what advantage we have in adding a <code>_disposed</code> field at each level of the hierarchy? Instead, we could take care of the <code>_disposed</code> only in the top level of the hierarchy (the one implementing directly <code>IDisposable</code> and not care about it in the derived classes.</p>

<p>Something like this:</p>

<pre class="lang-cs prettyprint-override"><code>using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass()
    {
       if (_disposed)
       {
          return;
       }

       Dispose(false);
       _disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        _disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
</code>```

This is such a widely used code sample that there must certainly be a good reason for it to be implemented with the repeated _disposed at each level, but I just can't find any.

It's a tiny bit more code in the base class, but less to worry about in the derived class, and some repeated information removed.

What else am I missing?

Edit:

As @InBetween correctly says that one drawback of my implementation is that if you'd need to check if your object is disposed in one method of the derived class you won't be able to check it. Let's correct that issue by making it a protected property with a private set.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    protected bool Disposed { get; private set; } = false;

    ~BaseClass()
    {
       if (Disposed)
       {
          return;
       }

       Dispose(false);
       Disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (Disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        Disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    public void DoSomething()
    {
       if(Disposed)
       {
           throw new ObjectDisposedException("Cannot access disposed resource");
       }
    }

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}
```

答:
If you are inheriting from a disposable class, one of two conditions must be true.

Your subcless does not introduce a new disposable resource. In this case you don't need to override Dispose and the question is moot.

Your subclass introduces a new disposable resource. In this case, you're going to override Dispose, insert your own disposal code, then call base.Dispose. The _disposed flag is there to help you remember to prevent your disposal code from executing twice.

You certainly can remove _disposed if you want. But you probably do not care much about the base class' _disposed flag, if it even has one. It worries about what it is disposing, and you worry about yours.

Body:
The Dispose pattern is notoriously complicated to get right, especially when we have a hierarchy of classes that needs to dispose things at different levels. The recommended implementation is as follow, took from Implement a Dispose method - Microsoft Docs.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass() => Dispose(false);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        _disposed = true;
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // To detect redundant calls
    private bool _disposed = false;

    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        _disposed = true;

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

What I don't get in this implementation is what advantage we have in adding a _disposed field at each level of the hierarchy? Instead, we could take care of the _disposed only in the top level of the hierarchy (the one implementing directly IDisposable and not care about it in the derived classes.

Something like this:

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    private bool _disposed = false;

    ~BaseClass()
    {
       if (_disposed)
       {
          return;
       }

       Dispose(false);
       _disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        _disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}

This is such a widely used code sample that there must certainly be a good reason for it to be implemented with the repeated _disposed at each level, but I just can't find any.

It's a tiny bit more code in the base class, but less to worry about in the derived class, and some repeated information removed.

What else am I missing?

Edit:

As @InBetween correctly says that one drawback of my implementation is that if you'd need to check if your object is disposed in one method of the derived class you won't be able to check it. Let's correct that issue by making it a protected property with a private set.

using System;

class BaseClass : IDisposable
{
    // To detect redundant calls
    protected bool Disposed { get; private set; } = false;

    ~BaseClass()
    {
       if (Disposed)
       {
          return;
       }

       Dispose(false);
       Disposed = true;
    }

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        if (Disposed)
        {
            return;
        }

        Dispose(true);
        GC.SuppressFinalize(this);
        Disposed = true;
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.
    }
}

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class DerivedClass : BaseClass
{
    // Instantiate a SafeHandle instance.
    private SafeHandle _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    public void DoSomething()
    {
       if(Disposed)
       {
           throw new ObjectDisposedException("Cannot access disposed resource");
       }
    }

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
           // Dispose managed state (managed objects).
            _safeHandle?.Dispose();
        }

        // Call base class implementation.
        base.Dispose(disposing);
    }
}


答:
```<code>    String s = "a.b,c";
    String[] split = s.split("[.|,]");
</code>```

how about this? Use “|” to separate multiple delimiters， remember to add [], Otherwise it needs to be escaped

Body:
    String s = "a.b,c";
    String[] split = s.split("[.|,]");

how about this? Use “|” to separate multiple delimiters， remember to add [], Otherwise it needs to be escaped


问:
How to convert JSON Object into key value pair in JS?
```<code>{"1":"val1","2":"val2","3":"val3"}
</code>```

i want it to converted like this:

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

little Help Please would be much appricated

答:
```<code>const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));
</code>```

The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]

Body:
{"1":"val1","2":"val2","3":"val3"}

i want it to converted like this:

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

little Help Please would be much appricated

Body:
const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));

The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]


问:
replaceFirst() fails when replacing with "$"
I don't understand why the "$" is special.

```<code>String str = "bla aa";
String tag = "$";
str = str.replaceFirst("aa", tag);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
</code>```

If I change the tag = "\\$", then it works fine.  But why does it need to be escaped?  thanks in advance.

答:
Because it is a special regex symbol (in results it's about capturing groups), and replaceFirst takes regex arguments. The documentation explicitly warns you:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Now a bit more about $. In the regex pattern it means "end of line".

In the replacement string, $g means "the g th group". So for a regex a([a-z]+)([0-9]+), you have two groups - $1 and $2, and you can refer to them when replacing. See the explanation here

ContentLicense: CC BY-SA 3.0

Body:
I don't understand why the "$" is special.

String str = "bla aa";
String tag = "$";
str = str.replaceFirst("aa", tag);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

If I change the tag = "\\$", then it works fine.  But why does it need to be escaped?  thanks in advance.


问:
prefetch_related for Authenticated user
I'm working on a django web application and i'm in the process of minimizing the amount of individual database hits by using the prefetch_related and select_related methods, i have a certain method in my User model that pulls a couple of different related objects from it.

```<code>def get_profile_info(self):
    *fetch data from a couple of models*
</code>```

And then i use this method in my view.

```<code>def profile(request):
    profile_info = request.user.get_profile_info()
    *rest of the view*
</code>```

The problem is, since request.user is not retrieved by the normal query methods, i don't get to use the prefetch_related and select_related along with pulling the user, and i can't find any way to retrieve the related data along with the model of that user.

Is there a way to, say, override the retrieving of the user model so i can run the prefetch_related and select_related methods?

答:
Sorry for this necroposting, but this theme is so important and really simple answer exists, just create a custom manager for your user model and override the get method with select_related like this:

from django.contrib.auth.models import AbstractUser, UserManager

class CustomUserManager(UserManager):
    def get(self, *args, **kwargs):
        return super().select_related('<put fields that you want>').get(*args, **kwargs)

class CustomUser(AbstractUser):
    ...

    objects = CustomUserManager()
```

Now, whenever Django will retrieve user instance for request.user, it will be using this manager. Also all your CustomUser.objects.get() queries will select specified related fields too.

Title: prefetch_related for Authenticated user

Body:
I'm working on a django web application and i'm in the process of minimizing the amount of individual database hits by using the prefetch_related and select_related methods, i have a certain method in my User model that pulls a couple of different related objects from it.

def get_profile_info(self):
    *fetch data from a couple of models*

And then i use this method in my view.

def profile(request):
    profile_info = request.user.get_profile_info()
    *rest of the view*

The problem is, since request.user is not retrieved by the normal query methods, i don't get to use the prefetch_related and select_related along with pulling the user, and i can't find any way to retrieve the related data along with the model of that user.

Is there a way to, say, override the retrieving of the user model so i can run the prefetch_related and select_related methods?

Body:
Sorry for this necroposting, but this theme is so important and really simple answer exists, just create a custom manager for your user model and override the get method with select_related like this:

from django.contrib.auth.models import AbstractUser, UserManager

class CustomUserManager(UserManager):
    def get(self, *args, **kwargs):
        return super().select_related('<put fields that you want>').get(*args, **kwargs)

class CustomUser(AbstractUser):
    ...

    objects = CustomUserManager()

Now, whenever Django will retrieve user instance for request.user, it will be using this manager. Also all your CustomUser.objects.get() queries will select specified related fields too.


问:
Read only replica on a different server using SQL Server 2019
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

```<code>**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*
</code>```

What option am I missing?

答:
May I suggest taking a step back, and ask yourself as to why you need another read-only database?
This will use some of the RAM in the server, and you can never have enough RAM...

If you enable Read Committed SnapShot Isolation Level Locking, then readers do not block writers.

You could also look into the Database Snapshot that "TheGameiswar" suggests. This will also conserve RAM.

Both suggestions use extra TempDB, so you need to ensure you get that on the fastest storage you can get.

Body:
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*

What option am I missing?


问:
CodeIgniter & WordPress Integration Routing
I have 2 separate sites, 1 is a CI membership management system and the other a WP public and members area site. They are hosted on different domains and servers.

Our requirement is to programatically add/edit users on the WP site from CI whilst keeping CI protected from WP. To achieve this we have created a copy of the WP site on the same install as CI but pointed it to the live WP database and blocked all public access to this copy. This way we can use the WP functions locally, allowing CI read/write access to WP and keep the CI system secure, minimising risk of attack via WP.

I have added to the CI index.php: require_once ./wordpress/wp-load.php;
Which works great (after fixing the site_url function), we are now adding and editing users YAY! but...
AJAX requests to some CI functions:- /members/getMemberJSON are returning 404's (which work fine when not loading WP. I think due to the fact that on the WP site /members/%username% pages already exist.

So the question is how to prevent WP overriding the CI routing.  I'm sure this is simple if you know how - Any smart internets help gratefully received.

答:
```<code>I modified the Codeigniter index.php one.

======================================
require_once 'wp-load.php';

above this line
require_once BASEPATH.'core/CodeIgniter.php';

Use Single .htaccess file in root wordpress folder

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpressFolderName/CIFolderName/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpressFolderName/CIFolderName/index.php [L]
</IfModule>
</code>```


答:
As pointed out this is invalis. If you want to convert it if would look like this:

[{"Id":"1","value":"val1"},{"Id":"2","value":"val2"},{"Id":"3","value":"val3"}]

You can make an function that converts this.

const object = {"1":"val1","2":"val2","3":"val3"};

console.log(Convert(object));

function Convert(obj){
  return Object.keys(obj).map(i => ({Id: i, value: obj[i]}));
}```

Title: How to convert JSON Object into key value pair in JS?


问:
TensorFlow keras Text classification: Applying model to score a word
The data i am using is BBC News Paper headlines , with its genre description category.
( Sport , Business, Politics, Tech , Entertainment ).

I am having trouble with interpreting the output after training the model and doing an assessment of the loss. I want to say which category out of the 5 ( Sport , Business, Politics, Tech , Entertainment ) the model would score a new sentence i give the model.

I know the model final layer outputs 5 categories+ 1 for no result :
resulttf.keras.layers.Dense(6, activation='softmax') .

Below is my attempt, I get the tokens. the predictions class are all 1 and the model predict gives me a matrix of (Number of letters in my test sentence x the number of classification categories)

for many examples i get this '1 1 1 1 1' answer which even when i try different category of words.

答:
I managed to find the solution to the issue by changing how i input a new sentence.
The key was to add it in this format.

sentence = ["""Olympic  games"""]

I then get one key reflecting one word
and a score classification per sentence/paragraph.


问:
Firebase dynamic link support custom parameters?
I am writing a App for a Open Source Conference.

Originally each attendees will receive different link via email or SMS like

https://example.com/?token=fccfc8bfa07643a1ca8015cbe74f5f17

then use this link to open app, we can know the user is which attendee by the token.

Firebase release a new feature Dynamic Links in I/O 2016, it provide better experience for users.

I had try that, but I can't find any way to pass the custom parameters (the token) in dynamic links, how to use the same link with different parameters to my users?

Thanks.

答:
1) From https://console.firebase.google.com/ (no need for custom parameter here.)

2) Create link somewhere, f.e. on your confluence page (here we add our parameter):

```<code>https://PROJECTNAME.page.link/?link=https://PROJECTNAME.page.link/LINKNAME?PARAMETER=1&ofl=https://www.PROJECTNAME.com/
</code>```

PARAMETER is your custom parameter.

ofl is a link where to go if click the link from another platform (PC, Mac).

3) Getting link data from android project Kotlin code:

```<code>Firebase.dynamicLinks
        .getDynamicLink(intent)
        .addOnSuccessListener { pendingDynamicLinkData ->
            val parameter: String =
                pendingDynamicLinkData?.link?.getQueryParameter("PARAMETER").orEmpty()
        }
</code>```

Body:
1) From https://console.firebase.google.com/ (no need for custom parameter here.)

2) Create link somewhere, f.e. on your confluence page (here we add our parameter):

https://PROJECTNAME.page.link/?link=https://PROJECTNAME.page.link/LINKNAME?PARAMETER=1&ofl=https://www.PROJECTNAME.com/

PARAMETER is your custom parameter.

ofl is a link where to go if click the link from another platform (PC, Mac).

3) Getting link data from android project Kotlin code:

Firebase.dynamicLinks
        .getDynamicLink(intent)
        .addOnSuccessListener { pendingDynamicLinkData ->
            val parameter: String =
                pendingDynamicLinkData?.link?.getQueryParameter("PARAMETER").orEmpty()
        }


问:
Cross site request error on calling api in Ionic 5
I am learning ionic and i have created a simple signup app in ionic 5.

I am getting this error when i try to call api for posting data.

```<code>Access to XMLHttpRequest at 'http://localhost:8888/php_project/mango/signup.php' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I tried by setting headers in my post request but still getting same error.
Here are the headers i am setting for post request:

```<code>'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, POST, GET, OPTIONS, DELETE',
</code>```

What else need to be done to call api from ionic.

答:
This is an issue caused by misconfigured same-origin policy. This policy prevents JavaScript from making requests across domain boundaries, and has spawned various hacks for making cross-domain requests.

To fix this, CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed.

Seems like you have PHP as your backend API. You will need to enable CORS on your backend to be able to connect from UI.

header("Access-Control-Allow-Origin: *");

This is a good start for local development. For more information: https://enable-cors.org/server_php.html

Body:
I am learning ionic and i have created a simple signup app in ionic 5.

I am getting this error when i try to call api for posting data.

Access to XMLHttpRequest at 'http://localhost:8888/php_project/mango/signup.php' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried by setting headers in my post request but still getting same error.
Here are the headers i am setting for post request:

'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, POST, GET, OPTIONS, DELETE',

What else need to be done to call api from ionic.


问:
Thymeleaf - output variable without a tag
I use Thymeleaf as a templating engine and I usually output variable value like this:

in Java I set:

```<code>ctx.setVariable("tester", "hello");
</code>```

and in html template I output:

```<code><span th:text="${tester}"></span>
</code>```

This works great, but I would like to output a variable without the need of a tag. Something following would be great:

```<code>${tester}
</code>```

Unfortunately it does not work. My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?

答:
Thymeleaf triggers on the "th:" tag and as far as I know thats the only way.
The behaviour you describe works with JSF.

Best regards

Ben

Body:
I use Thymeleaf as a templating engine and I usually output variable value like this:

in Java I set:

ctx.setVariable("tester", "hello");

and in html template I output:

This works great, but I would like to output a variable without the need of a tag. Something following would be great:

${tester}

Unfortunately it does not work. My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?


问:
Javascript Multidimensional Array complete column getting set
I am trying to make a game in Javascript. The game board is intialized to a zero-filled 2-D array. However, when I am setting the value of a single point, the complete column is getting set with that value. I think this is some issue with the way I am initializing the Array.

Method 1

```<code># initialization
gameState = Array(6).fill(Array(7).fill(0))

# later in the game
gameState[2][4] = 1

# results in complete 4th index column to be assigned the value 1, like so -
0: (7) [0, 0, 0, 0, 1, 0, 0]
1: (7) [0, 0, 0, 0, 1, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 1, 0, 0]
4: (7) [0, 0, 0, 0, 1, 0, 0]
5: (7) [0, 0, 0, 0, 1, 0, 0]
</code>```

Method 2

```<code># initialization
let gameState = [];
for (let i=0; i<MAX_ROWS; i++) {
    let row = []
    for (let j=0; j<MAX_COLUMNS; j++) {
       row.push(0)
    }
    gameState.push(row);
}

# again similar assignment
gameState[2][4] = 1

# results in correct state of the array
0: (7) [0, 0, 0, 0, 0, 0, 0]
1: (7) [0, 0, 0, 0, 0, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 0, 0, 0]
4: (7) [0, 0, 0, 0, 0, 0, 0]
5: (7) [0, 0, 0, 0, 0, 0, 0]
</code>```

Can someone please explain what I am doing wrong here?

答:
Your problem is pretty simple.

```<code>Array(6).fill(Array(7).fill(0))
</code>```

Let's explain what this does.

```<code>Array(6)
</code>```

creates a holey array with space for 6 items.

```<code>.fill(...)
</code>```

will fill up these 6 holes with what ever you put in as argument.

Now comes the issue..

In Javascript, the arguments are evaluated before the execution of the function is run.

This means (in this exact case where .fill(...) is only ran once) your code is exactly the same as:

```<code>const innerArray = [0,0,0,0,0,0,0];
gameState = Array(6).fill(innerArray);
</code>```

This means it fills the outer array with exactly the same array instance 6 times.

What you want is to create separate arrays each time. Just do this instead:

```<code>gameState = [...Array(6)].map(() => [...Array(7)].map(() => 0))
</code>```

Body:
I am trying to make a game in Javascript. The game board is intialized to a zero-filled 2-D array. However, when I am setting the value of a single point, the complete column is getting set with that value. I think this is some issue with the way I am initializing the Array.

Method 1

# initialization
gameState = Array(6).fill(Array(7).fill(0))

# later in the game
gameState[2][4] = 1

# results in complete 4th index column to be assigned the value 1, like so -
0: (7) [0, 0, 0, 0, 1, 0, 0]
1: (7) [0, 0, 0, 0, 1, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 1, 0, 0]
4: (7) [0, 0, 0, 0, 1, 0, 0]
5: (7) [0, 0, 0, 0, 1, 0, 0]

Method 2

# initialization
let gameState = [];
for (let i=0; i<MAX_ROWS; i++) {
    let row = []
    for (let j=0; j<MAX_COLUMNS; j++) {
       row.push(0)
    }
    gameState.push(row);
}

# again similar assignment
gameState[2][4] = 1

# results in correct state of the array
0: (7) [0, 0, 0, 0, 0, 0, 0]
1: (7) [0, 0, 0, 0, 0, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 0, 0, 0]
4: (7) [0, 0, 0, 0, 0, 0, 0]
5: (7) [0, 0, 0, 0, 0, 0, 0]

Can someone please explain what I am doing wrong here?

Body:
Your problem is pretty simple.

Array(6).fill(Array(7).fill(0))

Let's explain what this does.

Array(6)

creates a holey array with space for 6 items.

.fill(...)

will fill up these 6 holes with what ever you put in as argument.

Now comes the issue..

In Javascript, the arguments are evaluated before the execution of the function is run.

This means (in this exact case where .fill(...) is only ran once) your code is exactly the same as:

const innerArray = [0,0,0,0,0,0,0];
gameState = Array(6).fill(innerArray);

This means it fills the outer array with exactly the same array instance 6 times.

What you want is to create separate arrays each time. Just do this instead:

gameState = [...Array(6)].map(() => [...Array(7)].map(() => 0))


问:
C++ Localization best practices?
We are localizing a cross-platform C++-based client-side application. The first localization pass was done in a big rush for a big partner on a short deadline, and now it's time to refactor it.

We currently have an XML strings file per locale, with a common key and a localized value for each resource. However, sending our not-necessarily-technical localizers an xml file isn't ideal -- they don't know about encoding special characters, etc etc.  I'd like to use an easy, well-known format like Excel/csv with the localizers (also nice because we have server-side localization as well, which could be in a different tab of the same file), and then code-gen the strings files from there.  It seems that Excel doesn't like to output UTF-8 CSV files, which is annoying, and is preventing me from throwing together a few quick scripts to automate the Excel --> strings file conversion.

This problem has been solved hundreds of times.  What workflows have people found best, especially for cases where the localizers will be external to the company? I'm looking for something easy for non-technical users and also easy for the development team to then use to generate the strings file in some simple format like XML.

答:
This is an interesting topic. In the past i've handled outsourcing in a variety of ways

One time we just used simple text files in a prorietary format. We had a different file for each language. the format was like:

```<code> #LOCALIZATION_ID
 English String
</code>```

The localizers had no problem with that. Another thing I've used is a custom xls spreadsheet app. Basically the app posted its data via web services to a server. No need to have intermediate file formats such as csv. It is nice because all the strings are versioned and allow multiple outsources to work on the same strings file.

You should probably be able to write some vba that will take your excel spreadsheet and output a UTF-8 xml file that the outsourcer could email to you. A big button at the top of the sheet that says "SEND XML FILE".  and it would send it to either a predefined email address, or post it to your server. Worst case they could just email you the file itself.

OwnerDisplayName: Kevin Weil

Title: C++ Localization best practices?

Body:
This is an interesting topic. In the past i've handled outsourcing in a variety of ways

One time we just used simple text files in a prorietary format. We had a different file for each language. the format was like:

 #LOCALIZATION_ID
 English String

The localizers had no problem with that. Another thing I've used is a custom xls spreadsheet app. Basically the app posted its data via web services to a server. No need to have intermediate file formats such as csv. It is nice because all the strings are versioned and allow multiple outsources to work on the same strings file.

You should probably be able to write some vba that will take your excel spreadsheet and output a UTF-8 xml file that the outsourcer could email to you. A big button at the top of the sheet that says "SEND XML FILE".  and it would send it to either a predefined email address, or post it to your server. Worst case they could just email you the file itself.

OwnerDisplayName: Byron Whitlock

ContentLicense: CC BY-SA 2.5


问:
Serializing to JSON in jQuery
I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

```<code>var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
</code>```

and I need to turn this into a string to pass to $.ajax() like this:

```<code>$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...
</code>```

答:
I've been using jquery-json for 6 months and it works great.  It's very simple to use:</p>

```<code>var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}
</code>```

OwnerDisplayName: Herb Caudill

Title: Serializing to JSON in jQuery

Body:
I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...

LastEditorDisplayName: Herb Caudill

Body:
I've been using jquery-json for 6 months and it works great.  It's very simple to use:

var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}


问:
Summing values based on multiple criteria. Columns are different sizes
I have a Google Sheet (Test Sheet 2) with two sheets in it, Sheet 1 and Sheet 2.  Sheet 2 is where all of the data is and I need to get the sums of the counts of that column based on three criteria into sheet 1 column C.  The name, week, year and count need to match up.  I used the formula

```<code>=arrayformula(iferror(vlookup(A2:A&2020&B2:B, {Sheet2!A2:A&Sheet2!B2:B&Sheet2!C2:C, Sheet2!D2:D}, 2, FALSE)))
</code>```

but that only works for unique rows.  In the example sheet I am providing, the formula works well for Bill, Lisa, Katie and Jon because they all have one value for 'count' from Sheet2 when the parameters of name, week and year match up.  But Mike has two rows matching the criteria.  This formula returns the first match which is 3.  The other value is 4 so I would like the count in Sheet1 to show 7 instead of 3.  I need it to add them up.

I also tried to use sumifs but the columns are two different sizes so that didn't work.

Any idea? I did try to combine sumif with the above formula but that did not work either.

Link to Test Sheet

答:
Try this query()

```<code>=query(Sheet2!A:D, "Select A, C, sum(D) where B = 2020 group by A, C label C 'Week', sum(D) 'Count'", 1)
</code>```

UPDATED:

If you really need to use vlookup in arrayformula() you can always ise the query (that deals with the summing) as the lookup range. In the spreadsheet I used

```<code>=ArrayFormula(if(len(A2:A), iferror(vlookup(A2:A&year(D2:D)&E2:E, query({Sheet2!A:A&Sheet2!B:B&Sheet2!C:C, Sheet2!D:D}, "Select Col1, sum(Col2) where Col1 <>'' group by Col1", 1), 2, 0)),) )
</code>```

and see if that helps?

Body:
I have a Google Sheet (Test Sheet 2) with two sheets in it, Sheet 1 and Sheet 2.  Sheet 2 is where all of the data is and I need to get the sums of the counts of that column based on three criteria into sheet 1 column C.  The name, week, year and count need to match up.  I used the formula

=arrayformula(iferror(vlookup(A2:A&2020&B2:B, {Sheet2!A2:A&Sheet2!B2:B&Sheet2!C2:C, Sheet2!D2:D}, 2, FALSE)))

but that only works for unique rows.  In the example sheet I am providing, the formula works well for Bill, Lisa, Katie and Jon because they all have one value for 'count' from Sheet2 when the parameters of name, week and year match up.  But Mike has two rows matching the criteria.  This formula returns the first match which is 3.  The other value is 4 so I would like the count in Sheet1 to show 7 instead of 3.  I need it to add them up.

I also tried to use sumifs but the columns are two different sizes so that didn't work.

Any idea? I did try to combine sumif with the above formula but that did not work either.

Link to Test Sheet

Body:
Try this query()

=query(Sheet2!A:D, "Select A, C, sum(D) where B = 2020 group by A, C label C 'Week', sum(D) 'Count'", 1)

UPDATED:

If you really need to use vlookup in arrayformula() you can always ise the query (that deals with the summing) as the lookup range. In the spreadsheet I used

=ArrayFormula(if(len(A2:A), iferror(vlookup(A2:A&year(D2:D)&E2:E, query({Sheet2!A:A&Sheet2!B:B&Sheet2!C:C, Sheet2!D:D}, "Select Col1, sum(Col2) where Col1 <>'' group by Col1", 1), 2, 0)),) )

and see if that helps?


问:
How to pass function from Parent to Child when you already have proptypes in ReactJS
I am trying to pass a method as props to the child class.
Error: this.props.funcName is not a function.

```<code>class Poll extends Component {
  constructor(props) {
    super(props);

    this.state = {
      customPollReq: false,
      isPolling: false,
      customPollValues: [],
    };
    this.inputEditor = [];
    this.renderCustomMView = this.renderCustomMView.bind(this);
  }
.
.
.
renderCustomMView() {
    const { intl, startCustomPoll } = this.props;
    const isDisabled = _.compact(this.inputEditor).length < 1;
    if (this.inputEditor.length > 0) {
              Session.set('pollInitiated', true);
              this.setState({ isPolling: true }, () =>
              startCustomPoll('custom', _.compact(this.inputEditor)));
            }
render(){
        return(
            <div>
                <Video funcName={this.renderCustomMView} />
            </div>

const poll = Poll;
const withInjectIntl = injectIntl(Poll);
export { poll as Poll };
export default withModalMounter(withInjectIntl);

Poll.propTypes = {
  intl: PropTypes.shape({
    formatMessage: PropTypes.func.isRequired,
  }).isRequired,
  amIPresenter: PropTypes.bool.isRequired,
  pollTypes: PropTypes.instanceOf(Array).isRequired,
  startPoll: PropTypes.func.isRequired,
  startCustomPoll: PropTypes.func.isRequired,
  stopPoll: PropTypes.func.isRequired,
};

</code>```

Child

```<code>class VideoPlayer extends Component {
  constructor(props) {
    super(props);
.
.
.
    const { isPresenter } = props;
    this.newFuncCall = this.newFuncCall.bind(this);

.
.
.
newFuncCall(){
                console.log("12345");
                this.props.funcName();
        }

.
.
const video = VideoPlayer;
export {video as Video};
export default injectIntl(injectWbResizeEvent(VideoPlayer));

</code>```

When I try to call the function in my child class as "this.props.funcName()", it shows this.props.funcName is not a function. I am also using prop-types. Is it affecting the code? When I wrote a hello world program and implemented this child-parent inheritance, it worked well.

I am totally clueless.

this.props in Video Component

答: You passed it as funcName props. So you can call it this.props.funcName()

Body:
I am trying to pass a method as props to the child class.
Error: this.props.funcName is not a function.

class Poll extends Component {
  constructor(props) {
    super(props);

    this.state = {
      customPollReq: false,
      isPolling: false,
      customPollValues: [],
    };
    this.inputEditor = [];
    this.renderCustomMView = this.renderCustomMView.bind(this);
  }
.
.
.
renderCustomMView() {
    const { intl, startCustomPoll } = this.props;
    const isDisabled = _.compact(this.inputEditor).length < 1;
    if (this.inputEditor.length > 0) {
              Session.set('pollInitiated', true);
              this.setState({ isPolling: true }, () =>
              startCustomPoll('custom', _.compact(this.inputEditor)));
            }
render(){
        return(

                <Video funcName={this.renderCustomMView} />

const poll = Poll;
const withInjectIntl = injectIntl(Poll);
export { poll as Poll };
export default withModalMounter(withInjectIntl);

Poll.propTypes = {
  intl: PropTypes.shape({
    formatMessage: PropTypes.func.isRequired,
  }).isRequired,
  amIPresenter: PropTypes.bool.isRequired,
  pollTypes: PropTypes.instanceOf(Array).isRequired,
  startPoll: PropTypes.func.isRequired,
  startCustomPoll: PropTypes.func.isRequired,
  stopPoll: PropTypes.func.isRequired,
};

Child

class VideoPlayer extends Component {
  constructor(props) {
    super(props);
.
.
.
    const { isPresenter } = props;
    this.newFuncCall = this.newFuncCall.bind(this);

.
.
.
newFuncCall(){
                console.log("12345");
                this.props.funcName();
        }

.
.
const video = VideoPlayer;
export {video as Video};
export default injectIntl(injectWbResizeEvent(VideoPlayer));

When I try to call the function in my child class as "this.props.funcName()", it shows this.props.funcName is not a function. I am also using prop-types. Is it affecting the code? When I wrote a hello world program and implemented this child-parent inheritance, it worked well.

I am totally clueless.

this.props in Video Component


问:
The compiler doesnt show errors but I get no output. Whats wrong?
I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?

```<code>#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

bool PerfectCheck(int x) {

    int t; // divisor

    int sum; //  sum of divisors

    for (t = 0; t <= x; t++ ) {
        if (x%t == 0) {
            sum = sum + t;
        }
    }
    if (sum == x)
        return true;
    else
        return false;
}

int main() {

    srand(time(NULL));

    int x = rand()%(100-2+1)+2;

    if (PerfectCheck(x) == true )
        cout << x << "is a perfect number.";
    else
        cout << x << "is not a perfect number.";
    return 0;
}
</code>```

答:
if (x%t == 0) calculates the remainder after dividing x by t and compares the result with 0. That statement is correct, but look at the previous code for (t = 0; t <= x; t++ ) {. The first value of t is 0, so you have a division by zero. More than likely that is crashing your program which is why you see no output. Change for (t = 0; t <= x; t++ ) { to for (t = 1; t <= x; t++ ) {.

Also I believe the definition of a perfect number does not include division by the number itself. So the for loop should actually be for (t = 1; t < x; t++ ) {.

Finally you are using the sum variable to add up the divisors but you do not give it an initial value. Your code should say int sum = 0;.

Three errors in a ten line program (plus various style issues). Imagine how many errors here might be in a 5000 line program. Programming is tricky, you have to be very focused and get your code exactly right, nearly right is not good enough.

Body:
I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

bool PerfectCheck(int x) {

    int t; // divisor

    int sum; //  sum of divisors

    for (t = 0; t <= x; t++ ) {
        if (x%t == 0) {
            sum = sum + t;
        }
    }
    if (sum == x)
        return true;
    else
        return false;
}

int main() {

    srand(time(NULL));

    int x = rand()%(100-2+1)+2;

    if (PerfectCheck(x) == true )
        cout << x << "is a perfect number.";
    else
        cout << x << "is not a perfect number.";
    return 0;
}


问:
Redirect from default azure domain
I'm running an .NET Core 3.1 website (C#, Windows) on Azure (namewebsite.azurewebsites.net). I can't find any solution to redirect all traffic from namewebsite.azurewebsites.net to www.example.com. For example: when someone is visiting https://namewebsite.azurewebsites.net/profile/data, a permanent redirect should accomplished to https://www.example.com/profile/data. Any ideas?</p>

答:
i'm unsure about the exact requirements, but when it comes to redirecting, What you could do is edit the computes host.txt file and add a redirect there,

C:\Windows\System32\drivers\etc\hosts

https://en.wikipedia.org/wiki/Hosts_(file)

```<code>127.0.0.1  https://namewebsite.azurewebsites.net/profile/data
</code>```

https://www.online-tech-tips.com/computer-tips/edit-windows-hosts-file-to-block-redirect-websites/

Title: Redirect from default azure domain

Body:
i'm unsure about the exact requirements, but when it comes to redirecting, What you could do is edit the computes host.txt file and add a redirect there,

C:\Windows\System32\drivers\etc\hosts

https://en.wikipedia.org/wiki/Hosts_(file)

127.0.0.1  https://namewebsite.azurewebsites.net/profile/data

https://www.online-tech-tips.com/computer-tips/edit-windows-hosts-file-to-block-redirect-websites/


问:
Crop Functionality using FabricJs
How to implement crop tool on the image that is loaded on the canvas using fabric.js ?
I have a image loaded on the canvas .Now i want to implement crop tool where the user is allowed to crop the image and reload it on to the canvas when he is done.</p>

答:
I developed easy and faster cropping of image using latest fabric js version
https://github.com/kpomservices/Fabric-JS-Image-CROP

Demo: http://kpomservices.com/imagecropdemo/index.html

I used cropx, cropy for maintaining the crop.

Title: Crop Functionality using FabricJs


问:
Elixir: mix deps.get Request failed (403) and no cached copy
I am attempting to start using ratatouille in a project. This is,
I believe, the latest version of rataouille from github.

I started a new project for my learnings:

```<code>mix new rata_count
</code>```

In the ratatouille installation instructions I use the deps:

```<code>  defp deps do
    [{:ratatouille, "~> 0.5.0"} ]
  end
</code>```

Other than this deps code, the rest of mix.exs is as generated with "mix new rata_count". I have added no additional code to this project.

mix deps.get responds:

```<code>mix deps.get
Resolving Hex dependencies...
Dependency resolution completed:
New:
  asciichart 1.0.0
  elixir_make 0.6.0
  ex_termbox 1.0.1
  ratatouille 0.5.0
* Updating ratatouille (Hex package)
* Getting ex_termbox (Hex package)
Request failed (403)
** (Mix) Package fetch failed and no cached copy available (https://repo.hex.pm/tarballs/ex_termbox-1.0.1.tar)
</code>```

A search reveals nothing for this error.

I was able to compile and run the github examples of ratatouille. All the
examples worked as specified. Now I cannot seem to use rataouille
in my projects.

My system is Centos 7, elixir 1.9.4, Erlang/OTP 22 [erts-1-.4.3] 64 bits.

How do I resolve this error? Should I create a cached version? How do I create a cached version?

Is hex down?

答: I ran into this issue as well and nothing I tried fixed it. A day later, I tried running mix deps.get again and had no problems. So it may just be a server-side issue.

Body:
I am attempting to start using ratatouille in a project. This is,
I believe, the latest version of rataouille from github.

I started a new project for my learnings:

mix new rata_count

In the ratatouille installation instructions I use the deps:

  defp deps do
    [{:ratatouille, "~> 0.5.0"} ]
  end

Other than this deps code, the rest of mix.exs is as generated with "mix new rata_count". I have added no additional code to this project.

mix deps.get responds:

mix deps.get
Resolving Hex dependencies...
Dependency resolution completed:
New:
  asciichart 1.0.0
  elixir_make 0.6.0
  ex_termbox 1.0.1
  ratatouille 0.5.0
* Updating ratatouille (Hex package)
* Getting ex_termbox (Hex package)
Request failed (403)
** (Mix) Package fetch failed and no cached copy available (https://repo.hex.pm/tarballs/ex_termbox-1.0.1.tar)

A search reveals nothing for this error.

I was able to compile and run the github examples of ratatouille. All the
examples worked as specified. Now I cannot seem to use rataouille
in my projects.

My system is Centos 7, elixir 1.9.4, Erlang/OTP 22 [erts-1-.4.3] 64 bits.

How do I resolve this error? Should I create a cached version? How do I create a cached version?

Is hex down?


问:
Is it possible to find a memory leak using firebase performance?
ReactNative: 0.61.4

I am getting memory leak in my React Native app.
I found out what page it is, but I haven't found what the cause is.
In this situation, can use Firebase Performance Monitoring to find the cause of a memory leak?

```<code>this.trace = perf().newTrace('page1');
await this.trace.start();
</code>```

Firebase Performance Monitoring is inserted in this way.

However, when I use it in this way, I can see that the memory increases over time, but I can't find the cause.

In this case, which function of Firebase Performance Monitoring is suitable?

Is it a bad tool for finding memory leaks?

答: Firebase Performance Monitoring is not designed to detect memory leaks.  It's designed to measure the performance (speed) of code and HTTP requests.</p>

Body:
ReactNative: 0.61.4

I am getting memory leak in my React Native app.
I found out what page it is, but I haven't found what the cause is.
In this situation, can use Firebase Performance Monitoring to find the cause of a memory leak?

this.trace = perf().newTrace('page1');
await this.trace.start();

Firebase Performance Monitoring is inserted in this way.

However, when I use it in this way, I can see that the memory increases over time, but I can't find the cause.

In this case, which function of Firebase Performance Monitoring is suitable?

Is it a bad tool for finding memory leaks?