问:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays error
Backend (Spring Boot, REST(Spring Data Rest, Spring Data JPA) It's only happening with JPA, without it works perfectly, but a hella lot more code to write).

I tried all the remaining responses but I'm not getting the exact solution.

BACKEND API

```<code>New File
pizzatest.model.ts
export class Pizzas{

    firstName: string;
    description: string;
}

API BELOW

_embedded
pizzas
0
firstName   "Pizza Margarita"
description "Ingredients of Margarita"
_links
self
href    "http://localhost:8080/pizzas/1"
pizza
href    "http://localhost:8080/pizzas/1"
1
firstName   "Detroit Pizza"
description "Ingredients of Detroit Pizza"
_links
self
href    "http://localhost:8080/pizzas/2"
pizza
href    "http://localhost:8080/pizzas/2"
2
firstName   "Greek Pizza"
description "Ingredients of Greek Pizza"
_links
self
href    "http://localhost:8080/pizzas/3"
pizza
href    "http://localhost:8080/pizzas/3"
3
firstName   "Sicilian Pizza"
description "Ingredients of Sicilian Pizza"
_links
self
href    "http://localhost:8080/pizzas/4"
pizza
href    "http://localhost:8080/pizzas/4"
4
firstName   "Chicago Pizza"
description "Ingredients of Chicago Pizza"
_links
self
href    "http://localhost:8080/pizzas/5"
pizza
href    "http://localhost:8080/pizzas/5"
_links
self
href    "http://localhost:8080/pizzas{?page,size,sort}"
templated   true
profile
href    "http://localhost:8080/profile/pizzas"
page
size    20
totalElements   5
totalPages  1
number  0
</code>```

SERVICE

```<code>import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PizzatestService {

readonly rootUrl = 'http://localhost:8080/'

  constructor(private http: HttpClient) { }

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas');
}}
</code>```

TYPESCRIPT

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PizzatestService } from './pizzatest.service';
import {Pizzas} from './pizzatest.model';

@Component({
  selector: 'app-pizzatest',
  templateUrl: './pizzatest.component.html',
  styleUrls: ['./pizzatest.component.css']
})
export class PizzatestComponent implements OnInit {

pizzas : Pizzas[]

  constructor(private pizzaTestService: PizzatestService) { }

  ngOnInit() {
this.pizzaTestService.getPizzas().subscribe((data: any) => {
  console.log('from service', data)
  this.pizzas = data;
})
  }
}
</code>```

HTML

```<code><div *ngFor="let pizza of pizzas">
        <ul>
          <li> {{pizza.firstName}}</li>
          <li> {{pizza.description}}</li>
        </ul>
        </div>
</code>```

答:
Every return of data using HttpClient is in Json object format. For example:

Here's a sample code that you can try.

You can try to map your data inside the service.ts:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
  export class DataloadService {

    constructor(private http: HttpClient) { }

    LoadData(): Observable<any> {
      return this.http.get('https://jsonplaceholder.typicode.com/users')
        .map(this.extractData)
    }

    private extractData(res: Response) {
      let body = res;
      return body;
    }

  }
</code>```

Here's the app.component.ts:

```<code>import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {DataloadService} from './dataload.service';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent {

  dataFromServer: Observable<any>;

  constructor(private load: DataloadService) {}

  getDataServer() {
    let obj = this.load.LoadData();
    obj.subscribe(data => {this.dataFromServer = data;
    console.log("data:", data);
    })
  };

  ngOnInit() {this.getDataServer();}

}
</code>```

The html file:

```<code><h2>My Awesome Table:</h2>

<table *ngIf="dataFromServer">

  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Username</th>
    <th>Email</th>
  </tr>

  <tr *ngFor="let data of dataFromServer">
    <td>{{data.id}}</td>
    <td>{{data.name}}</td>
    <td>{{data.username}}</td>
    <td>{{data.email}}</td>
  </tr>

</table>
</code>```

Hope this will help your problem.

Body:
Backend (Spring Boot, REST(Spring Data Rest, Spring Data JPA) It's only happening with JPA, without it works perfectly, but a hella lot more code to write).

I tried all the remaining responses but I'm not getting the exact solution.

BACKEND API

New File
pizzatest.model.ts
export class Pizzas{

    firstName: string;
    description: string;
}

API BELOW

_embedded
pizzas
0
firstName   "Pizza Margarita"
description "Ingredients of Margarita"
_links
self
href    "http://localhost:8080/pizzas/1"
pizza
href    "http://localhost:8080/pizzas/1"
1
firstName   "Detroit Pizza"
description "Ingredients of Detroit Pizza"
_links
self
href    "http://localhost:8080/pizzas/2"
pizza
href    "http://localhost:8080/pizzas/2"
2
firstName   "Greek Pizza"
description "Ingredients of Greek Pizza"
_links
self
href    "http://localhost:8080/pizzas/3"
pizza
href    "http://localhost:8080/pizzas/3"
3
firstName   "Sicilian Pizza"
description "Ingredients of Sicilian Pizza"
_links
self
href    "http://localhost:8080/pizzas/4"
pizza
href    "http://localhost:8080/pizzas/4"
4
firstName   "Chicago Pizza"
description "Ingredients of Chicago Pizza"
_links
self
href    "http://localhost:8080/pizzas/5"
pizza
href    "http://localhost:8080/pizzas/5"
_links
self
href    "http://localhost:8080/pizzas{?page,size,sort}"
templated   true
profile
href    "http://localhost:8080/profile/pizzas"
page
size    20
totalElements   5
totalPages  1
number  0

SERVICE

import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PizzatestService {

readonly rootUrl = 'http://localhost:8080/'

  constructor(private http: HttpClient) { }

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas');
}}

TYPESCRIPT

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PizzatestService } from './pizzatest.service';
import {Pizzas} from './pizzatest.model';

@Component({
  selector: 'app-pizzatest',
  templateUrl: './pizzatest.component.html',
  styleUrls: ['./pizzatest.component.css']
})
export class PizzatestComponent implements OnInit {

pizzas : Pizzas[]

  constructor(private pizzaTestService: PizzatestService) { }

  ngOnInit() {
this.pizzaTestService.getPizzas().subscribe((data: any) => {
  console.log('from service', data)
  this.pizzas = data;
})
  }
}

HTML

 {{pizza.firstName}}

 {{pizza.description}}

Body:
Every return of data using HttpClient is in Json object format. For example:

Here's a sample code that you can try.

You can try to map your data inside the service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
  export class DataloadService {

    constructor(private http: HttpClient) { }

    LoadData(): Observable<any> {
      return this.http.get('https://jsonplaceholder.typicode.com/users')
        .map(this.extractData)
    }

    private extractData(res: Response) {
      let body = res;
      return body;
    }

  }

Here's the app.component.ts:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {DataloadService} from './dataload.service';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent {

  dataFromServer: Observable<any>;

  constructor(private load: DataloadService) {}

  getDataServer() {
    let obj = this.load.LoadData();
    obj.subscribe(data => {this.dataFromServer = data;
    console.log("data:", data);
    })
  };

  ngOnInit() {this.getDataServer();}

}

The html file:

<h2>My Awesome Table:</h2>

<table *ngIf="dataFromServer">

  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Username</th>
    <th>Email</th>
  </tr>

  <tr *ngFor="let data of dataFromServer">
    <td>{{data.id}}</td>
    <td>{{data.name}}</td>
    <td>{{data.username}}</td>
    <td>{{data.email}}</td>
  </tr>

</table>

Hope this will help your problem.


来源: stackexchange

问:
spring-repository save doesn't work when add spring-batch dependency?
There is application on spring4+jpa deploied on websphere 8.5.5.13
There is JPA saving in database.
So, after I added spring-batch -I faced with problem, jpa entities doesn't save.

