问:
Multiple yml files configuring in corresponding Configuration class (Spring Boot)
I have more than one yml files in Spring Boot in resource classpath location like following structure of Spring Boot. Initially I have written only for application-abc.yml and at the time all the values of this file was loading in their corresponding class but when I have added on another file application-xyz.yml then also it loads into their corresponding configuration classes but at this time only loading the values of application-xyz.yml in both the configuration classes. So, want help to configure values of both the files in their corresponding configuration files in a single build :

```<code>-src
  -main
     -java
        -packages
          -config
             -ApplicationAbcConfig.java
             -ApplicationConfig.java
             -ApplicationFactory.java
             -ApplicationXyzConfig.java
             -Authentication.java
             -Operations.java
             -Payload.java
             -RequestPayload.java
             -ResponsePayload.java

         -services
             -YmlConfigurationSelection.java

         -resources
            -application.yml
            -application-abc.yml
            -application-xyz.yml

         -MultipleYmlDemoProject.java
</code>```

Content of application-abc.yml

```<code>authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes1
          - attributes2
    response:
      - sequence: 1
        attributes:
          - attributes3
          - attributes4

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes5
          - attributes6
    response:
      - sequence: 1
        attributes:
          - attributes7
          - attributes8
</code>```

Content of application-xyz.yml

```<code>authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes9
          - attributes10
    response:
      - sequence: 1
        attributes:
          - attributes11
          - attributes12

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes13
          - attributes14
    response:
      - sequence: 1
        attributes:
          - attributes15
          - attributes16
</code>```

Content of ApplicationConfig.java

```<code>public interface ApplicationConfig {
    public Authentication getAuthentication();

    public void setAuthentication(Authentication authentication);

    public Operations getOperations();

    public void setOperations(Operations operations);
}
</code>```

Content of Authentication.java

```<code>public class Authentication {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}
</code>```

Content of Operations.java

```<code>public class Operations {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}
</code>```

Content of Payload.java

```<code>public class Payload {
    private List<RequestPayload> request;
    private List<ResponsePayload> response;

    public List<RequestPayload> getRequest() {
        return request;
    }

    public void setRequest(List<RequestPayload> request) {
        this.request = request;
    }

    public List<ResponsePayload> getResponse() {
        return response;
    }

    public void setResponse(List<ResponsePayload> response) {
        this.response = response;
    }
}
</code>```

Content of RequestPayload.java

```<code>public class RequestPayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}
</code>```

Content of ResponsePayload.java

```<code>public class ResponsePayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}
</code>```

Content of ApplicationAbcConfig.java

```<code>@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-abc.yml")
public class ApplicationAbcConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}
</code>```

Content of ApplicationXyzConfig.java

```<code>@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-xyz.yml")
public class ApplicationXyzConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}
</code>```

Content of ApplicationFactory.java

```<code>@Component
public class ApplicationFactory {
    @Autowired
    private ApplicationAbcConfig applicationAbcConfig;

    @Autowired
    private ApplicationXyzConfig applicationXyzConfig;

    public ApplicationConfig getApplicationPropertiesConfig(String application) {
        if (application.equalsIgnoreCase("abc")) {
            return applicationAbcConfig;
        } else if (application.equalsIgnoreCase("xyz")) {
            return applicationXyzConfig;
        } else {
            return null;
        }
    }
}
</code>```

Content of YmlConfigurationSelection.java

```<code>public class YmlConfigurationSelection {

    @Autowired
    private ApplicationFactory applicationFactory;

    private ApplicationConfig applicationConfig;

    public Object accessingProperties(String application) {
        applicationConfig = applicationFactory.getApplicationPropertiesConfig(application);

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

Content of MultipleYmlDemoProject.java

```<code>@SpringBootApplication
@SpringBootConfiguration
@PropertySource(factory = ApplicationAbcConfig.class, value = "classpath:application-abc.yml")
@PropertySource(factory = ApplicationXyzConfig.class, value = "classpath:application-xyz.yml")
public class MultipleYmlDemoProject {

    public class MultipleYmlDemo {

        public static void main(String[] args) {
            ConfigurableApplicationContext ctx =
                    SpringApplication.run(YamlPropertysourceApplication.class, args);
            ConfigurableEnvironment env = ctx.getEnvironment();
        }
    }

}
</code>```

答:
It looks like you have an old spring application that was attempted to be migrated to spring boot.

Spring boot works natively with yaml files, so if you do the integration in a spring boot way, it will be possible to delete a lot of boilerplate code that you have to maintain. Also the naming of configurations is problematic: the names application-<something>.yml are reserved to be used with spring boot profiles, maybe if you'll rename to myprops-abc/xyz.yaml it will behave in a different way, I can't say for sure.

All-in-all I suggest you the following way, which is much better IMO:

Both configuration sets must be loaded into one configuration, so create a configuration properties file that denotes this one configuration:

```<code>
@ConfigurationProperties(prexix="security")
public class SecurityConfigProperties {

    private SecurityRealm abc;
    private SecurityRealm xyz;

    // getters, setters
}

public class SecurityRealm {
    private Authentication autentication;
    private Operations operations;
    // getters setters
}

public class Authentication {...}
private class Operations {...}
</code>```

Now place all the content from abc and xyz yaml into one file application.yaml and give a 'security' prefix:

```<code>
security:
   abc:   // note, this 'abc' matches the field name of the configuration
     authentication:
        ...
     operations:
        ....
   xyz:
     authentication:
        ...
     operations:
        ....
</code>```

OK,  everything is mapped, create the configuration like this:

```<code>@Configuration
@EnableConfigurationProperties(SecurityConfigProperties.class)
public class SecurityConfiguration {

    @Bean
    public SecurityBeanForABC(SecurityConfigProperties config) {
      return new SecurityBeanForABC(config.getAbc().getAuthentication(), config.getAbc().getOperations());
    }

    ... the same for XYZ
}

