问:
Class not found on Laravel - Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Getting an error -  Class 'Ientry' not found on Laravel 5.6. while running page
localhost/work/i-upload-panel

My route.php code is below

```<code>Route::get('/i-upload-panel', function () {
    (new  Ientry())->importToDb();
        dd('done');
        return view('admin.i-upload-panel');
}
);
</code>```

Model Ientry.php

```<code><?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Ientry extends Model
{
     public function importToDb()
     {
        //Function here
     }
}

</code>```

答:
As you said it is model then you have to use a namespace with the model then you can create instance of that class.

```<code>(new App\Http\Model\Ientry())->importToDb();
</code>```

or

```<code>(new \App\Http\Model\Ientry())->importToDb();
</code>```

Body:
Getting an error -  Class 'Ientry' not found on Laravel 5.6. while running page
localhost/work/i-upload-panel

My route.php code is below

Route::get('/i-upload-panel', function () {
    (new  Ientry())->importToDb();
        dd('done');
        return view('admin.i-upload-panel');
}
);

Model Ientry.php

<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Ientry extends Model
{
     public function importToDb()
     {
        //Function here
     }
}

Body:
As you said it is model then you have to use a namespace with the model then you can create instance of that class.

(new App\Http\Model\Ientry())->importToDb();

or

(new \App\Http\Model\Ientry())->importToDb();


来源: stackexchange

问:
Change cell color based on selection from dropdown menu
This is a script I am writing to help me figure out how to write a more complex script.

In my spreadsheet, I have one column that contains a list of values ("testRange","testRangeValues"). I also have a dropdown list ("testCell","testCellValue"). The dropdown list contains some values that are in the "testRange" list and some that are not.

I would like my script to function in such a way that when I select a value from the dropdown list that matches value from the testRange list, the background color of the corresponding value in the testRange list changes to red.

function onEdit3(e) {

var testRange = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A4:A8");
var testRangeValues = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A4:A8").getValues();
var testCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("C4");
var testCellValue = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("C4").getValue();

for(var i = 0;i<testRange.length;i++){
if(testCellValue==testRangeValues[i]){
testRange[i].setBackground("Red");
}
}

}```

Currently no color change is happening. I guess I'm not quite sure how to correctly write my for loop/if statement to achieve the intended effect. Is there perhaps a way to do this using just some sort of conditional formatting formula in my spreadsheet?

答:
You want to change the background color of cell in the range of "A4:A8" that the value of dropdown list of "C4" is the same.

You want to achieve this using Google Apps Script.

From your script, you don't want to use the event object.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

The sheet object can be written by var sheet = SpreadsheetApp.getActiveSheet();. By this, you can use sheet for retrieving the range.

sheet.getRange("A4:A8") and sheet.getRange("C4") can be used one time.

In this case, the range object cannot be used in the loop, because testRange.length returns null.

When above points are reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, only background color of the selected value is changed to the red color. So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color. In this case, the background color of "A" is reset.

Modified script:

```<code>function onEdit3(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var testRange = sheet.getRange("A4:A8");
  var testRangeValues = testRange.getValues();
  var testCell = sheet.getRange("C4");
  var testCellValue = testCell.getValue();

  var backgroundColors = testRangeValues.map(function([a]) {return [a == testCellValue ? "Red" : ""]});
  testRange.setBackgrounds(backgroundColors);
}
</code>```

Pattern 2:

In this pattern, the background color of the selected value is saved. So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color. In this case, the background color of "A" is kept the red color.

Modified script:

```<code>function onEdit3(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var testRange = sheet.getRange("A4:A8");
  var testRangeValues = testRange.getValues();
  var testCell = sheet.getRange("C4");
  var testCellValue = testCell.getValue();

  for (var i = 0; i < testRangeValues.length; i++) {
    if (testRangeValues[i] == testCellValue) {
      sheet.getRange("A" + (4 + i)).setBackground("Red");
      break;
    }
  }
}
</code>```

Modern javascript:

You can use modern javascript syntax. For this you need to enable V8 runtime. After this you can

```<code>/**
 *
 * @param {GoogleAppsScript.Events.SheetsOnEdit} e
 */
const onEdit = e => {
  const sheet = e.range.getSheet();
  const value = e.range.getValue();
  if (sheet.getName() == 'Sheet1' && e.range.getA1Notation() === 'C2') {
    const range = sheet.getRange(2, 1, sheet.getLastRow() - 1, 1);
    range.setBackgrounds(
      range.getValues().map(row => [row[0] === value ? 'red' : ''])
    );
  }
};
</code>```

References:

setBackground(color)

setBackgrounds(color)

If I misunderstood your question and this was not the direction you want, I apologize.

ContentLicense: CC BY-SA 4.0

Body:
This is a script I am writing to help me figure out how to write a more complex script.

In my spreadsheet, I have one column that contains a list of values ("testRange","testRangeValues"). I also have a dropdown list ("testCell","testCellValue"). The dropdown list contains some values that are in the "testRange" list and some that are not.

I would like my script to function in such a way that when I select a value from the dropdown list that matches value from the testRange list, the background color of the corresponding value in the testRange list changes to red.

function onEdit3(e) {

var testRange = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A4:A8");
var testRangeValues = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A4:A8").getValues();
var testCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("C4");
var testCellValue = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("C4").getValue();

for(var i = 0;i<testRange.length;i++){
if(testCellValue==testRangeValues[i]){
testRange[i].setBackground("Red");
}
}

}

Currently no color change is happening. I guess I'm not quite sure how to correctly write my for loop/if statement to achieve the intended effect. Is there perhaps a way to do this using just some sort of conditional formatting formula in my spreadsheet?

Body:
You want to change the background color of cell in the range of "A4:A8" that the value of dropdown list of "C4" is the same.

You want to achieve this using Google Apps Script.

From your script, you don't want to use the event object.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

The sheet object can be written by var sheet = SpreadsheetApp.getActiveSheet();. By this, you can use sheet for retrieving the range.

sheet.getRange("A4:A8") and sheet.getRange("C4") can be used one time.

In this case, the range object cannot be used in the loop, because testRange.length returns null.

When above points are reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, only background color of the selected value is changed to the red color. So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color. In this case, the background color of "A" is reset.

Modified script:

function onEdit3(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var testRange = sheet.getRange("A4:A8");
  var testRangeValues = testRange.getValues();
  var testCell = sheet.getRange("C4");
  var testCellValue = testCell.getValue();

  var backgroundColors = testRangeValues.map(function([a]) {return [a == testCellValue ? "Red" : ""]});
  testRange.setBackgrounds(backgroundColors);
}

Pattern 2:

In this pattern, the background color of the selected value is saved. So for example, when "A" is selected, the background color of "A" is changed to the red color. And when "C" is selected, the background color of "C" is changed to the red color. In this case, the background color of "A" is kept the red color.

Modified script:

function onEdit3(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var testRange = sheet.getRange("A4:A8");
  var testRangeValues = testRange.getValues();
  var testCell = sheet.getRange("C4");
  var testCellValue = testCell.getValue();

  for (var i = 0; i < testRangeValues.length; i++) {
    if (testRangeValues[i] == testCellValue) {
      sheet.getRange("A" + (4 + i)).setBackground("Red");
      break;
    }
  }
}

Modern javascript:

You can use modern javascript syntax. For this you need to enable V8 runtime. After this you can

/**
 *
 * @param {GoogleAppsScript.Events.SheetsOnEdit} e
 */
const onEdit = e => {
  const sheet = e.range.getSheet();
  const value = e.range.getValue();
  if (sheet.getName() == 'Sheet1' && e.range.getA1Notation() === 'C2') {
    const range = sheet.getRange(2, 1, sheet.getLastRow() - 1, 1);
    range.setBackgrounds(
      range.getValues().map(row => [row[0] === value ? 'red' : ''])
    );
  }
};

References:

setBackground(color)

setBackgrounds(color)

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How to make regex work on corner case email address

Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

```<code>private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
</code>```

Most other corner cases work well with this regex, all of the below are rejected,

```<code>        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));
</code>```

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com

答:
You should use the MailAddress class, like this:

```<code>try {
    address = new MailAddress(address).Address;
} catch(FormatException) {
    //address is invalid
}
</code>```

If you use this approach to validate the e-mail address, be aware, that this MailAddress accepts the display name part of the e-mail address as well, and that may be not exactly what you want to achieve. For example, it accepts this strings as valid e-mail addresses:

"user1@hotmail.com; user2@gmail.com"

"user1@hotmail.com; user2@gmail.com; user3@company.com"

"User Display Name user3@company.com"

In these cases only the last part of the strings is parsed as the address, the rest before that is the display name. To get a plain e-mail address without any display name, you should check if the DisplayName property of the MailAddress instance is empty.

```<code>bool isValid = false;