So, the reason in transaction manager configuration like here, if I add transaction manager - JPA try to use it too.

I have root config like

```<code>@Configuration
@EnableWebMvc
@EnableBatchProcessing
@ComponentScan(basePackages = {"config"})
@PropertySource("classpath:application.properties")
public class WebAppInitalizer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(
                WebConfig.class,
                ServiceConfig.class,
                PersistenceConfig.class,
                BatchConfig.class
                );
                ....
    }
</code>```

For just save entity I use spring-controller and spring repositoty. Code for saving is

```<code>record = new UserRecord(name, surname, age, updateDateTime, serialize(UserToSave));
</code>```

entity:

```<code>@Entity
@Audited
@Table(name = "UserRecord")
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor
@Getter
@Setter
@Access(AccessType.FIELD)
public class UserRecord {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "PR_KEY")
    private String prKey;

    //Business Key
    @Column(name = "name", length = 100, unique = false)
    private String name;

    //Business Key
    @Column(name = "surname", length = 100, nullable = false)
    private String surname;

    //Business Key
    @Column(name = "age", length = 100, nullable = false)
    private int age;

    @Column(name = "updateDateTime", length = 50, nullable = false)
    private Timestamp updateDateTime;

    @Version
    private int version;

    @Column(name = "user", length = 100000)
    @Lob
    private byte[] user;

    public UserRecord(String name, String surname, String age, Timestamp updateDateTime, byte[] user) {
        this.name = name;
        this.surname = surname;
        this.age = age;
        this.updateDateTime = updateDateTime;
        this.user = user;
    }
}
</code>```

Spring-repository:

```<code>  @Repository
    public interface UserRepository extends CrudRepository<UserRecord, String>
     {}
</code>```

When I added BatchConfig and some bean into, doesn't saving occours..

```<code>@Configuration
@EnableBatchProcessing
@Import(PersistenceConfig.class)
public class BatchConfig {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job processJob() {
        return jobBuilderFactory
                .get("processJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener())
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").<Person, Person>chunk(1)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }

    @Bean
    public JobExecutionListener listener() {
        return new JobCompletionListener();
    }

    @Bean
    public ItemProcessor<Person, Person> processor(){
        return new ItemProcessor<Person, Person>(){
            @Override
            public Person process(Person person) throws Exception {
                person.setName(person.getName().toUpperCase());
                person.setSurname(person.getSurname().toUpperCase());
                person.setAge(person.getAge());
                adminInfo.append("processing person" + person);
                return person;
            }
        };
    }

    @Bean
    public FlatFileItemReader<Person> reader() {
        FlatFileItemReader<Person> reader = new FlatFileItemReader<>();
        reader.setResource(new FileSystemResource("simple-data.csv"));
        reader.setLinesToSkip(1);
        reader.setLineMapper(new DefaultLineMapper() {
            {
                //3 columns in each row
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(new String[] { "name", "surname", "age" });
                    }
                });
                //Set values in Employee class
                setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
                    {
                        setTargetType(Person.class);
                    }
                });
            }
        });

        return reader;
    }

    @Bean
    public ItemWriter<Person> writer(){
        ItemWriter<Person> writer = new ItemWriter<Person>() {
            @Override
            public void write(List<? extends Person> messages) throws Exception {
                for (Person msg : messages) {
                    logger.log(Level.INFO, "Writing the data " + msg);
                }
            }
        };
        return writer;
    }

    @Bean
    public ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public JobRepository jobRepository(ResourcelessTransactionManager transactionManager) throws Exception {
        MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(transactionManager);
        mapJobRepositoryFactoryBean.setTransactionManager(transactionManager);
        return mapJobRepositoryFactoryBean.getObject();
    }

    @Bean
    public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
        SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
        simpleJobLauncher.setJobRepository(jobRepository);
        return simpleJobLauncher;
    }
}
</code>```

my pom.xml is:

```<code>    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.13.RELEASE</spring.version>
        <spring.batch>3.0.8.RELEASE</spring.batch>
        <javax.servlet>3.0.1</javax.servlet>
        <spring.test>3.2.4.RELEASE</spring.test>
        <junit.version>4.11</junit.version>
        <slf4j.version>1.7.25</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <build>
        <finalName>SomeNAme</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <testSourceDirectory>src/test</testSourceDirectory>
    </build>

    <dependencies>
        <!--SPRING-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!--SPRING-BATCH CONFIGURED-->
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-tx</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.retry</groupId>
                    <artifactId>spring-retry</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.2.1.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
                                <!--JPA-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.9.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjrt</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
                           <!--DATABASE-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.spec.javax.transaction</groupId>
                    <artifactId>jboss-transaction-api_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>javax.transaction-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.spec.javax.transaction</groupId>
                    <artifactId>jboss-transaction-api_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.geronimo.specs</groupId>
                    <artifactId>geronimo-jta_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.oracle.odb</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>
                          <!--TEST-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
                        <!-- SERVLET-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet}</version>
            <scope>provided</scope>
        </dependency>
                         <!--JACKSON AND XML-->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.12</version>
        </dependency>
        <!--APACHE-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <!--TEST-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <!--LOG4J-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>
</project>
</code>```

So, this is libraries issue? (I tried to comment all spring-batch code and leaves only depedency in pom - and it starts to work..

my beans related with database is:

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = {"persistence"})
@ComponentScan(basePackages = {"persistence""})
public class PersistenceConfig {

    @Bean
    @Resource(type = DataSource.class, lookup = "jdbc/MyDataBase", name = "jdbc/MyDataBase")
    public DataSource dataSource() {
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/MyDataBase");
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource());
        entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setJpaProperties(getHibernateProperties());
        log.info("Entity Manager configured.");
        return entityManager;
    }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

    //Set properties hibernate
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field", false);

        properties.put("verifyServerCertificate", false);
        properties.put("useSSL", false);
        properties.put("requireSSL", false);
        properties.put("useLegacyDatetimeCode", false);
        properties.put("useUnicode", "yes");
        properties.put("characterEncoding", "UTF-8");
        properties.put("serverTimezone", "UTC");
        properties.put("useJDBCCompliantTimezoneShift", true);
        return properties;
    }
}
</code>```

I think that reason is in Transaction management, but can't to configure it correct way. If I use this way for creating transaction management:

```<code> public PlatformTransactionManager getTransactionManager() throws Exception {
        return new WebSphereUowTransactionManager();
    }
</code>```

or

```<code>public PlatformTransactionManager getTransactionManager() throws Exception {
    return new DataSourceTransactionManager(dataSource);
}
</code>```

I have an error message

Error 500: org.springframework.web.util.NestedServletException:
  Request processing failed; nested exception is
  org.springframework.jdbc.BadSqlGrammarException:
  PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID,
  JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?];
  nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table
  or view does not exist

this is because I have no temp table for spring batch..

If I used

```<code> public PlatformTransactionManager getTransactionManager() throws Exception {
        return new ResourcelessTransactionManager();
    }