</code>```

Note that with this approach you only maintain a configuration mapping in java objects and there is no code for loading / resolving properties) - everything is done by spring boot automatically. If you configure a special annotation processor and have a descent IDE you can get even auto-completion facilities for those yaml properties but its out of scope for this question. The point is that doing things in a way directly supported by spring boot has many advantages :)

Body:
I have more than one yml files in Spring Boot in resource classpath location like following structure of Spring Boot. Initially I have written only for application-abc.yml and at the time all the values of this file was loading in their corresponding class but when I have added on another file application-xyz.yml then also it loads into their corresponding configuration classes but at this time only loading the values of application-xyz.yml in both the configuration classes. So, want help to configure values of both the files in their corresponding configuration files in a single build :

-src
  -main
     -java
        -packages
          -config
             -ApplicationAbcConfig.java
             -ApplicationConfig.java
             -ApplicationFactory.java
             -ApplicationXyzConfig.java
             -Authentication.java
             -Operations.java
             -Payload.java
             -RequestPayload.java
             -ResponsePayload.java

         -services
             -YmlConfigurationSelection.java

         -resources
            -application.yml
            -application-abc.yml
            -application-xyz.yml

         -MultipleYmlDemoProject.java

Content of application-abc.yml

authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes1
          - attributes2
    response:
      - sequence: 1
        attributes:
          - attributes3
          - attributes4

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes5
          - attributes6
    response:
      - sequence: 1
        attributes:
          - attributes7
          - attributes8

Content of application-xyz.yml

authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes9
          - attributes10
    response:
      - sequence: 1
        attributes:
          - attributes11
          - attributes12

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes13
          - attributes14
    response:
      - sequence: 1
        attributes:
          - attributes15
          - attributes16

Content of ApplicationConfig.java

public interface ApplicationConfig {
    public Authentication getAuthentication();

    public void setAuthentication(Authentication authentication);

    public Operations getOperations();

    public void setOperations(Operations operations);
}

Content of Authentication.java

public class Authentication {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}

Content of Operations.java

public class Operations {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}

Content of Payload.java

public class Payload {
    private List<RequestPayload> request;
    private List<ResponsePayload> response;

    public List<RequestPayload> getRequest() {
        return request;
    }

    public void setRequest(List<RequestPayload> request) {
        this.request = request;
    }

    public List<ResponsePayload> getResponse() {
        return response;
    }

    public void setResponse(List<ResponsePayload> response) {
        this.response = response;
    }
}

Content of RequestPayload.java

public class RequestPayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}

Content of ResponsePayload.java

public class ResponsePayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}

Content of ApplicationAbcConfig.java

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-abc.yml")
public class ApplicationAbcConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

Content of ApplicationXyzConfig.java

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-xyz.yml")
public class ApplicationXyzConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

Content of ApplicationFactory.java

@Component
public class ApplicationFactory {
    @Autowired
    private ApplicationAbcConfig applicationAbcConfig;

    @Autowired
    private ApplicationXyzConfig applicationXyzConfig;

    public ApplicationConfig getApplicationPropertiesConfig(String application) {
        if (application.equalsIgnoreCase("abc")) {
            return applicationAbcConfig;
        } else if (application.equalsIgnoreCase("xyz")) {
            return applicationXyzConfig;
        } else {
            return null;
        }
    }
}

Content of YmlConfigurationSelection.java

public class YmlConfigurationSelection {

    @Autowired
    private ApplicationFactory applicationFactory;

    private ApplicationConfig applicationConfig;

    public Object accessingProperties(String application) {
        applicationConfig = applicationFactory.getApplicationPropertiesConfig(application);

        return null;
    }
}

Content of MultipleYmlDemoProject.java

@SpringBootApplication
@SpringBootConfiguration
@PropertySource(factory = ApplicationAbcConfig.class, value = "classpath:application-abc.yml")
@PropertySource(factory = ApplicationXyzConfig.class, value = "classpath:application-xyz.yml")
public class MultipleYmlDemoProject {

    public class MultipleYmlDemo {

        public static void main(String[] args) {
            ConfigurableApplicationContext ctx =
                    SpringApplication.run(YamlPropertysourceApplication.class, args);
            ConfigurableEnvironment env = ctx.getEnvironment();
        }
    }

}

Body:
It looks like you have an old spring application that was attempted to be migrated to spring boot.

Spring boot works natively with yaml files, so if you do the integration in a spring boot way, it will be possible to delete a lot of boilerplate code that you have to maintain. Also the naming of configurations is problematic: the names application-<something>.yml are reserved to be used with spring boot profiles, maybe if you'll rename to myprops-abc/xyz.yaml it will behave in a different way, I can't say for sure.

All-in-all I suggest you the following way, which is much better IMO:

Both configuration sets must be loaded into one configuration, so create a configuration properties file that denotes this one configuration:

@ConfigurationProperties(prexix="security")
public class SecurityConfigProperties {

    private SecurityRealm abc;
    private SecurityRealm xyz;

    // getters, setters
}

public class SecurityRealm {
    private Authentication autentication;
    private Operations operations;
    // getters setters
}

public class Authentication {...}
private class Operations {...}

Now place all the content from abc and xyz yaml into one file application.yaml and give a 'security' prefix:

security:
   abc:   // note, this 'abc' matches the field name of the configuration
     authentication:
        ...
     operations:
        ....
   xyz:
     authentication:
        ...
     operations:
        ....

OK,  everything is mapped, create the configuration like this:

@Configuration
@EnableConfigurationProperties(SecurityConfigProperties.class)
public class SecurityConfiguration {

    @Bean
    public SecurityBeanForABC(SecurityConfigProperties config) {
      return new SecurityBeanForABC(config.getAbc().getAuthentication(), config.getAbc().getOperations());
    }

    ... the same for XYZ
}

Note that with this approach you only maintain a configuration mapping in java objects and there is no code for loading / resolving properties) - everything is done by spring boot automatically. If you configure a special annotation processor and have a descent IDE you can get even auto-completion facilities for those yaml properties but its out of scope for this question. The point is that doing things in a way directly supported by spring boot has many advantages :)


来源: stackexchange

问:
Fill in cells in specific columns if cells are blank
Hi I am looking to edit this function I saw in a older post to something that is more dynamic and can actually fill in the blanks on the right column since right now it is filling in Column B instead of the blanks in D. Here is the function I have

```<code>function Absent() {
  var tss = SpreadsheetApp.getActiveSpreadsheet();
  var values = tss.getRange("Attendance!D1:D20").getValues();

  for(i=0; i<values.length; i++) {
    var value = values[i][0];

    if (value == "") {
      var rangeB = tss.getSheetByName("Attendance").getRange(i+1,2);

      if(!rangeB.isBlank()) {
        rangeB.setValue("A");
      }
    }
  }
}
</code>```

The current situation I have is that there are names in Column A that are marked with a P (because they are present) in columns "D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN" The people who are not there are left blank but I would like to fill them in with A when I run the scrip through a button. Here you can see the sheet.
The script below is what I run first to add Ps to everyone that is present but I am not sure how to edit to where after it adds P's it goes back in and if name is not found put an A so that is why I am doing the second script. But if there is a way to just add it to this one that would be great!

```<code>
  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var transpose = sprsheet.getSheetByName("Transpose");
  var attendance = sprsheet.getSheetByName("Attendance");

  //Ranges of Transpose
  var colDates = transpose.getRange("D1:BU1").getValues();
  var attendees = transpose.getRange("D2:BU2").getValues();

  //Ranges of Attendance
  var eventsCol = ["D","H","J","L","N","P","T","V","X","Z","AB","AF","AH","AJ","AL","AN","AR","AT","AV","AX","AZ","BD","BF","BH","BJ","BL","BP","BR","BT","BV","BX","BZ"]; //Add Column letters is need more dates added
  var kids = attendance.getRange("A2:A205").getValues(); //Increase this if you add more names

  loop1:
  for (var i = 0; i < eventsCol.length; i++){ //For each column

    var list = getIndividuals(attendees[0][i]); //Get the list of each Transpose row 2

    loop2:
    for (var x = 0; x < kids.length; x++){ //For each name in Attendance

      loop3:
      for (var y = 0; y < list.length; y++){ //Compare it with each name of the list

        if (list[y] == kids[x][0] || list[y] == " " + kids[x][0]){ //Second "or" is in case there is an space in the first position.

        attendance.getRange(eventsCol[i]+(x+2)).setValue("P");

          break loop3; //Once it finds a name it makes no sense to keep searching. Go back to the next name.

         }
        }

      }

    }
  }

