问:
Inconsistent behavior concatenating lists and tuples in python
I noticed a surprising behavior when trying to concatenate lists and tuples.

Usually, they don't mix:

```<code>(0, 1) + [2, 3]
</code>```

results in:

TypeError: can only concatenate tuple (not "list") to tuple

and, vice versa

```<code>[0, 1] + (2, 3)
</code>```

gives:

TypeError: can only concatenate list (not "tuple") to list

So far, nothing was unexpected.
However, if you use a variable assignment via "+=", the behavior for lists changes!

```<code>l = [0, 1]
l += (2, 3)
l
</code>```

gives

[0, 1, 2, 3]

But not for tuples:

```<code>t = (0, 1)
t += [2, 3]
t
</code>```

still produces an error:

TypeError: can only concatenate tuple (not "list") to tuple

Of course, there is no practical problem here, but I'm curious:
What's going on there?

答:
Each part on its own makes sense, putting it all together as you have happens to reveal inconsistencies.

Tuples define __add__ and accept other tuples to be concatenated together. Makes sense, you can add two things of the same type together. Same thing for lists, you can + two lists together.

Tuples are immutable, so they don't define an __iadd__ (+=).

Lists are mutable and define an extend method, which accepts any iterable. So you can do things like:

```<code>lst.extend(map(str, range(42)))
</code>```

Neat and convenient. += is basically an alias for that.

So:

tuple + tuple works

list + list works

tuple + list doesn't work, because they're different types

list + tuple also doesn't work, as expected

list.extend/list += works with any iterable, including tuples

+= on tuples is executed as a = a + b because they're immutable, so doesn't work if a and b are of different types

Body:
I noticed a surprising behavior when trying to concatenate lists and tuples.

Usually, they don't mix:

(0, 1) + [2, 3]

results in:

TypeError: can only concatenate tuple (not "list") to tuple

and, vice versa

[0, 1] + (2, 3)

gives:

TypeError: can only concatenate list (not "tuple") to list

So far, nothing was unexpected.
However, if you use a variable assignment via "+=", the behavior for lists changes!

l = [0, 1]
l += (2, 3)
l

gives

[0, 1, 2, 3]

But not for tuples:

t = (0, 1)
t += [2, 3]
t

still produces an error:

TypeError: can only concatenate tuple (not "list") to tuple

Of course, there is no practical problem here, but I'm curious:
What's going on there?

Body:
Each part on its own makes sense, putting it all together as you have happens to reveal inconsistencies.

Tuples define __add__ and accept other tuples to be concatenated together. Makes sense, you can add two things of the same type together. Same thing for lists, you can + two lists together.

Tuples are immutable, so they don't define an __iadd__ (+=).

Lists are mutable and define an extend method, which accepts any iterable. So you can do things like:

lst.extend(map(str, range(42)))

Neat and convenient. += is basically an alias for that.

So:

tuple + tuple works

list + list works

tuple + list doesn't work, because they're different types

list + tuple also doesn't work, as expected

list.extend/list += works with any iterable, including tuples

+= on tuples is executed as a = a + b because they're immutable, so doesn't work if a and b are of different types


来源: stackexchange

问:
2 angular material cards next to each other?
I want to have 2 angular material cards next to each other but I don't know how.

HTML

```<code><mat-card id="moth-card">
  <mat-card-title>Live Stats</mat-card-title>
  <app-card></app-card>
  <app-card></app-card>
</mat-card>
</code>```

At the moment the second one is under the first one.

答:
Try below CSS:

```<code>display: inline-block;
</code>```

HTML Code:

```<code><mat-card id="moth-card">
  <mat-card-title>Live Stats</mat-card-title>
 <mat-card class="inline-block">
   Part 1
 </mat-card>
 <mat-card class="inline-block">
   Part 2
 </mat-card>
</mat-card>
</code>```

CSS:

```<code>.inline-block {
  display: inline-block;
}
</code>```

Working_Demo

ContentLicense: CC BY-SA 4.0

Body:
I want to have 2 angular material cards next to each other but I don't know how.

HTML

<mat-card id="moth-card">
  <mat-card-title>Live Stats</mat-card-title>
  <app-card></app-card>
  <app-card></app-card>
</mat-card>

At the moment the second one is under the first one.

Body:
Try below CSS:

display: inline-block;

HTML Code:

<mat-card id="moth-card">
  <mat-card-title>Live Stats</mat-card-title>
 <mat-card class="inline-block">
   Part 1
 </mat-card>
 <mat-card class="inline-block">
   Part 2
 </mat-card>
</mat-card>

CSS:

.inline-block {
  display: inline-block;
}

Working_Demo


问:
node.js out of memory after file upload complete
I have a web-server running on an embedded linux running on an armv7 SBC (Atmel SAMA5D27-SOM with 128MB RAM).

The firmware update process requires a .tar.gz file to be uploaded via this interface, then untarred/unzipped and further processes run on it.

After successful upload using busboy module, I noticed that the memory usage is still high (see attached image) even though the upload is streamed directly into a file (code below).

Further processes implemented with the child_processes after the file upload are then killed due to the system being out of memory.

I have implemented the --max-old-size-space-size flag to = 32MB as i've read this sets a lower threshold for when the GC starts.

I have tried various methods of using child_processes APIs including:
1. execSync
2. async exec (as described in node.js docs)
3. spawn with {detached: true}

```<code>/* imports omitted for brevity */

module.exports = async (req, res, next) => { // eslint-disable-line no-unused-vars
  try {

    /* File validation omitted for brevity */

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      /* Further file validation omitted for brevity,
         File transfer debugging omitted for brevity */

      // Handle saving file stream to file
      const saveTo = path.join(updatesDir, path.basename(filename));
      file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', () => {
      return res.json({ updateFilename });
    });

    // This is required stream req progress back to browser
    return req.pipe(busboy);
  } catch (error) {
    console.error(error)
    next(error);
  }
}
</code>```

I understand that node.js uses a garbage collector, however the memory taken for the file upload isn't freed for later processes to use.

Is there something wrong with how I am streaming the file upload to a file?
Why is Node.js not releasing the memory?
Is there a way to trigger GC manually in this instance?

答:
Further testing reveal that the embedded linux system didn't include swap memory by default. I created a swap file and made it the same size as the systems RAM (128MB). Later I increased this to give extra overhead due to extra space availble on the SD Card.

This allows linux to manage the OOM issue automatically by moving non-critical memory usage onto disc. This process did slow down the upload by an extra few seconds but it did stop all OOM memory issues.

Body:
I have a web-server running on an embedded linux running on an armv7 SBC (Atmel SAMA5D27-SOM with 128MB RAM).

The firmware update process requires a .tar.gz file to be uploaded via this interface, then untarred/unzipped and further processes run on it.

After successful upload using busboy module, I noticed that the memory usage is still high (see attached image) even though the upload is streamed directly into a file (code below).

Further processes implemented with the child_processes after the file upload are then killed due to the system being out of memory.

I have implemented the --max-old-size-space-size flag to = 32MB as i've read this sets a lower threshold for when the GC starts.

I have tried various methods of using child_processes APIs including:
1. execSync
2. async exec (as described in node.js docs)
3. spawn with {detached: true}

/* imports omitted for brevity */

module.exports = async (req, res, next) => { // eslint-disable-line no-unused-vars
  try {

    /* File validation omitted for brevity */

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      /* Further file validation omitted for brevity,
         File transfer debugging omitted for brevity */

      // Handle saving file stream to file
      const saveTo = path.join(updatesDir, path.basename(filename));
      file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', () => {
      return res.json({ updateFilename });
    });

    // This is required stream req progress back to browser
    return req.pipe(busboy);
  } catch (error) {
    console.error(error)
    next(error);
  }
}

I understand that node.js uses a garbage collector, however the memory taken for the file upload isn't freed for later processes to use.

Is there something wrong with how I am streaming the file upload to a file?
Why is Node.js not releasing the memory?
Is there a way to trigger GC manually in this instance?


问:
Troubles with ajax. How to convert javascript variable to php variable?
I want to convert javascript variable to php variable to use it in sql query,but it doesn't work.

html code :

```<code><select id = "dep_ID" name = "dep_ID" onchange="myFunction()">
</code>```

javascript code in the same file:

```<code><script>
    function myFunction(){

        var xo = document.getElementById("dep_ID").value;
        document.getElementById("demo").innerHTML = "You selected: " + xo;

        $.ajax({
            url: 'insert.php',
            data: {duration: xo},
            type: 'POST',
            success: function(data) {
            alert(data);
            document.getElementById("demo").innerHTML = "You selected: " + <?php echo @$duration;?>;
            }
        });
    }
</script>
</code>```

insert.php code:

```<code><?php
$duration = $_POST['xo'];
return $duration ;
?>
</code>```

I expect the output of dep_ID variable, but i get nothing.

答:
$duration variable in PHP code is NOT defined in the HTML file that contains the javascript.

I think you're confusing what happens BEFORE the html page is produced, with what happens WHEN the page i rendered and the user selects a value, with what happens AFTER the ajax call has been done and insert.php has been executed.

To be clear, this:

gets executed BEFORE anything has happened in the browser, so $duration is undefined.

Body:
I want to convert javascript variable to php variable to use it in sql query,but it doesn't work.

html code :

<select id = "dep_ID" name = "dep_ID" onchange="myFunction()">

javascript code in the same file:

insert.php code:

<?php
$duration = $_POST['xo'];
return $duration ;
?>

I expect the output of dep_ID variable, but i get nothing.