</code>```

spring - batch work, but doesn't work saving jpa entities..

答:
Root cause is not in dependecy conflict. The reason is that there are 2 bean with same name for JPA and for spring-batch. So, creating bean with different name is solved a problem.</p>

```<code>@Bean
    public ResourcelessTransactionManager springBatchTransactionManager() {
        return new ResourcelessTransactionManager();
    }

 @Bean
    public JobRepository jobRepository(ResourcelessTransactionManager springBatchTransactionManager) throws Exception {
        MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(springBatchTransactionManager);
        mapJobRepositoryFactoryBean.setTransactionManager(springBatchTransactionManager);
        return mapJobRepositoryFactoryBean.getObject();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is application on spring4+jpa deploied on websphere 8.5.5.13
There is JPA saving in database.
So, after I added spring-batch -I faced with problem, jpa entities doesn't save.

So, the reason in transaction manager configuration like here, if I add transaction manager - JPA try to use it too.

I have root config like

@Configuration
@EnableWebMvc
@EnableBatchProcessing
@ComponentScan(basePackages = {"config"})
@PropertySource("classpath:application.properties")
public class WebAppInitalizer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(
                WebConfig.class,
                ServiceConfig.class,
                PersistenceConfig.class,
                BatchConfig.class
                );
                ....
    }

For just save entity I use spring-controller and spring repositoty. Code for saving is

record = new UserRecord(name, surname, age, updateDateTime, serialize(UserToSave));

entity:

@Entity
@Audited
@Table(name = "UserRecord")
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor
@Getter
@Setter
@Access(AccessType.FIELD)
public class UserRecord {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "PR_KEY")
    private String prKey;

    //Business Key
    @Column(name = "name", length = 100, unique = false)
    private String name;

    //Business Key
    @Column(name = "surname", length = 100, nullable = false)
    private String surname;

    //Business Key
    @Column(name = "age", length = 100, nullable = false)
    private int age;

    @Column(name = "updateDateTime", length = 50, nullable = false)
    private Timestamp updateDateTime;

    @Version
    private int version;

    @Column(name = "user", length = 100000)
    @Lob
    private byte[] user;

    public UserRecord(String name, String surname, String age, Timestamp updateDateTime, byte[] user) {
        this.name = name;
        this.surname = surname;
        this.age = age;
        this.updateDateTime = updateDateTime;
        this.user = user;
    }
}

Spring-repository:

  @Repository
    public interface UserRepository extends CrudRepository<UserRecord, String>
     {}

When I added BatchConfig and some bean into, doesn't saving occours..

@Configuration
@EnableBatchProcessing
@Import(PersistenceConfig.class)
public class BatchConfig {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job processJob() {
        return jobBuilderFactory
                .get("processJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener())
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").<Person, Person>chunk(1)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }

    @Bean
    public JobExecutionListener listener() {
        return new JobCompletionListener();
    }

    @Bean
    public ItemProcessor<Person, Person> processor(){
        return new ItemProcessor<Person, Person>(){
            @Override
            public Person process(Person person) throws Exception {
                person.setName(person.getName().toUpperCase());
                person.setSurname(person.getSurname().toUpperCase());
                person.setAge(person.getAge());
                adminInfo.append("processing person" + person);
                return person;
            }
        };
    }

    @Bean
    public FlatFileItemReader<Person> reader() {
        FlatFileItemReader<Person> reader = new FlatFileItemReader<>();
        reader.setResource(new FileSystemResource("simple-data.csv"));
        reader.setLinesToSkip(1);
        reader.setLineMapper(new DefaultLineMapper() {
            {
                //3 columns in each row
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(new String[] { "name", "surname", "age" });
                    }
                });
                //Set values in Employee class
                setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
                    {
                        setTargetType(Person.class);
                    }
                });
            }
        });

        return reader;
    }

    @Bean
    public ItemWriter<Person> writer(){
        ItemWriter<Person> writer = new ItemWriter<Person>() {
            @Override
            public void write(List<? extends Person> messages) throws Exception {
                for (Person msg : messages) {
                    logger.log(Level.INFO, "Writing the data " + msg);
                }
            }
        };
        return writer;
    }

    @Bean
    public ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public JobRepository jobRepository(ResourcelessTransactionManager transactionManager) throws Exception {
        MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(transactionManager);
        mapJobRepositoryFactoryBean.setTransactionManager(transactionManager);
        return mapJobRepositoryFactoryBean.getObject();
    }

    @Bean
    public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
        SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
        simpleJobLauncher.setJobRepository(jobRepository);
        return simpleJobLauncher;
    }
}

my pom.xml is:

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.13.RELEASE</spring.version>
        <spring.batch>3.0.8.RELEASE</spring.batch>
        <javax.servlet>3.0.1</javax.servlet>
        <spring.test>3.2.4.RELEASE</spring.test>
        <junit.version>4.11</junit.version>
        <slf4j.version>1.7.25</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <build>
        <finalName>SomeNAme</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <testSourceDirectory>src/test</testSourceDirectory>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-tx</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.retry</groupId>
                    <artifactId>spring-retry</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.2.1.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.9.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjrt</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.spec.javax.transaction</groupId>
                    <artifactId>jboss-transaction-api_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>javax.transaction-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.spec.javax.transaction</groupId>
                    <artifactId>jboss-transaction-api_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>4.0.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.geronimo.specs</groupId>
                    <artifactId>geronimo-jta_1.1_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.oracle.odb</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.12</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>
</project>

So, this is libraries issue? (I tried to comment all spring-batch code and leaves only depedency in pom - and it starts to work..

my beans related with database is:

@Configuration
@EnableTransactionManagement
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = {"persistence"})
@ComponentScan(basePackages = {"persistence""})
public class PersistenceConfig {

    @Bean
    @Resource(type = DataSource.class, lookup = "jdbc/MyDataBase", name = "jdbc/MyDataBase")
    public DataSource dataSource() {
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/MyDataBase");
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource());
        entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
        entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManager.setJpaProperties(getHibernateProperties());
        log.info("Entity Manager configured.");
        return entityManager;
    }

    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

    //Set properties hibernate
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field", false);

        properties.put("verifyServerCertificate", false);
        properties.put("useSSL", false);
        properties.put("requireSSL", false);
        properties.put("useLegacyDatetimeCode", false);
        properties.put("useUnicode", "yes");
        properties.put("characterEncoding", "UTF-8");
        properties.put("serverTimezone", "UTC");
        properties.put("useJDBCCompliantTimezoneShift", true);
        return properties;
    }
}

I think that reason is in Transaction management, but can't to configure it correct way. If I use this way for creating transaction management:

 public PlatformTransactionManager getTransactionManager() throws Exception {
        return new WebSphereUowTransactionManager();
    }

or

public PlatformTransactionManager getTransactionManager() throws Exception {
    return new DataSourceTransactionManager(dataSource);
}

I have an error message

Error 500: org.springframework.web.util.NestedServletException:
  Request processing failed; nested exception is
  org.springframework.jdbc.BadSqlGrammarException:
  PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID,
  JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?];
  nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table
  or view does not exist

this is because I have no temp table for spring batch..

If I used

 public PlatformTransactionManager getTransactionManager() throws Exception {
        return new ResourcelessTransactionManager();
    }

spring - batch work, but doesn't work saving jpa entities..

Body:
Root cause is not in dependecy conflict. The reason is that there are 2 bean with same name for JPA and for spring-batch. So, creating bean with different name is solved a problem.

@Bean
    public ResourcelessTransactionManager springBatchTransactionManager() {
        return new ResourcelessTransactionManager();
    }

 @Bean
    public JobRepository jobRepository(ResourcelessTransactionManager springBatchTransactionManager) throws Exception {
        MapJobRepositoryFactoryBean mapJobRepositoryFactoryBean = new MapJobRepositoryFactoryBean(springBatchTransactionManager);
        mapJobRepositoryFactoryBean.setTransactionManager(springBatchTransactionManager);
        return mapJobRepositoryFactoryBean.getObject();
    }


问:
What does 's(c)' stand for in the following query?
I would like to know the role of this method 's()' in the following postgresql query : </p>

```<code>SELECT name, employee_id
FROM users u
,LATERAL (SELECT COUNT(*) FROM users u2 WHERE u.employee_id = u2.employee_id) AS s(c)
WHERE c > 1;
</code>```