try
{
    MailAddress address = new MailAddress(emailAddress);
    isValid = (string.IsNullOrEmpty(address.DisplayName));
    // or
    //isValid = ((address.User + "@" + address.Host) == emailAddress);
}
catch (FormatException)
{
    //address is invalid
}
</code>```

Furthermore an address having a dot at the end, like "user@company." is accepted by MailAddress either.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

Most other corner cases work well with this regex, all of the below are rejected,

        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com

Body:
You should use the MailAddress class, like this:

try {
    address = new MailAddress(address).Address;
} catch(FormatException) {
    //address is invalid
}

If you use this approach to validate the e-mail address, be aware, that this MailAddress accepts the display name part of the e-mail address as well, and that may be not exactly what you want to achieve. For example, it accepts this strings as valid e-mail addresses:

"user1@hotmail.com; user2@gmail.com"

"user1@hotmail.com; user2@gmail.com; user3@company.com"

"User Display Name user3@company.com"

In these cases only the last part of the strings is parsed as the address, the rest before that is the display name. To get a plain e-mail address without any display name, you should check if the DisplayName property of the MailAddress instance is empty.

bool isValid = false;

try
{
    MailAddress address = new MailAddress(emailAddress);
    isValid = (string.IsNullOrEmpty(address.DisplayName));
    // or
    //isValid = ((address.User + "@" + address.Host) == emailAddress);
}
catch (FormatException)
{
    //address is invalid
}

Furthermore an address having a dot at the end, like "user@company." is accepted by MailAddress either.


问:
How to compre DateTime with generic times in ruby
I'm working on a ruby on rails app that can automatically schedule events. Every event has a start_time datetime and an end_time datetime.

Here is the problem:

In general, events shouldn't be scheduled before 9:00am or after 10:30pm. This is true for edge cases as well. I.e, even if an event ends after 9:00am, it shouldn't start before it. Similarly, if an event starts before 10:30pm, it should not go on passed 10:30pm.

How can I go about making sure that every event fits this criteria, when some of these events are on different dates?

The problem i'm having is that, yes, a DateTime object has a date and a time associated with it. But so does a Time object.

This means that if I have an event with a start and end datetime between 9am and 10:30pm, my comparison will always return false if I'm comparing a time object with a datetime object of a different date.

Here is what I had in mind:

```<code>def event_out_of_bounds?(event_start_time, event_end_time, min_start_time, max_end_time)

if event_start_time.hour > max_end_time.hour then
  return true
end

if event_end_time.hour > max_end_time.hour then
  return true
end

if event_start_time.hour < min_start_time.hour then
  return true
end

if event_end_time.hour < min_start_time.hour then
  return true
end

return false

end
</code>```

Problems with this code:

It doesn't take into account minutes. I.e., if I ever change min_start_time to 9:30 am, then this method won't work anymore.

There are different dates involved. event_start_time and event_end_time, which are DateTimes, obviously have the same date. However, min_start_time and max_end_time, Which are created using Time.new have a different date (I just default it 2020-01-01). This wouldn't be a big problem if I knew beforehand what the dates would be for the events, however I won't in this case.

Any ideas for an algorithm to make this check elegantly?

答:
events shouldn't be scheduled before 9:00am or after 10:30pm.

I might use Range#cover? for this.

require 'active_support/all'

def validate_schedule(s, e)
  min = s.time_zone.local(s.year, s.month, s.day, 9, 0, 0)
  max = s.time_zone.local(s.year, s.month, s.day, 22, 30, 0)
  (min..max).cover?(s..e)
end

# Tests
et = ActiveSupport::TimeZone.new('Eastern Time (US & Canada)')
t = ->(d, h, m) { et.local(2020, 2, d, h, m, 0) }
test = ->(s, e) { puts format('%s %s = %s', s, e, validate_schedule(s, e)) }
test[t[1, 8, 59], t[1, 22, 30]] # false, start too early
test[t[1, 9, 0], t[1, 22, 30]] # true, 10:30 pm ok
test[t[1, 9, 0], t[1, 21, 30]] # true, 9:30 pm also ok
test[t[1, 9, 0], t[1, 22, 31]] # false, end too late
test[t[1, 9, 0], t[2, 22, 30]] # false, no all night parties
```

<p>If you allow multi-day events, simply calculate <code>max</code> from the end date (<code>e</code>) instead:</p>

<pre class="lang-rb prettyprint-override"><code>  max = e.time_zone.local(e.year, e.month, e.day, 22, 30, 0)
</code>```

Range.cover? works with "any objects that can be compared using the <=> operator." (see Custom Objects in Ranges

Body:
I'm working on a ruby on rails app that can automatically schedule events. Every event has a start_time datetime and an end_time datetime.

Here is the problem:

In general, events shouldn't be scheduled before 9:00am or after 10:30pm. This is true for edge cases as well. I.e, even if an event ends after 9:00am, it shouldn't start before it. Similarly, if an event starts before 10:30pm, it should not go on passed 10:30pm.

How can I go about making sure that every event fits this criteria, when some of these events are on different dates?

The problem i'm having is that, yes, a DateTime object has a date and a time associated with it. But so does a Time object.

This means that if I have an event with a start and end datetime between 9am and 10:30pm, my comparison will always return false if I'm comparing a time object with a datetime object of a different date.

Here is what I had in mind:

def event_out_of_bounds?(event_start_time, event_end_time, min_start_time, max_end_time)

if event_start_time.hour > max_end_time.hour then
  return true
end

if event_end_time.hour > max_end_time.hour then
  return true
end

if event_start_time.hour < min_start_time.hour then
  return true
end

if event_end_time.hour < min_start_time.hour then
  return true
end

return false

end

Problems with this code:

It doesn't take into account minutes. I.e., if I ever change min_start_time to 9:30 am, then this method won't work anymore.

There are different dates involved. event_start_time and event_end_time, which are DateTimes, obviously have the same date. However, min_start_time and max_end_time, Which are created using Time.new have a different date (I just default it 2020-01-01). This wouldn't be a big problem if I knew beforehand what the dates would be for the events, however I won't in this case.

Any ideas for an algorithm to make this check elegantly?

Body:
events shouldn't be scheduled before 9:00am or after 10:30pm.

I might use Range#cover? for this.

require 'active_support/all'

def validate_schedule(s, e)
  min = s.time_zone.local(s.year, s.month, s.day, 9, 0, 0)
  max = s.time_zone.local(s.year, s.month, s.day, 22, 30, 0)
  (min..max).cover?(s..e)
end

# Tests
et = ActiveSupport::TimeZone.new('Eastern Time (US & Canada)')
t = ->(d, h, m) { et.local(2020, 2, d, h, m, 0) }
test = ->(s, e) { puts format('%s %s = %s', s, e, validate_schedule(s, e)) }
test[t[1, 8, 59], t[1, 22, 30]] # false, start too early
test[t[1, 9, 0], t[1, 22, 30]] # true, 10:30 pm ok
test[t[1, 9, 0], t[1, 21, 30]] # true, 9:30 pm also ok
test[t[1, 9, 0], t[1, 22, 31]] # false, end too late
test[t[1, 9, 0], t[2, 22, 30]] # false, no all night parties

If you allow multi-day events, simply calculate max from the end date (e) instead:

  max = e.time_zone.local(e.year, e.month, e.day, 22, 30, 0)

Range.cover? works with "any objects that can be compared using the <=> operator." (see Custom Objects in Ranges


答:
It looks you're attempting to use an imported as opposed to a fully qualified reference to it. The route files don't normally have a namespace declaration, so the best bet would be to explicitly reference.

It would be something like:

```<code>(new \App\Model\Ientry())->importToDb();
</code>```

Title: Class not found on Laravel - Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)

Body:
It looks you're attempting to use an imported as opposed to a fully qualified reference to it. The route files don't normally have a namespace declaration, so the best bet would be to explicitly reference.

It would be something like:

(new \App\Model\Ientry())->importToDb();


问:
AWS openshift Multus CNI
I was going through the recent addition of the Multus network plugin to Openshift which help pod to have multiple network interfaces. So my question if we install openshift on AWS with the Multus plugin, Is this going to reduce the number of pods one instance if we use multiple network interfaces in pods. As the number of pod running on the instance depends on attached eni and that depends on the instance type</p>

答:
The usage of additional networks is not to reduce number of pods its mainly for situations where network isolation is needed, including data plane and control plane separation. Isolating network traffic is useful for the following performance and security reasons:

Performance

You can send traffic on two different planes in order to manage how much traffic is along each plane.

Security

You can send sensitive traffic onto a network plane that is managed specifically for security considerations, and you can separate private data that must not be shared between tenants or customers

Title: AWS openshift Multus CNI


问:
CheckBox are not working in ListItem rendered with Flatlist
I am using ListItems with checkbox. Every Item in the list contain the checkBox. I am not able to check or unCheck the checkbox and also not able to select all the checkbox in the listItems. I have made both functions with 'checkBoxTest()' and 'selectAll()' I think i am not using the setState correctly. Here is my code</p>

```<code>import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';