问:
React native code changes not reflecting on device
Today morning on wards i am facing an issue with react native android build. The new changes in the code not reflecting on device. There is no build failure. I tried the followings

Deleted and reinstalled the node modules

react-native link

./gradlew clean

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

watchman shutdown-server

rm -rf /usr/local/var/run/watchman && brew uninstall watchman && brew install watchman

npm start - --reset-cache

My package.json

```<code>{
"name": "",
"version": "0.0.1",
"private": true,
"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "ipad": "react-native run-ios --simulator 'iPad Pro (10.5-inch) (12.0)' --configuration Debug"
},
"dependencies": {
    "@babel/runtime": "^7.2.0",
    "accordion-collapse-react-native": "^0.1.9",
    "aws-amplify": "^1.1.18",
    "aws-amplify-react-native": "^2.1.6",
    "aws-sdk": "^2.394.0",
    "buffer": "^5.2.1",
    "i18next": "^12.1.0",
    "moment": "^2.24.0",
    "nanoid": "^2.0.0",
    "native-base": "^2.8.1",
    "react": "^16.6.3",
    "react-i18next": "^8.3.8",
    "react-native": "^0.57.8",
    "react-native-app-intro-slider": "^2.0.1",
    "react-native-check-box": "^2.1.7",
    "react-native-collapsible": "^1.4.0",
    "react-native-fetch-blob": "^0.10.8",
    "react-native-gesture-handler": "^1.0.10",
    "react-native-image-crop-picker": "^0.21.3",
    "react-native-image-resizer": "^1.0.0",
    "react-native-img-button": "^1.0.1",
    "react-native-keyboard-aware-scroll-view": "^0.8.0",
    "react-native-keyboard-manager": "^4.0.13-10",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-languages": "^3.0.1",
    "react-native-linear-gradient": "^2.5.3",
    "react-native-locale-detector": "^1.0.1",
    "react-native-material-dropdown": "^0.11.1",
    "react-native-material-ripple": "^0.8.0",
    "react-native-modal-datetime-picker": "^6.0.0",
    "react-native-paper": "^2.15.2",
    "react-native-segmented-control-tab": "^3.3.1",
    "react-native-signature-pad-react-16": "^0.4.0",
    "react-native-size-matters": "^0.1.4",
    "react-native-vector-icons": "^6.1.0",
    "react-navigation": "^2.18.2",
    "react-redux": "^5.1.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "remote-redux-devtools": "^0.5.16",
    "rnkit-alert-view": "^0.1.2"
},
"devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.2",
    "react-test-renderer": "16.6.1"
},
"jest": {
    "preset": "react-native"
},
"rnpm": {
    "assets": [
        "./src/assets/fonts"
    ]
}
}
</code>```

答:
Don't use 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 for running react native in Android. This command bundles the JS server within the package(APK). So there will be no communication with your metro server that runs on the system.

Use react-native run-android command for debugging the app. In this js server won't ship with package. So the changes will reflect when you refresh the app

Body:
Today morning on wards i am facing an issue with react native android build. The new changes in the code not reflecting on device. There is no build failure. I tried the followings

Deleted and reinstalled the node modules

react-native link

./gradlew clean

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

watchman shutdown-server

rm -rf /usr/local/var/run/watchman && brew uninstall watchman && brew install watchman

npm start - --reset-cache

My package.json

{
"name": "",
"version": "0.0.1",
"private": true,
"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "ipad": "react-native run-ios --simulator 'iPad Pro (10.5-inch) (12.0)' --configuration Debug"
},
"dependencies": {
    "@babel/runtime": "^7.2.0",
    "accordion-collapse-react-native": "^0.1.9",
    "aws-amplify": "^1.1.18",
    "aws-amplify-react-native": "^2.1.6",
    "aws-sdk": "^2.394.0",
    "buffer": "^5.2.1",
    "i18next": "^12.1.0",
    "moment": "^2.24.0",
    "nanoid": "^2.0.0",
    "native-base": "^2.8.1",
    "react": "^16.6.3",
    "react-i18next": "^8.3.8",
    "react-native": "^0.57.8",
    "react-native-app-intro-slider": "^2.0.1",
    "react-native-check-box": "^2.1.7",
    "react-native-collapsible": "^1.4.0",
    "react-native-fetch-blob": "^0.10.8",
    "react-native-gesture-handler": "^1.0.10",
    "react-native-image-crop-picker": "^0.21.3",
    "react-native-image-resizer": "^1.0.0",
    "react-native-img-button": "^1.0.1",
    "react-native-keyboard-aware-scroll-view": "^0.8.0",
    "react-native-keyboard-manager": "^4.0.13-10",
    "react-native-keyboard-spacer": "^0.4.1",
    "react-native-languages": "^3.0.1",
    "react-native-linear-gradient": "^2.5.3",
    "react-native-locale-detector": "^1.0.1",
    "react-native-material-dropdown": "^0.11.1",
    "react-native-material-ripple": "^0.8.0",
    "react-native-modal-datetime-picker": "^6.0.0",
    "react-native-paper": "^2.15.2",
    "react-native-segmented-control-tab": "^3.3.1",
    "react-native-signature-pad-react-16": "^0.4.0",
    "react-native-size-matters": "^0.1.4",
    "react-native-vector-icons": "^6.1.0",
    "react-navigation": "^2.18.2",
    "react-redux": "^5.1.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "remote-redux-devtools": "^0.5.16",
    "rnkit-alert-view": "^0.1.2"
},
"devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.2",
    "react-test-renderer": "16.6.1"
},
"jest": {
    "preset": "react-native"
},
"rnpm": {
    "assets": [
        "./src/assets/fonts"
    ]
}
}


问:
How to save an Entity with a OneToMany relationship using auto incremented IDs that are related
I am trying to save a "User" object that is related by a OneToMany relationship to a "Volunteer" object.

When I try to save it, it only works when I provide the primary IDs for both these objects. However, what I need is to save the entity and let the database dictate the ID's via autoIncrement. I am not sure how am I suppose to do this or even if it's possible.

Json Mapping that works:

```<code>{
    "id":8,
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "id":6,
            "committeesId": 2,
            "outreachDate": "2019-12-07",
            "usersId": 8
        }]
}
</code>```

Json Mapping that I need (but will not work):

```<code>{
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "committeesId": 2,
            "outreachDate": "2019-12-07",
        }]
}
</code>```

So I am thinking maybe there's a way to connect the foreign keys so that I wont have to explicitly add the autoIncrement IDs (usersId, volunteersId).

User controller:

```<code>@Controller
public class UserController {
    @RequestMapping(value = "/v1/users", method = RequestMethod.POST)
    public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
        try {
            return ResponseEntity.ok(userService.saveUser(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
</code>```

User service:

```<code>@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> saveUser(UserEntity user){
        userRepository.save(user);
        Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }
}
</code>```

User Repository:

```<code>public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public List<UserEntity> findAllByOrderByIdAsc();
    public List<UserEntity> findAllByOrderByIdDesc();
    public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}
</code>```

User Entity:

```<code>@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    private long id;
    @Column(name = "username")
    private String userName;
    private String password;
    @Column(name = "volunteers_id", nullable = true)
    private Long volunteersId;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "users_id")
    private List<VolunteerEntity> volunteers = new ArrayList<>();

// omitted getters and setters
}
</code>```

Volunteer Entity:

```<code>@Entity
@Table(name = "volunteers")

public class VolunteerEntity {

     @Id
     private long id;
     @Column(name = "committees_id")
     private long committeesId;
     @Column(name = "outreach_date")
     private Date outreachDate;
     @Column(name = "users_id")
     private Long usersId;

// omitted getters and setters
}
</code>```

Any ideas or suggestions how to save this whole entity? I am wondering if this is really possible to save as in one whole process. Though if not, I am thinking of just saving them independently (User info first, then Volunteer next) but just in case it would be possible, it would really be a great help

答:
You need to add @GeneratedValue anotation next to the @id

```<code>@Id
@GeneratedValue(strategy = GenerationType.selectOne)
private long id;
</code>```

In case of sequence you need to add an extra anotation

```<code>@Id
@SequenceGenerator(name = "customName", sequenceName = "sequenceNameInDatabase")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="customName")
private long id;
</code>```

Body:
I am trying to save a "User" object that is related by a OneToMany relationship to a "Volunteer" object.

When I try to save it, it only works when I provide the primary IDs for both these objects. However, what I need is to save the entity and let the database dictate the ID's via autoIncrement. I am not sure how am I suppose to do this or even if it's possible.

Json Mapping that works:

{
    "id":8,
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "id":6,
            "committeesId": 2,
            "outreachDate": "2019-12-07",
            "usersId": 8
        }]
}

Json Mapping that I need (but will not work):

{
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "committeesId": 2,
            "outreachDate": "2019-12-07",
        }]
}

So I am thinking maybe there's a way to connect the foreign keys so that I wont have to explicitly add the autoIncrement IDs (usersId, volunteersId).

User controller:

@Controller
public class UserController {
    @RequestMapping(value = "/v1/users", method = RequestMethod.POST)
    public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
        try {
            return ResponseEntity.ok(userService.saveUser(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

User service:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> saveUser(UserEntity user){
        userRepository.save(user);
        Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }
}

User Repository:

public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public List<UserEntity> findAllByOrderByIdAsc();
    public List<UserEntity> findAllByOrderByIdDesc();
    public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}

User Entity:

@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    private long id;
    @Column(name = "username")
    private String userName;
    private String password;
    @Column(name = "volunteers_id", nullable = true)
    private Long volunteersId;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "users_id")
    private List<VolunteerEntity> volunteers = new ArrayList<>();

// omitted getters and setters
}