//Split the list into each name, removing the first space
function getIndividuals(attendees){

  var individuals = attendees.split(",");

  for (var i = 0; i < individuals.length; i++){

    if (individuals[i][0] == " "){

      individuals[i][0].replace(" ", "");

    }

  }

  return individuals;
}
</code>```

答:
Filling in the Empties With an A

Hmm. Great school.  You get an A even if you don't show up.

```<code>function fillTheEmptiesWithA() {
  var ss=SpreadsheetApp.getActive();
  var cols= ["D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN"];
  var sh=ss.getSheetByName('Attendance');
  var sr=3;
  cols.forEach(function(c,i){
    var col=sh.getRange(c+1).getColumn();
    var rg=sh.getRange(sr,col,sh.getLastRow()-sr+1,1)
    var vals=rg.getValues();
    vals.forEach(function(p,j,v){if(p==''){v[j][0]='A';}});
    rg.setValues(vals);
  });
}
</code>```

According to this var kids = attendance.getRange("A2:A205").getValues(); your data starts on row 2.  According to you image your data starts on row 3.  I put a startRow(sr) into the code so that you could decide which one it is later.

Animation:

*This version only fills Empties when header row is not blank in each column

```<code>function runTwo() {
  var ss=SpreadsheetApp.getActive();
  var cols= ["D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN"];
  var sh=ss.getSheetByName('Attendance');
  var sr=3;
  cols.forEach(function(c,i){
    var col=sh.getRange(c+1).getColumn();
    if(sh.getRange(sr-1,col).getValue()!='') {
      var rg=sh.getRange(sr,col,sh.getLastRow()-sr+1,1)
      var vals=rg.getValues();
      vals.forEach(function(p,j,v){if(p==''){v[j][0]='A';}});
      rg.setValues(vals);
    }
  });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi I am looking to edit this function I saw in a older post to something that is more dynamic and can actually fill in the blanks on the right column since right now it is filling in Column B instead of the blanks in D. Here is the function I have

function Absent() {
  var tss = SpreadsheetApp.getActiveSpreadsheet();
  var values = tss.getRange("Attendance!D1:D20").getValues();

  for(i=0; i<values.length; i++) {
    var value = values[i][0];

    if (value == "") {
      var rangeB = tss.getSheetByName("Attendance").getRange(i+1,2);

      if(!rangeB.isBlank()) {
        rangeB.setValue("A");
      }
    }
  }
}

The current situation I have is that there are names in Column A that are marked with a P (because they are present) in columns "D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN" The people who are not there are left blank but I would like to fill them in with A when I run the scrip through a button. Here you can see the sheet.
The script below is what I run first to add Ps to everyone that is present but I am not sure how to edit to where after it adds P's it goes back in and if name is not found put an A so that is why I am doing the second script. But if there is a way to just add it to this one that would be great!

  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var transpose = sprsheet.getSheetByName("Transpose");
  var attendance = sprsheet.getSheetByName("Attendance");

  //Ranges of Transpose
  var colDates = transpose.getRange("D1:BU1").getValues();
  var attendees = transpose.getRange("D2:BU2").getValues();

  //Ranges of Attendance
  var eventsCol = ["D","H","J","L","N","P","T","V","X","Z","AB","AF","AH","AJ","AL","AN","AR","AT","AV","AX","AZ","BD","BF","BH","BJ","BL","BP","BR","BT","BV","BX","BZ"]; //Add Column letters is need more dates added
  var kids = attendance.getRange("A2:A205").getValues(); //Increase this if you add more names

  loop1:
  for (var i = 0; i < eventsCol.length; i++){ //For each column

    var list = getIndividuals(attendees[0][i]); //Get the list of each Transpose row 2

    loop2:
    for (var x = 0; x < kids.length; x++){ //For each name in Attendance

      loop3:
      for (var y = 0; y < list.length; y++){ //Compare it with each name of the list

        if (list[y] == kids[x][0] || list[y] == " " + kids[x][0]){ //Second "or" is in case there is an space in the first position.

        attendance.getRange(eventsCol[i]+(x+2)).setValue("P");

          break loop3; //Once it finds a name it makes no sense to keep searching. Go back to the next name.

         }
        }

      }

    }
  }

//Split the list into each name, removing the first space
function getIndividuals(attendees){

  var individuals = attendees.split(",");

  for (var i = 0; i < individuals.length; i++){

    if (individuals[i][0] == " "){

      individuals[i][0].replace(" ", "");

    }

  }

  return individuals;
}

Body:
Filling in the Empties With an A

Hmm. Great school.  You get an A even if you don't show up.

function fillTheEmptiesWithA() {
  var ss=SpreadsheetApp.getActive();
  var cols= ["D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN"];
  var sh=ss.getSheetByName('Attendance');
  var sr=3;
  cols.forEach(function(c,i){
    var col=sh.getRange(c+1).getColumn();
    var rg=sh.getRange(sr,col,sh.getLastRow()-sr+1,1)
    var vals=rg.getValues();
    vals.forEach(function(p,j,v){if(p==''){v[j][0]='A';}});
    rg.setValues(vals);
  });
}

According to this var kids = attendance.getRange("A2:A205").getValues(); your data starts on row 2.  According to you image your data starts on row 3.  I put a startRow(sr) into the code so that you could decide which one it is later.

Animation:

*This version only fills Empties when header row is not blank in each column

function runTwo() {
  var ss=SpreadsheetApp.getActive();
  var cols= ["D","H","J","L","N","P","R","T","V","X","Z","AB","AF","AH","AJ","AL","AN"];
  var sh=ss.getSheetByName('Attendance');
  var sr=3;
  cols.forEach(function(c,i){
    var col=sh.getRange(c+1).getColumn();
    if(sh.getRange(sr-1,col).getValue()!='') {
      var rg=sh.getRange(sr,col,sh.getLastRow()-sr+1,1)
      var vals=rg.getValues();
      vals.forEach(function(p,j,v){if(p==''){v[j][0]='A';}});
      rg.setValues(vals);
    }
  });
}


问:
Switch, case, try and catch in C# probelm
I am very new to C# programming. I wanted to catch the errors for example invalid input (not a number from 1-6) and print out a message stating the error. This is my code.

```<code>private static bool ManageStudents()
    {
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return true;
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("error message");
            Console.ReadLine();
            return true;
        }

    }
</code>```

When I run the program the message "error message" didn't appear after I enter an invalid character.

答:
You need to understand the difference between when the default is called and when the catch is called. The default is called when non of the cases are true (here the number is not in the range 1-6). The catch is called when one of the functions inside the switch threw an exception (it could be AddStudents() or SearchStudents(), etc...).

Then you can handle your error more generically by adding a function receiving a message as parameter. So then you should have something like:

```<code>private static bool HandleError(string message) { // More generic handling
   Console.WriteLine(message);
   Console.ReadLine();
   return true;
}

private static bool ManageStudents()
{
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return HandleError("Out of range"); // Not in range 1-6
            }
        }

        catch (Exception e) // This catch exception happening in the all switch
        {
            return HandleError("Execution problem");
        }

    }
</code>```

Body:
I am very new to C# programming. I wanted to catch the errors for example invalid input (not a number from 1-6) and print out a message stating the error. This is my code.