const list = [
  {
    name: 'PinkMan',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
    subtitle: 'Vice President'
  },
  {
    name: 'Mr White',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
    subtitle: 'Vice Chairman'
  },
]

export default class Members extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,

    }
  }
  selectAll(){
    this.setState({checked: !this.state.checked})
  }

  checkBoxTest() {
    this.setState({checked: !this.state.checked})
  }

  keyExtractor = (item, index) => index.toString()
  renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      subtitle={item.subtitle}
      leftAvatar={{
        source: item.avatar_url && { uri: item.avatar_url },
        title: item.name[0]
      }}
      checkBox={{
        checkedColor: '#744DD2',
        uncheckedColor: 'grey',
        onPress: this.checkBoxTest,
        checked: this.state.checked,
      }}
      bottomDivider
    />
  )

  render() {
    return(
      <>
        <View style={{ bottom: 60 }}>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={list}
            renderItem={this.renderItem}
          />
        </View>
        <View>
          <TouchableOpacity onPress={this.selectAll} >
            <Text style={styles.textStyle}>Select All</Text>
          </TouchableOpacity>
        </View>
      </>
    );
  }
}

</code>```

答:
Try passing extraData={this.state} to your FlatList component.

https://facebook.github.io/react-native/docs/flatlist#extradata

Edit:

You might want to just pass extraData={this.state.checked} instead. Your FlatList should only re-render when the checked state changes. Pass other props as needed.

Body:
I am using ListItems with checkbox. Every Item in the list contain the checkBox. I am not able to check or unCheck the checkbox and also not able to select all the checkbox in the listItems. I have made both functions with 'checkBoxTest()' and 'selectAll()' I think i am not using the setState correctly. Here is my code

import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';

const list = [
  {
    name: 'PinkMan',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
    subtitle: 'Vice President'
  },
  {
    name: 'Mr White',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
    subtitle: 'Vice Chairman'
  },
]

export default class Members extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,

    }
  }
  selectAll(){
    this.setState({checked: !this.state.checked})
  }

  checkBoxTest() {
    this.setState({checked: !this.state.checked})
  }

  keyExtractor = (item, index) => index.toString()
  renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      subtitle={item.subtitle}
      leftAvatar={{
        source: item.avatar_url && { uri: item.avatar_url },
        title: item.name[0]
      }}
      checkBox={{
        checkedColor: '#744DD2',
        uncheckedColor: 'grey',
        onPress: this.checkBoxTest,
        checked: this.state.checked,
      }}
      bottomDivider
    />
  )

  render() {
    return(
      <>
        <View style={{ bottom: 60 }}>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={list}
            renderItem={this.renderItem}
          />
        </View>
        <View>
          <TouchableOpacity onPress={this.selectAll} >
            <Text style={styles.textStyle}>Select All</Text>
          </TouchableOpacity>
        </View>
      </>
    );
  }
}


问:
react-native hellow world app - working in emulator but not in physical device
I'm new to React-native and i create my first hello world program. In android studio emulator it works fine.
Emulator shows

I used following commands

```<code>react-native start
react-native run-android
</code>```

But when i get the app-debug.apk file from output folder and install in my physical mobile phone it gives following error. (This is a screenshot)

Have i done wrong somewhere?

Thank you

答:
i suggest to use this steps to run your apk from this  answer

These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Step 3: Build your APK: react-native run-android

Body:
I'm new to React-native and i create my first hello world program. In android studio emulator it works fine.
Emulator shows

I used following commands

react-native start
react-native run-android

But when i get the app-debug.apk file from output folder and install in my physical mobile phone it gives following error. (This is a screenshot)

Have i done wrong somewhere?

Thank you


问:
How to transfer files between local machine and minikube?
I am using OS Ubuntu 16.0.4 and i installed minikube on it.
I need to copy some files to minikube, so how can i do that?
I tried next command but it asked me on password and i don't know it

```<code>scp /media/myuser/sourceFolder docker@192.168.99.100:/home/docker/destiationFolder
</code>```

Note: minikube IP is 192.168.99.100, and i used docker as default user for minikube but actually i don't know if it correct ot not.

So what is the default username and password for minikube and how can i copy files from my local machine into minikube?

Thanks :)

答:
if you have installed minikube Windows Host then you can find the ssh public & private keys for docker user (docker user is in the minikube vm)
in

```<code>C:\Users\{yourusername}\.minikube\machines\minikube
</code>```

on Windows Host.

The files are copied by minikube.exe during vm creation.

The files are id_rsa & id_rsa.pub.

Then open the id_rsa in puttygen and save the private key in .ppk format.

After that you can use the newly saved private key with Winscp.

Host name: ip-address of you minikube vm  { can get it with c:\minikube ip }

username: docker

port : 22

Go to Advanced ---> Advanced ----> SSH ----> Authentication ---->private key file

Then open...

Body:
I am using OS Ubuntu 16.0.4 and i installed minikube on it.
I need to copy some files to minikube, so how can i do that?
I tried next command but it asked me on password and i don't know it

scp /media/myuser/sourceFolder docker@192.168.99.100:/home/docker/destiationFolder

Note: minikube IP is 192.168.99.100, and i used docker as default user for minikube but actually i don't know if it correct ot not.

So what is the default username and password for minikube and how can i copy files from my local machine into minikube?

Thanks :)

Body:
if you have installed minikube Windows Host then you can find the ssh public & private keys for docker user (docker user is in the minikube vm)
in

C:\Users\{yourusername}\.minikube\machines\minikube

on Windows Host.

The files are copied by minikube.exe during vm creation.

The files are id_rsa & id_rsa.pub.

Then open the id_rsa in puttygen and save the private key in .ppk format.

After that you can use the newly saved private key with Winscp.

Host name: ip-address of you minikube vm  { can get it with c:\minikube ip }

username: docker

port : 22

Go to Advanced ---> Advanced ----> SSH ----> Authentication ---->private key file

Then open...


问:
How to sort a dictionary of [int: String] in Swift 5
I have an array that has integers as keys, and strings for values

```<code>var dictionary = [Int: String]()
</code>```

All of these try's either end in compile error for Swift 5:

```<code>dictionary = dictionary.keys.sorted()

dictionary = (dictionary.sorted{ $0.key < $1.key })

dictionary = dictionary.sorted { $0.0 < $1.0 } .map { $0.1 }

reverseSortedValues = dictionary.sorted { $0.0 > $1.0 } .map { $0.1 }

dictionary = profileImagesDictionary.sorted(by: { $0.0.compare($1.0) == .OrderedAscending })

