问:
loading data using ng-table issue
I am trying to display data set using, ng-table. but data is not loading. please check my sample service and controller

```<code>app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
    ];
}
</code>```

i need to access above array to populate table. my controller

```<code>app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   $scope.bfLosses
    });
});
</code>```

when define array inside the controller , working well. but my requirement is accessing it inside the controller.

答:
Service should return reference:

```<code>app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
      ];
    return {
      bfLosses: bfLosses
    };
}
</code>```

Service should be accessed by the dependency you injected:

```<code>app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   ContactService.bfLosses
      });
});
</code>```

Title: loading data using ng-table issue

Body:
I am trying to display data set using, ng-table. but data is not loading. please check my sample service and controller

app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
    ];
}

i need to access above array to populate table. my controller

app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   $scope.bfLosses
    });
});

when define array inside the controller , working well. but my requirement is accessing it inside the controller.

Body:
Service should return reference:

app.service('ContactService', function () {
    var bfLosses = [
        { idx: 0, uid: 'User 11', name: 'Name 11', area: 'Area 1'},
        { idx: 1, uid: 'User 12', name: 'Name 12', area: 'Area 1'},
        { idx: 2, uid: 'User 21', name: 'Name 21', area: 'Area 2'},
        { idx: 3, uid: 'User 22', name: 'Name 22', area: 'Area 2'}
      ];
    return {
      bfLosses: bfLosses
    };
}

Service should be accessed by the dependency you injected:

app.controller("businessController", function ($scope,NgTableParams,ContactService){
    $scope.tableParams = new NgTableParams({
        group: "area"
      },{
        dataset:   ContactService.bfLosses
      });
});


来源: stackexchange

问:
delete Not-Owned files in Android Q using Java code
How can we delete Not-Owned files  in Android Q

I dont want to use SAF file picker

can we trigger directly SAF to delete file

or is there a better sollution

I came across this

```<code>if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.Q) {
                    try {
                        String uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
                        String where = MediaStore.Audio.Media._ID + "=?";
                        String[] selectionArgs = new String[]{String.valueOf(songforpopup._id)};
                        int deleted = getApplicationContext().getContentResolver().delete(Uri.parse(uri1), where, selectionArgs);
                        Toast.makeText(AllSongsActivity.this, "" + deleted, Toast.LENGTH_SHORT).show();
                        if (deleted>=0){
                            Toast.makeText(AllSongsActivity.this, "Succesfully deleted in Android Q",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (SecurityException securityException) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            RecoverableSecurityException recoverableSecurityException;
                            if (securityException instanceof RecoverableSecurityException) {
                                recoverableSecurityException =
                                        (RecoverableSecurityException)securityException;
                            } else {
                                throw new RuntimeException(
                                        securityException.getMessage(), securityException);
                            }
                            IntentSender intentSender =recoverableSecurityException.getUserAction()
                                    .getActionIntent().getIntentSender();
                            try {
                                startIntentSenderForResult(intentSender, DELETE_PERMISSION_REQUEST,
                                        null, 0, 0, 0, null);
                            } catch (IntentSender.SendIntentException e) {
                                e.printStackTrace();
                            }
                        } else {
                            throw new RuntimeException(
                                    securityException.getMessage(), securityException);
                        }
                    }

                    new AsyncListViewLoader().execute(Order);
                    timerDelayRunForScroll(100);
                }
</code>```

but It doesn't delete the file and neither  does the security exception is thrown

答:
Try:</p>

```<code>Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);

int deleted = context.getContentResolver().delete(uri, null, null);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can we delete Not-Owned files  in Android Q

I dont want to use SAF file picker

can we trigger directly SAF to delete file

or is there a better sollution

I came across this

if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.Q) {
                    try {
                        String uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
                        String where = MediaStore.Audio.Media._ID + "=?";
                        String[] selectionArgs = new String[]{String.valueOf(songforpopup._id)};
                        int deleted = getApplicationContext().getContentResolver().delete(Uri.parse(uri1), where, selectionArgs);
                        Toast.makeText(AllSongsActivity.this, "" + deleted, Toast.LENGTH_SHORT).show();
                        if (deleted>=0){
                            Toast.makeText(AllSongsActivity.this, "Succesfully deleted in Android Q",
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (SecurityException securityException) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            RecoverableSecurityException recoverableSecurityException;
                            if (securityException instanceof RecoverableSecurityException) {
                                recoverableSecurityException =
                                        (RecoverableSecurityException)securityException;
                            } else {
                                throw new RuntimeException(
                                        securityException.getMessage(), securityException);
                            }
                            IntentSender intentSender =recoverableSecurityException.getUserAction()
                                    .getActionIntent().getIntentSender();
                            try {
                                startIntentSenderForResult(intentSender, DELETE_PERMISSION_REQUEST,
                                        null, 0, 0, 0, null);
                            } catch (IntentSender.SendIntentException e) {
                                e.printStackTrace();
                            }
                        } else {
                            throw new RuntimeException(
                                    securityException.getMessage(), securityException);
                        }
                    }

                    new AsyncListViewLoader().execute(Order);
                    timerDelayRunForScroll(100);
                }

but It doesn't delete the file and neither  does the security exception is thrown

Body:
Try:

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);

int deleted = context.getContentResolver().delete(uri, null, null);


问:
Using java streams to compare two lists of objects with fields
I need to compare two list of objects with their field values using streams

for example

```<code>List<Object> originalObjectList
List<Object> modifiedObjectList

</code>```

i need to find differences in objects from two lists at field levels and get list of difference as below

I am trying with this approach

```<code>originalObjectList
.stream()
.map(originalObject -> modifiedObjectList
.stream()
.map(modifiedObject -> findDifferences(originalObject.getField1(), modifiedObject.getField1())
.collect(// not understanding how to collect the result returned from findDifferences)

//Method

Result findDifferences(String originalValue, String modifiedValue){
Result result = new Result();

if(StringUtils.isEmpty(originalValue) && StringUtils.isNotEmpty(modifiedValue)){
     result.setStatus("ADDED");
     result.setValue(modifiedValue);
}
else if(StringUtils.isNotEmpty(originalValue) && StringUtils.isEmpty(modifiedValue)){
          result.setStatus("DELETED");
          result.setValue(originalValue);
}
else if(!originalValue.equals(modifiedValue)){
          result.setStatus("MODIFIED");
          result.setValue(modifiedValue);
        }
return result;
}

</code>```

Result should contain value of the field and status of the field like 'Deleted' 'Modified' or 'Added'
Please suggest if there is any better way to achieve this? I am new to java streams

答:
Something like this. Feel free to ask questions.</p>

```<code>import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class App6 {
    public static final String ADDED = "ADDED";
    public static final String DELETED = "DELETED";
    public static final String MODIFIED = "MODIFIED";
    public static final String NOT_MODIFIED = "NOT_MODIFIED";

    public static void main(String[] args) {
        List<A> originalObjectList = Arrays.asList(new A("a"), new A(""), new A("a"), new A("a"));
        List<A> modifiedObjectList = Arrays.asList(new A("a"), new A("b"), new A("b"), new A(""));

        List<Result> results = IntStream
                .range(0, originalObjectList.size())
                .mapToObj(i -> {
                    A original = originalObjectList.get(i);
                    A modified = modifiedObjectList.get(i);
                    return compare(original, modified);
                })
                .collect(Collectors.toList());
        System.out.println(results);
    }

    public static Result compare(A or, A mod) {
        if (or == null || mod == null) {
            throw new IllegalArgumentException("Comparable objects should not be null");
        }
        if (or.field == null || mod.field == null) {
            throw new IllegalArgumentException("Comparable fields of objects should not be null");
        }
        if (or.field.equals(mod.field)) {
            return new Result(NOT_MODIFIED, or.field);
        } else if (or.field.isEmpty() && !mod.field.isEmpty()) {
            return new Result(ADDED, mod.field);
        } else if (!or.field.isEmpty() && mod.field.isEmpty()) {
            return new Result(DELETED, or.field);
        } else {
            return new Result(MODIFIED, mod.field);
        }
    }
}

class A {
    String field;

    public A(String field) {
        this.field = field;
    }
}

class Result {
    String status;
    String value;

    public Result(String status, String value) {
        this.status = status;
        this.value = value;
    }

    @Override
    public String toString() {
        return "Result{" +
                "status='" + status + '\'' +
                ", value='" + value + '\'' +
                '}';
    }
}
</code>```

Body:
I need to compare two list of objects with their field values using streams

for example

List<Object> originalObjectList
List<Object> modifiedObjectList

i need to find differences in objects from two lists at field levels and get list of difference as below

I am trying with this approach

originalObjectList
.stream()
.map(originalObject -> modifiedObjectList
.stream()
.map(modifiedObject -> findDifferences(originalObject.getField1(), modifiedObject.getField1())
.collect(// not understanding how to collect the result returned from findDifferences)

//Method

Result findDifferences(String originalValue, String modifiedValue){
Result result = new Result();

if(StringUtils.isEmpty(originalValue) && StringUtils.isNotEmpty(modifiedValue)){
     result.setStatus("ADDED");
     result.setValue(modifiedValue);
}
else if(StringUtils.isNotEmpty(originalValue) && StringUtils.isEmpty(modifiedValue)){
          result.setStatus("DELETED");
          result.setValue(originalValue);
}
else if(!originalValue.equals(modifiedValue)){
          result.setStatus("MODIFIED");
          result.setValue(modifiedValue);
        }
return result;
}

Result should contain value of the field and status of the field like 'Deleted' 'Modified' or 'Added'
Please suggest if there is any better way to achieve this? I am new to java streams

Body:
Something like this. Feel free to ask questions.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class App6 {
    public static final String ADDED = "ADDED";
    public static final String DELETED = "DELETED";
    public static final String MODIFIED = "MODIFIED";
    public static final String NOT_MODIFIED = "NOT_MODIFIED";

    public static void main(String[] args) {
        List<A> originalObjectList = Arrays.asList(new A("a"), new A(""), new A("a"), new A("a"));
        List<A> modifiedObjectList = Arrays.asList(new A("a"), new A("b"), new A("b"), new A(""));

        List<Result> results = IntStream
                .range(0, originalObjectList.size())
                .mapToObj(i -> {
                    A original = originalObjectList.get(i);
                    A modified = modifiedObjectList.get(i);
                    return compare(original, modified);
                })
                .collect(Collectors.toList());
        System.out.println(results);
    }

    public static Result compare(A or, A mod) {
        if (or == null || mod == null) {
            throw new IllegalArgumentException("Comparable objects should not be null");
        }
        if (or.field == null || mod.field == null) {
            throw new IllegalArgumentException("Comparable fields of objects should not be null");
        }
        if (or.field.equals(mod.field)) {
            return new Result(NOT_MODIFIED, or.field);
        } else if (or.field.isEmpty() && !mod.field.isEmpty()) {
            return new Result(ADDED, mod.field);
        } else if (!or.field.isEmpty() && mod.field.isEmpty()) {
            return new Result(DELETED, or.field);
        } else {
            return new Result(MODIFIED, mod.field);
        }
    }
}

class A {
    String field;

    public A(String field) {
        this.field = field;
    }
}

class Result {
    String status;
    String value;

    public Result(String status, String value) {
        this.status = status;
        this.value = value;
    }

    @Override
    public String toString() {
        return "Result{" +
                "status='" + status + '\'' +
                ", value='" + value + '\'' +
                '}';
    }
}


问:
How correctly filter column with data separated by a comma?
Let's say I have such DataFrame.

```<code>+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
|56,89      |
+-----------+
</code>```

Also, I have an array with numbers: var array = Array(200, 73).

I want to filter this DataFrame by the array and take such a result:

```<code>+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
+-----------+
</code>```

I used such code but it doesn't work the way I thought it would

```<code>df.filter(col("amount").isin(array: _*))
</code>```

My next code returns such a result:

```<code>+-----------+
|amount     |
+-----------+
|73         |
+-----------+
</code>```

What's wrong I did?

答:
If you have Spark 2.4+, use array functions like array_intersect, otherwise use UDF:

```<code>val containsStr = udf((data:String) => data.split(",").exists(array.contains))

df
  .where(containsStr($"amount"))
  .show()
</code>```

Body:
Let's say I have such DataFrame.

+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
|56,89      |
+-----------+

Also, I have an array with numbers: var array = Array(200, 73).

I want to filter this DataFrame by the array and take such a result:

+-----------+
|amount     |
+-----------+
|100,200,300|
|73         |
+-----------+

I used such code but it doesn't work the way I thought it would

df.filter(col("amount").isin(array: _*))

My next code returns such a result:

+-----------+
|amount     |
+-----------+
|73         |
+-----------+

What's wrong I did?

Body:
If you have Spark 2.4+, use array functions like array_intersect, otherwise use UDF:

val containsStr = udf((data:String) => data.split(",").exists(array.contains))

df
  .where(containsStr($"amount"))
  .show()


问:
lat must be a number when creating a GeoPoint
I'm using Loopback 3.x. I got an error lat must be a number when creating a GeoPoint while creating a custom API for finding nearby doctors.

user.json file

```<code>"findNearByDoctors": {
  "accepts": [
    {
      "arg": "geoPoint",
      "type": "geopoint",
      "required": true,
      "description": "user's location"
    },
    {
      "arg": "range",
      "type": "number",
      "required": false,
      "description": "range"
    }
  ],
  "returns": [],
  "description": "find nearby doctors",
  "http": [
    {
      "path": "/get-nearby-doctors",
      "verb": "get"
    }
  ]
}
</code>```

Input I given is

geoPoint: (1.28210155945393, 103.81722480263163)

Body:
I'm using Loopback 3.x. I got an error lat must be a number when creating a GeoPoint while creating a custom API for finding nearby doctors.

user.json file

"findNearByDoctors": {
  "accepts": [
    {
      "arg": "geoPoint",
      "type": "geopoint",
      "required": true,
      "description": "user's location"
    },
    {
      "arg": "range",
      "type": "number",
      "required": false,
      "description": "range"
    }
  ],
  "returns": [],
  "description": "find nearby doctors",
  "http": [
    {
      "path": "/get-nearby-doctors",
      "verb": "get"
    }
  ]
}

Input I given is

geoPoint: (1.28210155945393, 103.81722480263163)

Body: geoPoint: {"lat": 1.28210155945393, lng": 103.81722480263163}


问:
'url' attribute is not specified and no embedded datasource could be configured
I'm trying to implement Spring application which uses 2 databases. I tried this:

application.properties

```<code>spring.production.datasource.url=jdbc:mariadb://localhost:3306/production_gateway
spring.production.datasource.username=wildfly
spring.production.datasource.password=qwerty
spring.production.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.production.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.production.datasource.jpa.show-sql = true
spring.production.datasource.jpa.hibernate.ddl-auto = update

spring.warehouse.datasource.url=jdbc:mariadb://localhost:3306/production_warehouse
spring.warehouse.datasource.username=wildfly
spring.warehouse.datasource.password=qwerty
spring.warehouse.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.warehouse.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.warehouse.datasource.jpa.show-sql = true
spring.warehouse.datasource.jpa.hibernate.ddl-auto = update
</code>```

Configuration Bean:

```<code>@Configuration
@EnableJpaRepositories(
        basePackages = "org.plugin.production.service",
        entityManagerFactoryRef = "productionEntityManagerFactory",
        transactionManagerRef = "productionTransactionManager"
    )
@EnableTransactionManagement
public class ContextProductionDatasource {

    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "productionDataSourceProperties")
    @ConfigurationProperties(prefix="spring.production.datasource")
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan(new String[] { "org.plugin.production.service" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect", env.getProperty("jpa.properties.hibernate.dialect"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean(name = "productionDataSourceProperties")
    @ConfigurationProperties(prefix="spring.production.datasource")
    public DataSource userDataSource()
    {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("datasource.url"));
        dataSource.setUsername(env.getProperty("username"));
        dataSource.setPassword(env.getProperty("password"));

        return dataSource;
    }

    @Primary
    @Bean(name = "productionTransactionManager")
    @ConfigurationProperties("spring.production.datasource")
    public PlatformTransactionManager productionTransactionManager(final EntityManagerFactory emf) {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Primary
    @Bean(name = "productionExceptionTranslation")
    @ConfigurationProperties("spring.production.datasource")
    public PersistenceExceptionTranslationPostProcessor productionExceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}
</code>```

But when I start the application I get error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
        If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
        If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
</code>```

Do you know how I can fix this issue?

答:
Please exclude DataSourceAutoConfiguration.class:</p>

```<code>  @SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class})
</code>```

Body:
I'm trying to implement Spring application which uses 2 databases. I tried this:

application.properties

spring.production.datasource.url=jdbc:mariadb://localhost:3306/production_gateway
spring.production.datasource.username=wildfly
spring.production.datasource.password=qwerty
spring.production.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.production.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.production.datasource.jpa.show-sql = true
spring.production.datasource.jpa.hibernate.ddl-auto = update

spring.warehouse.datasource.url=jdbc:mariadb://localhost:3306/production_warehouse
spring.warehouse.datasource.username=wildfly
spring.warehouse.datasource.password=qwerty
spring.warehouse.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.warehouse.datasource.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.warehouse.datasource.jpa.show-sql = true
spring.warehouse.datasource.jpa.hibernate.ddl-auto = update

Configuration Bean:

@Configuration
@EnableJpaRepositories(
        basePackages = "org.plugin.production.service",
        entityManagerFactoryRef = "productionEntityManagerFactory",
        transactionManagerRef = "productionTransactionManager"
    )
@EnableTransactionManagement
public class ContextProductionDatasource {

    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "productionDataSourceProperties")
    @ConfigurationProperties(prefix="spring.production.datasource")
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan(new String[] { "org.plugin.production.service" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect", env.getProperty("jpa.properties.hibernate.dialect"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean(name = "productionDataSourceProperties")
    @ConfigurationProperties(prefix="spring.production.datasource")
    public DataSource userDataSource()
    {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("datasource.url"));
        dataSource.setUsername(env.getProperty("username"));
        dataSource.setPassword(env.getProperty("password"));

        return dataSource;
    }

    @Primary
    @Bean(name = "productionTransactionManager")
    @ConfigurationProperties("spring.production.datasource")
    public PlatformTransactionManager productionTransactionManager(final EntityManagerFactory emf) {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Primary
    @Bean(name = "productionExceptionTranslation")
    @ConfigurationProperties("spring.production.datasource")
    public PersistenceExceptionTranslationPostProcessor productionExceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

But when I start the application I get error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
        If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
        If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Do you know how I can fix this issue?

Body:
Please exclude DataSourceAutoConfiguration.class:

  @SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class})


问:
APP_INITIALIZER is not firing before factory
I'm using APP_INITIALIZER to load environment specific variables. I need to use these variables inside of my authConfigFactory, but the factory keeps loading before APP_INITIALIZER has completed inside of the app config.

I'm using this library: https://github.com/manfredsteyer/angular-oauth2-oidc

I want to use the value of APP_CONFIG.authConfig.allowedUrls inside of my auth config factory. How can I make sure it sets the configuration first before the auth factory.

I get this error in the factory : Cannot read property 'authConfig' of undefined

app.module.ts:

```<code>providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: (config: AppConfigService) => () => config.load(),
      multi: true,
      deps: [AppConfigService]
    },
    {
      provide: OAuthModuleConfig,
      useFactory: authConfigFactory
    }
]
</code>```

app.config.ts:

```<code>export let APP_CONFIG: AppConfig;

@Injectable()
export class AppConfigService {
  constructor(
    private injector: Injector
  ) {}

  config = null;

  public load() {
    const http = this.injector.get(HttpClient);

    return http
      .get('../assets/config/config.json')
      .pipe(
        tap(returnedConfig => {
          const t = new AppConfig();
          APP_CONFIG = Object.assign(t, returnedConfig);
        })
      )
      .toPromise();
  }

}
</code>```

auth-config-factor:

```<code>export function authConfigFactory(): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: APP_CONFIG.authConfig.allowedUrls,
      sendAccessToken: true
    }
  };
}
</code>```

答:
I had the same problem. The OAuthModuleConfig needs to be set synchronously. So the settings need to be loaded before the OAuthModuleConfig is created (in a factory).

I implemented it by loading the settings before the AppModule is bootstrapped.

Main.ts:

```<code>fetch('/assets/config.json')
.then(response => response.json())
.then(config => {

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic([{ provide: APP_SETTINGS, useValue: config }])
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));
});
</code>```

App.module.ts

Inside the module declaration:

```<code>....
providers: [
{ provide: OAuthModuleConfig, useFactory: authConfigFactory, deps: [APP_SETTINGS] },
],
bootstrap: [AppComponent]
.....

export function authConfigFactory(settings: AppSettings): OAuthModuleConfig {
return {
resourceServer: {
    allowedUrls: settings.protectedUrls,
    sendAccessToken: true,
   }
 };
}
</code>```

Body:
I'm using APP_INITIALIZER to load environment specific variables. I need to use these variables inside of my authConfigFactory, but the factory keeps loading before APP_INITIALIZER has completed inside of the app config.

I'm using this library: https://github.com/manfredsteyer/angular-oauth2-oidc

I want to use the value of APP_CONFIG.authConfig.allowedUrls inside of my auth config factory. How can I make sure it sets the configuration first before the auth factory.

I get this error in the factory : Cannot read property 'authConfig' of undefined

app.module.ts:

providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: (config: AppConfigService) => () => config.load(),
      multi: true,
      deps: [AppConfigService]
    },
    {
      provide: OAuthModuleConfig,
      useFactory: authConfigFactory
    }
]

app.config.ts:

export let APP_CONFIG: AppConfig;

@Injectable()
export class AppConfigService {
  constructor(
    private injector: Injector
  ) {}

  config = null;

  public load() {
    const http = this.injector.get(HttpClient);

    return http
      .get('../assets/config/config.json')
      .pipe(
        tap(returnedConfig => {
          const t = new AppConfig();
          APP_CONFIG = Object.assign(t, returnedConfig);
        })
      )
      .toPromise();
  }

}

auth-config-factor:

export function authConfigFactory(): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: APP_CONFIG.authConfig.allowedUrls,
      sendAccessToken: true
    }
  };
}