Volunteer Entity:

@Entity
@Table(name = "volunteers")

public class VolunteerEntity {

     @Id
     private long id;
     @Column(name = "committees_id")
     private long committeesId;
     @Column(name = "outreach_date")
     private Date outreachDate;
     @Column(name = "users_id")
     private Long usersId;

// omitted getters and setters
}

Any ideas or suggestions how to save this whole entity? I am wondering if this is really possible to save as in one whole process. Though if not, I am thinking of just saving them independently (User info first, then Volunteer next) but just in case it would be possible, it would really be a great help

Body:
You need to add @GeneratedValue anotation next to the @id

@Id
@GeneratedValue(strategy = GenerationType.selectOne)
private long id;

In case of sequence you need to add an extra anotation

@Id
@SequenceGenerator(name = "customName", sequenceName = "sequenceNameInDatabase")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="customName")
private long id;


问:
How to iterate through array that is value of key in JSON
I have JSON file like this

```<code>[
 {
    "id": 1,
    "country": "Afghanistan",
    "city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
 },
 {
    "id": 2,
    "country": "Italy",
    "city": ["Milano","Rome","Torino","Venezia"]
 }
</code>```

]

and I want to iterate through array placed in the city. Idea is to have two selects, where the first select is reserved for countries and the second is reserved for cities. Whenever the user selects a country, I want to populate the second select with a list of cities. Problem is that I receive only one array of all cities for that country. Here is my code:

export default class DiffCountries extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            contacts: [],
            selectedCountry: [],
            selectedCity: []
        }
    }

    onChangeHandler = (event) => {
      const test = CountriesData[event.target.value - 1];

        this.setState({
            selectedCountry: test,
            selectedCity: this.state.selectedCountry.city
        })

        console.log(this.state.selectedCity);
    }

    render() {
        const { contacts } = this.state;
        return (

            <select name="" id="" onChange={this.onChangeHandler}>
                            {CountriesData.map(item => {
                                const { id, country } = item;
                                return <option key={id} value={id}>{country}</option>
                            })}
                        </select>
                        <select name="" id="">
                            {this.state.selectedCountry !== undefined ?
                                <option value="">{this.state.selectedCountry.city}</option> :
                                null
                            }

                        </select>

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

And here is the screenshot of my problem

Thank you in advance!

答:
You need to iterate through the array.

```<code>this.state.selectedCountry.city.map((city, index) => {
    return <option value={city} key={index}>{city}</option>
})
</code>```

Be aware, that using the index as a key is considered an anti pattern. You could use the name of the city as a key as well. E.g.:

```<code>this.state.selectedCountry.city.map(city => {
    return <option value={city} key={city}>{city}</option>
})
</code>```

edit to add link to mdn docs as suggested in comments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Body:
I have JSON file like this

[
 {
    "id": 1,
    "country": "Afghanistan",
    "city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
 },
 {
    "id": 2,
    "country": "Italy",
    "city": ["Milano","Rome","Torino","Venezia"]
 }

]

and I want to iterate through array placed in the city. Idea is to have two selects, where the first select is reserved for countries and the second is reserved for cities. Whenever the user selects a country, I want to populate the second select with a list of cities. Problem is that I receive only one array of all cities for that country. Here is my code:

export default class DiffCountries extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            contacts: [],
            selectedCountry: [],
            selectedCity: []
        }
    }

    onChangeHandler = (event) => {
      const test = CountriesData[event.target.value - 1];

        this.setState({
            selectedCountry: test,
            selectedCity: this.state.selectedCountry.city
        })

        console.log(this.state.selectedCity);
    }

    render() {
        const { contacts } = this.state;
        return (

            <select name="" id="" onChange={this.onChangeHandler}>
                            {CountriesData.map(item => {
                                const { id, country } = item;
                                return <option key={id} value={id}>{country}</option>
                            })}
                        </select>
                        <select name="" id="">
                            {this.state.selectedCountry !== undefined ?
                                <option value="">{this.state.selectedCountry.city}</option> :
                                null
                            }

                        </select>

And here is the screenshot of my problem

Thank you in advance!

Body:
You need to iterate through the array.

this.state.selectedCountry.city.map((city, index) => {
    return <option value={city} key={index}>{city}</option>
})

Be aware, that using the index as a key is considered an anti pattern. You could use the name of the city as a key as well. E.g.:

this.state.selectedCountry.city.map(city => {
    return <option value={city} key={city}>{city}</option>
})

edit to add link to mdn docs as suggested in comments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


问:
extract matching rows from a matrix and average them and produce a new matrix
I have two matrices which contain unique rows. Also, I have another matrix which doesn't have unique rows. I have to select unique rows from the second matrix with respect to the first matrix and if two rows have the same name then the value will have to be calculated as an average of two rows.

1ST MATRIX:
Click To download the first Matrix

FIRST MATRIX

2ND MATRIX:
Click to download the second matrix

SECOND MATRIX

答:
As OP does not provide full scriptcode used I can only provide a general answer related to a matrix (database, list, etc) itteration step:

```<code>...snippet... # all import and other processing scriptcode here...

x = matrix1
y = matrix2

count1    = 0  # matrix 1
count2    = 0  # matrix 2
count_dbl = 0  # summary of encountered doubles within both matrixes

for item1 in x:
    count1 +=1
    for item2 in y:
            count2 += 1
        if item1 == item2:
            ..do whatever you need to do here...
            count_dbl+=1

        else:
            ... do something else here...
            pass

 print ('validation check on items in matrix 1: %s - 2: %s. Doubles: %s' % (count1, count2, count_dbl)
</code>```

Tip: item1 or 2 can be methods processing readline information from e.g. xml or excel files, etc.

Enjoy ;p

Body:
As OP does not provide full scriptcode used I can only provide a general answer related to a matrix (database, list, etc) itteration step:

...snippet... # all import and other processing scriptcode here...

x = matrix1
y = matrix2

count1    = 0  # matrix 1
count2    = 0  # matrix 2
count_dbl = 0  # summary of encountered doubles within both matrixes

for item1 in x:
    count1 +=1
    for item2 in y:
            count2 += 1
        if item1 == item2:
            ..do whatever you need to do here...
            count_dbl+=1

        else:
            ... do something else here...
            pass

 print ('validation check on items in matrix 1: %s - 2: %s. Doubles: %s' % (count1, count2, count_dbl)

Tip: item1 or 2 can be methods processing readline information from e.g. xml or excel files, etc.

Enjoy ;p


问:
How does Github do localization?
They seem to go against the advice

You may be tempted to store the chosen
  locale in a session or a cookie. Do
  not do so. The locale should be
  transparent and a part of the URL.

from the official Rails I18n guide

I tried seeing if they set a cookie for the locale, and it seems like they don't.

So how do they do it and why they chose not to use URLs for different languages, like http://github.com/en/foo, http://github.com/fr/foo, etc. ?

答:
It uses the _gh_sess cookie to store that information.

Multiple URLS are sometimes avoided because they create something looking a lot like duplicate content for search engines. This can deplete your Google Karma and lead to poor SEO performance.

ContentLicense: CC BY-SA 3.0

Title: How does Github do localization?


问:
Arithmetic operation in PHP String with colon ( : ) punctuation
I'm trying to solve the problem comparing two-time string and it's working fine. Here's code.

Somehow I'm not getting why it's working. How String with colon ( : )  punctuation is correctly comparing?

$start = "10:00";
$end = "22:00";

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}
```

Now everything is working fine and output is:

End time is less than Start time.

Sorry if I'm missing something kindly provide details into this.

Thank you.

答:
You need to convert string into timestamp object. So please use following code:</p>

```<code>$start = strtotime("10:00:00");
$end = strtotime("22:00:00");

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}
</code>```

Body:
I'm trying to solve the problem comparing two-time string and it's working fine. Here's code.

Somehow I'm not getting why it's working. How String with colon ( : )  punctuation is correctly comparing?

$start = "10:00";
$end = "22:00";

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}

Now everything is working fine and output is:

End time is less than Start time.

Sorry if I'm missing something kindly provide details into this.

Thank you.

Body:
You need to convert string into timestamp object. So please use following code:

$start = strtotime("10:00:00");
$end = strtotime("22:00:00");

if($start > $end) {
    echo "Start time is more than End time.";
} else {
    echo "End time is less than Start time.";
}


问:
How to write csv file row by row in python?
I want to write a csv file userperday.csv row by row with a loop. I have a list dates with dates and I want to check if they are in the second list dates2. I tried with the code below

```<code>with open('userperday.csv', "w") as f:
    writer = csv.writer(f)
    for j in dates:
        n=0
        if j in dates2:
            n+=1
        rows=zip(j, n)
        for row in rows:
                writer.writerow(row)
</code>```

My expected output is a csv file with two columns and in the first columns there a the dates from the list dates and in the second column should be a 1 or a 0, so if the particular date is in dates2or not. In addition I wisch to have a header.

答:
The problem I see is that you continue to increment n, but don't set it back to zero after a match is found. For this kind of problem I would use a dictionary to keep track of the counts.</p>

```<code>with open('userperday.csv',"w") as f:
  writer = csv.writer(f)
  rows = {}

  for j in dates:
      rows[j] = 0
      if j in dates2:
          rows[j] += 1

  #Fill in the header
  writer.writerow(["Date","Counts"])

  # Iterate through dict to get date and counts
  for key,val in rows.items():
      writer.writerow([key,val])
</code>```

Body:
I want to write a csv file userperday.csv row by row with a loop. I have a list dates with dates and I want to check if they are in the second list dates2. I tried with the code below

with open('userperday.csv', "w") as f:
    writer = csv.writer(f)
    for j in dates:
        n=0
        if j in dates2:
            n+=1
        rows=zip(j, n)
        for row in rows:
                writer.writerow(row)

My expected output is a csv file with two columns and in the first columns there a the dates from the list dates and in the second column should be a 1 or a 0, so if the particular date is in dates2or not. In addition I wisch to have a header.

Body:
The problem I see is that you continue to increment n, but don't set it back to zero after a match is found. For this kind of problem I would use a dictionary to keep track of the counts.

with open('userperday.csv',"w") as f:
  writer = csv.writer(f)
  rows = {}

  for j in dates:
      rows[j] = 0
      if j in dates2:
          rows[j] += 1

  #Fill in the header
  writer.writerow(["Date","Counts"])

  # Iterate through dict to get date and counts
  for key,val in rows.items():
      writer.writerow([key,val])


问:
Using integrated graphics for headless rendering inside a cloud docker container

Short version

How can I get an integrated-graphics-accelerated headless X display running inside a Google Cloud Kubernetes Engine pod?

Background

I'm working on a reinforcement learning project that involves running a large number of simulated environments in parallel. I'm doing the simulations using Google Cloud Kubernetes Engine, with panda3d rendering to an Xvfb virtual display.

However, I've noticed that the simulation on my Macbook runs 2x faster than the one on Kubernetes, and profiling suggests the difference is entirely from drawing the frame. Other operations - like linear algebra - are at most 30% slower. My theory is this is because on my Macbook panda3d can take advantage of the integrated graphics, while Xvfb uses software rendering.

My suspicion - gathering together the info in the links below - is the trick is to get a hardware-accelerated headless X server running, then use Virtual GL to fork it across a second Xvfb display. But lord, I am way out of my depth here.

Uncertainties

Is hardware vs software rendering actually the source of my slowdown?

Do Google Cloud instances have integrated graphics?

Can a Kubernetes pod use integrated graphics without modifications to the host?

Useful sources

Headless rendering on a VM using an NVidia card

Setting up Intel hardware-accelerated docker instances, though it requires some host commands

NVidia-accelerated hardware rendering in Docker

Discussion of combining VirtualGL and Xvfb

答:
I will answer your questions in order :

Most likely yes but it is hard to determine for sure with the information you provided. It depends on how your software and the library you are using (panda3d) handle the rendering.

Google Cloud Compute Engine instances do not have integrated graphics, but you can always use GPUs (supported GPUs and related zones listed here). You can enable virtual displays on certain instances as explained in this document.

You can setup Kubernetes clusters or node pools in Google Cloud where the nodes are equipped with Nvidia GPUs as it is explained here.

You can take a look in here to check some examples on how to use Kubernetes with GPUs on Google Cloud Platform.


问:
geopandas assign to geometry
I have a geopandas GeoDataframe representing the continental US states.  I want to transform all the coordinates to a different coordinate system with non-trivial mapping.

My plan was to do something like (this is just a simple test, not the real transform):

```<code>from shapely.ops import transform
def id_func(x, y):
    return x-10, y

alabama = conus.iloc[0]
alabama.geometry = transform (id_func, alabama.geometry)
</code>```

This doesn't work, the values of conus.geometry seem to be unchanged.

Any hints?

答:
This code works:

```<code>from shapely.ops import transform
def touv (x, y):
    if type(x) is not float:
        raise TypeError
    return ll2UV (satlat, satlon, BSlat, BSlon, y, x)

for row in conus.index:
    conus.at[row,'geometry'] = transform (touv, conus.loc[row,'geometry'])
</code>```

The key, it seems, is I needed to use '.at' to perform the assignment.

Title: geopandas assign to geometry

Body:
I have a geopandas GeoDataframe representing the continental US states.  I want to transform all the coordinates to a different coordinate system with non-trivial mapping.

My plan was to do something like (this is just a simple test, not the real transform):

from shapely.ops import transform
def id_func(x, y):
    return x-10, y

alabama = conus.iloc[0]
alabama.geometry = transform (id_func, alabama.geometry)

This doesn't work, the values of conus.geometry seem to be unchanged.

Any hints?

Body:
This code works:

from shapely.ops import transform
def touv (x, y):
    if type(x) is not float:
        raise TypeError
    return ll2UV (satlat, satlon, BSlat, BSlon, y, x)

for row in conus.index:
    conus.at[row,'geometry'] = transform (touv, conus.loc[row,'geometry'])

The key, it seems, is I needed to use '.at' to perform the assignment.


问:
How to compare BIGINT in Pig
In table commit_time is BIGINT and value store is like 20190508143744
when I try to compare with commit_time > 1000 it works without error
but when I try with commit_time > 20190508143743, it gives error as below

2019-05-29 17:35:38,390 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: For input string: "20190508143743"

Steps:

```<code>pig -useHCatalog

custProf = LOAD 'alisy3p.cust_change' using org.apache.hive.hcatalog.pig.HCatLoader();

// this step gives error
deviceChange= filter custProf by (commit_time > 20190508143743);
</code>```

Also Tried:

deviceChange= filter custProf by (commit_time > (bigint)20190508143743);

deviceChange= filter custProf by (commit_time > (long)20190508143743);

答:
Answer:
deviceChange= filter custProf by (commit_time > 20190508143743L);

BIGINT is not supported and BIGINTEGER is different as per the documentation of hive we could use Long.

https://cwiki.apache.org/confluence/display/Hive/HCatalog+LoadStore#HCatalogLoadStore-DataTypeMappings

https://pig.apache.org/docs/r0.17.0/basic.html#constants

Thanks to Savagedata for his input!

Title: How to compare BIGINT in Pig

Body:
In table commit_time is BIGINT and value store is like 20190508143744
when I try to compare with commit_time > 1000 it works without error
but when I try with commit_time > 20190508143743, it gives error as below

2019-05-29 17:35:38,390 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: For input string: "20190508143743"

Steps:

pig -useHCatalog

custProf = LOAD 'alisy3p.cust_change' using org.apache.hive.hcatalog.pig.HCatLoader();

// this step gives error
deviceChange= filter custProf by (commit_time > 20190508143743);

Also Tried:

deviceChange= filter custProf by (commit_time > (bigint)20190508143743);

deviceChange= filter custProf by (commit_time > (long)20190508143743);


问:
Function not working even though variable looks fine
Function should end up doing like this and running the command:

```<code>Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'
</code>```

However variable gets messed up like this with current working directory added and backslashes:

```<code>Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist
</code>```

ECHO looks fine and also redirect to file is fine as well:

```<code>Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'
</code>```

Sample run:

```<code>PS C:\temp> Get-Check-Func2 "webcA" "mode" "system.web/customErrors"
'MACHINE/WEBROOT/APPHOST/Default Web Site'
system.web/customErrors
mode

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist.
At line:10 char:16
+ ...             Get-WebConfigurationProperty -pspath ` $mypspath ` -filte ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\usern...fault Web Site':String) [Get-WebConfigurationProperty
   ], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.IIs.PowerShell.Provider.GetConfigurationPropertyCommand