dictionary = profileImagesDictionary.sorted { $0.key
</code>```

Code:

```<code>profileImagesDictionary = [Int : String](uniqueKeysWithValues: profileImagesDictionary.sorted{ $0.key > $1.key})
</code>```

Console Output printed keys

```<code>before: dictionary = [3, 1, 2, 4, 0]

after: dictionary = [3, 0, 2, 1, 4]
</code>```

I need it to rearrange the dictionary / actually sort it by keys.

So like instead of:

```<code>dictionary = [1: "a", 3: "c", 2: "b"]
</code>```

It after being sorted would be:

```<code>dictionary = [1: "a", 2: "b", 3: "c"]
</code>```

答:
Simply give the following code to print sorted keys.</p>

```<code>print(dictionary.keys.sorted)
</code>```

Body:
I have an array that has integers as keys, and strings for values

var dictionary = [Int: String]()

All of these try's either end in compile error for Swift 5:

dictionary = dictionary.keys.sorted()

dictionary = (dictionary.sorted{ $0.key < $1.key })

dictionary = dictionary.sorted { $0.0 < $1.0 } .map { $0.1 }

reverseSortedValues = dictionary.sorted { $0.0 > $1.0 } .map { $0.1 }

dictionary = profileImagesDictionary.sorted(by: { $0.0.compare($1.0) == .OrderedAscending })

dictionary = profileImagesDictionary.sorted { $0.key

Code:

profileImagesDictionary = [Int : String](uniqueKeysWithValues: profileImagesDictionary.sorted{ $0.key > $1.key})

Console Output printed keys

before: dictionary = [3, 1, 2, 4, 0]

after: dictionary = [3, 0, 2, 1, 4]

I need it to rearrange the dictionary / actually sort it by keys.

So like instead of:

dictionary = [1: "a", 3: "c", 2: "b"]

It after being sorted would be:

dictionary = [1: "a", 2: "b", 3: "c"]

Body:
Simply give the following code to print sorted keys.

print(dictionary.keys.sorted)


问:
Problem iterating through a struct and class to find the lowest priced item. My function did the opposite, it found the most expensive
I am new to stack overflow so any tips on how to improve questions would be very much appreciated. I am working on a homework project. This function, using pointers should iterate through the all the cars and find the lowest price. However, I am getting the highest value of the input file data and simply switch the less than or greater than sign does not suffice. One prints the highest value the latter prints out a memory address any advice? Here is a chunk of the first portion of the input file data: (There are two other blocks just like it in the input file, so a total of three chunks).

Hertz 93619
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1
```

```void findCheapestRental(RentalAgency *agencies){
RentalCar * leastExpensive;
RentalAgency * agenciesPtr = agencies;
RentalCar * invPtr = agenciesPtr->inventory;
leastExpensive = invPtr;

for(int i = 0;i < 3; i++, agenciesPtr++){
 for(int j = 0;j < 5; j++, invPtr++){
     if(invPtr->getPrice() < leastExpensive->getPrice()){
         leastExpensive = invPtr;
     }
 }
}
cout << "The least expensive car is: " << leastExpensive->getMake() << " " << leastExpensive->getModel() << " $" << leastExpensive->getPrice() << endl;
}
```

答:
Your code most likely has undefined behavior. I think you need to initialize invPtr in every iteration of the outer for loop.

```<code>for(int i = 0;i < 3; i++, agenciesPtr++){

   // Need this line
   invPtr = agenciesPtr->inventory;

   for(int j = 0;j < 5; j++, invPtr++){
      if(invPtr->getPrice() < leastExpensive->getPrice()){
         leastExpensive = invPtr;
      }
   }
}
</code>```

Body:
I am new to stack overflow so any tips on how to improve questions would be very much appreciated. I am working on a homework project. This function, using pointers should iterate through the all the cars and find the lowest price. However, I am getting the highest value of the input file data and simply switch the less than or greater than sign does not suffice. One prints the highest value the latter prints out a memory address any advice? Here is a chunk of the first portion of the input file data: (There are two other blocks just like it in the input file, so a total of three chunks).

Hertz 93619
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1

void findCheapestRental(RentalAgency *agencies){
RentalCar * leastExpensive;
RentalAgency * agenciesPtr = agencies;
RentalCar * invPtr = agenciesPtr->inventory;
leastExpensive = invPtr;

for(int i = 0;i < 3; i++, agenciesPtr++){
 for(int j = 0;j < 5; j++, invPtr++){
     if(invPtr->getPrice() < leastExpensive->getPrice()){
         leastExpensive = invPtr;
     }
 }
}
cout << "The least expensive car is: " << leastExpensive->getMake() << " " << leastExpensive->getModel() << " $" << leastExpensive->getPrice() << endl;
}

Body:
Your code most likely has undefined behavior. I think you need to initialize invPtr in every iteration of the outer for loop.

for(int i = 0;i < 3; i++, agenciesPtr++){

   // Need this line
   invPtr = agenciesPtr->inventory;

   for(int j = 0;j < 5; j++, invPtr++){
      if(invPtr->getPrice() < leastExpensive->getPrice()){
         leastExpensive = invPtr;
      }
   }
}


问:
Handling device communication and GUI updates separately in C#
I'm developing an application that scans images from connected scanners on well defined time intervals, say every 5 minutes, for a specified amount of time. While my app is running I have a label (timerlabel) counting down the total time of the project left, and this is handled by a DispatcherTimer which updates the label every second.

The scanners are handled by another DispatcherTimer which every five minutes will call a function Scan() for each scanner. When this function is called the scanning starts, but the GUI stops updating, and the timerlabel freezes for the duration of the scan. When it starts again it just keeps counting down, not having registered the time that elapsed when the scanning was in progress.

How can I make the timerlabel keep running while the scanning is in progress?

答:
Try spawning a background thread. Instead of havinhg your DispatchTimer call Scan() directly, have it call BeginInvoke() on a delegate or lambda that calls Scan(). Now, Scan() will run in a different thread, leaving the UI thread free to respond to graphics messages.

If Scan() will update UI controls, such as images or textbox text, you will need to have any such logic encapsulated in a delegate that you pass to your window's Invoke() method. This will prevent "cross-threading", which is dangerous when dealing with the UI and causes exceptions to be thrown by the runtime.


问:
What is location ID in Flipkart input payload?
I was trying to upload a listing in my Flipkart sandbox account which requires a payload as an input.
I am not able to figure out what is my location ID or where will I get it from my flipkart dashboard.
This is my JSON payload :

```<code>{
    "<sku>": {
        "product_id": "<product-id>",
        "price": {
            "mrp": 0,
            "selling_price": 0,
            "currency": "INR"
        },
        "tax": {
            "hsn": "<harmonized-system-nomenclature>",
            "tax_code" : "<tax-code to determine goods>"
        },
        "listing_status": "ACTIVE|INACTIVE",
        "shipping_fees": {
            "local": 0,
            "zonal": 0,
            "national": 0,
            "currency": "INR"
        },
        "fulfillment_profile": "NON_FBF|FBF_LITE|FBF",
        "fulfillment": {
            "dispatch_sla": 1,
            "shipping_provider": "FLIPKART|SELLER|FLIPKART_SELLER",
            "procurement_type": "REGULAR|EXPRESS|INTERNATIONAL|MADE_TO_ORDER|DOMESTIC"
        },
        "packages": [
            {
                "name": "<package-identifier>",
                "dimensions": {
                    "length": 1,
                    "breadth": 1,
                    "height": 1
                },
                "weight": 1,
                "description": "",
                "handling": {
                    "fragile": true
                },
                "notional_value": {
                    "amount": 1,
                    "unit": "PERCENTAGE|<CURRENCY>"
                }
            }
        ],
        "locations": [
            {
                "id": "<location-id>",
                "status": "ENABLED|DISABLED",
                "inventory": 0
            }
        ],
        "address_label": {
            "manufacturer_details": [
                "<address_of_manufacturer>"
            ],
            "importer_details": [
                "<address_of_importer>"
            ],
            "packer_details": [
                "<address_of_packer>"
            ],
            "countries_of_origin": [
                "<iso_alpha2_code_of_country_of_origin>"
            ]
        },
        "dating_label": {
            "mfg_date": "<Manufacturing date of the product in linux EPOCH (Seconds)>",
            "shelf_life": "<Shelf life of the product in Seconds>"
        }
    }
}
</code>```

This i what they need as the input.
https://seller.flipkart.com/api-docs/listing-api-docs/LMAPIRef.html. You may use this Flipkart Documentation.

答: Location ID is a unique ID provided to every seller for it's registered and dispatch addresses. If you have created the Flipkart seller account and want to use Flipkart Seller APIs, you will be needing the location ID for which you will have to contact the Flipkart API team. They will provide you the location ID. You can mail the Flipkart support team for the same.</p>

Body:
I was trying to upload a listing in my Flipkart sandbox account which requires a payload as an input.
I am not able to figure out what is my location ID or where will I get it from my flipkart dashboard.
This is my JSON payload :

{
    "<sku>": {
        "product_id": "<product-id>",
        "price": {
            "mrp": 0,
            "selling_price": 0,
            "currency": "INR"
        },
        "tax": {
            "hsn": "<harmonized-system-nomenclature>",
            "tax_code" : "<tax-code to determine goods>"
        },
        "listing_status": "ACTIVE|INACTIVE",
        "shipping_fees": {
            "local": 0,
            "zonal": 0,
            "national": 0,
            "currency": "INR"
        },
        "fulfillment_profile": "NON_FBF|FBF_LITE|FBF",
        "fulfillment": {
            "dispatch_sla": 1,
            "shipping_provider": "FLIPKART|SELLER|FLIPKART_SELLER",
            "procurement_type": "REGULAR|EXPRESS|INTERNATIONAL|MADE_TO_ORDER|DOMESTIC"
        },
        "packages": [
            {
                "name": "<package-identifier>",
                "dimensions": {
                    "length": 1,
                    "breadth": 1,
                    "height": 1
                },
                "weight": 1,
                "description": "",
                "handling": {
                    "fragile": true
                },
                "notional_value": {
                    "amount": 1,
                    "unit": "PERCENTAGE|<CURRENCY>"
                }
            }
        ],
        "locations": [
            {
                "id": "<location-id>",
                "status": "ENABLED|DISABLED",
                "inventory": 0
            }
        ],
        "address_label": {
            "manufacturer_details": [
                "<address_of_manufacturer>"
            ],
            "importer_details": [
                "<address_of_importer>"
            ],
            "packer_details": [
                "<address_of_packer>"
            ],
            "countries_of_origin": [
                "<iso_alpha2_code_of_country_of_origin>"
            ]
        },
        "dating_label": {
            "mfg_date": "<Manufacturing date of the product in linux EPOCH (Seconds)>",
            "shelf_life": "<Shelf life of the product in Seconds>"
        }
    }
}

This i what they need as the input.
https://seller.flipkart.com/api-docs/listing-api-docs/LMAPIRef.html. You may use this Flipkart Documentation.


问:
Combinations in Pandas Python
I have a dataframe where each row has a particular activity of a user:

```<code>UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House
</code>```

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

答:
I'm going to set the index to the "UserID", then we'll select just the users for which the condition returns True.

```<code>idf = df.set_index('UserID')
idf.loc[df.groupby(['UserID'])['Purchased'].apply(lambda x:
                                                  sorted(x)==['Car', 'Laptop'])]
</code>```

Result:

```<code>In [95]: idf.loc[df.groupby(['UserID'])['Purchased'].apply(lambda x: sorted(x)==['Car', 'Laptop'])]
Out[95]:
              Date Purchased
UserID
A       2020-02-01    Laptop
A       2020-02-01       Car
</code>```

Title: Combinations in Pandas Python

Body:
I have a dataframe where each row has a particular activity of a user:

UserID  Date    Purchased
A       1 feb   Laptop
B       2 Feb   Laptop
A       2 Feb   Car
B       2 Feb   House

Now I want to find the number of unique users who have purchased 2 different products (not more than 2) and their products should be 'Laptop' and 'Car'. So User A would be fall into this category. I have figured out how to get product count against each user but cant figure out how to filter user A.

Body:
I'm going to set the index to the "UserID", then we'll select just the users for which the condition returns True.

idf = df.set_index('UserID')
idf.loc[df.groupby(['UserID'])['Purchased'].apply(lambda x:
                                                  sorted(x)==['Car', 'Laptop'])]

Result:

In [95]: idf.loc[df.groupby(['UserID'])['Purchased'].apply(lambda x: sorted(x)==['Car', 'Laptop'])]
Out[95]:
              Date Purchased
UserID
A       2020-02-01    Laptop
A       2020-02-01       Car


问:
How to properly draw Residual Neural Network blocks with Graphviz?
I am trying to create a graph showing the ConvNet architecture with residual connections. I use the following graph definition.

```<code>digraph Model {
    node [shape=box];

    input [label="Input"];
    n1 [label="Conv2d(256, BN, ReLU)"];
    n2 [label="Conv2D(256, BN, ReLU)"];
    n3 [label="Conv2D(128, BN, ReLU)"];
    n4 [label="Conv2D(128, BN, ReLU)"];
    n5 [label="GlobalPool2d"];
    n6 [label="Flatten"];
    top [label="Dense(1, Sigmoid)"];

    add1 [label="Add"];
    add2 [label="Add"];

    input -> n1;
    n1 -> n2;
    n1 -> add1;
    n2 -> add1;
    add1 -> n3;

    n3 -> n4;
    n3 -> add2;
    n4 -> add2;
    add2 -> n5;

    n5 -> n6 -> top;
}
</code>```

The generated plot looks like the following image shows.

The problem is that the residual connections shift the convolution layers to the left. I wonder if it's possible to align the boxes by vertical axis? So all the layers are on the same vertical line and the residual connections go around. I've tried to do some manipulations with rank and rankdir but without any luck.

Could you help me with it? Or maybe point to the relevant part of the documentation where I can read how to properly do what I need?

答:
The weight attribute will do what you want.
Change two lines to:

```<code>   n1 -> add1 [weight=0];
   n3 -> add2 [weight=0];
</code>```

You'll get this:

Body:
I am trying to create a graph showing the ConvNet architecture with residual connections. I use the following graph definition.

digraph Model {
    node [shape=box];

    input [label="Input"];
    n1 [label="Conv2d(256, BN, ReLU)"];
    n2 [label="Conv2D(256, BN, ReLU)"];
    n3 [label="Conv2D(128, BN, ReLU)"];
    n4 [label="Conv2D(128, BN, ReLU)"];
    n5 [label="GlobalPool2d"];
    n6 [label="Flatten"];
    top [label="Dense(1, Sigmoid)"];

    add1 [label="Add"];
    add2 [label="Add"];

    input -> n1;
    n1 -> n2;
    n1 -> add1;
    n2 -> add1;
    add1 -> n3;

    n3 -> n4;
    n3 -> add2;
    n4 -> add2;
    add2 -> n5;

    n5 -> n6 -> top;
}

The generated plot looks like the following image shows.

The problem is that the residual connections shift the convolution layers to the left. I wonder if it's possible to align the boxes by vertical axis? So all the layers are on the same vertical line and the residual connections go around. I've tried to do some manipulations with rank and rankdir but without any luck.

Could you help me with it? Or maybe point to the relevant part of the documentation where I can read how to properly do what I need?

Body:
The weight attribute will do what you want.
Change two lines to:

   n1 -> add1 [weight=0];
   n3 -> add2 [weight=0];

You'll get this:


问:
How to get the local API url in custom command
I want to call the local API

I can access this from wget

wget http://localhost:8000/api/item

So the code below works

```<code>get_url_info = requests.get('http://localhost:8000/api/items')
print(get_url_info)
</code>```

However, url could be changed depending on server (ex http://localhost:8000/ -> http://localhost/

How should I access to the local API???

答:
You can do something like this:</p>

```<code># put all possible urls in a list:
urls = [ 'url1', 'url2', 'url3', ...]

# iterate over each url:
for url in urls:

    try:

        # try to access url:
        url_info = requests.get(url)

        # break out of the loop if successfull:
        break

    except:

        # continue to next url in list:
        pass
</code>```

Body:
I want to call the local API

I can access this from wget

wget http://localhost:8000/api/item

So the code below works

get_url_info = requests.get('http://localhost:8000/api/items')
print(get_url_info)

However, url could be changed depending on server (ex http://localhost:8000/ -> http://localhost/

How should I access to the local API???

Body:
You can do something like this:

# put all possible urls in a list:
urls = [ 'url1', 'url2', 'url3', ...]

# iterate over each url:
for url in urls:

    try:

        # try to access url:
        url_info = requests.get(url)

        # break out of the loop if successfull:
        break

    except:

        # continue to next url in list:
        pass


答: Here you have a Dictionary not an Array, to sort your dictionary based on your keys you could use let sortedKeys = Array(dictionary.keys).sort(<) , but it only contains keys in array

Title: How to sort a dictionary of [int: String] in Swift 5


问:
How to use sync token on Google People API
I cannot really find an example on how to use this.

Right now, I'm doing like this:

```<code>    // Request 10 connections.
    ListConnectionsResponse response = peopleService.people().connections()
            .list("people/me")
            .setRequestSyncToken(true)
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .execute();
</code>```

I make some changes to my contacts (adding, removing, updating), then I do this:

```<code>    // Request 10 connections.
    ListConnectionsResponse response2 = peopleService.people().connections()
            .list("people/me")
            .setSyncToken(response.getNextSyncToken())
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .execute();
</code>```

But it seems like I cannot get the changes I've done earlier, not even if I do them directly from the UI. I'm pretty sure I'm using the sync token in the wrong way.

Update (19/02/2020): In this example I call the API requesting the sync token in the first request (I successfully get the contacts), pause the execution (by breakpoint), delete a contact and update another one (from the web page), resume the execution and then I call the API again with the sync token that I extracted from the previous call. The result is that no change was made for some reason:

```<code>   // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    PeopleService peopleService = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    // Request 10 connections.
    ListConnectionsResponse response = peopleService.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .setRequestSyncToken(true)
            .execute();

    // Print display name of connections if available.
    List<Person> connections = response.getConnections();
    if (connections != null && connections.size() > 0) {
        for (Person person : connections) {
            List<Name> names = person.getNames();
            if (names != null && names.size() > 0) {
                System.out.println("Name: " + person.getNames().get(0)
                        .getDisplayName());
            } else {
                System.out.println("No names available for connection.");
            }
        }
    } else {
        System.out.println("No connections found.");
    }
    // CORRECT: 2 CONTACTS PRINTED

    // CORRECT: THE SYNC TOKEN IS THERE
    String syncToken = response.getNextSyncToken();
    System.out.println("syncToken = "+syncToken);

    // I SETUP A BREAKPOINT BELOW, I DELETE ONE CONTACT AND EDIT ANOTHER AND THEN I RESUME THE EXECUTING
    // Request 10 connections.
    response = peopleService.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .setSyncToken(syncToken)
            .execute();

    // Print display name of connections if available.
    connections = response.getConnections();
    if (connections != null && connections.size() > 0) {
        for (Person person : connections) {
            List<Name> names = person.getNames();
            if (names != null && names.size() > 0) {
                System.out.println("Name: " + person.getNames().get(0)
                        .getDisplayName());
            } else {
                System.out.println("No names available for connection.");
            }
        }
    } else {
        System.out.println("No connections found.");
    }
    // WRONG: I GET "NO CONNECTIONS FOUND"
</code>```

答:
Something I've found out is that, when requesting or setting a sync token, you must iterate the entirety of the contacts for the nextSyncToken to be populated.

That means that as long as there is a nextPageToken (wink wink setPageSize(10)), the sync token will not be populated.

You could either:

A) Loop over all the contacts using your current
     pagination, doing whatever you need to do at every
     iteration, and after the last call retrieve the populated
     sync token.

B) Iterate over all the contacts in one go, using the max
     page size of 2000 and a single personField, retrieve the
     token, and then do whatever you need to do. Note that if
     you are expecting a user to have more than 2000
     contacts, you will still need to call the next pages using
     the nextPageToken.

Here is an exemple of a sync loop, adapted from Synchronize Resources Efficiently. Note that I usually use the Python client, so this Java code might not be 100% error free:

```<code>private static void run() throws IOException {
    Request request = people_service.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses");

    // Load the sync token stored from the last execution, if any.
    // The syncSettingsDataStore is whatever you use for storage.
    String syncToken = syncSettingsDataStore.get(SYNC_TOKEN_KEY);

    String syncType = null;

    // Perform the appropiate sync
    if (syncToken == null) {
        // Perform a full sync
        request.setRequestSyncToken(true);
        syncType = "FULL";
    } else {
        // Try to perform an incremental sync.
        request.setSyncToken(syncToken);
        syncType = "INCREMENTAL";
    }

    String pageToken = null;
    ListConnectionsResponse response = null;
    List<Person> contacts = null;

    // Iterate over all the contacts, page by page.
    do {
        request.setPageToken(pageToken);

        try {
            response = request.execute();
        } catch (GoogleJsonResponseException e) {
            if (e.getStatusCode() == 410) {
                // A 410 status code, "Gone", indicates that the sync token is
                // invalid/expired.
                // WARNING: The code is 400 in the Python client. I think the
                //  Java client uses the correct code, but be on the lookout.

                // Clear the sync token.
                syncSettingsDataStore.delete(SYNC_TOKEN_KEY);
                // And anything else you need before re-syncing.
                dataStore.clear();
                // Restart
                run();
            } else {
              throw e;
            }
        }

        contacts = response.getItems();
        if (contacts.size() == 0) {
            System.out.println("No contacts to sync.");
        } else if (syncType == "FULL"){
            //do full sync for this page.
        } else if (syncType == "INCREMENTAL") {
            //do incremental sync for this page.
        } else {
            // What are you doing here???
        }

        pageToken = response.getNextPageToken();
    } while (pageToken != null);

    // Store the sync token from the last request for use at the next execution.
    syncSettingsDataStore.set(SYNC_TOKEN_KEY, response.getNextSyncToken());

    System.out.println("Sync complete.");
}
</code>```

Body:
I cannot really find an example on how to use this.

Right now, I'm doing like this:

    // Request 10 connections.
    ListConnectionsResponse response = peopleService.people().connections()
            .list("people/me")
            .setRequestSyncToken(true)
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .execute();

I make some changes to my contacts (adding, removing, updating), then I do this:

    // Request 10 connections.
    ListConnectionsResponse response2 = peopleService.people().connections()
            .list("people/me")
            .setSyncToken(response.getNextSyncToken())
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .execute();

But it seems like I cannot get the changes I've done earlier, not even if I do them directly from the UI. I'm pretty sure I'm using the sync token in the wrong way.

Update (19/02/2020): In this example I call the API requesting the sync token in the first request (I successfully get the contacts), pause the execution (by breakpoint), delete a contact and update another one (from the web page), resume the execution and then I call the API again with the sync token that I extracted from the previous call. The result is that no change was made for some reason:

   // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    PeopleService peopleService = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    // Request 10 connections.
    ListConnectionsResponse response = peopleService.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .setRequestSyncToken(true)
            .execute();

    // Print display name of connections if available.
    List<Person> connections = response.getConnections();
    if (connections != null && connections.size() > 0) {
        for (Person person : connections) {
            List<Name> names = person.getNames();
            if (names != null && names.size() > 0) {
                System.out.println("Name: " + person.getNames().get(0)
                        .getDisplayName());
            } else {
                System.out.println("No names available for connection.");
            }
        }
    } else {
        System.out.println("No connections found.");
    }
    // CORRECT: 2 CONTACTS PRINTED

    // CORRECT: THE SYNC TOKEN IS THERE
    String syncToken = response.getNextSyncToken();
    System.out.println("syncToken = "+syncToken);

    // I SETUP A BREAKPOINT BELOW, I DELETE ONE CONTACT AND EDIT ANOTHER AND THEN I RESUME THE EXECUTING
    // Request 10 connections.
    response = peopleService.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses")
            .setSyncToken(syncToken)
            .execute();

    // Print display name of connections if available.
    connections = response.getConnections();
    if (connections != null && connections.size() > 0) {
        for (Person person : connections) {
            List<Name> names = person.getNames();
            if (names != null && names.size() > 0) {
                System.out.println("Name: " + person.getNames().get(0)
                        .getDisplayName());
            } else {
                System.out.println("No names available for connection.");
            }
        }
    } else {
        System.out.println("No connections found.");
    }
    // WRONG: I GET "NO CONNECTIONS FOUND"

Body:
Something I've found out is that, when requesting or setting a sync token, you must iterate the entirety of the contacts for the nextSyncToken to be populated.

That means that as long as there is a nextPageToken (wink wink setPageSize(10)), the sync token will not be populated.

You could either:

A) Loop over all the contacts using your current
     pagination, doing whatever you need to do at every
     iteration, and after the last call retrieve the populated
     sync token.