Body:
I had the same problem. The OAuthModuleConfig needs to be set synchronously. So the settings need to be loaded before the OAuthModuleConfig is created (in a factory).

I implemented it by loading the settings before the AppModule is bootstrapped.

Main.ts:

fetch('/assets/config.json')
.then(response => response.json())
.then(config => {

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic([{ provide: APP_SETTINGS, useValue: config }])
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));
});

App.module.ts

Inside the module declaration:

....
providers: [
{ provide: OAuthModuleConfig, useFactory: authConfigFactory, deps: [APP_SETTINGS] },
],
bootstrap: [AppComponent]
.....

export function authConfigFactory(settings: AppSettings): OAuthModuleConfig {
return {
resourceServer: {
    allowedUrls: settings.protectedUrls,
    sendAccessToken: true,
   }
 };
}


问:
How to remove a dynamic component on deletion in angular?
I am trying to create a mat-expansion panel and have mat-list inside it dynamiclly.
The code is as provided below:

```<code><mat-expansion-panel *ngFor="let bAttr of bAttrList" (opened)="openPanel(bAttr)">
            <mat-expansion-panel-header>
              <mat-panel-title>
                {{bAttr}}
              </mat-panel-title>
              <mat-panel-description>
                {{bAttr}}
              </mat-panel-description>
            </mat-expansion-panel-header>

            <mat-list *ngFor="let baValue of baValueList">
              <app-ba-update [baValue]="baValue" [bAttr]="bAttr" [lob]="lobSelected"></app-ba-update>

            </mat-list>

          </mat-expansion-panel>
</code>```