private static bool ManageStudents()
    {
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return true;
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("error message");
            Console.ReadLine();
            return true;
        }

    }

When I run the program the message "error message" didn't appear after I enter an invalid character.

Body:
You need to understand the difference between when the default is called and when the catch is called. The default is called when non of the cases are true (here the number is not in the range 1-6). The catch is called when one of the functions inside the switch threw an exception (it could be AddStudents() or SearchStudents(), etc...).

Then you can handle your error more generically by adding a function receiving a message as parameter. So then you should have something like:

private static bool HandleError(string message) { // More generic handling
   Console.WriteLine(message);
   Console.ReadLine();
   return true;
}

private static bool ManageStudents()
{
        Console.Clear();
        Console.WriteLine("========================");
        Console.WriteLine(" Choose an option:");
        Console.WriteLine("  1. Add a new student");
        Console.WriteLine("  2. View all students");
        Console.WriteLine("  3. Search students");
        Console.WriteLine("  4. Delete students");
        Console.WriteLine("  5. Update students");
        Console.WriteLine("  6. Back to main menu");
        Console.WriteLine("========================");
        Console.Write("\r\nPlease choose: ");

        try
        {
            switch (Console.ReadLine())
            {
                case "1":
                    AddStudents();
                    return true;
                case "2":
                    ViewStudents();
                    return true;
                case "3":
                    SearchStudents();
                    return true;
                case "4":
                    DeleteStudents();
                    return true;
                case "5":
                    UpdateStudents();
                    return true;
                case "6":
                    return false;
                default:
                    return HandleError("Out of range"); // Not in range 1-6
            }
        }

        catch (Exception e) // This catch exception happening in the all switch
        {
            return HandleError("Execution problem");
        }

    }


问:
Is it OK to remove Nginx when using Azure application gateway?
I have a Web app for docker currently running django with gunicorn as wsgi server and Nginx as reverse proxy. I am not serving any static assets via Nginx and the SSL is taken care by Azure.

So my question is, if I use Azure application gateway (with or without WAF) can I remove Nginx? I don't see any use for it, unless I want to use cache, which I don't. HTTP/2 is also provided by application gateway.

答: Go for Azure Application gateway... and get rid of Nginx. When in cloud, it makes sense to use all PaaS platform features. </p>


问:
Dynamically sized boost::asio::buffer
I'm reading from a boost::asio::ip::udp::socket like this:

```<code>using boost::asio::ip::udp;

// ...

char recv_buf[128];
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
</code>```

Now, this works perfectly fine, but the maximum amount of characters that I am able to recieve is now 127. However I am facing a problem because I need to accept some data input of which the length can greatly vary (and is not of well-defined length with prefixed headers, for example). A solution to this would be a dynamically expanding buffer, like a vector. Is it possible to create a dynamically expanding boost::asio::buffer to accept (theoretical) infite amounts of input and store it in a container?

答:
If you use smaller buffers, you can easily chain them together via the *BufferSequences concepts. For example, you can pass in a MutableBufferSequence
 to accept data from a read(2) call or pass a ConstBufferSequence for a list of buffers that you are going to write(2) out. That said, I tend to recommend using a single buffer in each direction because it tends to simplify code (though that's not always possible).</p>

ContentLicense: CC BY-SA 3.0

Title: Dynamically sized boost::asio::buffer

Body:
I'm reading from a boost::asio::ip::udp::socket like this:

using boost::asio::ip::udp;

// ...

char recv_buf[128];
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);

Now, this works perfectly fine, but the maximum amount of characters that I am able to recieve is now 127. However I am facing a problem because I need to accept some data input of which the length can greatly vary (and is not of well-defined length with prefixed headers, for example). A solution to this would be a dynamically expanding buffer, like a vector. Is it possible to create a dynamically expanding boost::asio::buffer to accept (theoretical) infite amounts of input and store it in a container?


问:
How could I upload an icon I made in Adobe Illustrator to my HTML document?
I can export the file as an SVG, but how would I actually customize it with a hover effect afterwards? I use FontAwesome for most of my icons, but I'm not sure how I'd get my own icon to carry the  tag so that I could modify it the same way as the others.

Body:
in your CSS you should access the SVG tag then instead of color use fill for SVG than in your HTML just have your SVG tag.

svg:hover{
fill:red;
}

<svg id="Layer_1" enable-background="new 0 0 512.843 512.843" height="512" viewBox="0 0 512.843 512.843" width="512" xmlns="http://www.w3.org/2000/svg"><path d="m398.254 492.44c0 11.046-8.954 20-20 20s-20-8.954-20-20 8.954-20 20-20 20 8.954 20 20zm-288-19.964c-11.028 0-20-8.972-20-20v-246.489l166-151.439 166 151.439v72.147c13.732 3.002 27.121 7.419 40 13.19v-48.846l23.296 21.252 26.958-29.55-256.254-233.776-256.254 233.776 26.958 29.55 23.296-21.252v209.998c0 33.084 26.916 59.964 60 59.964h208.744l-39.957-39.964zm268-83.036c-24.131 0-50.247 11.167-68.241 29.143l-14.15 14.135 28.269 28.299 14.15-14.134c10.607-10.597 27.261-17.442 40.972-17.442 13.55 0 29.168 6.847 39.775 17.442l14.15 14.134 28.269-28.299-14.15-14.135c-17.996-17.977-45.074-29.143-69.044-29.143zm120.486-24.825c-32.822-33.002-75.379-51.177-119.833-51.176-44.463.001-87.021 18.176-119.834 51.178l-14.103 14.183 28.365 28.203 14.102-14.183c25.25-25.394 57.734-39.38 91.47-39.381 33.728-.001 66.213 13.985 91.471 39.383l14.103 14.181 28.362-28.207z"/></svg>


问:
Dockerfile keytool: getting "Certificate alias <name> already exists" even using "keytool - delete"
I use Dockerfile to create an image for our web app which requires HTTPS. However, I am getting Certificate not imported, alias <my-cert-name> already exists Java exception. When I tried without using Dockerfile, just from command line, I was able to delete the existing alias and export, import worked. But not with Dockerfile. Any ideas? Thanks!

Dockerfile:

```<code>  FROM openjdk:8-alpine

  #Starting https and certs configuration
  #Make directory for certs inside the container
  RUN mkdir -p usr/app/ssl/certs/

  #Copy certs from local to the container
  COPY myWebApp/src/main/resources/PT/certificates/my-cert-name.jks usr/app/ssl/certs/
  COPY myWebApp/src/main/resources/PT/certificates/trustStore.jks usr/app/ssl/certs/

  #Export/Import certificate
  RUN cd usr/app/ssl/certs/ && \
      keytool -delete -alias my-cert-name -keystore my-cert-name.jks -storepass password123! && \
      keytool -export -alias my-cert-name -keystore my-cert-name.jks -file my-cert-name.crt -storepass password123! && \
      keytool -importcert -keystore trustStore.jks -alias my-cert-name -storepass password123! -file my-cert-name.crt -noprompt
  #Ending https and certs configuration

  RUN mkdir -p /usr/app/myweb

  COPY myWebApp/target/myWeb.war /usr/app/myweb

  CMD java -Xms512M -Xmx6144M -XX:MaxMetaspaceSize=3072M -jar /usr/app/myweb/myWeb.war
  EXPOSE 8080
</code>```