答:
s is the subquery alias. c is an alias for name of the column in the subquery.

Let's take a simpler example

```<code>select s.c from (SELECT 1) AS s(c);
 c
---
 1
</code>```

which can also be written as

```<code>select s.c from (SELECT 1 as c) AS s;
 c
---
 1
</code>```

Body:
I would like to know the role of this method 's()' in the following postgresql query :

SELECT name, employee_id
FROM users u
,LATERAL (SELECT COUNT(*) FROM users u2 WHERE u.employee_id = u2.employee_id) AS s(c)
WHERE c > 1;

Body:
s is the subquery alias. c is an alias for name of the column in the subquery.

Let's take a simpler example

select s.c from (SELECT 1) AS s(c);
 c
---
 1

which can also be written as

select s.c from (SELECT 1 as c) AS s;
 c
---
 1


问:
How to split on commas and dot?
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0
```

<p>I am using Python 3.7.2 and I tried <code>re.split</code> by using <code>\,*</code> and <code>\.*</code> as shown below in the code but it seems to print after every numeral.</p>

```regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))
```

<p>However, this seems to be printing in the wrong order. </p>

<p>What should I add in <code>regex_pattern</code>?</p>

<p>Expected result was:</p>

<pre class="lang-none prettyprint-override"><code>100
000
000
000
</code>```

However, I am getting:

1
0
0

0
0
0

0
0
0
```

答:
Another way to do the job is to replace comma and dot with linebreak:

```<code>import re

string = "100,000,000.000"
print re.sub(r"[,.]", '\n', string)
</code>```

Output:

```<code>100
000
000
000
</code>```

Title: How to split on commas and dot?

Body:
You are given a string consisting only of digits, commas, and dots. Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in. It's guaranteed that every comma and every dot in is preceded and followed by a digit.

Sample Input 0

100,000,000.000

Sample Output 0

I am using Python 3.7.2 and I tried re.split by using \,* and \.* as shown below in the code but it seems to print after every numeral.

regex_pattern = r"\,*\.*"

import re
print("\n".join(re.split(regex_pattern, input())))

However, this seems to be printing in the wrong order.

What should I add in regex_pattern?

Expected result was:

100
000
000
000

However, I am getting:

1
0
0

0
0
0

0
0
0

Body:
Another way to do the job is to replace comma and dot with linebreak:

import re

string = "100,000,000.000"
print re.sub(r"[,.]", '\n', string)

Output:

100
000
000
000


问:
google health api
in my app i want to show the data of google health data for a particular account .how can i
proceed.any suggetion.where can i get the jar of the api</p>

答:
Google health api is to be used with Google Data api, which works on android. Check out the documentation.

And here is google api android java client

ContentLicense: CC BY-SA 3.0

Title: google health api


问:
Returning error from OKHttp interceptor (using retrofit)
I am using OkHttp with Retrofit to make my app's network requests. I am also using Interceptors for Authentication and retrying requests if necessary.

The server sometimes has temporary problems, and returns an empty body although the response status is 200 OK. This causes my app to crash, because the success block of the Retrofit Callback is called, the custom object returned (and parsed with GSON) is null, and the code in success callback assumes an object is returned.

I have already reported this to the server team, but I want to fix it as well, without having to wrap all success callback code all over the app with null checks.

Currenty I am inclined to two options, although any other ideas are most welcome:
1) Not returning from the interceptor (is this even possible?) and just displaying an error dialog
2) Returning something that will make Retrofit call the failure part of the callback.

My code is below. As you may see, I retry the request for a maximum of 3 times when an empty body is received.

```<code>@Override
public Response intercept(Chain chain) throws IOException
{
    // First
    Request request = chain.request();
    Response response = chain.proceed(request);

    ....
    ....
    ....

    // Retry empty body response requests for a maximum of 3 times
    Integer retryMaxCount = 3;
    MediaType contentType = response.body().contentType();
    String bodyString = response.body().string();

    while (bodyString.length() == 0 && retryMaxCount > 0)
    {
        //Empty body received!, Retrying...

        retryMaxCount--;
        response = chain.proceed(request);
        bodyString = response.body().string();
    }

    if (bodyString.length() != 0)
    {
        // Create and return new response because it was consumed
        ResponseBody newResponseBody = ResponseBody.create(contentType, bodyString);
        return response.newBuilder().body(newResponseBody).build();
    }
    else
    {
        // WHAT TO WRITE HERE???
    }
}
</code>```

Thanks a lot.

答:
My solution taken from okhttp3.logging.HttpLoggingInterceptor</p>

```<code>class ErrorResponseInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val code = response.code()
        if (code in 400..500) {
            responseBody(response)?.also { errorString ->
                // error string here is a body of server error
            }
        }
        return response
    }

    private fun responseBody(response: Response): String? {
        val responseBody = response.body() ?: return null
        val contentLength = responseBody.contentLength()

        if (contentLength == 0L) {
            return null
        }

        val source = responseBody.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        var buffer = source.buffer()
        val headers = response.headers()

        if ("gzip".equals(headers.get("Content-Encoding"), ignoreCase = true)) {
            var gzippedResponseBody: GzipSource? = null
            try {
                gzippedResponseBody = GzipSource(buffer.clone())
                buffer = okio.Buffer()
                buffer.writeAll(gzippedResponseBody)
            } finally {
                gzippedResponseBody?.close()
            }
        }

        val charset: Charset = responseBody.contentType()?.charset(UTF8) ?: UTF8
        return buffer.clone().readString(charset)
    }

    private companion object {
        val UTF8: Charset = Charset.forName("UTF-8")
    }
}
</code>```

Body:
I am using OkHttp with Retrofit to make my app's network requests. I am also using Interceptors for Authentication and retrying requests if necessary.

The server sometimes has temporary problems, and returns an empty body although the response status is 200 OK. This causes my app to crash, because the success block of the Retrofit Callback is called, the custom object returned (and parsed with GSON) is null, and the code in success callback assumes an object is returned.

I have already reported this to the server team, but I want to fix it as well, without having to wrap all success callback code all over the app with null checks.

Currenty I am inclined to two options, although any other ideas are most welcome:
1) Not returning from the interceptor (is this even possible?) and just displaying an error dialog
2) Returning something that will make Retrofit call the failure part of the callback.

My code is below. As you may see, I retry the request for a maximum of 3 times when an empty body is received.

@Override
public Response intercept(Chain chain) throws IOException
{
    // First
    Request request = chain.request();
    Response response = chain.proceed(request);

    ....
    ....
    ....

    // Retry empty body response requests for a maximum of 3 times
    Integer retryMaxCount = 3;
    MediaType contentType = response.body().contentType();
    String bodyString = response.body().string();

    while (bodyString.length() == 0 && retryMaxCount > 0)
    {
        //Empty body received!, Retrying...

        retryMaxCount--;
        response = chain.proceed(request);
        bodyString = response.body().string();
    }

    if (bodyString.length() != 0)
    {
        // Create and return new response because it was consumed
        ResponseBody newResponseBody = ResponseBody.create(contentType, bodyString);
        return response.newBuilder().body(newResponseBody).build();
    }
    else
    {
        // WHAT TO WRITE HERE???
    }
}

Thanks a lot.

Body:
My solution taken from okhttp3.logging.HttpLoggingInterceptor

class ErrorResponseInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val code = response.code()
        if (code in 400..500) {
            responseBody(response)?.also { errorString ->
                // error string here is a body of server error
            }
        }
        return response
    }

    private fun responseBody(response: Response): String? {
        val responseBody = response.body() ?: return null
        val contentLength = responseBody.contentLength()

        if (contentLength == 0L) {
            return null
        }

        val source = responseBody.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        var buffer = source.buffer()
        val headers = response.headers()

        if ("gzip".equals(headers.get("Content-Encoding"), ignoreCase = true)) {
            var gzippedResponseBody: GzipSource? = null
            try {
                gzippedResponseBody = GzipSource(buffer.clone())
                buffer = okio.Buffer()
                buffer.writeAll(gzippedResponseBody)
            } finally {
                gzippedResponseBody?.close()
            }
        }

        val charset: Charset = responseBody.contentType()?.charset(UTF8) ?: UTF8
        return buffer.clone().readString(charset)
    }

    private companion object {
        val UTF8: Charset = Charset.forName("UTF-8")
    }
}


问:
Is defining a default value for a Boolean input property in Angular bad practice?
I'm looking through an old Angular project and one component has an input property:

```<code>@Input()
isNotAdmin = true;
</code>```

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?

答:
Yes, it is considered a bad practice, Instead you can assign an input to true in ngOnChanges, Check there if changes.isNotAdmin === undefined, then assign it to 'true'.

There you can control any input property and react accordingly

Body:
I'm looking through an old Angular project and one component has an input property:

@Input()
isNotAdmin = true;

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?


问:
how to sort the key value of a map entry in descending order?
I am relatively new to Java, and the whole sort by using comparators is a bit confusing to me.

Is it possible to sort the current output of the code below in descending order without using comparators?

Or is there an easier way for me to understand how to sort said values.

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot , String s) {
        Map<String, Object> userInfo = (Map<String, Object>)dataSnapshot.getValue();
        String username = (String) userInfo.get("username");

        Map<String, Long> steps = (Map<String, Long>) userInfo.get("steps");

        long existingSteps = 0;
        for (Map.Entry<String, Long> step : steps.entrySet()) {
            existingSteps += Long.valueOf(step.getValue());
        }

        arrayList.add(new String( username + "  -  " + "steps:  " + existingSteps));

        arrayAdapter = new ArrayAdapter<>(Leaderboard.this ,
        android.R.layout.simple_list_item_1 , arrayList);

        listView.setAdapter(arrayAdapter);
}
```