Here you can see, I am trying to call another child component for each bAttr element. Inside the child element , we have the option to edit and delete the baValue. Once I delete, I need to remove the element from the list / refresh the content of currently opened mat-expansion panel's mat-list.
When I expand the expansion panel, openPanel() method gets called and it sets the value of baValueList.
How do I let the parent element  know exactly which child element I need to remove, or tell the parent element to refresh the baValueList?

NOTE: There are multiple bAttr list and corresponding to them , there are multiple baValueList.

答: You need to destroy the component and load that component again. you need to have flag to open and close the expansion and put the directive *ngIf on the selector.

Body:
I am trying to create a mat-expansion panel and have mat-list inside it dynamiclly.
The code is as provided below:

<mat-expansion-panel *ngFor="let bAttr of bAttrList" (opened)="openPanel(bAttr)">
            <mat-expansion-panel-header>
              <mat-panel-title>
                {{bAttr}}
              </mat-panel-title>
              <mat-panel-description>
                {{bAttr}}
              </mat-panel-description>
            </mat-expansion-panel-header>

            <mat-list *ngFor="let baValue of baValueList">
              <app-ba-update [baValue]="baValue" [bAttr]="bAttr" [lob]="lobSelected"></app-ba-update>

            </mat-list>

          </mat-expansion-panel>