Docker build command

```<code>  >docker build -it test-https-image .
</code>```

Env:

```<code> Using Docker desktop on windows 10.
</code>```

Thanks in advance!

答:
I prefer the notation:

```<code>RUN cd usr/app/ssl/certs/ && \
    keytool -delete -alias my-cert-name -keystore my-cert-name.jks -storepass password123! && \
    keytool -export -alias my-cert-name -keystore my-cert-namet.jks \
      -file my-cert-name.crt -storepass password123! && \
    keytool -importcert -keystore trustStore.jks -alias my-cert-name -storepass password123! \
      -file my-cert-name.crt -noprompt
</code>```

It is easier to double-check you are importing the same name you have deleted.

(since -delete is a good way to force update an existing certificate)

But the gist is:

you delete in my-cert-name.jks, while you import in trustStore.jks.

if the import fails, that means trustStore.jks already has a certificate for that name

If that certificate was already in the copied keystore, I would not export/re-import it. (I only imported it in my previous answer)

Make sure the "usr/app/ssl/certs" is the right path: I would rather use an absolute path, rather than a relative path.

The OP fongfong confirms in the comments:

I should delete the existing alias from trustStore.jks, not my-cert-name.jks

Body:
I use Dockerfile to create an image for our web app which requires HTTPS. However, I am getting Certificate not imported, alias <my-cert-name> already exists Java exception. When I tried without using Dockerfile, just from command line, I was able to delete the existing alias and export, import worked. But not with Dockerfile. Any ideas? Thanks!

Dockerfile:

  FROM openjdk:8-alpine

  #Starting https and certs configuration
  #Make directory for certs inside the container
  RUN mkdir -p usr/app/ssl/certs/

  #Copy certs from local to the container
  COPY myWebApp/src/main/resources/PT/certificates/my-cert-name.jks usr/app/ssl/certs/
  COPY myWebApp/src/main/resources/PT/certificates/trustStore.jks usr/app/ssl/certs/

  #Export/Import certificate
  RUN cd usr/app/ssl/certs/ && \
      keytool -delete -alias my-cert-name -keystore my-cert-name.jks -storepass password123! && \
      keytool -export -alias my-cert-name -keystore my-cert-name.jks -file my-cert-name.crt -storepass password123! && \
      keytool -importcert -keystore trustStore.jks -alias my-cert-name -storepass password123! -file my-cert-name.crt -noprompt
  #Ending https and certs configuration

  RUN mkdir -p /usr/app/myweb

  COPY myWebApp/target/myWeb.war /usr/app/myweb

  CMD java -Xms512M -Xmx6144M -XX:MaxMetaspaceSize=3072M -jar /usr/app/myweb/myWeb.war
  EXPOSE 8080

Docker build command

  >docker build -it test-https-image .

Env:

 Using Docker desktop on windows 10.

Thanks in advance!

Body:
I prefer the notation:

RUN cd usr/app/ssl/certs/ && \
    keytool -delete -alias my-cert-name -keystore my-cert-name.jks -storepass password123! && \
    keytool -export -alias my-cert-name -keystore my-cert-namet.jks \
      -file my-cert-name.crt -storepass password123! && \
    keytool -importcert -keystore trustStore.jks -alias my-cert-name -storepass password123! \
      -file my-cert-name.crt -noprompt

It is easier to double-check you are importing the same name you have deleted.

(since -delete is a good way to force update an existing certificate)

But the gist is:

you delete in my-cert-name.jks, while you import in trustStore.jks.

if the import fails, that means trustStore.jks already has a certificate for that name

If that certificate was already in the copied keystore, I would not export/re-import it. (I only imported it in my previous answer)

Make sure the "usr/app/ssl/certs" is the right path: I would rather use an absolute path, rather than a relative path.

The OP fongfong confirms in the comments:

I should delete the existing alias from trustStore.jks, not my-cert-name.jks


问:
Page break inside avoid in flex not working as expected
I have a container which contains several divs which 2 column layout. I want the divs to printed in the new page when I convert to pdf.

I have gone through few articles on page-break-inside, but it didn't go well. Also tried many SO answers, everything was my bad luck.

I don't understand why page-break-inside:avoid not working in my code.

I want the .item class to break to new page when it is in the middle of two pages.

Here is the full code of it:

.item {
  width: 100%
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.container>div {
  flex: 0 50%;
  box-sizing:border-box;
     border:2px solid red;
}

@media print {
    .container>div {
        display: block;
        page-break-inside: avoid;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item">1. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>
  <div class="item">2 . Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>
  <div class="item">3. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>
  <div class="item">4. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ip</div>
   <div class="item">5. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>
   <div class="item">6. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of</div>
</div></code>```

I am hoping to get the answer.

Also tried with bootstrap, but still of no luck.
below is the code using bootstrap.

https://codepen.io/chintuyadav/pen/wvaMZQg?editors=1100

Thank you in advance for your time.

答:
Page-break-inside applies to block-level elements in the normal flow of the root element.

User agents may also apply it to other elements like table-row elements.

For reference: https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-inside

Body:
I have a container which contains several divs which 2 column layout. I want the divs to printed in the new page when I convert to pdf.

I have gone through few articles on page-break-inside, but it didn't go well. Also tried many SO answers, everything was my bad luck.

I don't understand why page-break-inside:avoid not working in my code.

I want the .item class to break to new page when it is in the middle of two pages.

Here is the full code of it:

.item {
  width: 100%
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.container>div {
  flex: 0 50%;
  box-sizing:border-box;
     border:2px solid red;
}

@media print {
    .container>div {
        display: block;
        page-break-inside: avoid;
    }
}

1. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

2 . Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

3. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

4. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ip

5. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

6. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of

I am hoping to get the answer.

Also tried with bootstrap, but still of no luck.
below is the code using bootstrap.

https://codepen.io/chintuyadav/pen/wvaMZQg?editors=1100

Thank you in advance for your time.


问:
Python authorization
I need to write a script that is included in the personal account of my Internet provider and transmits information about the current balance.

At the moment I am stuck at the time of authorization. I found and edited such a script for myself:

```<code>import requests

url = 'https://bill.tomtel.ru/login.html'

USERNAME, PASSWORD, = 'mylogin', 'mypass'

resp = requests.get(url, auth=(USERNAME, PASSWORD))

r = requests.post(url)

print(r.content)
</code>```

But this does not help to pass authorization...

I can enter this link through a browser and go to a page of this type:

```<code>https://bill.tomtel.ru/fastcom/!w3_p_main.showform?FORMNAME=QFRAME&CONFIG=CONTRACT&SID=BLABLABLA&NLS=WR
</code>```

I can go through browser authorization through both links, but why can't I do this through a script?

Please help with this.

答:
I think you should try this:</p>

```<code>import requests

url = 'https://bill.tomtel.ru/signin.php'

USERNAME = input('Enter your username: ')
PASSWORD = input('Enter your password: ')
d = {
'USERNAME' : USERNAME,
'PASSWORD' : PASSWORD,
'FORMNAME' : 'QFRAME'}

session = requests.Session()

resp = session.post(url, data=d).text
if not '<TITLE>' in resp:
    print('Incorrect username or password!')
    quit()
print('Logging in ... ')
for line in resp.split('\n'):
    if 'location' in line:
        red = 'https://bill.tomtel.ru/fastcom/!w3_p_main.showform%s' % line.replace(' if (P>0) self.location.replace("', '').replace('");', '')
if not red:
    print('An error has occured')
    quit()
print('Redirecting to %s' % red)
page = session.get(red).text

print('')
print('          MAIN PAGE')
print(page)
</code>```

Title: Python authorization

Body:
I need to write a script that is included in the personal account of my Internet provider and transmits information about the current balance.

At the moment I am stuck at the time of authorization. I found and edited such a script for myself:

import requests

url = 'https://bill.tomtel.ru/login.html'

USERNAME, PASSWORD, = 'mylogin', 'mypass'

resp = requests.get(url, auth=(USERNAME, PASSWORD))

r = requests.post(url)

print(r.content)

But this does not help to pass authorization...

I can enter this link through a browser and go to a page of this type:

https://bill.tomtel.ru/fastcom/!w3_p_main.showform?FORMNAME=QFRAME&CONFIG=CONTRACT&SID=BLABLABLA&NLS=WR

I can go through browser authorization through both links, but why can't I do this through a script?

Please help with this.

Body:
I think you should try this:

import requests

url = 'https://bill.tomtel.ru/signin.php'

USERNAME = input('Enter your username: ')
PASSWORD = input('Enter your password: ')
d = {
'USERNAME' : USERNAME,
'PASSWORD' : PASSWORD,
'FORMNAME' : 'QFRAME'}

session = requests.Session()

resp = session.post(url, data=d).text
if not '<TITLE>' in resp:
    print('Incorrect username or password!')
    quit()
print('Logging in ... ')
for line in resp.split('\n'):
    if 'location' in line:
        red = 'https://bill.tomtel.ru/fastcom/!w3_p_main.showform%s' % line.replace(' if (P>0) self.location.replace("', '').replace('");', '')
if not red:
    print('An error has occured')
    quit()
print('Redirecting to %s' % red)
page = session.get(red).text

print('')
print('          MAIN PAGE')
print(page)


问:
Bootstrap datepicker date alignment changes when screen size is reduced
I have used bootstrap datepicker . Everytime I reduce the screen size the datepicker changes the alignment of the dates like below.

```<code>  <div class='input-group date' id='fromDate'>
   @Html.TextBoxFor(model => model.FromDate, new { @class = "form-control", name = "startDate", id = "startDate", @readonly = "true" })
   <span class="input-group-addon">
     <span class="glyphicon glyphicon-calendar"></span>
   </span>
 </div>
</code>```

And on document onload the below code.

```<code>$('#fromDate')
  .datepicker({
    format: 'dd/mm/yyyy',
    autoclose: true,
    orientation: 'bottom'
  })
</code>```

I have tried giving height and width, but nothing worked.

答:
Make sure you have this ViewPort meta in your _Layout.cshtml file. And your Jquery ID should be startDate not fromDate according to your text field.

```<code>$('#startDate')
        .datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true,
            orientation: 'bottom'
        })
</code>```

Hope this will fix it.

Body:
I have used bootstrap datepicker . Everytime I reduce the screen size the datepicker changes the alignment of the dates like below.

   @Html.TextBoxFor(model => model.FromDate, new { @class = "form-control", name = "startDate", id = "startDate", @readonly = "true" })

And on document onload the below code.

$('#fromDate')
  .datepicker({
    format: 'dd/mm/yyyy',
    autoclose: true,
    orientation: 'bottom'
  })

I have tried giving height and width, but nothing worked.

Body:
Make sure you have this ViewPort meta in your _Layout.cshtml file. And your Jquery ID should be startDate not fromDate according to your text field.

$('#startDate')
        .datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true,
            orientation: 'bottom'
        })

Hope this will fix it.


问:
How to resolve this error? xcode generated Project-Swift.h error
```<code>SWIFT_CLASS("_TtC12palaceCookie18OrangeExchangeUtil")
@interface OrangeExchangeUtil : NSObject <SKPaymentTransactionObserver, SKProductsRequestDelegate>
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
- (void)productsRequest:(SKProductsRequest * _Nonnull)request didReceiveResponse:(SKProductsResponse * _Nonnull)response;
- (void)paymentQueue:(SKPaymentQueue * _Nonnull)queue updatedTransactions:(NSArray<SKPaymentTransaction *> * _Nonnull)transactions;
@end}
</code>```

palaceCookie-Swift.h:353:43: Unknown class name
  'SKPaymentTransactionObserver'; did you mean 'SKPaymentTransaction'?

palaceCookie-Swift.h:353:73: Unknown class name
  'SKProductsRequestDelegate'; did you mean 'SKProductsRequest'?

palaceCookie-Swift.h:353:43: Type argument 'SKPaymentTransaction' must
  be a pointer (requires a '*')

palaceCookie-Swift.h:353:73: Type argument 'SKProductsRequest' must be
  a pointer (requires a '*')

palaceCookie-Swift.h:353:33: Type arguments cannot be applied to
  non-parameterized class 'NSObject'

Screenshot

Code:

```<code>import Foundation
import StoreKit

class OrangeExchangeUtil: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
</code>```

How to solve this error？Using Xcode 11.2.

Thank you!

答:
This is a problem with mixed compilation
oc,swift,c++
add

```<code>@protocol SKPaymentTransactionObserver;
@protocol SKProductsRequestDelegate;
</code>```

in c++ .h file

Body:
SWIFT_CLASS("_TtC12palaceCookie18OrangeExchangeUtil")
@interface OrangeExchangeUtil : NSObject <SKPaymentTransactionObserver, SKProductsRequestDelegate>
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
- (void)productsRequest:(SKProductsRequest * _Nonnull)request didReceiveResponse:(SKProductsResponse * _Nonnull)response;
- (void)paymentQueue:(SKPaymentQueue * _Nonnull)queue updatedTransactions:(NSArray<SKPaymentTransaction *> * _Nonnull)transactions;
@end}

palaceCookie-Swift.h:353:43: Unknown class name
  'SKPaymentTransactionObserver'; did you mean 'SKPaymentTransaction'?

palaceCookie-Swift.h:353:73: Unknown class name
  'SKProductsRequestDelegate'; did you mean 'SKProductsRequest'?

palaceCookie-Swift.h:353:43: Type argument 'SKPaymentTransaction' must
  be a pointer (requires a '*')

palaceCookie-Swift.h:353:73: Type argument 'SKProductsRequest' must be
  a pointer (requires a '*')

palaceCookie-Swift.h:353:33: Type arguments cannot be applied to
  non-parameterized class 'NSObject'

Screenshot

Code:

import Foundation
import StoreKit

class OrangeExchangeUtil: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {

How to solve this error？Using Xcode 11.2.

Thank you!

Body:
This is a problem with mixed compilation
oc,swift,c++
add

@protocol SKPaymentTransactionObserver;
@protocol SKProductsRequestDelegate;

in c++ .h file


问:
How to pass ID from url to controller in laravel
I want my view page to open when the type the url as www.domain-name.in/sample/ID. ID can be an integer valure of 5 digits. Right now my view page is opening when I type the url as www.domain-name.in/sample but when i type www.domain-name.in/sample/ID, I'm getting 404 error.
This is my route :

Route::get('/{$id}','HomeController@index');```
</div>
</div>
</p>