<p>The current output of this code is:  </p>

```John Doe I - Steps: 79
John Doe II - Steps: 111
John Doe III - Steps: 0
John Doe IV - Steps: 88
John Doe V - Steps: 12
John Doe VI - Steps: 0
```

<p>Is it possible to get this code to run the following output:  </p>

```John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0
```

Database Structure

答:
The simplest solution I can think of, is to add under each user object, the total number of steps, as a new property. In this case, there is one more thing that you need to do, which is to increment that property with the number of steps that you get every day. Your new schema should look like this:

```<code>Firebase-root
  |
  --- user
       |
       --- userId
            |
            --- steps
            |    |
            |    --- //daily steps
            |
            --- target: 100
            |
            --- username: "John Doe I"
            |
            --- totalNumberOfSteps: 111
</code>```

To get the users in (ascending) order according to the totalNumberOfSteps property, please use the following lines of code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
Query query = userRef.orderByChild("totalNumberOfSteps");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String username = ds.child("username").getValue(String.class);
            long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
            Log.d(TAG, username + " - Steps: " + totalNumberOfSteps);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);
</code>```

Then to order it descending, please see my answer from the following post:

How to arrange firebase database data in ascending or descending order?

Finally, the result in the logcat will be:

```<code>John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0
</code>```

Body:
I am relatively new to Java, and the whole sort by using comparators is a bit confusing to me.

Is it possible to sort the current output of the code below in descending order without using comparators?

Or is there an easier way for me to understand how to sort said values.

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot , String s) {
        Map<String, Object> userInfo = (Map<String, Object>)dataSnapshot.getValue();
        String username = (String) userInfo.get("username");

        Map<String, Long> steps = (Map<String, Long>) userInfo.get("steps");

        long existingSteps = 0;
        for (Map.Entry<String, Long> step : steps.entrySet()) {
            existingSteps += Long.valueOf(step.getValue());
        }

        arrayList.add(new String( username + "  -  " + "steps:  " + existingSteps));

        arrayAdapter = new ArrayAdapter<>(Leaderboard.this ,
        android.R.layout.simple_list_item_1 , arrayList);

        listView.setAdapter(arrayAdapter);
}

The current output of this code is:

John Doe I - Steps: 79
John Doe II - Steps: 111
John Doe III - Steps: 0
John Doe IV - Steps: 88
John Doe V - Steps: 12
John Doe VI - Steps: 0

Is it possible to get this code to run the following output:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

Database Structure

Body:
The simplest solution I can think of, is to add under each user object, the total number of steps, as a new property. In this case, there is one more thing that you need to do, which is to increment that property with the number of steps that you get every day. Your new schema should look like this:

Firebase-root
  |
  --- user
       |
       --- userId
            |
            --- steps
            |    |
            |    --- //daily steps
            |
            --- target: 100
            |
            --- username: "John Doe I"
            |
            --- totalNumberOfSteps: 111

To get the users in (ascending) order according to the totalNumberOfSteps property, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
Query query = userRef.orderByChild("totalNumberOfSteps");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String username = ds.child("username").getValue(String.class);
            long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
            Log.d(TAG, username + " - Steps: " + totalNumberOfSteps);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Then to order it descending, please see my answer from the following post:

How to arrange firebase database data in ascending or descending order?

Finally, the result in the logcat will be:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0


问:
Text is getting hidden in chart js while testing on phone
Error image is attached

I am develooping chart in my application which is working working fine in web browser but while i am testing the changes as UAT testing on phone then on galaxy S5 phone its hiding the text.

Please let me know if you require anything else from my side as the i am getting stuck here.

```<code>function dashboardPieChart() {
    Highcharts.chart('dashboardPieChart', {
        colors: [
            '#cff484',
            '#4c89d3',
            '#8bbc21',
            '#910000',
            '#1aadce',
            '#492970',
            '#f28f43',
            '#77a1e5',
            '#c42525',
            '#a6c96a'
        ],

        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'

        },
        title: {
            text: 'Wallet Balance'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: false,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name} RM {point.y:.2f}</b>',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || '#4c651e'
                    }

                }

            }
        },

        credits: {
            enabled: false
        },
        series: [
            {
                name: 'Balance',
                colorByPoint: true,
                data: [
                    {
                        name: 'Balance',
                        y: Number($scope.currentBalance.replace(',', '')),
                        sliced: true,
                        selected: true

                    },
                    {
                        name: 'Market Cap',
                        y: 10000 - Number($scope.currentBalance.replace(',', '')),
                        sliced: true,
                        selected: true
                    }
                ]
            }
        ]
    });
}
</code>```

And the code from the HTML Page is like b

```<code>  <div class="col-lg-6">
    <div class="card">
        <div class="card-body">
            <div class="row">
                <div class="col-12">
                    <div id="dashboardPieChart">
                      <!--   style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
I think it's because the width of your screen is too small to display correctly the 2 texts.

So you can add the option: textOverflow: 'none' in plotOptions.pie.dataLabels.style.

So your plotOptions become:

```<code>        plotOptions: {
        pie: {
            allowPointSelect: false,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name} RM {point.y:.2f}</b>',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || '#4c651e',
                    textOverflow: 'none'
                }

            }

        }
    },
</code>```

This is a working example:
https://jsfiddle.net/noswx17b/1/

Body:
Error image is attached

I am develooping chart in my application which is working working fine in web browser but while i am testing the changes as UAT testing on phone then on galaxy S5 phone its hiding the text.

Please let me know if you require anything else from my side as the i am getting stuck here.