Here you can see, I am trying to call another child component for each bAttr element. Inside the child element , we have the option to edit and delete the baValue. Once I delete, I need to remove the element from the list / refresh the content of currently opened mat-expansion panel's mat-list.
When I expand the expansion panel, openPanel() method gets called and it sets the value of baValueList.
How do I let the parent element  know exactly which child element I need to remove, or tell the parent element to refresh the baValueList?

NOTE: There are multiple bAttr list and corresponding to them , there are multiple baValueList.


问:
Android: Is it possible to get notified when enter/quit TouchMode?
When system enters into TouchMode, I'd like to know which widget will lose focus. When system quits TouchMode, I'd also like to know which widget will get focus. Overriding onFocusChange() didn't satisfy me, since it couldn't tell TouchMode change, since it could happen in every mode, touch, trackball, key navigation, etc.

SDK said only one API View.isInTouchMode() there it is. So, is it possible to detect TouchMode change?

答: Long shot but you probably need to maintain states manually. So you keep a a flag , lets say isTouchMode which you can set every time any of the widgets are touched and unset when something gets focus. </p>

ContentLicense: CC BY-SA 3.0


问:
CSS background linear gradient bug using Chrome?

html {
  background:#ffffff;
}
body {
  height:250px;
  background: linear-gradient(
    to bottom,
    #ffffff 0px,
    #ffffff 100px,
    #0065A2 100px,
    #0065A2 145px,
    #074A8B 145px,
    #074A8B 163px,
    #0065A2 163px,
    #0065A2 203px,
    transparent 203px
  );
}```
</div>
</div>
</p>

<p>I am trying to use a background linear gradient and with great surprise it works good on Firefox and IE but not on Google Chrome.</p>

<p>The code is here for example: https://jsfiddle.net/be1rgpez/1/</p>

```background: linear-gradient(
    to bottom,
    #ffffff 0px,
    #ffffff 100px,
    #0065A2 100px,
    #0065A2 145px,
    #074A8B 145px,
    #074A8B 163px,
    #0065A2 163px,
    #0065A2 203px,
    transparent 203px
);
```

I need a linear gradient with several color stops, but using Google Chrome it renders a strange shadow between colors (see image left box). The effect I need is "striped" without shadows).

In the attachment I show what I see using Chrome. The left box is what I need but without the shadows (like in the right box). The same jsfiddle renders correctly on Firefox and IE.

UPDATE: this is a zoomed picture. As you can see, the left box has a small shadow between the white and the blue color (and also between other colors).

答:
I found that there's an issue between linear gradient and containers overflow.
I tried many solutions and it didn't work.

Then when i tried to give overflow:auto, it worked for me.

this is before i apply the fix to the right container which holds many content

this is after applying the overflow: auto !important; to the right container
and it works fine now without any issue and here it is.

Body:
html {
  background:#ffffff;
}
body {
  height:250px;
  background: linear-gradient(
    to bottom,
    #ffffff 0px,
    #ffffff 100px,
    #0065A2 100px,
    #0065A2 145px,
    #074A8B 145px,
    #074A8B 163px,
    #0065A2 163px,
    #0065A2 203px,
    transparent 203px
  );
}

I am trying to use a background linear gradient and with great surprise it works good on Firefox and IE but not on Google Chrome.

The code is here for example: https://jsfiddle.net/be1rgpez/1/

background: linear-gradient(
    to bottom,
    #ffffff 0px,
    #ffffff 100px,
    #0065A2 100px,
    #0065A2 145px,
    #074A8B 145px,
    #074A8B 163px,
    #0065A2 163px,
    #0065A2 203px,
    transparent 203px
);

I need a linear gradient with several color stops, but using Google Chrome it renders a strange shadow between colors (see image left box). The effect I need is "striped" without shadows).

In the attachment I show what I see using Chrome. The left box is what I need but without the shadows (like in the right box). The same jsfiddle renders correctly on Firefox and IE.

UPDATE: this is a zoomed picture. As you can see, the left box has a small shadow between the white and the blue color (and also between other colors).


问:
overriding property in maven plugin from command line
This maven command launches an older version (1.3.162) of the H2 database:

```<code>mvn -debug com.edugility:h2-maven-plugin:1.0:spawn
</code>```

As recommended here, I'm trying to override a property of the plugin on the command line....so I can instead use a more recent h2 version:

```<code>mvn -debug -Dh2Version=1.4.200 com.edugility:h2-maven-plugin:1.0:spawn
</code>```

This h2Version property with the older h2 version is defined here on github in the plugin's pom.

Here is the end of the verbose maven output

```<code> [DEBUG] Process arguments: [C:\java\jdk-9.0.4\bin\java, -cp, C:\Users\eoste\.m2\repository\com\h2database\h2\1.3.162\h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 9092]
 [INFO] H2 server spawned at tcp://localhost:9092
</code>```

Not only does the old 1.3.162 version launch, but the there is zero mention anywhere of the h2Version property that I placed on the command line.

I tried moving the -Dh2Version parameter to the end of the command line.  I also tried deleting the plugin from the local repo, to force a download so maybe the h2Version would then get reevaluated....none of these things worked.
This blog shows how to embed a dependency inside a plugin, but that's tons more complicated than my simple command line invocation.

What am I doing wrong?

Using windows 10, java 9, maven 3.6.2

答:
I don't think you'll be able to do that using this particular maven-plugin. Here is another answer for someone that had a similar issue: How to pass parameter to Maven plugin from CLI?.

Basically, the h2Version property is not defined as a user property.

When you start the plugin, using the command that you've mentioned, there is an output for pre-defined configuration properties:

```<code><configuration>
  <allowOthers>${h2.allowOthers}</allowOthers>
  <baseDirectory>${h2.baseDirectory}</baseDirectory>
  <forceShutdown>${h2.forceShutdown}</forceShutdown>
  <ifExists>${h2.ifExists}</ifExists>
  <java>${h2.java}</java>
  <port default-value="9092">${h2.port}</port>
  <shutdownAllServers>${h2.shutdownAllServers}</shutdownAllServers>
  <shutdownHost default-value="localhost">${h2.shutdownHost}</shutdownHost>
  <shutdownPassword default-value="h2-maven-plugin">${h2.shutdownPassword}</shutdownPassword>
  <trace>${h2.trace}</trace>
  <useSSL>${h2.useSSL}</useSSL>
</configuration>
</code>```

Only these properties could be defined by the user. For example, changing the running port:

```<code>mvn -debug com.edugility:h2-maven-plugin:1.0:spawn -Dport=9090
</code>```

Body:
This maven command launches an older version (1.3.162) of the H2 database:

mvn -debug com.edugility:h2-maven-plugin:1.0:spawn

As recommended here, I'm trying to override a property of the plugin on the command line....so I can instead use a more recent h2 version:

mvn -debug -Dh2Version=1.4.200 com.edugility:h2-maven-plugin:1.0:spawn

This h2Version property with the older h2 version is defined here on github in the plugin's pom.

Here is the end of the verbose maven output

 [DEBUG] Process arguments: [C:\java\jdk-9.0.4\bin\java, -cp, C:\Users\eoste\.m2\repository\com\h2database\h2\1.3.162\h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 9092]
 [INFO] H2 server spawned at tcp://localhost:9092

Not only does the old 1.3.162 version launch, but the there is zero mention anywhere of the h2Version property that I placed on the command line.

I tried moving the -Dh2Version parameter to the end of the command line.  I also tried deleting the plugin from the local repo, to force a download so maybe the h2Version would then get reevaluated....none of these things worked.
This blog shows how to embed a dependency inside a plugin, but that's tons more complicated than my simple command line invocation.

What am I doing wrong?

Using windows 10, java 9, maven 3.6.2

Body:
I don't think you'll be able to do that using this particular maven-plugin. Here is another answer for someone that had a similar issue: How to pass parameter to Maven plugin from CLI?.

Basically, the h2Version property is not defined as a user property.

When you start the plugin, using the command that you've mentioned, there is an output for pre-defined configuration properties:

<configuration>
  <allowOthers>${h2.allowOthers}</allowOthers>
  <baseDirectory>${h2.baseDirectory}</baseDirectory>
  <forceShutdown>${h2.forceShutdown}</forceShutdown>
  <ifExists>${h2.ifExists}</ifExists>
  <java>${h2.java}</java>
  <port default-value="9092">${h2.port}</port>
  <shutdownAllServers>${h2.shutdownAllServers}</shutdownAllServers>
  <shutdownHost default-value="localhost">${h2.shutdownHost}</shutdownHost>
  <shutdownPassword default-value="h2-maven-plugin">${h2.shutdownPassword}</shutdownPassword>
  <trace>${h2.trace}</trace>
  <useSSL>${h2.useSSL}</useSSL>
</configuration>

Only these properties could be defined by the user. For example, changing the running port:

mvn -debug com.edugility:h2-maven-plugin:1.0:spawn -Dport=9090


问:
Enabling "Multi select" on a datagridview
I want to force the datagridview to act as if I am holding down Control all the time. E.g; If I click a cell, it highlights, and if I click another separate cell, it highlights without the first becoming deselected.

The reason for this is I am running the app on a touch screen, and need this function without a keyboard.

I would prefer not to emulate holding down ctrl for the entire form, as this may mess with some of my other objects. But I will if no one can think of a better solution.

I have datagridview.multiSelect enabled.

答:
While it isn't ideal, you could handle the OnMouseUp event and get a list of the currently selected rows as well as the row that was just clicked and then programatically select the required rows again.

You would need to see if the current row was already select it and then toggle the unselect it if necessary also.

I'm sure someone will have a better idea of how to do this, but if not, try this at any rate.


问:
Cronjob is not working due to module missing
I saw similar threads but it could not solve my issue so I try a new one.
I can run my script from a shell script file from the terminal but I have an error when it is from a cronjob. I can give addition information as needed. Any help would be super appreciated. I am stuck here for too long.

I am using Anaconda3 and all modules are installed on Conda.

the shell script:

```<code>#!/bin/bash
export PATH=/usr/local/bin:${PATH}
echo $1 'report'
if [ -z "$1" ]; then
    echo 'no parameter about report type'
    exit 1