Get-WebConfigurationProperty -pspath  'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter  'system.web/customErrors'  -name  'mode'
</code>```

Please be kind as I am a newbie to PowerShell.

Coming from korn/bash background.

```<code>function Get-Check-Func2 {
$a = Get-Website
$myws = $a.Name
$mypspath = 'MACHINE/WEBROOT/APPHOST/' + "$myws"
$mypspath = '''' + $mypspath + ''''
$myfilter = '''' +  $args[2] + ''''
$myname = '''' +  $args[1] + ''''
 echo "$mypspath"
 echo $args[2]
           Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname
     echo "Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname"
     }
</code>```

Expect  Get-WebConfigurationProperty to run but seems like variable gets messed up.

答:
Seems like you did have the right idea Mark ... my apologies.
Also got some input from another powershell guru :-)
This works fine now!

```<code>function Check-Webca-Select {
param(
$WebsitePSPath  = 'MACHINE/WEBROOT/APPHOST/',
$Filter ,
$ComponentName,
$Myexpect
)
 $a = get-website
 $w = $a.name
  foreach ($WebsiteName in $w) {
   $WebsiteFullPath = "{0}{1}" -f $WebsitePSPath,$WebsiteName
   Get-WebConfigurationProperty -PSPath "$WebsiteFullPath" -Filter $Filter -Name $ComponentName | Select-String "$Myexpect"
 }
}
</code>```

exec sample

Check-Webca-Select -Filter "system.web/customErrors" -ComponentName "mode" -Myexpect "Remoteonly"

Body:
Function should end up doing like this and running the command:

Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'

However variable gets messed up like this with current working directory added and backslashes:

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist

ECHO looks fine and also redirect to file is fine as well:

Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'

Sample run:

PS C:\temp> Get-Check-Func2 "webcA" "mode" "system.web/customErrors"
'MACHINE/WEBROOT/APPHOST/Default Web Site'
system.web/customErrors
mode

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist.
At line:10 char:16
+ ...             Get-WebConfigurationProperty -pspath ` $mypspath ` -filte ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\usern...fault Web Site':String) [Get-WebConfigurationProperty
   ], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.IIs.PowerShell.Provider.GetConfigurationPropertyCommand

Get-WebConfigurationProperty -pspath  'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter  'system.web/customErrors'  -name  'mode'

Please be kind as I am a newbie to PowerShell.

Coming from korn/bash background.

function Get-Check-Func2 {
$a = Get-Website
$myws = $a.Name
$mypspath = 'MACHINE/WEBROOT/APPHOST/' + "$myws"
$mypspath = '''' + $mypspath + ''''
$myfilter = '''' +  $args[2] + ''''
$myname = '''' +  $args[1] + ''''
 echo "$mypspath"
 echo $args[2]
           Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname
     echo "Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname"
     }

Expect  Get-WebConfigurationProperty to run but seems like variable gets messed up.

Body:
Seems like you did have the right idea Mark ... my apologies.
Also got some input from another powershell guru :-)
This works fine now!

function Check-Webca-Select {
param(
$WebsitePSPath  = 'MACHINE/WEBROOT/APPHOST/',
$Filter ,
$ComponentName,
$Myexpect
)
 $a = get-website
 $w = $a.name
  foreach ($WebsiteName in $w) {
   $WebsiteFullPath = "{0}{1}" -f $WebsitePSPath,$WebsiteName
   Get-WebConfigurationProperty -PSPath "$WebsiteFullPath" -Filter $Filter -Name $ComponentName | Select-String "$Myexpect"
 }
}

exec sample

Check-Webca-Select -Filter "system.web/customErrors" -ComponentName "mode" -Myexpect "Remoteonly"


问:
How to downgrade to Angular 7 from Angular 8 or 9
So I was trying to upgrade our entire web-application earlier from Angular 6 to 7. And I was able to do that since the script I run earlier installed the most latest version available of Angular which is Angular 8 (should have been 7 though as I thought) release 2 days ago. But it turns out there are build issues in the node modules when I did the upgrade to Angular 8. So instead, I want to downgrade my project from Angular 8 to Angular 7. How do I do that?. TIA.

PS:
I did not expect that there is Angular 8 alright, so I thought it would install Angular 7 as the latest version.

答:
you can specify the version while install,

```<code>npm install -g @angular/cli@7.x.x
</code>```

if you dont specify it will install latest version , incase specified will install given version.

here is the doc, list of angular version and its command..

Body:
you can specify the version while install,

npm install -g @angular/cli@7.x.x

if you dont specify it will install latest version , incase specified will install given version.

here is the doc, list of angular version and its command..


问:
How to use Puppeteer to get the specified element
One page has two divs:

```<code><div class='class1'>...</div>