<p>This is my controller</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public function index(Request $request,$id)
    {
        return view('filename');
    }</code>```

How can I get view page with this url : www.domain-name.in/sample/ID

答:
Your route will be

```<code>Route::get('sample/{id}','HomeController@index')->where(['id' => '[0-9]{1,5}');
</code>```

Your controller will be

```<code>public function index($id)
{
   echo $id;
   exit;
   return view('filename');
}
</code>```

Now you can access it as url as below.

```<code>www.domain-name.in/sample/12345
</code>```

"12345" is integer value of 5 digits sample id.

Body:
I want my view page to open when the type the url as www.domain-name.in/sample/ID. ID can be an integer valure of 5 digits. Right now my view page is opening when I type the url as www.domain-name.in/sample but when i type www.domain-name.in/sample/ID, I'm getting 404 error.
This is my route :

Route::get('/{$id}','HomeController@index');

This is my controller

public function index(Request $request,$id)
    {
        return view('filename');
    }

How can I get view page with this url : www.domain-name.in/sample/ID

Body:
Your route will be

Route::get('sample/{id}','HomeController@index')->where(['id' => '[0-9]{1,5}');

Your controller will be

public function index($id)
{
   echo $id;
   exit;
   return view('filename');
}

Now you can access it as url as below.

www.domain-name.in/sample/12345

"12345" is integer value of 5 digits sample id.


问:
How to mask string after first character
Let's say I have a string that consists of a person's name:

```<code>var name = "Jason, Bruno Mars";
</code>```

How do I mask the string with X for the name behind the comma and returns:

```<code>var name = "Jason, BXXXX MXXX";
</code>```

I have tried using the following methods but only front characters are masked:

```<code>string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}
</code>```

Anyone has a better idea of how can I achieve the same result in a more efficient way?

答:
```<code>Using This code..

    static string MaskName(string name)
    {
        string maskedString = string.Empty;

        string[] names = name.Split(',');
        if (names.Length > 0)
        {
            maskedString = names[0] + ",";
        }
        if (names.Length > 1)
        {
            string[] arrName = names[1].Split(' ');
            foreach (string s in arrName)
            {
                if (s.Length > 0)
                    maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
            }
        }
        return maskedString;
    }
</code>```

Output :-

Body:
Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?

Body:
Using This code..

    static string MaskName(string name)
    {
        string maskedString = string.Empty;

        string[] names = name.Split(',');
        if (names.Length > 0)
        {
            maskedString = names[0] + ",";
        }
        if (names.Length > 1)
        {
            string[] arrName = names[1].Split(' ');
            foreach (string s in arrName)
            {
                if (s.Length > 0)
                    maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
            }
        }
        return maskedString;
    }

Output :-


问:
AngularDart: How to run locally release build
I made release build of AngularDart app with webdev build.

How can I run it locally before deploying to remote hosting server?

At the moment I am using Built-in web server in PHP:

cd build
php -S localhost:8888
```

Is it possible to run locally release build with webdev or build_runner commands?

Thank you in advance!

答:
Sure!

```<code>webdev serve --release
</code>```

or, if you want to run it with a specific build config, replace the build with serve in your build_runner command:

```<code>pub run build_runner serve -c production --release -o web:build
</code>```

And if you want to get to it from somewhere other then localhost:

```<code>webdev serve --release --hostname 0.0.0.0
</code>```

Body:
I made release build of AngularDart app with webdev build.

How can I run it locally before deploying to remote hosting server?

At the moment I am using Built-in web server in PHP:

cd build
php -S localhost:8888

Is it possible to run locally release build with webdev or build_runner commands?

Thank you in advance!

Body:
Sure!

webdev serve --release

or, if you want to run it with a specific build config, replace the build with serve in your build_runner command:

pub run build_runner serve -c production --release -o web:build

And if you want to get to it from somewhere other then localhost:

webdev serve --release --hostname 0.0.0.0


问:
How to call ExitPopUp widgets from other pages in Flutter?
I wrote a code for ExitPopUp on a single page. Here is the code -

```<code>import 'package:flutter/material.dart';

class ExitPopUp extends StatelessWidget {
  final page;
  ExitPopUp(this.page);
  @override
  Widget build(BuildContext context) {
    Future<bool> showExitPopUp() {
      return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Confirm"),
              content: Text("Do you want to Exit ?"),
              actions: <Widget>[
                RaisedButton(child: Text("No"), onPressed: null),
                RaisedButton(child: Text("Yes "), onPressed: null)
              ],
            );
          });
    }

    return WillPopScope(child: page, onWillPop: showExitPopUp);
  }
}
</code>```

Now I want to call this ExitPopUp from other page (***example:* registration.dart)**. Here is the code of Registration page-

```<code>import 'package:bloodhero/widgets/drawer.dart';
import 'package:bloodhero/widgets/exitpop.dart';
import 'package:flutter/material.dart';
import 'package:bloodhero/widgets/form.dart';

class Registration extends StatefulWidget {
  @override
  _RegistrationState createState() => _RegistrationState();
}

class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          print("Hey I am Dialog Box");
          return ExitPopUp();
        },
        child: Scaffold(
            appBar: AppBar(
              title: Text("Registration"),
              backgroundColor: Colors.deepOrange,
            ),
            drawer: DrawerApp(),
            body: ListView(
              children: <Widget>[
                FormPage(),
              ],
            )));
  }
}
</code>```

But It's not working. Error show in OnWillPop.

How can I fix it?

答:
You can copy paste run full code below

You can pass Scaffold part code as parameter of ExitPopUp

code snippet

```<code>class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return ExitPopUp(Scaffold(
        appBar: AppBar(
          title: Text("Registration"),
          backgroundColor: Colors.deepOrange,
        ),
        //drawer: DrawerApp(),
        body: ListView(
          children: <Widget>[
            Text("FormPage()"),
          ],
        )));
  }
}
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';

class ExitPopUp extends StatelessWidget {
  final page;
  ExitPopUp(this.page);
  @override
  Widget build(BuildContext context) {
    Future<bool> showExitPopUp() {
      return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Confirm"),
              content: Text("Do you want to Exit ?"),
              actions: <Widget>[
                RaisedButton(child: Text("No"), onPressed: (){}),
                RaisedButton(child: Text("Yes "), onPressed: null)
              ],
            );
          });
    }

    return WillPopScope(child: page, onWillPop: showExitPopUp);
  }
}

class Registration extends StatefulWidget {
  @override
  _RegistrationState createState() => _RegistrationState();
}

class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return ExitPopUp(Scaffold(
        appBar: AppBar(
          title: Text("Registration"),
          backgroundColor: Colors.deepOrange,
        ),
        //drawer: DrawerApp(),
        body: ListView(
          children: <Widget>[
            Text("FormPage()"),
          ],
        )));
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Registration(),
    );
  }
}
</code>```

Body:
I wrote a code for ExitPopUp on a single page. Here is the code -

import 'package:flutter/material.dart';