fi
TOPDIR=~/extra/cronjobs
JOBDIR=unify_reports
REPORT_TYPE=$1
DAY=$(date +"%Y%m%d")
SOURCE_PATH_base=~/market_risk
SUB_PATH=$REPORT_TYPE/src/code
INTERAPI_PATH=control_tdrive_mail
OUTPATH="${SOURCE_PATH_base}/$REPORT_TYPE/output"
OUT=$(date +%Y-%m-%d -d "1 day ago")$REPORT_TYPE.xlsx
echo 'output ' $OUTPATH $OUT
FILENO_FLAG=SINGLE
SUBJECT="[DATA BATCH] $REPORT_TYPE daily report for ""${OUT}"
TO="xxxxxxxxxxxxx@xxxxx.com"
CC=${TO}
top_dir=${TOPDIR}/${JOBDIR}
dir=$top_dir
if [ -e $dir ]; then
    echo 'exists' $dir
else
    mkdir $dir
    # log folder
    dir=$dir/logs
    if [ -e $dir ]; then
        echo 'exists' $dir
    else
        mkdir $dir
    fi
    echo 'log dorectory created' $dir
fi
cd ${TOPDIR}/${JOBDIR}
(
    # run each code to generate files
    cd "${SOURCE_PATH_base}/${SUB_PATH}"
    python3 $REPORT_TYPE.py
    # output file link
    dir=$top_dir/output_$REPORT_TYPE
    echo $dir 'output link'
    if [ -e $dir ]; then
        echo 'exists' $dir
    else
        # create link to real path
        echo 'no output link' $dir
        echo 'real output path' ${OUTPATH}
        cd ${TOPDIR}/${JOBDIR}
        trap `ln -s "${OUTPATH}" "output_${REPORT_TYPE}"` 1 2 3 15
        echo 'created output link' $dir
    fi
    # upload to gdrive
    echo 'test'  "${SOURCE_PATH_base}/${INTERAPI_PATH}"
    cd "${SOURCE_PATH_base}/${INTERAPI_PATH}"
    echo 'test2'   "${OUTPATH}/${OUT}" "${TO}" "${FILENO_FLAG}" "${SUBJECT}"
    python3 teamdrive_control.py Market_Risk $REPORT_TYPE "${OUTPATH}/${OUT}" "${TO}" "${FILENO_FLAG}" "${SUBJECT}"
) 2>&1 | xz -9ec > logs/${JOBDIR}-$(date +%s)_$REPORT_TYPE.log.xz
</code>```

the error:

```<code>    Traceback (most recent call last):
  File "risk_position.py", line 3, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
/home/ubuntu/extra/cronjobs/unify_reports/output_risk_position output link
exists /home/ubuntu/extra/cronjobs/unify_reports/output_risk_position
test /home/ubuntu/market_risk/control_tdrive_mail
test2 /home/ubuntu/market_risk/risk_position/output/2020-02-16risk_position.xlsx  SINGLE [DATA BATCH] risk_position daily report for 2020-02-16risk_position.xlsx
----------base src:   /home/ubuntu/market_risk/control_tdrive_mail
Traceback (most recent call last):
  File "teamdrive_control.py", line 10, in <module>
    import common_config
  File "/home/ubuntu/market_risk/control_tdrive_mail/common_config.py", line 15, in <module>
    from rpt_utils import Parameters
  File "/home/ubuntu/market_risk/control_tdrive_mail/utils/rpt_utils.py", line 1, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'
</code>```

EDIT: new error after 'pip3 install pandas'

```<code>Traceback (most recent call last):
  File "risk_position2.py", line 3, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
/home/ubuntu/extra/cronjobs/unify_reports/output_risk_position2 output link
exists /home/ubuntu/extra/cronjobs/unify_reports/output_risk_position2
test /home/ubuntu/market_risk/control_tdrive_mail
test2 /home/ubuntu/market_risk/risk_position2/output/2020-02-16risk_position2.xlsx SINGLE [DATA BATCH] risk_position2 daily report for 2020-02-16risk_position2.xlsx
----------base src:   /home/ubuntu/market_risk/control_tdrive_mail
Traceback (most recent call last):
  File "teamdrive_control.py", line 10, in <module>
    import common_config
  File "/home/ubuntu/market_risk/control_tdrive_mail/common_config.py", line 16, in <module>
    from db_utils import DBQuery
  File "/home/ubuntu/market_risk/control_tdrive_mail/utils/db_utils.py", line 1, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