<div class='class1 class2'>...</div>
</code>```

Use the code below:

```<code>let result = await page.$$eval('div.class1', nodes => {...})
</code>```

get the two kinds divs above, but I just want to get the divs(class='class1') .

How can I do that?

答:
According to the docs, page.$$eval uses document.querySelectorAll to find elements with the passed selector, so we can tell it not to retrieve class2:

```<code>let result = await page.$$eval('div.class1:not(.class2)', nodes => {...})
</code>```

But obviously this doesn't scale well: you'll need to keep track of all of the other classes that are not supposed to be chosen and constantly update the code.

It's better to filter only those nodes that have exactly the necessary class name:

```<code>let result = await page.$$eval('.class1', nodes =>
    nodes.filter(node => node.className === "class1").map(node => node.textContent)
);
</code>```

Note how we don't have to convert a nodeList to an array here (for example with [...nodes] or Array.from(nodes)) and can use filter and map right away. That's because page.$$eval conveniently does it for us.

Body:
One page has two divs:

...

...

Use the code below:

let result = await page.$$eval('div.class1', nodes => {...})

get the two kinds divs above, but I just want to get the divs(class='class1') .

How can I do that?

Body:
According to the docs, page.$$eval uses document.querySelectorAll to find elements with the passed selector, so we can tell it not to retrieve class2:

let result = await page.$$eval('div.class1:not(.class2)', nodes => {...})

But obviously this doesn't scale well: you'll need to keep track of all of the other classes that are not supposed to be chosen and constantly update the code.

It's better to filter only those nodes that have exactly the necessary class name:

let result = await page.$$eval('.class1', nodes =>
    nodes.filter(node => node.className === "class1").map(node => node.textContent)
);

Note how we don't have to convert a nodeList to an array here (for example with [...nodes] or Array.from(nodes)) and can use filter and map right away. That's because page.$$eval conveniently does it for us.


问:
Is there any way to check whether my application has auto start permission in android
I am trying to check whether the user already has an autostart permission to avoid the permission dialog.</p>

答:
It is not possible to verify that the autostart option is enabled or disabled in your app. What you can do is, you can ask the user for enabling it manually when the user opens the app for the first time.

You can redirect the user to autostart permission's settings page for enabling your app using the following code:

```<code>    Intent intent = new Intent();
    String manufacturer = android.os.Build.MANUFACTURER;
    if ("xiaomi".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    } else if ("oppo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
    } else if ("vivo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
    } else if ("Letv".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
    } else if ("Honor".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
    }

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if  (list.size() > 0) {
        startActivity(intent);
    }
</code>```

Body:
It is not possible to verify that the autostart option is enabled or disabled in your app. What you can do is, you can ask the user for enabling it manually when the user opens the app for the first time.

You can redirect the user to autostart permission's settings page for enabling your app using the following code:

    Intent intent = new Intent();
    String manufacturer = android.os.Build.MANUFACTURER;
    if ("xiaomi".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    } else if ("oppo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
    } else if ("vivo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
    } else if ("Letv".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
    } else if ("Honor".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
    }

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if  (list.size() > 0) {
        startActivity(intent);
    }


答:
You need to use map() on the city array.

```<code><select name = "" id = "" > {
    this.state.selectedCountry !== undefined ?
    this.state.selectedCountry.city.map((x,i) => <option value={x} key={i}>{x}</option>)
    :null
  }

</select>
</code>```

Title: How to iterate through array that is value of key in JSON

Body:
You need to use map() on the city array.

<select name = "" id = "" > {
    this.state.selectedCountry !== undefined ?
    this.state.selectedCountry.city.map((x,i) => <option value={x} key={i}>{x}</option>)
    :null
  }

</select>


问:
Python re not working with requests' POST response
I'm extracting data from a website using Python requests and I've run into a strange problem.

I'm using re with the response from my post requests to extract some table data like this:

import re
import requests

tables = re.compile(r'^\s*(
)$', flags=re.DOTALL | re.MULTILINE)
with open(tableInfoFile, fileSaveFormat) as f:
    chartInfoPage = session.post(tableURL, headers=postLoginHeaders, data=data, verify=False)
    for table in re.findall(tables, chartInfoPage.content.decode('utf-8'), flags=re.DOTALL | re.MULTILINE):
        f.write(table)
```

<p>However this doesn't write anything! I've already tested the regex and it works perfectly when i use it directly on the response data(copied from the browser).<br>
What's even stranger is that this code works just fine too:</p>

<pre class="lang-py prettyprint-override"><code>import re
import requests

tables = re.compile(r'^\s*(<table width.*?table>)$', flags=re.DOTALL | re.MULTILINE)
with open(tableInfoFile, fileSaveFormat) as f:
    chartInfoPage = session.post(tableURL, headers=postLoginHeaders, data=data, verify=False)
    with open('test.html', 'w') as temp:
        temp.write(chartInfoPage.content.decode('utf-8'))
    with open('test.html', 'r') as temp:
        data = temp.read()
    for table in re.findall(tables, data, flags=re.DOTALL | re.MULTILINE):
        f.write(table)
</code>```

This makes no sense to me. All I'm doing is saving the data to a file and then just reading it. How is this any different from using the data directly??

Thanks in advance.

Edit: Oh and here's an example of the table data I'm trying to extract if it helps:

لیست دروس ارایه شده توسط دانشکده مهندسی عمران

    <nobr> شماره درس</nobr>
    <nobr>گروه
    <nobr>واحد
    <nobr>نام درس
    <nobr>پيشنياز و همنياز
    <nobr>ظرفيت
    <nobr>تعداد ثبت نامی
    <nobr>نام استاد
    <nobr>تاريخ امتحان
    <nobr>برنامه هفتگی
    <nobr>ملاحظات
    <nobr>پیغام به هنگام ثبت نام

    <nobr>10021
    <nobr>1
    <nobr>1
    <nobr>آز هیدرولیک
    پيشنياز: 13410: 13110
    <nobr> 16
    <nobr>
    Crossed out
    <nobr>
    <nobr> شنبه  8:0 تا 12:0 شنبه  13:0 تا 15:0
    برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است

    برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است

```

答:
If you're trying to pull out/parse html, BeautifulSoup is the way to go. In this particular case, you have
 tags.