function dashboardPieChart() {
    Highcharts.chart('dashboardPieChart', {
        colors: [
            '#cff484',
            '#4c89d3',
            '#8bbc21',
            '#910000',
            '#1aadce',
            '#492970',
            '#f28f43',
            '#77a1e5',
            '#c42525',
            '#a6c96a'
        ],

        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'

        },
        title: {
            text: 'Wallet Balance'
        },
        tooltip: {
            pointFormat: '{series.name}: {point.percentage:.1f}%'
        },
        plotOptions: {
            pie: {
                allowPointSelect: false,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.name} RM {point.y:.2f}',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || '#4c651e'
                    }

                }

            }
        },

        credits: {
            enabled: false
        },
        series: [
            {
                name: 'Balance',
                colorByPoint: true,
                data: [
                    {
                        name: 'Balance',
                        y: Number($scope.currentBalance.replace(',', '')),
                        sliced: true,
                        selected: true

                    },
                    {
                        name: 'Market Cap',
                        y: 10000 - Number($scope.currentBalance.replace(',', '')),
                        sliced: true,
                        selected: true
                    }
                ]
            }
        ]
    });
}

And the code from the HTML Page is like b

Body:
I think it's because the width of your screen is too small to display correctly the 2 texts.

So you can add the option: textOverflow: 'none' in plotOptions.pie.dataLabels.style.

So your plotOptions become:

        plotOptions: {
        pie: {
            allowPointSelect: false,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name} RM {point.y:.2f}</b>',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || '#4c651e',
                    textOverflow: 'none'
                }

            }

        }
    },

This is a working example:
https://jsfiddle.net/noswx17b/1/


问:
How to check if environment variable contains specific string (in a BATCH file)
I have tried this but it doesn't work because variable (PATH environment variable)contains spaces: Check if variable contains a piece of text in BATCH</p>

答:
Much depends on the string you are attempting to detect. Some examples would be helpful.

Perhaps

```<code>if "%path:yourstring=%" neq "%path%" echo String found
</code>```

would work in your particular situation, but without a few details, it's little more than a guess.

Body:
Much depends on the string you are attempting to detect. Some examples would be helpful.

Perhaps

if "%path:yourstring=%" neq "%path%" echo String found

would work in your particular situation, but without a few details, it's little more than a guess.


问:
Bootstrap modal doesn't work on iPhone
I'm using a Bootstrap modal dialog on my site (which works fine on desktop). When I try to use this function on iPhones and iPads, the modals do not work.

Is there a reason for this? Has anyone come up with a fix for this whilst using Bootstrap's CSS via @import?

I use the Bootstrap override file to make changes to the Bootstrap CSS.

答:
Very easy, just add the an inline style, "cursor" to pointer and it will work straight away. style="cursor:pointer;"

```<code><li><a data-toggle="modal" data-target="#testModal" style="cursor:pointer;">Modal</a></li>
</code>```

Title: Bootstrap modal doesn't work on iPhone

Body:
Very easy, just add the an inline style, "cursor" to pointer and it will work straight away. style="cursor:pointer;"

<li><a data-toggle="modal" data-target="#testModal" style="cursor:pointer;">Modal</a></li>


问:
How to copy whole workbook to a desired location by changing a cell value
I have a excel workbook containing 5 sheets and a drop-down button in sheet-3. I want to save the entire file when i choose a option from the drop-down button with the drop-down selected option to a desired folder. It would be great if anyone can help me.

Thanks.

答:
You could try Change event:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Path As String

    If Not Intersect(Target, Range("A2")) Is Nothing And Target.Count = 1 Then 'Change the range to fit your needs

        Application.ScreenUpdating = False
        Application.DisplayAlerts = False

            Path = Target.Value

            ThisWorkbook.SaveAs Filename:="D:\R\" & Path

        Application.ScreenUpdating = True
        Application.DisplayAlerts = True

        MsgBox "Completed"

    End If

End Sub
</code>```

Notes:

It s a good idea to include the extension of the file you want to save.

You may need to check if the file exist in order to handle each situation accordingly.

Avoid Active, instead use Thisworkbook or it s name.

Body:
You could try Change event:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Path As String

    If Not Intersect(Target, Range("A2")) Is Nothing And Target.Count = 1 Then 'Change the range to fit your needs

        Application.ScreenUpdating = False
        Application.DisplayAlerts = False

            Path = Target.Value

            ThisWorkbook.SaveAs Filename:="D:\R\" & Path

        Application.ScreenUpdating = True
        Application.DisplayAlerts = True

        MsgBox "Completed"

    End If

End Sub

Notes:

It s a good idea to include the extension of the file you want to save.

You may need to check if the file exist in order to handle each situation accordingly.

Avoid Active, instead use Thisworkbook or it s name.


问:
how to parse url add params in reactJs
I'm using react-router-dom to parse a url, my current URL

localhost:3000/q=sldkfjsdlkjflksfd

but what I want is add a new param in url &test=1

localhost:3000/q=sldkfjsdlkjflksfd&test=1

const parsed = parse(window.location.search);
```

答:
You can use HTML Api  URLSearchParams,

```<code>componentDidMount(){
  let params = new URLSearchParams(this.props.location.search);
  let q = params.get('q');
  let test = params.get('test');
}
</code>```

Also, import { withRouter } from 'react-router-dom'; in your component if this.props.location is undefined and export default withRouter(ComponentName);

Title: how to parse url add params in reactJs

Body:
You can use HTML Api  URLSearchParams,

componentDidMount(){
  let params = new URLSearchParams(this.props.location.search);
  let q = params.get('q');
  let test = params.get('test');
}

Also, import { withRouter } from 'react-router-dom'; in your component if this.props.location is undefined and export default withRouter(ComponentName);


问:
Error due to unexpected value in module when use command "ionic cordova build android --release --prod"
I tried to do ionic cordova build android --release --prod but this error come out.

ERROR in : Unexpected value 'ServicePage in C:/Users/User/Ionic project/PLUMS/src/app/service/service.page.ts' declared by the module 'ServicePageModule in C:/Users/User/Ionic project/PLUMS/src/app/service/service.module.ts'. Please add a @Pipe/@Directive/@Component annotation.
[ERROR] An error occurred while running subprocess ng.

What should I do to solve the error?

```<code>**code for service.module.ts**
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { ServicePage } from './service.page';

const routes: Routes = [
  {
    path: '',
    component: ServicePage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  declarations: [ServicePage]
})
export class ServicePageModule {}
</code>```

```<code>**code for service.page.ts**
import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})

@Component({
  selector: 'app-service',
  templateUrl: './service.page.html',
  styleUrls: ['./service.page.scss'],
})

export class ServicePage {
  constructor(private firestore: AngularFirestore) { }
}
</code>```

答:
You need to add

```<code>@IonicPage()
</code>```

because ServicePage is a page and you don't forget add the import for this annotation. Apart of that, you need to remove

```<code>@Injectable({ providedIn: 'root'})
</code>```

because that annotation is for services.

Regards!

Body:
I tried to do ionic cordova build android --release --prod but this error come out.

ERROR in : Unexpected value 'ServicePage in C:/Users/User/Ionic project/PLUMS/src/app/service/service.page.ts' declared by the module 'ServicePageModule in C:/Users/User/Ionic project/PLUMS/src/app/service/service.module.ts'. Please add a @Pipe/@Directive/@Component annotation.
[ERROR] An error occurred while running subprocess ng.

What should I do to solve the error?

**code for service.module.ts**
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { ServicePage } from './service.page';

const routes: Routes = [
  {
    path: '',
    component: ServicePage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  declarations: [ServicePage]
})
export class ServicePageModule {}

**code for service.page.ts**
import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})