</code>```

答:
Your error is: ModuleNotFoundError: No module named 'pandas' which means your environment does not have pandas yet. Install the library using:

Python 2.x : pip install pandas

Python 3.x : pip3 install pandas

And run it again.

Body:
I saw similar threads but it could not solve my issue so I try a new one.
I can run my script from a shell script file from the terminal but I have an error when it is from a cronjob. I can give addition information as needed. Any help would be super appreciated. I am stuck here for too long.

I am using Anaconda3 and all modules are installed on Conda.

the shell script:

#!/bin/bash
export PATH=/usr/local/bin:${PATH}
echo $1 'report'
if [ -z "$1" ]; then
    echo 'no parameter about report type'
    exit 1
fi
TOPDIR=~/extra/cronjobs
JOBDIR=unify_reports
REPORT_TYPE=$1
DAY=$(date +"%Y%m%d")
SOURCE_PATH_base=~/market_risk
SUB_PATH=$REPORT_TYPE/src/code
INTERAPI_PATH=control_tdrive_mail
OUTPATH="${SOURCE_PATH_base}/$REPORT_TYPE/output"
OUT=$(date +%Y-%m-%d -d "1 day ago")$REPORT_TYPE.xlsx
echo 'output ' $OUTPATH $OUT
FILENO_FLAG=SINGLE
SUBJECT="[DATA BATCH] $REPORT_TYPE daily report for ""${OUT}"
TO="xxxxxxxxxxxxx@xxxxx.com"
CC=${TO}
top_dir=${TOPDIR}/${JOBDIR}
dir=$top_dir
if [ -e $dir ]; then
    echo 'exists' $dir
else
    mkdir $dir
    # log folder
    dir=$dir/logs
    if [ -e $dir ]; then
        echo 'exists' $dir
    else
        mkdir $dir
    fi
    echo 'log dorectory created' $dir
fi
cd ${TOPDIR}/${JOBDIR}
(
    # run each code to generate files
    cd "${SOURCE_PATH_base}/${SUB_PATH}"
    python3 $REPORT_TYPE.py
    # output file link
    dir=$top_dir/output_$REPORT_TYPE
    echo $dir 'output link'
    if [ -e $dir ]; then
        echo 'exists' $dir
    else
        # create link to real path
        echo 'no output link' $dir
        echo 'real output path' ${OUTPATH}
        cd ${TOPDIR}/${JOBDIR}
        trap `ln -s "${OUTPATH}" "output_${REPORT_TYPE}"` 1 2 3 15
        echo 'created output link' $dir
    fi
    # upload to gdrive
    echo 'test'  "${SOURCE_PATH_base}/${INTERAPI_PATH}"
    cd "${SOURCE_PATH_base}/${INTERAPI_PATH}"
    echo 'test2'   "${OUTPATH}/${OUT}" "${TO}" "${FILENO_FLAG}" "${SUBJECT}"
    python3 teamdrive_control.py Market_Risk $REPORT_TYPE "${OUTPATH}/${OUT}" "${TO}" "${FILENO_FLAG}" "${SUBJECT}"
) 2>&1 | xz -9ec > logs/${JOBDIR}-$(date +%s)_$REPORT_TYPE.log.xz

the error:

    Traceback (most recent call last):
  File "risk_position.py", line 3, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
/home/ubuntu/extra/cronjobs/unify_reports/output_risk_position output link
exists /home/ubuntu/extra/cronjobs/unify_reports/output_risk_position
test /home/ubuntu/market_risk/control_tdrive_mail
test2 /home/ubuntu/market_risk/risk_position/output/2020-02-16risk_position.xlsx  SINGLE [DATA BATCH] risk_position daily report for 2020-02-16risk_position.xlsx
----------base src:   /home/ubuntu/market_risk/control_tdrive_mail
Traceback (most recent call last):
  File "teamdrive_control.py", line 10, in <module>
    import common_config
  File "/home/ubuntu/market_risk/control_tdrive_mail/common_config.py", line 15, in <module>
    from rpt_utils import Parameters
  File "/home/ubuntu/market_risk/control_tdrive_mail/utils/rpt_utils.py", line 1, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'

EDIT: new error after 'pip3 install pandas'

Traceback (most recent call last):
  File "risk_position2.py", line 3, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
/home/ubuntu/extra/cronjobs/unify_reports/output_risk_position2 output link
exists /home/ubuntu/extra/cronjobs/unify_reports/output_risk_position2
test /home/ubuntu/market_risk/control_tdrive_mail
test2 /home/ubuntu/market_risk/risk_position2/output/2020-02-16risk_position2.xlsx SINGLE [DATA BATCH] risk_position2 daily report for 2020-02-16risk_position2.xlsx
----------base src:   /home/ubuntu/market_risk/control_tdrive_mail
Traceback (most recent call last):
  File "teamdrive_control.py", line 10, in <module>
    import common_config
  File "/home/ubuntu/market_risk/control_tdrive_mail/common_config.py", line 16, in <module>
    from db_utils import DBQuery
  File "/home/ubuntu/market_risk/control_tdrive_mail/utils/db_utils.py", line 1, in <module>
    import psycopg2 as ps
  File "/home/ubuntu/.local/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: libpq.so.5: cannot open shared object file: No such file or directory


问:
Mysql Count row data by every date but only have few data date
I have a table "activity" like this

```<code>idEmployee  | activity | Date
1           | a        | 2019/01/01
1           | b        | 2019/01/01
2           | c        | 2019/01/01
2           | d        | 2019/01/01
1           | e        | 2019/01/02
2           | f        | 2019/01/03
1           | f        | 2019/01/03
3           | c        | 2019/01/01
4           | d        | 2019/01/03
1           | e        | 2019/01/02
2           | f        | 2019/01/03
</code>```

and i want to count every date from 2019/01/01 - 2019/01/03 that has no activity by every idEmpolyee (as total_no_actitivity) like this

```<code>idEmployee | total_no_activity
1          | 0
2          | 1 (2019/01/02
3          | 2 (2019/01/02,2019/01/03)
4          | 2 (2019/01/01,2019/01/02)
</code>```

but i only can select idemployee that has no activity , without count total_no_activity.

```<code>SELECT idEmployee, namaLengkap, date
FROM account LEFT JOIN timesheet USING (idEmployee)
WHERE NOT EXISTS (SELECT idEmployee
                  FROM timesheet
                  WHERE account.idEmployee = timesheet.idEmployee AND weekday(date) AND date                    between '2019/08/05' and '2019/08/09' AND idrole = '4' AND statusaktif = '1' )
ORDER BY idEmployee ASC
</code>```

is it possible to count total_no_activity with table "activity" only?

答:
```<code>SELECT idEmployee,
       3 - COUNT(DISTINCT `Date`) total_no_activity
FROM account
WHERE `Date` BETWEEN `2019/01/01` AND `2019/01/03`
GROUP BY idEmployee
</code>```

where 3 is the amount of days in the period if interest, inclusive.

If some idEmployee have no records at all in the period in interest then this value will not be listed in output.

unfortunately i need the idEmployee that have no records will be listed in the output

Assiming that you need all idEmployee values which are present in source table at least once (maybe even out of the period in interest) use

```<code>SELECT account.idEmployee,
       3 - COUNT(DISTINCT account.`Date`) total_no_activity
FROM (SELECT DISTINCT idEmployee FROM account) all_employees
LEFT JOIN account USING (idEmployee)
WHERE account.`Date` BETWEEN `2019/01/01` AND `2019/01/03`
GROUP BY account.idEmployee
</code>```

Body:
I have a table "activity" like this

idEmployee  | activity | Date
1           | a        | 2019/01/01
1           | b        | 2019/01/01
2           | c        | 2019/01/01
2           | d        | 2019/01/01
1           | e        | 2019/01/02
2           | f        | 2019/01/03
1           | f        | 2019/01/03
3           | c        | 2019/01/01
4           | d        | 2019/01/03
1           | e        | 2019/01/02
2           | f        | 2019/01/03

and i want to count every date from 2019/01/01 - 2019/01/03 that has no activity by every idEmpolyee (as total_no_actitivity) like this

idEmployee | total_no_activity
1          | 0
2          | 1 (2019/01/02
3          | 2 (2019/01/02,2019/01/03)
4          | 2 (2019/01/01,2019/01/02)

but i only can select idemployee that has no activity , without count total_no_activity.

SELECT idEmployee, namaLengkap, date
FROM account LEFT JOIN timesheet USING (idEmployee)
WHERE NOT EXISTS (SELECT idEmployee
                  FROM timesheet
                  WHERE account.idEmployee = timesheet.idEmployee AND weekday(date) AND date                    between '2019/08/05' and '2019/08/09' AND idrole = '4' AND statusaktif = '1' )
ORDER BY idEmployee ASC

is it possible to count total_no_activity with table "activity" only?

Body:
SELECT idEmployee,
       3 - COUNT(DISTINCT `Date`) total_no_activity
FROM account
WHERE `Date` BETWEEN `2019/01/01` AND `2019/01/03`
GROUP BY idEmployee

where 3 is the amount of days in the period if interest, inclusive.

If some idEmployee have no records at all in the period in interest then this value will not be listed in output.

unfortunately i need the idEmployee that have no records will be listed in the output

Assiming that you need all idEmployee values which are present in source table at least once (maybe even out of the period in interest) use

SELECT account.idEmployee,
       3 - COUNT(DISTINCT account.`Date`) total_no_activity
FROM (SELECT DISTINCT idEmployee FROM account) all_employees
LEFT JOIN account USING (idEmployee)
WHERE account.`Date` BETWEEN `2019/01/01` AND `2019/01/03`
GROUP BY account.idEmployee


问:
How can I use PPMD compression for text files in Python?
I would love to use PPMd compression (https://en.wikipedia.org/wiki/Prediction_by_partial_matching) in a Python script that saves log files (since PPMD is amazing at compressing text/log files).

However, I can't seem to find any library that implements this. I have found a gzip library, but this is slower and worse than PPMd for my situation.

If there is no library for PPMd compression, how would I go about implementing it?

答:
Python core offers some compression algorithms, but PPMd is not supported yet. [1]

You could anyhow call eg. 7zip with the subprocess module. Here is an example on how to use 7zip with PPMd in the command line:

7z a -m0=PPMd archive.7z text.txt

You also might want to have a look at this answer Mimic 7zip with python where two Python libraries for using 7zip are mentioned, but the first one only works on Linux and the other only on Windows.


问:
NPM Error When Trying To Install node-sass
I was trying to install node-sass on Linux Mint by running the command sudo npm install node-sass, but I got some errors.  It says that it does not have access to some directories, which doesn't make any sense because I ran it with sudo.  I have tried many solutions on StackOverflow, including purging node, using a different version, etc. but none have worked.  Here is the full terminal log:

```<code>> node-sass@4.9.3 install /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
> node scripts/install.js

Unable to save binary /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor'
    at Object.fs.mkdirSync (fs.js:885:18)
    at sync (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/mkdirp/index.js:77:24)
    at checkAndDownloadBinary (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/scripts/install.js:114:11)
    at Object.<anonymous> (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/scripts/install.js:157:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
  errno: -13,
  code: 'EACCES',
  syscall: 'mkdir',
  path: '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor' }

> node-sass@4.9.3 postinstall /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
> node scripts/build.js

Building: /usr/local/bin/node /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [ '/usr/local/bin/node',
gyp verb cli   '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library=' ]
gyp info using node-gyp@3.8.0
gyp info using node@8.11.0 | linux | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` succeeded python2 /usr/bin/python2
gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.12
gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
gyp verb get node dir no --target version specified, falling back to host node version: 8.11.0
gyp verb command install [ '8.11.0' ]
gyp verb install input version string "8.11.0"
gyp verb install installing version: 8.11.0
gyp verb install --ensure was passed, so won't reinstall if already installed
gyp verb install version is already installed, need to check "installVersion"
gyp verb got "installVersion" 9
gyp verb needs "installVersion" 9
gyp verb install version is good
gyp verb get node dir target node version installed: 8.11.0
gyp verb build dir attempting to create "build" dir: /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/build
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/build'
gyp ERR! System Linux 4.10.0-37-generic
gyp ERR! command "/usr/local/bin/node" "/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
gyp ERR! node -v v8.11.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.9.3 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.9.3 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/caden/.npm/_logs/2018-08-10T00_32_24_558Z-debug.log
</code>```

答:
Try using the following command</p>

```<code>npm install -f node-sass
</code>```

Body:
I was trying to install node-sass on Linux Mint by running the command sudo npm install node-sass, but I got some errors.  It says that it does not have access to some directories, which doesn't make any sense because I ran it with sudo.  I have tried many solutions on StackOverflow, including purging node, using a different version, etc. but none have worked.  Here is the full terminal log:

> node-sass@4.9.3 install /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
> node scripts/install.js

Unable to save binary /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor'
    at Object.fs.mkdirSync (fs.js:885:18)
    at sync (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/mkdirp/index.js:77:24)
    at checkAndDownloadBinary (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/scripts/install.js:114:11)
    at Object.<anonymous> (/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/scripts/install.js:157:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
  errno: -13,
  code: 'EACCES',
  syscall: 'mkdir',
  path: '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/vendor' }

> node-sass@4.9.3 postinstall /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
> node scripts/build.js

Building: /usr/local/bin/node /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [ '/usr/local/bin/node',
gyp verb cli   '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library=' ]
gyp info using node-gyp@3.8.0
gyp info using node@8.11.0 | linux | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` succeeded python2 /usr/bin/python2
gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.12
gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
gyp verb get node dir no --target version specified, falling back to host node version: 8.11.0
gyp verb command install [ '8.11.0' ]
gyp verb install input version string "8.11.0"
gyp verb install installing version: 8.11.0
gyp verb install --ensure was passed, so won't reinstall if already installed
gyp verb install version is already installed, need to check "installVersion"
gyp verb got "installVersion" 9
gyp verb needs "installVersion" 9
gyp verb install version is good
gyp verb get node dir target node version installed: 8.11.0
gyp verb build dir attempting to create "build" dir: /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/build
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass/build'
gyp ERR! System Linux 4.10.0-37-generic
gyp ERR! command "/usr/local/bin/node" "/home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /home/caden/Desktop/Infinite_Robots_Work/infinite-robots-homepage/infinite-robots-homepage/node_modules/node-sass
gyp ERR! node -v v8.11.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.9.3 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.9.3 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/caden/.npm/_logs/2018-08-10T00_32_24_558Z-debug.log

Body:
Try using the following command

npm install -f node-sass


问:
Thread in Android
I have an example like this:

```<code>package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}
</code>```

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

```<code>            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);
</code>```

Anybody can tell me why i can't?

答: The android UI framework (like pretty much every UI framework before it) only allows you to update the UI state from the main thread. You may want to look at AsyncTask which include the plumbing needed to route progress updates onto the main thread.</p>

Title: Thread in Android

Body:
I have an example like this:

package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //---do some work in background thread---
    new Thread(new Runnable()
    {
        public void run()
        {
            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            handler.post(new Runnable()
            {
                public void run()
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        //---do some long lasting work here---
        private int doSomeWork()
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

            //---do some work here---
            while (progressStatus < 10)
            {
                progressStatus = doSomeWork();
            }

            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);

Anybody can tell me why i can't?


问:
How to get the values of the coefficients in the constraint matrix of an MILP in SCIP C++ interface
I am trying to get the coefficients of a variable in the constraint matrix of an MILP in SCIP. What I had been thinking was to loop through all the constraints that the variables appear in and somehow get the coefficients ( I am not sure how to). But is there a way to get all the coefficients in an std::vector by using any inbuilt functions.

答:
What type of constraints do you have? If all your constraints are linear, you can include cons_linear.h, loop through all constraints and call SCIPconsGetVars and SCIPconsGetVals.
This gives you all the variables that appear in your current constraint, as well as the coefficients.

What is it exactly that you want to do with these coefficients?


问:
How to fix "TypeError: fsevents is not a constructor" react error
While staring React app using npm start this error occurred...

I tried below things:

remove node_module package and reinstall

use yarn instead npm

3.update fsevent library using npm

still getting this error

Note: If we create react app fresh/new yarn start will work, but we close the terminal and restart using same thing  below error occurred

```<code>/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:28
</code>```

return (new fsevents(path)).on('fsevent', callback).start();
          ^

TypeError: fsevents is not a constructor
      at createFSEventsInstance (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:28:11)
      at setFSEventsListener (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:82:16)
      at FSWatcher.FsEventsHandler._watchWithFsEvents (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:252:16)
      at FSWatcher. (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:386:25)
      at LOOP (fs.js:1565:14)
      at process._tickCallback (internal/process/next_tick.js:61:11) error Command failed with exit code 1. info Visit
  https://yarnpkg.com/en/docs/cli/run for documentation about this
  command.

答:
I had the same issue. I run the following command and it is working fine now, without using Yarn.

"npm audit fix"

Body:
While staring React app using npm start this error occurred...

I tried below things:

remove node_module package and reinstall

use yarn instead npm

3.update fsevent library using npm

still getting this error

Note: If we create react app fresh/new yarn start will work, but we close the terminal and restart using same thing  below error occurred

/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:28

return (new fsevents(path)).on('fsevent', callback).start();
          ^

TypeError: fsevents is not a constructor
      at createFSEventsInstance (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:28:11)
      at setFSEventsListener (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:82:16)
      at FSWatcher.FsEventsHandler._watchWithFsEvents (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:252:16)
      at FSWatcher. (/Users/nannam/test-app-2/node_modules/chokidar/lib/fsevents-handler.js:386:25)
      at LOOP (fs.js:1565:14)
      at process._tickCallback (internal/process/next_tick.js:61:11) error Command failed with exit code 1. info Visit
  https://yarnpkg.com/en/docs/cli/run for documentation about this
  command.


问:
ImportError: Couldn't import Django ... Did you forget to activate a virtual environment?
I know there are several questions/answers about this, but I can;t figure out what I should do.
I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my environmental variables, and I guess it worked, because I can run several Python commands in my shell.
But every time I try to

```<code>    python manage.py runserver
</code>```

it gives me an error.

I also set up my virtual environment and activated it, but I think there's a problem with Django. But because I installed it with pip install django I know it's there and I can use commands like django-admin startapp ... So I guess Django is working. I don't really know what PYTHONPATH means and where to find it. It would be pretty nice if anybody could take a look at my error.

Here you can see that Django is installed :
    #

```<code>**C:\Users\Kampet\Desktop\Python-Django\mysite>pip install django Requirement already satisfied: django in c:\users\kampet\appdata\local\programs\ python\python37-32\lib\site-packages (2.2.4) Requirement already satisfied: pytz in c:\users\kampet\appdata\local\programs\py thon\python37-32\lib\site-packages (from django) (2019.2) Requirement already satisfied: sqlparse in c:\users\kampet\appdata\local\program s\python\python37-32\lib\site-packages (from django) (0.3.0)**