```<code>html = '''<table width="100%" class="contentTable" cellpading=3>
<tr>
<td colspan=12 class="header">لیست دروس ارایه شده توسط دانشکده مهندسی عمران</td>
</tr>
  <tr>
    <td class="header" ><nobr> شماره درس</nobr></td>
    <td class="header" ><nobr>گروه</td>
    <td class="header" ><nobr>واحد</td>
    <td class="header" ><nobr>نام درس</td>
    <td class="header" ><nobr>پيشنياز و همنياز</td>
    <td class="header" ><nobr>ظرفيت</td>
    <td class="header" ><nobr>تعداد ثبت نامی</td>
    <td class="header" ><nobr>نام استاد</td>
    <td class="header" ><nobr>تاريخ امتحان</td>
    <td class="header" ><nobr>برنامه هفتگی</td>
    <td class="header" ><nobr>ملاحظات</td>
    <td class="header" ><nobr>پیغام به هنگام ثبت نام</td>
  </tr>

  <tr>
    <td  class="contentCell"><nobr>10021</td>
    <td  class="contentCell"><nobr>1</td>
    <td  class="contentCell"><nobr>1</td>
    <td  class="contentCell"><nobr>آز هیدرولیک</td>
    <td  class="contentCell" width=150>پيشنياز: 13410: 13110</td>
    <td class = "contentCell"><nobr><span dir="ltr"> 16</span></font></td>
    <td class="contentCell" ><nobr>  </font></td>
    <td class="contentCell" width=150>Crossed out</font></td>
    <td  class="contentCell"><nobr><span dir=ltr>   </span></td>
    <td  class="contentCell"><nobr> شنبه  8:0 تا 12:0 شنبه  13:0 تا 15:0</td>
    <td  class="contentCell">برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است
    </td>
    <td  class="contentCell">برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است</td>
  </tr>
</table>'''
</code>```

The .find_all('table') will store a list of the elements with the
 tag. It's then just a matter of selecting the table you want by index, or just iterate through the list of elements and print it out, write it to file, do what you would like with it:

```<code>import pandas as pd
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tables = soup.find_all('table')

for table in tables:
    print (table)
</code>```

Body:
I'm extracting data from a website using Python requests and I've run into a strange problem.

I'm using re with the response from my post requests to extract some table data like this:

import re
import requests

tables = re.compile(r'^\s*(
)$', flags=re.DOTALL | re.MULTILINE)
with open(tableInfoFile, fileSaveFormat) as f:
    chartInfoPage = session.post(tableURL, headers=postLoginHeaders, data=data, verify=False)
    for table in re.findall(tables, chartInfoPage.content.decode('utf-8'), flags=re.DOTALL | re.MULTILINE):
        f.write(table)

However this doesn't write anything! I've already tested the regex and it works perfectly when i use it directly on the response data(copied from the browser).

What's even stranger is that this code works just fine too:

import re
import requests

tables = re.compile(r'^\s*(
)$', flags=re.DOTALL | re.MULTILINE)
with open(tableInfoFile, fileSaveFormat) as f:
    chartInfoPage = session.post(tableURL, headers=postLoginHeaders, data=data, verify=False)
    with open('test.html', 'w') as temp:
        temp.write(chartInfoPage.content.decode('utf-8'))
    with open('test.html', 'r') as temp:
        data = temp.read()
    for table in re.findall(tables, data, flags=re.DOTALL | re.MULTILINE):
        f.write(table)

This makes no sense to me. All I'm doing is saving the data to a file and then just reading it. How is this any different from using the data directly??

Thanks in advance.

Edit: Oh and here's an example of the table data I'm trying to extract if it helps:

لیست دروس ارایه شده توسط دانشکده مهندسی عمران

    <nobr> شماره درس</nobr>
    <nobr>گروه
    <nobr>واحد
    <nobr>نام درس
    <nobr>پيشنياز و همنياز
    <nobr>ظرفيت
    <nobr>تعداد ثبت نامی
    <nobr>نام استاد
    <nobr>تاريخ امتحان
    <nobr>برنامه هفتگی
    <nobr>ملاحظات
    <nobr>پیغام به هنگام ثبت نام

    <nobr>10021
    <nobr>1
    <nobr>1
    <nobr>آز هیدرولیک
    پيشنياز: 13410: 13110
    <nobr> 16
    <nobr>
    Crossed out
    <nobr>
    <nobr> شنبه  8:0 تا 12:0 شنبه  13:0 تا 15:0
    برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است

    برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است

Body:
If you're trying to pull out/parse html, BeautifulSoup is the way to go. In this particular case, you have <table> tags.

html = '''<table width="100%" class="contentTable" cellpading=3>
<tr>
<td colspan=12 class="header">لیست دروس ارایه شده توسط دانشکده مهندسی عمران</td>
</tr>
  <tr>
    <td class="header" ><nobr> شماره درس</nobr></td>
    <td class="header" ><nobr>گروه</td>
    <td class="header" ><nobr>واحد</td>
    <td class="header" ><nobr>نام درس</td>
    <td class="header" ><nobr>پيشنياز و همنياز</td>
    <td class="header" ><nobr>ظرفيت</td>
    <td class="header" ><nobr>تعداد ثبت نامی</td>
    <td class="header" ><nobr>نام استاد</td>
    <td class="header" ><nobr>تاريخ امتحان</td>
    <td class="header" ><nobr>برنامه هفتگی</td>
    <td class="header" ><nobr>ملاحظات</td>
    <td class="header" ><nobr>پیغام به هنگام ثبت نام</td>
  </tr>

  <tr>
    <td  class="contentCell"><nobr>10021</td>
    <td  class="contentCell"><nobr>1</td>
    <td  class="contentCell"><nobr>1</td>
    <td  class="contentCell"><nobr>آز هیدرولیک</td>
    <td  class="contentCell" width=150>پيشنياز: 13410: 13110</td>
    <td class = "contentCell"><nobr><span dir="ltr"> 16</span></font></td>
    <td class="contentCell" ><nobr> &nbsp;</font></td>
    <td class="contentCell" width=150>Crossed out</font></td>
    <td  class="contentCell"><nobr><span dir=ltr>&nbsp;&nbsp;&nbsp;</span></td>
    <td  class="contentCell"><nobr> شنبه  8:0 تا 12:0 شنبه  13:0 تا 15:0</td>
    <td  class="contentCell">برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است
    </td>
    <td  class="contentCell">برگزاری این درس فقط با شرط ثبت نام قطعی حداقل 15 نفر امکان پذیر است</td>
  </tr>
</table>'''

The .find_all('table') will store a list of the elements with the <table> tag. It's then just a matter of selecting the table you want by index, or just iterate through the list of elements and print it out, write it to file, do what you would like with it:

import pandas as pd
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tables = soup.find_all('table')

for table in tables:
    print (table)


问:
I have the map set to rotate to the users location. How do I allow the user to interact with the map?
I have the map set to center and rotate to the user's location and direction but the map view is locked, as in, I can not interact with it.

```<code>extension MapScreen: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        mapView.camera.heading = newHeading.magneticHeading
        mapView.setCamera(mapView.camera, animated: true)
            }
        }
    }
}
</code>```

How do I allow the user to explore his surroundings; scroll, zoom, interact with pins, etcetera, while centering and rotating to the user?

答:
This is what I ended up putting together and it works perfectly.

func centerViewOnUserLocation() { mapView.setUserTrackingMode(.followWithHeading, animated:true)}

Body:
I have the map set to center and rotate to the user's location and direction but the map view is locked, as in, I can not interact with it.

extension MapScreen: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        mapView.camera.heading = newHeading.magneticHeading
        mapView.setCamera(mapView.camera, animated: true)
            }
        }
    }
}

How do I allow the user to explore his surroundings; scroll, zoom, interact with pins, etcetera, while centering and rotating to the user?


问:
Spring App Not Connecting to Kafka with SSL
I have a Spring boot app with a very simple kafka producer. Everything works great if I connect to a kafka cluster without encryption. But times out if I try to connect to a kafka cluster with SSL. Is there some other configuration I need in the producer or some other property I need to define to allow spring to correctly use all of the configurations?

I have the following properties set:

```<code>spring.kafka.producer.bootstrap-servers=broker1.kafka.poc.com:9093,broker3.kafka.poc.com:9093,broker4.kafka.poc.com:9093,broker5.kafka.poc.com:9093
spring.kafka.ssl.key-store-type=jks
spring.kafka.ssl.trust-store-location=file:/home/ec2-user/truststore.jks
spring.kafka.ssl.trust-store-password=test1234
spring.kafka.ssl.key-store-location=file:/home/ec2-user/keystore.jks
spring.kafka.ssl.key-store-password=test1234
logging.level.org.apache.kafka=debug
server.ssl.key-password=test1234
spring.kafka.ssl.key-password=test1234
spring.kafka.producer.client-id=sym
spring.kafka.admin.ssl.protocol=ssl
</code>```

With the following result printing as the ProducerConfig when the app starts up:

```<code>o.a.k.clients.producer.ProducerConfig    : ProducerConfig values:
acks = 1
batch.size = 16384
bootstrap.servers = [broker1.kafka.allypoc.com:9093, broker3.kafka.allypoc.com:9093, broker4.kafka.allypoc.com:9093, broker5.kafka.allypoc.com:9093]
buffer.memory = 33554432
client.dns.lookup = default
client.id = sym
compression.type = none
connections.max.idle.ms = 540000
delivery.timeout.ms = 120000
enable.idempotence = false
interceptor.classes = []
key.serializer = class org.apache.kafka.common.serialization.StringSerializer
linger.ms = 0
max.block.ms = 60000
max.in.flight.requests.per.connection = 5
max.request.size = 1048576
metadata.max.age.ms = 300000
metric.reporters = []
metrics.num.samples = 2
metrics.recording.level = INFO
metrics.sample.window.ms = 30000
partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner
receive.buffer.bytes = 32768
reconnect.backoff.max.ms = 1000
reconnect.backoff.ms = 50
request.timeout.ms = 30000
retries = 2147483647
retry.backoff.ms = 100
sasl.client.callback.handler.class = null
sasl.jaas.config = null
sasl.kerberos.kinit.cmd = /usr/bin/kinit
sasl.kerberos.min.time.before.relogin = 60000
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
sasl.kerberos.ticket.renew.window.factor = 0.8
sasl.login.callback.handler.class = null
sasl.login.class = null
sasl.login.refresh.buffer.seconds = 300
sasl.login.refresh.min.period.seconds = 60
sasl.login.refresh.window.factor = 0.8
sasl.login.refresh.window.jitter = 0.05
sasl.mechanism = GSSAPI
security.protocol = PLAINTEXT
send.buffer.bytes = 131072
ssl.cipher.suites = null
ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
ssl.endpoint.identification.algorithm = https
ssl.key.password = [hidden]
ssl.keymanager.algorithm = SunX509
ssl.keystore.location = /home/ec2-user/keystore.jks
ssl.keystore.password = [hidden]
ssl.keystore.type = jks
ssl.protocol = ssl
ssl.provider = null
ssl.secure.random.implementation = null
ssl.trustmanager.algorithm = PKIX
ssl.truststore.location = /home/ec2-user/truststore.jks
ssl.truststore.password = [hidden]
ssl.truststore.type = JKS
transaction.timeout.ms = 60000
transactional.id = null
value.serializer = class org.apache.kafka.common.serialization.StringSerializer
</code>```