class ExitPopUp extends StatelessWidget {
  final page;
  ExitPopUp(this.page);
  @override
  Widget build(BuildContext context) {
    Future<bool> showExitPopUp() {
      return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Confirm"),
              content: Text("Do you want to Exit ?"),
              actions: <Widget>[
                RaisedButton(child: Text("No"), onPressed: null),
                RaisedButton(child: Text("Yes "), onPressed: null)
              ],
            );
          });
    }

    return WillPopScope(child: page, onWillPop: showExitPopUp);
  }
}

Now I want to call this ExitPopUp from other page (***example:* registration.dart)**. Here is the code of Registration page-

import 'package:bloodhero/widgets/drawer.dart';
import 'package:bloodhero/widgets/exitpop.dart';
import 'package:flutter/material.dart';
import 'package:bloodhero/widgets/form.dart';

class Registration extends StatefulWidget {
  @override
  _RegistrationState createState() => _RegistrationState();
}

class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          print("Hey I am Dialog Box");
          return ExitPopUp();
        },
        child: Scaffold(
            appBar: AppBar(
              title: Text("Registration"),
              backgroundColor: Colors.deepOrange,
            ),
            drawer: DrawerApp(),
            body: ListView(
              children: <Widget>[
                FormPage(),
              ],
            )));
  }
}

But It's not working. Error show in OnWillPop.

How can I fix it?

Body:
You can copy paste run full code below

You can pass Scaffold part code as parameter of ExitPopUp

code snippet

class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return ExitPopUp(Scaffold(
        appBar: AppBar(
          title: Text("Registration"),
          backgroundColor: Colors.deepOrange,
        ),
        //drawer: DrawerApp(),
        body: ListView(
          children: <Widget>[
            Text("FormPage()"),
          ],
        )));
  }
}

working demo

full code

import 'package:flutter/material.dart';

class ExitPopUp extends StatelessWidget {
  final page;
  ExitPopUp(this.page);
  @override
  Widget build(BuildContext context) {
    Future<bool> showExitPopUp() {
      return showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Confirm"),
              content: Text("Do you want to Exit ?"),
              actions: <Widget>[
                RaisedButton(child: Text("No"), onPressed: (){}),
                RaisedButton(child: Text("Yes "), onPressed: null)
              ],
            );
          });
    }

    return WillPopScope(child: page, onWillPop: showExitPopUp);
  }
}

class Registration extends StatefulWidget {
  @override
  _RegistrationState createState() => _RegistrationState();
}

class _RegistrationState extends State<Registration> {
  @override
  Widget build(BuildContext context) {
    return ExitPopUp(Scaffold(
        appBar: AppBar(
          title: Text("Registration"),
          backgroundColor: Colors.deepOrange,
        ),
        //drawer: DrawerApp(),
        body: ListView(
          children: <Widget>[
            Text("FormPage()"),
          ],
        )));
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Registration(),
    );
  }
}


问:
Extract values from a text
I've log like following from test run results and from which I have to extract count of total run tests, passed tests, failed tests, skipped tests etc

```<code>[INFO] Results:\n" +
                "[INFO] \n" +
                "[ERROR] Errors: \n" +
                "[ERROR]   AttachRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for...\n" +
                "[ERROR]   CallbackActionRestTest>GenericRestBase.pre:102 » Business I/O error on GET req...\n" +
                "[ERROR]   CountRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for ..." +
                "[INFO] \n" +
                "[INFO] \n" +
                "[ERROR] Tests run: 55, Failures: 0, Errors: 44, Skipped: 0\n" +
                "[INFO] \n" +
                "[INFO] ------------------------------------------------------------------------
</code>```

In order to do that I got line with results details using following code -

```<code>String content = "[INFO] Results:\n" +
                "[INFO] \n" +
                "[ERROR] Errors: \n" +
                "[ERROR]   AttachRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for...\n" +
                "[ERROR]   CallbackActionRestTest>GenericRestBase.pre:102 » Business I/O error on GET req...\n" +
                "[ERROR]   CountRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for ..." +
                "[INFO] \n" +
                "[INFO] \n" +
                "[ERROR] Tests run: 55, Failures: 0, Errors: 44, Skipped: 0\n" +
                "[INFO] \n" +
                "[INFO] ------------------------------------------------------------------------";

        Pattern pattern = Pattern.compile("Tests run(.*)");
        Matcher matcher = pattern.matcher(content);

        if(matcher.find()) {
              String foundText = matcher.group();
        }
</code>```

It gives me following value in foundText -

```<code>Tests run: 55, Failures: 0, Errors: 44, Skipped: 0
</code>```

Now I want to extract, total count, failurs, Errors, Skipped etc.

I can use split() method over that string but that would make code lengthy and not reliable.

Is there any better way in Java I can extract those values?

Notes: Because of some limitations in my project, I cannot use libraries which are not part of Java. I mean no extra jar or maven dependency.

答:
How about using split after removing non-digit characters with regex?</p>

```<code>String str = "Tests run: 55, Failures: 0, Errors: 44, Skipped: 0";
str = str.replaceAll("\\D+"," ").trim();
str.split(" "); // [55, 0, 44, 0]
</code>```

Title: Extract values from a text

Body:
I've log like following from test run results and from which I have to extract count of total run tests, passed tests, failed tests, skipped tests etc

[INFO] Results:\n" +
                "[INFO] \n" +
                "[ERROR] Errors: \n" +
                "[ERROR]   AttachRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for...\n" +
                "[ERROR]   CallbackActionRestTest>GenericRestBase.pre:102 » Business I/O error on GET req...\n" +
                "[ERROR]   CountRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for ..." +
                "[INFO] \n" +
                "[INFO] \n" +
                "[ERROR] Tests run: 55, Failures: 0, Errors: 44, Skipped: 0\n" +
                "[INFO] \n" +
                "[INFO] ------------------------------------------------------------------------

In order to do that I got line with results details using following code -

String content = "[INFO] Results:\n" +
                "[INFO] \n" +
                "[ERROR] Errors: \n" +
                "[ERROR]   AttachRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for...\n" +
                "[ERROR]   CallbackActionRestTest>GenericRestBase.pre:102 » Business I/O error on GET req...\n" +
                "[ERROR]   CountRestTest>GenericRestBase.pre:102 » Business I/O error on GET request for ..." +
                "[INFO] \n" +
                "[INFO] \n" +
                "[ERROR] Tests run: 55, Failures: 0, Errors: 44, Skipped: 0\n" +
                "[INFO] \n" +
                "[INFO] ------------------------------------------------------------------------";

        Pattern pattern = Pattern.compile("Tests run(.*)");
        Matcher matcher = pattern.matcher(content);

        if(matcher.find()) {
              String foundText = matcher.group();
        }

It gives me following value in foundText -

Tests run: 55, Failures: 0, Errors: 44, Skipped: 0

Now I want to extract, total count, failurs, Errors, Skipped etc.

I can use split() method over that string but that would make code lengthy and not reliable.

Is there any better way in Java I can extract those values?

Notes: Because of some limitations in my project, I cannot use libraries which are not part of Java. I mean no extra jar or maven dependency.

Body:
How about using split after removing non-digit characters with regex?

String str = "Tests run: 55, Failures: 0, Errors: 44, Skipped: 0";
str = str.replaceAll("\\D+"," ").trim();
str.split(" "); // [55, 0, 44, 0]