# And thats my error
**C:\Users\Kampet\Desktop\Python-Django\mysite>python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 10, in main
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 16, in main
    ) from exc
ImportError: Couldn't import Django. Are you sure it's installed and available o
n your PYTHONPATH environment variable? Did you forget to activate a virtual env
ironment?**
###################
</code>```

Here is where my virtual environment is located.

Python-Django

-----------------mysite

-------------------------main

-------------------------mysite

-------------------------manage.py

-----------------venv

-------------------------Include

-------------------------Lib

-------------------------Scripts

-------------------------pyvenv.cfg

This is my manage.py:

```<code>#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()
</code>```

#

I don't know why it can't find the module "django" / django.core.management
I also can't find django.core.management anywhere in my files, but I reinstalled and upgraded django several times. I don't know if this helps you.

Thank you for your time.

答: try running it in anaconda prompt instead of cmd, that worked for me</p>

Body:
I know there are several questions/answers about this, but I can;t figure out what I should do.
I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my environmental variables, and I guess it worked, because I can run several Python commands in my shell.
But every time I try to

    python manage.py runserver

it gives me an error.

I also set up my virtual environment and activated it, but I think there's a problem with Django. But because I installed it with pip install django I know it's there and I can use commands like django-admin startapp ... So I guess Django is working. I don't really know what PYTHONPATH means and where to find it. It would be pretty nice if anybody could take a look at my error.

Here you can see that Django is installed :
    #

**C:\Users\Kampet\Desktop\Python-Django\mysite>pip install django Requirement already satisfied: django in c:\users\kampet\appdata\local\programs\ python\python37-32\lib\site-packages (2.2.4) Requirement already satisfied: pytz in c:\users\kampet\appdata\local\programs\py thon\python37-32\lib\site-packages (from django) (2019.2) Requirement already satisfied: sqlparse in c:\users\kampet\appdata\local\program s\python\python37-32\lib\site-packages (from django) (0.3.0)**

# And thats my error
**C:\Users\Kampet\Desktop\Python-Django\mysite>python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 10, in main
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 16, in main
    ) from exc
ImportError: Couldn't import Django. Are you sure it's installed and available o
n your PYTHONPATH environment variable? Did you forget to activate a virtual env
ironment?**
###################

Here is where my virtual environment is located.

Python-Django

-----------------mysite

-------------------------main

-------------------------mysite

-------------------------manage.py

-----------------venv

-------------------------Include

-------------------------Lib

-------------------------Scripts

-------------------------pyvenv.cfg

This is my manage.py:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

#

I don't know why it can't find the module "django" / django.core.management
I also can't find django.core.management anywhere in my files, but I reinstalled and upgraded django several times. I don't know if this helps you.

Thank you for your time.


问:
Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
I am setting up a React app with a Rails backend. I am getting the error "Objects are not valid as a React child (found: object with keys {id, name, info, created_at, updated_at}). If you meant to render a collection of children, use an array instead."

This is what my data looks like:

```<code>[
    {
        "id": 1,
        "name": "Home Page",
        "info": "This little bit of info is being loaded from a Rails
        API.",
        "created_at": "2018-09-18T16:39:22.184Z",
        "updated_at": "2018-09-18T16:39:22.184Z"
    }
]
</code>```

My code is as follows:

```<code>import React from 'react';

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      homes: []
    };
  }

  componentDidMount() {
    fetch('http://localhost:3000/api/homes')
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            homes: result
          });
        },
        // error handler
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {

    const { error, isLoaded, homes } = this.state;

    if (error) {
      return (
        <div className="col">
          Error: {error.message}
        </div>
      );
    } else if (!isLoaded) {
      return (
        <div className="col">
          Loading...
        </div>
      );
    } else {
      return (
        <div className="col">
          <h1>Mi Casa</h1>
          <p>This is my house y'all!</p>
          <p>Stuff: {homes}</p>
        </div>
      );
    }
  }
}