B) Iterate over all the contacts in one go, using the max
     page size of 2000 and a single personField, retrieve the
     token, and then do whatever you need to do. Note that if
     you are expecting a user to have more than 2000
     contacts, you will still need to call the next pages using
     the nextPageToken.

Here is an exemple of a sync loop, adapted from Synchronize Resources Efficiently. Note that I usually use the Python client, so this Java code might not be 100% error free:

private static void run() throws IOException {
    Request request = people_service.people().connections()
            .list("people/me")
            .setPageSize(10)
            .setPersonFields("names,emailAddresses");

    // Load the sync token stored from the last execution, if any.
    // The syncSettingsDataStore is whatever you use for storage.
    String syncToken = syncSettingsDataStore.get(SYNC_TOKEN_KEY);

    String syncType = null;

    // Perform the appropiate sync
    if (syncToken == null) {
        // Perform a full sync
        request.setRequestSyncToken(true);
        syncType = "FULL";
    } else {
        // Try to perform an incremental sync.
        request.setSyncToken(syncToken);
        syncType = "INCREMENTAL";
    }

    String pageToken = null;
    ListConnectionsResponse response = null;
    List<Person> contacts = null;

    // Iterate over all the contacts, page by page.
    do {
        request.setPageToken(pageToken);

        try {
            response = request.execute();
        } catch (GoogleJsonResponseException e) {
            if (e.getStatusCode() == 410) {
                // A 410 status code, "Gone", indicates that the sync token is
                // invalid/expired.
                // WARNING: The code is 400 in the Python client. I think the
                //  Java client uses the correct code, but be on the lookout.

                // Clear the sync token.
                syncSettingsDataStore.delete(SYNC_TOKEN_KEY);
                // And anything else you need before re-syncing.
                dataStore.clear();
                // Restart
                run();
            } else {
              throw e;
            }
        }

        contacts = response.getItems();
        if (contacts.size() == 0) {
            System.out.println("No contacts to sync.");
        } else if (syncType == "FULL"){
            //do full sync for this page.
        } else if (syncType == "INCREMENTAL") {
            //do incremental sync for this page.
        } else {
            // What are you doing here???
        }

        pageToken = response.getNextPageToken();
    } while (pageToken != null);

    // Store the sync token from the last request for use at the next execution.
    syncSettingsDataStore.set(SYNC_TOKEN_KEY, response.getNextSyncToken());

    System.out.println("Sync complete.");
}