My producer is extremely simple:

```<code>@Service
public class Producer {
    private final KafkaTemplate<String, String> kafkaTemplate;

    public Producer(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    void sendMessage(String topic, String message) {
        this.kafkaTemplate.send(topic, message);
    }

    void sendMessage(String topic, String key, String message) {
        this.kafkaTemplate.send(topic, key, message);
    }
}
</code>```

Connecting to kafka with SSL gets a TimeoutException saying Topic symbols not present in metadata after 60000 ms.
If I turn on debug logs, I get this repeatedly, looping all of my brokers.

```<code>2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Completed connection to node -4. Fetching API versions.
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initiating API versions fetch from node -4.
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initialize connection to node 10.25.77.13:9093 (id: -3 rack: null) for sending metadata request
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initiating connection to node 10.25.77.13:9093 (id: -3 rack: null) using address /10.25.77.13
2019-05-29 20:10:25.994 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.bytes-sent
2019-05-29 20:10:25.996 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.bytes-received
2019-05-29 20:10:25.997 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.latency
2019-05-29 20:10:25.998 DEBUG 1381 --- [rk-thread | sym] o.apache.kafka.common.network.Selector   : [Producer clientId=sym] Created socket with SO_RCVBUF = 32768, SO_SNDBUF = 131072, SO_TIMEOUT = 0 to node -3
2019-05-29 20:10:26.107 DEBUG 1381 --- [rk-thread | sym] o.apache.kafka.common.network.Selector   : [Producer clientId=sym] Connection with /10.25.75.151 disconnected

java.io.EOFException: null
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:119) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:381) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:342) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:609) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:541) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.poll(Selector.java:467) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:535) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:311) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:235) ~[kafka-clients-2.1.1.jar!/:na]
    at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]

2019-05-29 20:10:26.108 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Node -1 disconnected.
2019-05-29 20:10:26.110 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Completed connection to node -3. Fetching API versions.
</code>```

答: In producer config security.protocol should be set to SSL. You could also try setting ssl.endpoint.identification.algirithm = "" to disable hostname validation of the certificate in case that's the issue. Other than that, would be useful to see the Kafka broker config.</p>

Body:
I have a Spring boot app with a very simple kafka producer. Everything works great if I connect to a kafka cluster without encryption. But times out if I try to connect to a kafka cluster with SSL. Is there some other configuration I need in the producer or some other property I need to define to allow spring to correctly use all of the configurations?

I have the following properties set:

spring.kafka.producer.bootstrap-servers=broker1.kafka.poc.com:9093,broker3.kafka.poc.com:9093,broker4.kafka.poc.com:9093,broker5.kafka.poc.com:9093
spring.kafka.ssl.key-store-type=jks
spring.kafka.ssl.trust-store-location=file:/home/ec2-user/truststore.jks
spring.kafka.ssl.trust-store-password=test1234
spring.kafka.ssl.key-store-location=file:/home/ec2-user/keystore.jks
spring.kafka.ssl.key-store-password=test1234
logging.level.org.apache.kafka=debug
server.ssl.key-password=test1234
spring.kafka.ssl.key-password=test1234
spring.kafka.producer.client-id=sym
spring.kafka.admin.ssl.protocol=ssl

With the following result printing as the ProducerConfig when the app starts up:

o.a.k.clients.producer.ProducerConfig    : ProducerConfig values:
acks = 1
batch.size = 16384
bootstrap.servers = [broker1.kafka.allypoc.com:9093, broker3.kafka.allypoc.com:9093, broker4.kafka.allypoc.com:9093, broker5.kafka.allypoc.com:9093]
buffer.memory = 33554432
client.dns.lookup = default
client.id = sym
compression.type = none
connections.max.idle.ms = 540000
delivery.timeout.ms = 120000
enable.idempotence = false
interceptor.classes = []
key.serializer = class org.apache.kafka.common.serialization.StringSerializer
linger.ms = 0
max.block.ms = 60000
max.in.flight.requests.per.connection = 5
max.request.size = 1048576
metadata.max.age.ms = 300000
metric.reporters = []
metrics.num.samples = 2
metrics.recording.level = INFO
metrics.sample.window.ms = 30000
partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner
receive.buffer.bytes = 32768
reconnect.backoff.max.ms = 1000
reconnect.backoff.ms = 50
request.timeout.ms = 30000
retries = 2147483647
retry.backoff.ms = 100
sasl.client.callback.handler.class = null
sasl.jaas.config = null
sasl.kerberos.kinit.cmd = /usr/bin/kinit
sasl.kerberos.min.time.before.relogin = 60000
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
sasl.kerberos.ticket.renew.window.factor = 0.8
sasl.login.callback.handler.class = null
sasl.login.class = null
sasl.login.refresh.buffer.seconds = 300
sasl.login.refresh.min.period.seconds = 60
sasl.login.refresh.window.factor = 0.8
sasl.login.refresh.window.jitter = 0.05
sasl.mechanism = GSSAPI
security.protocol = PLAINTEXT
send.buffer.bytes = 131072
ssl.cipher.suites = null
ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
ssl.endpoint.identification.algorithm = https
ssl.key.password = [hidden]
ssl.keymanager.algorithm = SunX509
ssl.keystore.location = /home/ec2-user/keystore.jks
ssl.keystore.password = [hidden]
ssl.keystore.type = jks
ssl.protocol = ssl
ssl.provider = null
ssl.secure.random.implementation = null
ssl.trustmanager.algorithm = PKIX
ssl.truststore.location = /home/ec2-user/truststore.jks
ssl.truststore.password = [hidden]
ssl.truststore.type = JKS
transaction.timeout.ms = 60000
transactional.id = null
value.serializer = class org.apache.kafka.common.serialization.StringSerializer

My producer is extremely simple:

@Service
public class Producer {
    private final KafkaTemplate<String, String> kafkaTemplate;

    public Producer(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    void sendMessage(String topic, String message) {
        this.kafkaTemplate.send(topic, message);
    }

    void sendMessage(String topic, String key, String message) {
        this.kafkaTemplate.send(topic, key, message);
    }
}

Connecting to kafka with SSL gets a TimeoutException saying Topic symbols not present in metadata after 60000 ms.
If I turn on debug logs, I get this repeatedly, looping all of my brokers.

2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Completed connection to node -4. Fetching API versions.
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initiating API versions fetch from node -4.
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initialize connection to node 10.25.77.13:9093 (id: -3 rack: null) for sending metadata request
2019-05-29 20:10:25.768 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Initiating connection to node 10.25.77.13:9093 (id: -3 rack: null) using address /10.25.77.13
2019-05-29 20:10:25.994 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.bytes-sent
2019-05-29 20:10:25.996 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.bytes-received
2019-05-29 20:10:25.997 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.common.metrics.Metrics  : Added sensor with name node--3.latency
2019-05-29 20:10:25.998 DEBUG 1381 --- [rk-thread | sym] o.apache.kafka.common.network.Selector   : [Producer clientId=sym] Created socket with SO_RCVBUF = 32768, SO_SNDBUF = 131072, SO_TIMEOUT = 0 to node -3
2019-05-29 20:10:26.107 DEBUG 1381 --- [rk-thread | sym] o.apache.kafka.common.network.Selector   : [Producer clientId=sym] Connection with /10.25.75.151 disconnected

java.io.EOFException: null
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:119) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:381) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:342) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:609) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:541) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.common.network.Selector.poll(Selector.java:467) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:535) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:311) ~[kafka-clients-2.1.1.jar!/:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:235) ~[kafka-clients-2.1.1.jar!/:na]
    at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]

2019-05-29 20:10:26.108 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Node -1 disconnected.
2019-05-29 20:10:26.110 DEBUG 1381 --- [rk-thread | sym] org.apache.kafka.clients.NetworkClient   : [Producer clientId=sym] Completed connection to node -3. Fetching API versions.


问:
How to "close" database when the query happens?
```<code>$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}
</code>```

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

答:
If you are using InnoDB, you can play with the Transaction Isolation Level so that dirty reads are not allowed. Make sure you use repeatable reads as your Transaction Isolation Level.

BTW The DELETE line should say DELETE FROM table WHERE item_id = 1;

Body:
$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.


问:
Please teach me how to sort the data list of php by 4 to the right
I want to draw out four different lists on the right. But I don't know how to solve it because the same list is repeated vertically like this.
The form I want is

1234

4567