export default Home;
</code>```

What am I doing wrong?

答:
In JavaScript, arrays and collections are different, although they are somewhat similar, but here the react needs an array.
You need to create an array from the collection and apply it.

```<code>let homeArray = new Array(homes.length);
let i = 0

for (var key in homes) {
    homeArray[i] =  homes[key];
    i = i + 1;
}
</code>```

Body:
I am setting up a React app with a Rails backend. I am getting the error "Objects are not valid as a React child (found: object with keys {id, name, info, created_at, updated_at}). If you meant to render a collection of children, use an array instead."

This is what my data looks like:

[
    {
        "id": 1,
        "name": "Home Page",
        "info": "This little bit of info is being loaded from a Rails
        API.",
        "created_at": "2018-09-18T16:39:22.184Z",
        "updated_at": "2018-09-18T16:39:22.184Z"
    }
]

My code is as follows:

import React from 'react';

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      homes: []
    };
  }

  componentDidMount() {
    fetch('http://localhost:3000/api/homes')
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            homes: result
          });
        },
        // error handler
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {

    const { error, isLoaded, homes } = this.state;

    if (error) {
      return (

          Error: {error.message}

      );
    } else if (!isLoaded) {
      return (

          Loading...

      );
    } else {
      return (

Mi Casa

This is my house y'all!

Stuff: {homes}

      );
    }
  }
}

export default Home;

What am I doing wrong?

Body:
In JavaScript, arrays and collections are different, although they are somewhat similar, but here the react needs an array.
You need to create an array from the collection and apply it.

let homeArray = new Array(homes.length);
let i = 0

for (var key in homes) {
    homeArray[i] =  homes[key];
    i = i + 1;
}


问:
why my merge sort code is giving an index error
I have written a code for merge sort following the pseudocode given in "introduction to algorithms" by Cormen, but as I run my code I'm getting a long traceback error followed by an index error of list assignment index out of range.
the code is as follows:

```<code>def merge(a, p, q, r):
    n = q-p+1
    m = r-q
    b = [0]*(n)
    c = [0]*(m)
    for i in range(0, n):
        b[i] = a[p+i]
    for j in range(0, m):
        c[i] = a[q+1+j]
    b[n+1] = math.inf
    c[m+1] = math.inf
    i = 0
    j = 0

    for k in range(p, r+1):
        if b[i] < c[j]:
            a[k] = b[i]
            i += 1
        else:
            a[k] = c[j]
            j += 1

def mergesort(a, p, r):
    if p < r:
        q = (p+r)//2
        mergesort(a, p, q)
        mergesort(a, q+1, r)
        merge(a, p, q, r)

a = [4, 0, 6, 1, 5, 2, 3]
n = len(a)
print(*a, sep=" ")
mergesort(a, 0, n-1)
for i in range(0, n):
    print("the  sorted array is", a[i])
</code>```

the code is giving the following traceback error:

```<code>  File "m.py", line 38, in <module>
    mergesort(a, 0, n-1)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 32, in mergesort
    merge(a, p, q, r)
  File "m.py", line 13, in merge
    b[n+1] = math.inf
IndexError: list assignment index out of range
</code>```

答:
Instead of

```<code>    b[n+1] = math.inf
    c[m+1] = math.inf
</code>```

use

```<code>    b.append(math.inf)
    c.append(math.inf)
</code>```

Body:
I have written a code for merge sort following the pseudocode given in "introduction to algorithms" by Cormen, but as I run my code I'm getting a long traceback error followed by an index error of list assignment index out of range.
the code is as follows:

def merge(a, p, q, r):
    n = q-p+1
    m = r-q
    b = [0]*(n)
    c = [0]*(m)
    for i in range(0, n):
        b[i] = a[p+i]
    for j in range(0, m):
        c[i] = a[q+1+j]
    b[n+1] = math.inf
    c[m+1] = math.inf
    i = 0
    j = 0

    for k in range(p, r+1):
        if b[i] < c[j]:
            a[k] = b[i]
            i += 1
        else:
            a[k] = c[j]
            j += 1

def mergesort(a, p, r):
    if p < r:
        q = (p+r)//2
        mergesort(a, p, q)
        mergesort(a, q+1, r)
        merge(a, p, q, r)

a = [4, 0, 6, 1, 5, 2, 3]
n = len(a)
print(*a, sep=" ")
mergesort(a, 0, n-1)
for i in range(0, n):
    print("the  sorted array is", a[i])

the code is giving the following traceback error:

  File "m.py", line 38, in <module>
    mergesort(a, 0, n-1)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 32, in mergesort
    merge(a, p, q, r)
  File "m.py", line 13, in merge
    b[n+1] = math.inf
IndexError: list assignment index out of range

Body:
Instead of

    b[n+1] = math.inf
    c[m+1] = math.inf

use

    b.append(math.inf)
    c.append(math.inf)