问:
highlight last 3 number in the string
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

```<code>$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '<b>$0</b>', $str);

</code>```

but it highlight:

ab9c5lek94ke72koe8nsk9

答:
You can achieve that easily using regular expression with PHP's preg_replace() function. Just find last 3 digits 3 times at the end of the string. See the following code:

```<code>$str1 = 'ab9c5lek94ke2koe8nsk9';
$str2 = 'dag2vue41a89au76zhz30';

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str1);
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str2);
</code>```

Outputs

ab9c5lek94ke2koe8nsk9

and

dag2vue41a89au76zhz30

Title: highlight last 3 number in the string

Body:
how to highlight last 3 number in the string:
ab9c5lek94ke72koe8nsk9

i want output:

ab9c5lek94ke72koe8nsk9

i tried following:

$str = "ab9c5lek94ke72koe8nsk9";
$numbers = preg_replace('/[^0-9]/', '', $str );
$last3 = substr($numbers, -3);
$highlights = str_split($last3);
$output = preg_replace('/'.implode('|', $highlights).'/i', '$0', $str);

but it highlight:

ab9c5lek94ke72koe8nsk9

Body:
You can achieve that easily using regular expression with PHP's preg_replace() function. Just find last 3 digits 3 times at the end of the string. See the following code:

$str1 = 'ab9c5lek94ke2koe8nsk9';
$str2 = 'dag2vue41a89au76zhz30';

echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str1);
echo preg_replace('/(\d)([^\d]*)(\d)([^\d]*)(\d)([^\d]*)$/mui', '<b>$1</b>$2<b>$3</b>$4<b>$5</b>$6', $str2);

Outputs

ab9c5lek94ke2koe8nsk9

and

dag2vue41a89au76zhz30


问:
How to right join a date table in T-SQL?
I have done RIGHT JOINS in the past with no problems.  However, for some reason now, I am not able successfully join a date table on the date field.  In summary, I have two tables.  The first table has one date column and a couple more non-date columns.  Then I have a date table, which just has two date columns.

I initialize this date table by inserting into it first of month dates for 13 consecutive months.  But my other table only has 9 months of data.

So table A looks like:

```<code>col_A    col_B     col_C
-----    ------    -------
sfds     jkjlj     7-1-2009
rewr     sfsfsd    5-1-2009
xcxvg    sdfsfk    4-1-2009
...
</code>```

But table B looks like:

```<code>StartDate   EndDate
---------   ---------
7-1-2009    7-31-2009
6-1-2009    6-30-2009
5-1-2009    5-31-2009
...
</code>```

But when I right join table B onto A like so:

```<code>    SELECT *
      FROM TABLE_A A
RIGHT JOIN TABLE_B B ON A.COL_C = B.StartDate
</code>```

I expect to get 12 months of data since Table_B has 13 months/records.  However, instead I am only getting 9 months total.  Does anybody understand why this would be?  And other things I might try to achieve the same result?

My main goal is to make Table_A include every month for past 13 months, even if there are null values.  Right now though, it just includes 9 months since there no records for the other 4 months.

答:
What I usually do when joining on dates is to convert them to integers first since joining on dates (1) often gives unexpected results, and (2) it is slow.

I would do the join like so:

```<code>Select *
From
TABLE_A A
Right Join
TABLE_B B
On
((Year(A.COL_C)*10000) + (Month(A.COL_C)*100) + Day(A.COL_C)) = ((Year(B.StartDate)*10000) + (Month(B.StartDate)*100) + Day(B.StartDate))
</code>```

However it seems you really want to join the year and month since the date on Table_A is always the 1st.
I would do that like so:

```<code>Select *
From
TABLE_A A
Right Join
TABLE_B B
On
((Year(A.COL_C)*100) + Month(A.COL_C)) = ((Year(B.StartDate)*100) + Month(B.StartDate))
</code>```

Hope this helps.

Body:
I have done RIGHT JOINS in the past with no problems.  However, for some reason now, I am not able successfully join a date table on the date field.  In summary, I have two tables.  The first table has one date column and a couple more non-date columns.  Then I have a date table, which just has two date columns.

I initialize this date table by inserting into it first of month dates for 13 consecutive months.  But my other table only has 9 months of data.

So table A looks like:

col_A    col_B     col_C
-----    ------    -------
sfds     jkjlj     7-1-2009
rewr     sfsfsd    5-1-2009
xcxvg    sdfsfk    4-1-2009
...

But table B looks like:

StartDate   EndDate
---------   ---------
7-1-2009    7-31-2009
6-1-2009    6-30-2009
5-1-2009    5-31-2009
...

But when I right join table B onto A like so:

    SELECT *
      FROM TABLE_A A
RIGHT JOIN TABLE_B B ON A.COL_C = B.StartDate

I expect to get 12 months of data since Table_B has 13 months/records.  However, instead I am only getting 9 months total.  Does anybody understand why this would be?  And other things I might try to achieve the same result?

My main goal is to make Table_A include every month for past 13 months, even if there are null values.  Right now though, it just includes 9 months since there no records for the other 4 months.

Body:
What I usually do when joining on dates is to convert them to integers first since joining on dates (1) often gives unexpected results, and (2) it is slow.

I would do the join like so:

Select *
From
TABLE_A A
Right Join
TABLE_B B
On
((Year(A.COL_C)*10000) + (Month(A.COL_C)*100) + Day(A.COL_C)) = ((Year(B.StartDate)*10000) + (Month(B.StartDate)*100) + Day(B.StartDate))

However it seems you really want to join the year and month since the date on Table_A is always the 1st.
I would do that like so:

Select *
From
TABLE_A A
Right Join
TABLE_B B
On
((Year(A.COL_C)*100) + Month(A.COL_C)) = ((Year(B.StartDate)*100) + Month(B.StartDate))

Hope this helps.


问:
Columns containing circles overlap vertically in Bootrap 4
I'm trying to achieve the look displayed in the image below with 'Bootstrap 4'. What I achieved is partly what I want, because there is too much vertical distance between the dots.

I first tried nesting the cols and then I used negative 'margins', but it didn't help move the circles vertically closer to each other. Is it even possible to make the 'cols' "overlap", or do I have to find another way to achieve the Look I want?

.block {
  text-align: center;
  vertical-align: middle;
}
.circle {
  background-color: darkred;
  color: white;
  border-radius: 200px;
  height: 110px;
  width: 110px;
  display: table;
  /* margin-bottom: -50px; */

}
.circle p {
  vertical-align: middle;
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Circles-->
  <div class="row no-gutters justify-content-center">
    <div class="col-lg-3 ">
      <div class="col-lg-2 block">
        <div class="circle   ">
          <p>Circle 1</p>
        </div>
      </div>
      <div class="col-lg-1 block offset-5">
        <div class="circle  ">
          <p>Circle 2</p>
        </div>
      </div>
      <div class="col-lg-1 block ">
        <div class="circle  ">
          <p>Circle 3</p>
        </div>
      </div>
      <div class="col-lg-1 block  offset-5 ">
        <div class="circle  ">
          <p>Circle 4</p>
        </div>
      </div>
      <div class="col-lg-1 block ">
        <div class="circle  ">
          <p>Circle 5</p>
        </div>
      </div>
<!-- Text-->
    </div>
    <div class="col-lg-7 ">
      <p>
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
        dolore magna aliquyam erat, sed diam voluptua.
      </p>
    </div>
  </div></code>```

答:
You can achieve by Bootstrap4 predefined classes.

Take a div and define class="d-flex justify-content-center align-items-center" & inside this div take two another div with class="col-5 px-0" so in left side div define circle div 1,3,5 and right side div define circle div 2,4,

For .circle define width:100%, height:0, so height will auto equal to width from this padding technique like padding-top: 50% & padding-bottom: 50% so from this technique to circle will responsive and resize as per parent div width.

.circle {
  background-color: #E94954;
  color: #fff;
  border-radius: 50%;
  margin-bottom: 15px;
  height: 0;
  width: 100%;
  padding-top: 50%;
  padding-bottom: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.circle p{
  margin: 0;
  font-size: 90%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class="container my-3">
  <div class="row no-gutters justify-content-center">
    <div class="col-sm-5 col-md-4 col-lg-3">
      <div class="d-flex justify-content-center align-items-center">
        <div class="col-5 px-0">
          <div class="circle">
            <p>Circle 1</p>
          </div>
          <div class="circle">
            <p>Circle 3</p>
          </div>
          <div class="circle">
            <p>Circle 5</p>
          </div>
        </div>
        <div class="col-5 px-0">
          <div class="circle">
            <p>Circle 2</p>
          </div>
          <div class="circle">
            <p>Circle 4</p>
          </div>
        </div>
      </div>
    </div>
    <div class="col-sm-7 col-md-8 col-lg-7">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        <br>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
  </div>
</div></code>```

Body:
I'm trying to achieve the look displayed in the image below with 'Bootstrap 4'. What I achieved is partly what I want, because there is too much vertical distance between the dots.

I first tried nesting the cols and then I used negative 'margins', but it didn't help move the circles vertically closer to each other. Is it even possible to make the 'cols' "overlap", or do I have to find another way to achieve the Look I want?

.block {
  text-align: center;
  vertical-align: middle;
}
.circle {
  background-color: darkred;
  color: white;
  border-radius: 200px;
  height: 110px;
  width: 110px;
  display: table;
  /* margin-bottom: -50px; */

}
.circle p {
  vertical-align: middle;
  display: table-cell;
}

Circle 1

Circle 2

Circle 3

Circle 4

Circle 5

        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
        dolore magna aliquyam erat, sed diam voluptua.

Body:
You can achieve by Bootstrap4 predefined classes.

Take a div and define class="d-flex justify-content-center align-items-center" & inside this div take two another div with class="col-5 px-0" so in left side div define circle div 1,3,5 and right side div define circle div 2,4,

For .circle define width:100%, height:0, so height will auto equal to width from this padding technique like padding-top: 50% & padding-bottom: 50% so from this technique to circle will responsive and resize as per parent div width.

.circle {
  background-color: #E94954;
  color: #fff;
  border-radius: 50%;
  margin-bottom: 15px;
  height: 0;
  width: 100%;
  padding-top: 50%;
  padding-bottom: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.circle p{
  margin: 0;
  font-size: 90%;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class="container my-3">
  <div class="row no-gutters justify-content-center">
    <div class="col-sm-5 col-md-4 col-lg-3">
      <div class="d-flex justify-content-center align-items-center">
        <div class="col-5 px-0">
          <div class="circle">
            <p>Circle 1</p>
          </div>
          <div class="circle">
            <p>Circle 3</p>
          </div>
          <div class="circle">
            <p>Circle 5</p>
          </div>
        </div>
        <div class="col-5 px-0">
          <div class="circle">
            <p>Circle 2</p>
          </div>
          <div class="circle">
            <p>Circle 4</p>
          </div>
        </div>
      </div>
    </div>
    <div class="col-sm-7 col-md-8 col-lg-7">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        <br>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
  </div>
</div>


问:
How to navigate to a new page when a grid is tapped in flutter?
This is a part of code from an app under development , I have created dart file for each of the item present in the list but i don't know how to give onpress function on the  list so that it will navigate me to next page

Here is the code

```<code>class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            );
          }).toList()),
    );
  }
}

</code>```

I want to navigate to the new page when each item is tapped by the user. How to navigate it?

答:
```<code>class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return GestureDetector(
              onTap: (){
                Navigator.push(context,MaterialPageRoute(builder: (context)=> *your_new_route_page*))
              },
              child: Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            )
            );
          }).toList()),
    );
  }
}
</code>```

What you only need to do is Wrap your "returned Container inside your GridView.count" in a GestureDetector

Body:
This is a part of code from an app under development , I have created dart file for each of the item present in the list but i don't know how to give onpress function on the  list so that it will navigate me to next page

Here is the code

class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            );
          }).toList()),
    );
  }
}