@Component({
  selector: 'app-service',
  templateUrl: './service.page.html',
  styleUrls: ['./service.page.scss'],
})

export class ServicePage {
  constructor(private firestore: AngularFirestore) { }
}

Body:
You need to add

@IonicPage()

because ServicePage is a page and you don't forget add the import for this annotation. Apart of that, you need to remove

@Injectable({ providedIn: 'root'})

because that annotation is for services.

Regards!


问:
How do I use JavaScript RegExp to replace last occurance of a string
I have a JavaScript variable with string contents having commas (,). How do I replace the last comma (,) with 'and' using RegExp?</p>

```<code>var band = "John, Paul, George, Ringo";
var beatles = band.replace(<reg-exp>, "and");
console.log(beatles); //outputs "John, Paul, George and Ringo"
</code>```

答:
You can use greedy .* at the start before comma and capture in a group to put it back in replacement:

```<code>str = str.replace(/^(.*),/, "$1 and");
</code>```

RegEx Demo

.* will match longest string before matching last ,.

Another approach is to use negated character class in the end to match 0 or more non-comma characters after comma:

```<code>str = str.replace(/,\s*([^,]*)$/, " and $1");
</code>```

RegEx Demo 2

Body:
I have a JavaScript variable with string contents having commas (,). How do I replace the last comma (,) with 'and' using RegExp?

var band = "John, Paul, George, Ringo";
var beatles = band.replace(<reg-exp>, "and");
console.log(beatles); //outputs "John, Paul, George and Ringo"

Body:
You can use greedy .* at the start before comma and capture in a group to put it back in replacement:

str = str.replace(/^(.*),/, "$1 and");

RegEx Demo

.* will match longest string before matching last ,.

Another approach is to use negated character class in the end to match 0 or more non-comma characters after comma:

str = str.replace(/,\s*([^,]*)$/, " and $1");

RegEx Demo 2


问:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I'm trying to execute a Python script, but I am getting the following error:

```<code>Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
</code>```

I'm using python 3.5.2 on a Linux Mint 18.1 Serena OS

Can someone tell me why this happens, and how can I solve?

答: Another possible cause (which I encountered today) is that you're trying to read/write a file which is open. In this case, simply closing the file and rerunning the script solved the issue.</p>

Body:
I'm trying to execute a Python script, but I am getting the following error:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

I'm using python 3.5.2 on a Linux Mint 18.1 Serena OS

Can someone tell me why this happens, and how can I solve?


问:
How can i get image to some imageView, which is in another Viewcontroller, and wasn't created(is nil) yet
How can i get image to some imageView, which is in another Viewcontroller, and wasn't created(is nil) yet

```<code>let vc = SelectedCellViewController()
vc.nameLabel.text = MainViewController.dishesArray[indexPath.section].name
</code>```

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

答:
Create a variable name and set that variable while creating the instance of SelectedCellViewController. Set the text to nameLabel in viewDidLoad().

```<code>class SelectedCellViewController: UIViewController {
    @IBOutlet weak var nameLabel: UILabel!
    var name: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.nameLabel.text = self.name
    }
}
</code>```

Usage:

```<code>if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SelectedCellViewController") as? SelectedCellViewController {
    vc.name = MainViewController.dishesArray[indexPath.section].name
}
</code>```

Body:
How can i get image to some imageView, which is in another Viewcontroller, and wasn't created(is nil) yet

let vc = SelectedCellViewController()
vc.nameLabel.text = MainViewController.dishesArray[indexPath.section].name

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

Body:
Create a variable name and set that variable while creating the instance of SelectedCellViewController. Set the text to nameLabel in viewDidLoad().

class SelectedCellViewController: UIViewController {
    @IBOutlet weak var nameLabel: UILabel!
    var name: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.nameLabel.text = self.name
    }
}

Usage:

if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SelectedCellViewController") as? SelectedCellViewController {
    vc.name = MainViewController.dishesArray[indexPath.section].name
}


问:
Nock does not returns the setted headers
I'm using Nock to intercept a http request.

test.js:

```<code>const nock = require('nock');
const server = require('../server');
const request = require('request');

describe('My test', () =>{
   it('Should returns the customized header', () => {
      nock('url')
      .get('/test')
      .reply(302, {
         'user-agent': 'Mozilla'
       })

      const { headers } = await request(server).get('/test');
      expect(headers['user-agent']).to.include('Mozilla');

   }
})
</code>```

When I run the test, it fails and the log of headers received by request is like that:

```<code> {

 'user-agent': 'node-superagent/3.8.3',
  location: 'undefined',
  vary: 'Accept, Accept-Encoding',
  'content-type': 'text/plain; charset=utf-8',
  'content-length': '31',
  date: 'Fri, 24 May 2019 09:15:46 GMT',
  connection: 'close'
 }
</code>```

Do I missed something or it's the normal behaviour of Nock?

答:
The issue is with the way you're passing the headers to the reply function. Headers are the third argument for that method, but you're providing them as the second arg which means the object with the the user-agent key is being used as the body. Since it's a 302 and you probably want an empty body, you should pass an empty string as the second arg.

```<code>nock('url')
  .get('/test')
  .reply(302, '', {
    'user-agent': 'Mozilla'
  })
</code>```

Related docs.

Body:
I'm using Nock to intercept a http request.

test.js:

const nock = require('nock');
const server = require('../server');
const request = require('request');