I want a form like this.

This is my html code.

```<code>@foreach($penpals as $penpal)
<div class="row">
<div class="col" style="border:1px solid red">
    <table border>
        <tr style="border:1px solid red">
            <td>
                @if($penpal->image != null)
                    <a href="#"><img src="{{ $penpal->image }}" alt="No Image"
                            style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                            class="img-thumbnail"></a>
                @else
                    <a href="#"><img src="{{ asset("data/ProjectImages/master/logoImage/6.png") }}" alt="No Image"
                        style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                        class="img-thumbnail"></a>
                @endif
            </td>
        </tr>
        <tr class="text-center">
            <td>
                    {{ $penpal->user->name  }}
                    @if($penpal->user->gender == 'men')
                        <img src="{{ asset("data/ProjectImages/master/men.png") }}" alt="men">
                    @else
                        <img src="{{ asset("data/ProjectImages/master/women.png") }}" alt="women">
                    @endif
                    {{ $penpal->user->age  }}
                    @if($penpal->user->country == 'ko')
                        <img src="{{ asset("data/ProjectImages/master/korea.png") }}" alt="men">
                    @else
                        <img src="{{ asset("data/ProjectImages/master/japan.png") }}" alt="women">
                    @endif
            </td>
        </tr>
    </table>
</div>
<div class="col" style="border:1px solid red">

</div>
<div class="col" style="border:1px solid red">
    3 of 3
</div>
<div class="col" style="border:1px solid red">
    4 of 4
</div>
 </div>
@endforeach
</code>```

I'm rotating iterations and inserting the data in the remaining one div, but I don't know how to put the data in order in the remaining three divis

答:
I think your problem is trying resolve your problem with a table, instead css or bootstrap, if you're using bootstrap, I guess yes, you can do something like this:

```<code><div class="row">
    @foreach( $penpals as $penpal )
        <div class="col-3">
            //Content here
        </div>
    @endforeach
</div>
</code>```

It should work.

Body:
I want to draw out four different lists on the right. But I don't know how to solve it because the same list is repeated vertically like this.
The form I want is

1234

4567

I want a form like this.

This is my html code.

@foreach($penpals as $penpal)

                @if($penpal->image != null)
                    image }}" alt="No Image"
                            style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                            class="img-thumbnail">
                @else

                @endif

                    {{ $penpal->user->name  }}
                    @if($penpal->user->gender == 'men')

                    @else

                    @endif
                    {{ $penpal->user->age  }}
                    @if($penpal->user->country == 'ko')

                    @else

                    @endif

    3 of 3

    4 of 4

@endforeach

I'm rotating iterations and inserting the data in the remaining one div, but I don't know how to put the data in order in the remaining three divis

Body:
I think your problem is trying resolve your problem with a table, instead css or bootstrap, if you're using bootstrap, I guess yes, you can do something like this:

<div class="row">
    @foreach( $penpals as $penpal )
        <div class="col-3">
            //Content here
        </div>
    @endforeach
</div>

It should work.


问:
Which command do I use to generate the build of a Vue app?
What should I do after developing a Vue app with vue-cli?

In Angular there was some command that bundle all the scripts into one single script.

Is there something the same in Vue?

答:
The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:

```<code>"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
</code>```

If you are looking to run your site locally, you can test it with

```<code>npm serve
</code>```

If you are looking to prep your site for production, you would use

```<code>npm build
</code>```

This command will generate a dist folder that has a compressed version of your site.

Body:
The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

If you are looking to run your site locally, you can test it with

npm serve

If you are looking to prep your site for production, you would use

npm build

This command will generate a dist folder that has a compressed version of your site.


问:
How to update remote files, with updated files with changed name?
my files (inside a folder) in remote have been updated by merging from some branch.

In my local project(which I had cloned from remote before merging clone with other branch), I have same set of files in same folder. I have changed codes inside of files, added one file, ALSO have changed names of almost all files.

I want to replace remote files with my local files (no need to merge, since these are complete).

I tried by committing and pushing to remote from my local. It tells me to update project. When I update, it replaces my folder with remote folder.

Please suggest, how to do it?

答:
If you change your file name, and make changes to that file, Git will treat this as new file.

Please handle it, as if you have deleted some files and added new files.
Or you should not change the file names before pushing.


问:
Python 3.7 BeautifullSoup soup.find error - find() takes no keyword arguments
I had the below HTML from URL:

```<code><h4>
   \r\n                            \r\n\r\n
   <a href="/l">
      \r\n    <!-- mp_trans_rt_start id="1" args="as" 1 -->\r\n    <span class="brandWrapTitle">\r\n        <span class="productdescriptionbrand">Mxxx</span>\r\n    </span>\r\n    <span class="nameWrapTitle">\r\n        <span class="productdescriptionname">Axxxname</span>\r\n    </span>\r\n    <!-- mp_trans_rt_end 1 -->\r\n
   </a>
   \r\n\r\n
</h4>
</code>```

And im trying to use python to find  class name:

```<code>  import urllib.request
from bs4 import BeautifulSoup
url = "https://link"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
urlwithagent = urllib.request.Request(url,headers={'User-Agent': user_agent})
response = urllib.request.urlopen(urlwithagent)
soup = response.read()
product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
print (product)
</code>```

Everythink works perfect until line :

```<code>product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
</code>```

Im getting error like:

```<code>find() takes no keyword arguments
</code>```

And I had no idea how to fix it - there is lot of info around but nothing works :/

答:
You need to convert it to a BeautifulSoup object before using find or else it uses str.find

Ex:

```<code>soup = BeautifulSoup(response.read(), "html.parser")
product = soup.find("h4", attrs ={"class": "productdescriptionname"})
print (product)
</code>```

Body:
I had the below HTML from URL:

   \r\n                            \r\n\r\n

      \r\n    \r\n    \r\n        Mxxx\r\n    \r\n    \r\n        Axxxname\r\n    \r\n    \r\n

   \r\n\r\n

And im trying to use python to find  class name:

  import urllib.request
from bs4 import BeautifulSoup
url = "https://link"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
urlwithagent = urllib.request.Request(url,headers={'User-Agent': user_agent})
response = urllib.request.urlopen(urlwithagent)
soup = response.read()
product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
print (product)

Everythink works perfect until line :

product = soup.find("h4", attrs ={"class=": "productdescriptionname"})

Im getting error like:

find() takes no keyword arguments

And I had no idea how to fix it - there is lot of info around but nothing works :/

Body:
You need to convert it to a BeautifulSoup object before using find or else it uses str.find

Ex:

soup = BeautifulSoup(response.read(), "html.parser")
product = soup.find("h4", attrs ={"class": "productdescriptionname"})
print (product)


问:
What is the use case of Styled-Components' .attrs() function?
I came across the .attrs() function in styled components, but I do not understand what it does, or what it does differently?

I tried to understand the example in their docs, but as far as I am concerned, I can do the exact same thing without the attrs() function.

Could somebody please explain this to me or give a simple example?

答:
Focus on naming is very important.

Styled components as the name suggests are for styling the native DOM elements or custom components.

attrs is for mentioning the attributes of that very same DOM element in the attrs constructor without the need to even mention it in actual component call.

What above line means is you can do

```<code> <Input placeholder="A small text input" />
</code>```

with

```<code>const Input = styled.input.attrs(({ type }) => ({
  type:  type || "password"
}))`
  align-items: center;
  display: flex;
  margin: 1.5vh 0;
`
</code>```

See that component usage <Input .../> doesn't have type prop anywhere. It came from your attribute constructor function(static)

You couldn't have done this otherwise in your style rules because these are just the string literal of your CSS properties.

It saved you from writing type='password' in every usage of

<Input type='password' ... />

Bonus:

Now, that's a specific input component with type attribute of password. What if you wish to have a general input (styled component) with any value of type attribute?

Tada!

```<code>
const Input = styled.input.attrs(({ type }) => ({

  type:  type || "password",
  ...

</code>```

Your type is now dynamic i.e. it will take whatever input type prop you specify from your usage of component and render the input as that type (text, password, file etc. ) or if you skip the type prop it will pick up default of password. You can use as much conditional logic as you want up there.

Example:

```<code><Input .../> // renders type="password"
<Input type="text" .../>
<Input type="email" .../>
</code>```

Hope that answers your question.

Body:
Focus on naming is very important.

Styled components as the name suggests are for styling the native DOM elements or custom components.

attrs is for mentioning the attributes of that very same DOM element in the attrs constructor without the need to even mention it in actual component call.

What above line means is you can do

 <Input placeholder="A small text input" />

with

const Input = styled.input.attrs(({ type }) => ({
  type:  type || "password"
}))`
  align-items: center;
  display: flex;
  margin: 1.5vh 0;
`

See that component usage <Input .../> doesn't have type prop anywhere. It came from your attribute constructor function(static)

You couldn't have done this otherwise in your style rules because these are just the string literal of your CSS properties.

It saved you from writing type='password' in every usage of

<Input type='password' ... />

Bonus:

Now, that's a specific input component with type attribute of password. What if you wish to have a general input (styled component) with any value of type attribute?

Tada!

const Input = styled.input.attrs(({ type }) => ({

  type:  type || "password",
  ...

Your type is now dynamic i.e. it will take whatever input type prop you specify from your usage of component and render the input as that type (text, password, file etc. ) or if you skip the type prop it will pick up default of password. You can use as much conditional logic as you want up there.

Example:

<Input .../> // renders type="password"
<Input type="text" .../>
<Input type="email" .../>

Hope that answers your question.