I want to navigate to the new page when each item is tapped by the user. How to navigate it?

Body:
class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return GestureDetector(
              onTap: (){
                Navigator.push(context,MaterialPageRoute(builder: (context)=> *your_new_route_page*))
              },
              child: Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            )
            );
          }).toList()),
    );
  }
}

What you only need to do is Wrap your "returned Container inside your GridView.count" in a GestureDetector


问:
Haskell trying to understand typeclass syntax
I am new to Haskell and I am trying to understand the syntax. I have data type Vec and it implements Show, Floating and Foldable. But the syntax is different for Foldable, why?

```<code>data Vec a = Vec [a]

instance Show a => Show (Vec a) where
   show (Vec x) = show x

instance Floating a => Floating (Vec a) where
  pi = Vec (repeat pi)
  exp (Vec x) = Vec (map exp x)
  log (Vec x) = Vec (map log x)
  sin (Vec x) = Vec (map sin x)
  cos (Vec x) = Vec (map cos x)

instance Foldable Vec where
  foldr f x (Vec y) = foldr f x y
</code>```

答:
Your instance for Foldable is "self-contained", it does not depend on the availability of other instances (of this or a different type class).

But for your instance of Show (Vec a) you also need an instance of Show a first (so that you can in your implementation call show x).

That => syntax establishes this requirement/dependency.

Body:
I am new to Haskell and I am trying to understand the syntax. I have data type Vec and it implements Show, Floating and Foldable. But the syntax is different for Foldable, why?

data Vec a = Vec [a]

instance Show a => Show (Vec a) where
   show (Vec x) = show x

instance Floating a => Floating (Vec a) where
  pi = Vec (repeat pi)
  exp (Vec x) = Vec (map exp x)
  log (Vec x) = Vec (map log x)
  sin (Vec x) = Vec (map sin x)
  cos (Vec x) = Vec (map cos x)

instance Foldable Vec where
  foldr f x (Vec y) = foldr f x y


问:
Proper values for gluPerspective() or glFrustum()
I've been using gluPerspective and somewhat have a grasp on what it's doing and how it works. But I still don't quite understand how to use it for any effect beyond that of where it starts and stops. changing the zfar and znear never seems to affect anything much. Am I missing a cool effect? what are some ranges of values and what visual distortions can you do?

答:
The geometric meaning of the projection matrix in the OpenGL function GLFrustum(), which was explained in the  official guide of OpenGL (the nineth edition of the book, OpenGL programming guide-- the official guide to learning OpenGL), from an algebraic point of view, actually corresponds to many geometric meanings that are unluckily different from what the authors expected.

A significant difference between them are:
1. in the official guide, the authors are illustrating a compound linear transform with one of its factors as central projection, so the final compound perspective projecction matrix should be a singular or degenerated matrix;
2. while still in the official guide, at the appendix, the GLFrustum() perspective projection matrix is a nonsingular 4 times 4 square matrix!

Note that: The authors are trying to explain a nonsingular matrix into a theoretically singular one!

The following matrix decomposition (not unique) corresponds to one of the geometric meanings of the nonsingualr GLFrustum() matrix:

enter image description here

All of the above matrix factors except for No. (2), have their geoemtric meaning clearly redefined in Unified Framework of Elementary Geometric Transformations. If you choose this factorization as the geometric meaning explanation of the GLFrustum() perspective projection matrix, you will have to make sure any computation or transforms you are doing in your code are consistent to its geometric meaning.

So when you are programming with OpenGL GLFrustum(), probably may have to compare with what has been illustrated in the official guide and what the GLFrustum() perspective projection matrix really means from the view point of pure algebraic projective geometry, and use any one of your own.


问:
Manipulation with large dimensional matrix in R
I would like to calculate the following function for each row of a matrix M of dimension 3e+07x4.

```<code>func <- function(x){

   (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)

}
</code>```

I am using the following code

```<code>as.numeric(unlist(apply(M, 1, function(v) func(v))))
</code>```

Unfortunately, it is taking a long time. I'd like to do this in a short time.

答:
Something like this, but I haven't verified the correctness.  Your:

```<code>func <- function(x) {
  (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)
}
</code>```

can be written as:

```<code>func <- function(x) {
  a <- x[c(1,2)]
  b <- 50 - (a[1] + a[2])
  d <- c(a, b)
  e <- dmultinom(d, size = NULL, rep(1/3,3), log = FALSE)
  f <- x[3]^2 + x[4]^3
  e / f
}
</code>```

The d part you can vectorize via matrix calculations as:

```<code>A <- M[, 1:2]
B <- 50 - (A[,1] + A[,2])
D <- cbind(A, B)
</code>```

Without diving into dmultinom(), the e part can be calculated via apply() as:

```<code>prob <- rep(1/3, times = 3L)
E <- apply(D, MARGIN = 1L, function(d) {
  dmultinom(d, size = NULL, prob = prob, log = FALSE)
})
</code>```

The f part you can vectorize via matrix calculations as:

```<code>F <- M[,3]^2 + M[,4]^3
</code>```

which gives that:

```<code>Y <- apply(M, 1, function(v) func(v))
</code>```

can be written as:

```<code>Y <- E / F
</code>```

Disclaimer: Haven't verified but you should get the idea of how to vectorize and avoid duplicate things.

PS. If you look at dmultinom(), I think you can vectorize that as well in a similar fashion.  It's not unlikely that you can get rid of the remaining apply() call.

Body:
I would like to calculate the following function for each row of a matrix M of dimension 3e+07x4.

func <- function(x){

   (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)

}

I am using the following code

as.numeric(unlist(apply(M, 1, function(v) func(v))))

Unfortunately, it is taking a long time. I'd like to do this in a short time.

Body:
Something like this, but I haven't verified the correctness.  Your:

func <- function(x) {
  (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)
}

can be written as:

func <- function(x) {
  a <- x[c(1,2)]
  b <- 50 - (a[1] + a[2])
  d <- c(a, b)
  e <- dmultinom(d, size = NULL, rep(1/3,3), log = FALSE)
  f <- x[3]^2 + x[4]^3
  e / f
}

The d part you can vectorize via matrix calculations as:

A <- M[, 1:2]
B <- 50 - (A[,1] + A[,2])
D <- cbind(A, B)

Without diving into dmultinom(), the e part can be calculated via apply() as:

prob <- rep(1/3, times = 3L)
E <- apply(D, MARGIN = 1L, function(d) {
  dmultinom(d, size = NULL, prob = prob, log = FALSE)
})

The f part you can vectorize via matrix calculations as:

F <- M[,3]^2 + M[,4]^3

which gives that:

Y <- apply(M, 1, function(v) func(v))

can be written as:

Y <- E / F

Disclaimer: Haven't verified but you should get the idea of how to vectorize and avoid duplicate things.

PS. If you look at dmultinom(), I think you can vectorize that as well in a similar fashion.  It's not unlikely that you can get rid of the remaining apply() call.