describe('My test', () =>{
   it('Should returns the customized header', () => {
      nock('url')
      .get('/test')
      .reply(302, {
         'user-agent': 'Mozilla'
       })

      const { headers } = await request(server).get('/test');
      expect(headers['user-agent']).to.include('Mozilla');

   }
})

When I run the test, it fails and the log of headers received by request is like that:

 {

 'user-agent': 'node-superagent/3.8.3',
  location: 'undefined',
  vary: 'Accept, Accept-Encoding',
  'content-type': 'text/plain; charset=utf-8',
  'content-length': '31',
  date: 'Fri, 24 May 2019 09:15:46 GMT',
  connection: 'close'
 }

Do I missed something or it's the normal behaviour of Nock?

Body:
The issue is with the way you're passing the headers to the reply function. Headers are the third argument for that method, but you're providing them as the second arg which means the object with the the user-agent key is being used as the body. Since it's a 302 and you probably want an empty body, you should pass an empty string as the second arg.

nock('url')
  .get('/test')
  .reply(302, '', {
    'user-agent': 'Mozilla'
  })

Related docs.


问:
Fonts in pdf documents screwed up when generated with latex (specifically, pdflatex) on mac osx
My colleague suggests that texniscope is somehow to blame and that I should try purging it from my system.  I really hope not to have to resort to that!

Possible clues:

This wasn't an issue till I upgraded to Leopard.

When I say the fonts are screwed up, I mean the main text looks like maybe it's the default mac system font, and all math is completely unreadable.  Basically all special symbols are completely garbled.

I installed latex from here:  http://www.tug.org/mactex/.  I had already had texniscope installed.

When I run /usr/texbin/pdflatex foo.tex, it seems to work:

```
     This is pdfTeXk, Version 3.1415926-1.40.9 (Web2C 7.5.7)
     %&-line parsing enabled.
     entering extended mode
    ...
```

but the resulting pdf file has screwed up fonts.

The same thing happens both with pdflatex on the command line, or using TeXShop.

答:
Apple knows about the problem and isn't planning to fix it (I had a faculty member spend a lot of time testing and submit a bug to Apple).  Their claim is that PDFTeX is embedding the fonts incorrectly, and they have fixed the Apple PDF library to be more strict about what it will and won't accept, which means that you will continue to see problems with PDF documents created with PDFTeX in Preview, TeXShop, or other tools that display PDF using Apple's PDF engine.  Unfortunately, they weren't at all clear about exactly what it is that PDFTeX is doing wrong, which makes fixing it or even reporting the bug to the PDFTeX developers problematic.  Note that Adobe's Acrobat or Reader applications can often display these documents without any problems; presumably Adobe's error-checking is more liberal than Apple's.

You can actually recover from this problem without rebooting, although you may see it recur with the same document in the same session.  You need to run

```<code>atsutil server -shutdown
</code>```

which will kill the Apple Type Services server daemon (ATSServer) and spawn a new instance, coincidentally rebuilding its cache files.

OwnerDisplayName: dreeves

ContentLicense: CC BY-SA 2.5

Body:
My colleague suggests that texniscope is somehow to blame and that I should try purging it from my system.  I really hope not to have to resort to that!

Possible clues:

This wasn't an issue till I upgraded to Leopard.

When I say the fonts are screwed up, I mean the main text looks like maybe it's the default mac system font, and all math is completely unreadable.  Basically all special symbols are completely garbled.

I installed latex from here:  http://www.tug.org/mactex/.  I had already had texniscope installed.

When I run /usr/texbin/pdflatex foo.tex, it seems to work:

     This is pdfTeXk, Version 3.1415926-1.40.9 (Web2C 7.5.7)
     %&-line parsing enabled.
     entering extended mode
    ...

but the resulting pdf file has screwed up fonts.

The same thing happens both with pdflatex on the command line, or using TeXShop.

LastEditorDisplayName: dreeves

Body:
Apple knows about the problem and isn't planning to fix it (I had a faculty member spend a lot of time testing and submit a bug to Apple).  Their claim is that PDFTeX is embedding the fonts incorrectly, and they have fixed the Apple PDF library to be more strict about what it will and won't accept, which means that you will continue to see problems with PDF documents created with PDFTeX in Preview, TeXShop, or other tools that display PDF using Apple's PDF engine.  Unfortunately, they weren't at all clear about exactly what it is that PDFTeX is doing wrong, which makes fixing it or even reporting the bug to the PDFTeX developers problematic.  Note that Adobe's Acrobat or Reader applications can often display these documents without any problems; presumably Adobe's error-checking is more liberal than Apple's.

You can actually recover from this problem without rebooting, although you may see it recur with the same document in the same session.  You need to run

atsutil server -shutdown

which will kill the Apple Type Services server daemon (ATSServer) and spawn a new instance, coincidentally rebuilding its cache files.

OwnerDisplayName: Claire


问:
Different asp:menu on a user basis
I have a oracle database which stores menu and user data, for a local Intranet.

The data includes which usesr have access to which pages.

Originally I created a class which extened the StaticSiteMapProvider class, however when this went in to the testing environment, i found that this was cached for the whole site (and not on a user basis).  After reading up on line on various forums, it was suggested that I should inherit from SiteMapProvider as this would enable me to have a seperated instance of thet SiteMapProvider and ASP:MENU item on a user basis, however this still hasn't solved the problem.

Currently I have a user control, which conrains the asp:menu, and uses my custom site map provider as its data source.

Could anyone suggest how I can display the menu on a user basis, driven from database authorisation?

Also the whole menu should still appear to all users, it only after thy click on a menu node that they will find out whether they have access to that page/node.

Thanks

答: You can make use of Roles on the SiteMap to define what menu will appear.</p>

Title: Different asp:menu on a user basis


问:
Serial read only returns reverse question marks in Blutooth connection read
I'm facing problem with my Arduino Bluetooth controller car.

I'm only getting reverse question marks.

I'm using an HC-05 Bluetooth module. The pins are connected as following:

HC 05 -> Arduino

RX -> TX

TX -> RX

5V -> 5V

GND -> GND

Ardunio code:

#include <AFMotor.h>
AF_DCMotor right_motor(3, MOTOR12_8KHZ);
AF_DCMotor left_motor(4, MOTOR12_8KHZ);

String readString;

void setup() {
  Serial.begin(9600);
  right_motor.setSpeed(250);
  left_motor.setSpeed(250);
}

void loop() {
  while(Serial.available()){
    delay(50);
    char c=Serial.read();
    readString+=c;
  }
  if(readString.length()>0){
    Serial.println(readString);
    if (readString =="FORWARD"){
      right_motor.run (FORWARD);
      left_motor.run (FORWARD);
      delay(500);
    }
    if (readString =="BACKWARD"){
      right_motor.run (BACKWARD);
      left_motor.run (BACKWARD);
      delay(500);
    }
    if (readString =="LEFT"){
      right_motor.run (FORWARD);
      left_motor.run (BACKWARD);
      delay(500);
    }
    if (readString =="RIGHT"){
      right_motor.run (BACKWARD);
      left_motor.run (FORWARD);
      delay(500);
    }
    if (readString =="STOP"){
      right_motor.run (RELEASE);
      left_motor.run (RELEASE);
      delay(500);
    }

    readString="";
  }
}
```

Serial monitor:

I have tried many types of changes in the code, but they are not working.

答:
The baud rates must be identical between Bluetooth module and Arduino Serial port. You can check the Bluetooth module baud rate by entering the following AT command:
AT+UART?, also, you can change it using the following AT command: AT+UART=desired_baud_rate, stop_bit, parity_bit,\r\n.

Moreover, you can't use Serial.read() then compare the output with "STRING"! Instead, use Serial.readString();.

Body:
I'm facing problem with my Arduino Bluetooth controller car.

I'm only getting reverse question marks.

I'm using an HC-05 Bluetooth module. The pins are connected as following:

HC 05 -> Arduino

RX -> TX

TX -> RX

5V -> 5V

GND -> GND

Ardunio code:

#include <AFMotor.h>
AF_DCMotor right_motor(3, MOTOR12_8KHZ);
AF_DCMotor left_motor(4, MOTOR12_8KHZ);

String readString;

void setup() {
  Serial.begin(9600);
  right_motor.setSpeed(250);
  left_motor.setSpeed(250);
}

void loop() {
  while(Serial.available()){
    delay(50);
    char c=Serial.read();
    readString+=c;
  }
  if(readString.length()>0){
    Serial.println(readString);
    if (readString =="FORWARD"){
      right_motor.run (FORWARD);
      left_motor.run (FORWARD);
      delay(500);
    }
    if (readString =="BACKWARD"){
      right_motor.run (BACKWARD);
      left_motor.run (BACKWARD);
      delay(500);
    }
    if (readString =="LEFT"){
      right_motor.run (FORWARD);
      left_motor.run (BACKWARD);
      delay(500);
    }
    if (readString =="RIGHT"){
      right_motor.run (BACKWARD);
      left_motor.run (FORWARD);
      delay(500);
    }
    if (readString =="STOP"){
      right_motor.run (RELEASE);
      left_motor.run (RELEASE);
      delay(500);
    }

    readString="";
  }
}

Serial monitor:

I have tried many types of changes in the code, but they are not working.


问:
The value of attribute "name" associated with an element type "item" must not contain the '<' character

java.io.IOException: Could not parse XML from android/accounts/annotations.xml

Anybody can help with the error above ?

答:
Well the error message tells you exactly the problem:

The name attribute of your item must not containt the < character. What else is there to say? In case you cannot read HTML: < produces a "less than" character and > produces a "greater than" character. So they are likely the reason for the error. But there are many other < and > charaters in the name attribute..try to get rid of them.

Body:
Well the error message tells you exactly the problem:

The name attribute of your item must not containt the < character. What else is there to say? In case you cannot read HTML: &lt; produces a "less than" character and &gt; produces a "greater than" character. So they are likely the reason for the error. But there are many other < and > charaters in the name attribute..try to get rid of them.