问:
PowerShell $PROFILE, Variables and NoteProperty / Add-Member
$profile is causing me some headaches. $Profile.GetType() resolves to String which is fine, but it has NoteProperty values:

```<code>$profile | Get-Member -Type NoteProperty
</code>```

AllUsersAllHosts, AllUsersCurrentHost, CurrentUserAllHosts, CurrentUserCurrentHost

When I type $profile, the CurrentUserCurrentHost NoteProperty is returned. This is fine, but I need to change this value - it's complicated, but my corporate VPN uses a network profile and when I am online it tries to reference that location for my $profile meaning that every console startup takes 9 seconds (horribly slow). I can get that down to 1 sec if the profile is loaded locally, but that means changing these values. To do this, I put the following into the AllUsersAllHosts profile.ps1

```<code>$profile = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
</code>```

That's fine, but by doing this, I find that all of the NoteProperty values are deleted! So I tried:

```<code>$profile.CurrentUserCurrentHost = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
</code>```

But this fails, as the root value of $Profile continues to point at the network profile and Console startup is 9 seconds again!

I then also noticed the following weirdness:

```<code>$x = [string]$profile
$x -eq $profile
</code>```

Ny main questions are:

• Why does $x return True even though $x has none of the NoteProperty values in $profile (as the objects are definitely not the same!)?

• How do I control what the root value of $profile is without destroying the NoteProperty values, and

• How can I update .CurrentUserAllHosts and .CurrentUserCurrentHost in such a way that the root value will also update accordingly? i.e. Even if I do the below, the root value of $profile remains unchanged (still points at the very slow network profile location):

```<code>Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersAllHosts" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersCurrentHost" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserAllHosts" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserCurrentHost" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
</code>```

答:
As @mklement0 pointed out, I cannot bypass the functionality of $profile, but I can trick it. Without the below, all shells and scripts take 6.5 to 9 sec to start when I am remotely connected to my corporate VPN (part of that, about 3 seconds is my $profile functions etc). With the below, all consoles and scripts startup in 1 second (and that includes my $profile functions about 1000 lines of code). Putting this solution here in case of help to others.

Running the code at the bottom of this answer results in pushing the following into my $Profile.AllUsersAllHosts which will now always reference a profile at the default C:\ location (and correctly per host type as well - console, ISE, VSCode etc).

```<code>Set-Location C:\Users\$($env:Username)

# Prevent loading profile from network share
if ($Profile.CurrentUserCurrentHost -ne "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])") {
    $Profile = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])"
    if (Test-Path "$Profile") { . $Profile }
}
</code>```

All I then need to do is delete any profiles on the network share and now I get 1 second load times whether connected remotely to the VPN or not, and whether I open a console or a script etc.

```<code>Write-Host ""
Write-Host "Do you want to update `$Profile.AllUsersAllHosts to always redirect to C:\Users\$($env:Username) ?"
Write-Host "This can significantly speed up PowerShell load times when working with a network share over a VPN."
Write-Host "Note that this is just a bypass to always use the *default* profile location on C:\."
Write-Host "   `$Profile.AllUsersAllHosts = C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
Write-Host "   `$Profile.CurrentHostCurrentUser = C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split("\"))[-1]_profile.ps1"
Write-Host ""

$ProfileAdmin = "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
# Use  (($Profile).split("\"))[-1]  to capture correct prefix PowerShell, VSCode. $ShellId does not work for VSCode etc
$ProfileUser = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split('\')[-1])"
$ProfileUserText = '"C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])"'

Write-Host "Press any key to use `$Profile.AllUsersAllHosts to stop using a profile from a network share"
pause
# - Create $Profile.AllUsersAllHosts
# - Set-Location C:\Users\$($env:Username)   (override Admin defaulting into system32)
# - If the system decides that it will use C:\ have to check that so that we do not double-load $Profile!
# - If that condition is ok, set $Profile = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$($ShellId)_profile.ps1"
# - Then just dotsource $Profile as it's set to the C:\ drive as required.
if (!(Test-Path $(Split-Path $ProfileAdmin))) { mkdir $(Split-Path $ProfileAdmin) -Force }
if (!(Test-Path $(Split-Path $ProfileUser))) { mkdir $(Split-Path $ProfileUser) -Force }
Write-Host "`nCreating backup of existing profile ..."
If (Test-Path $ProfileAdmin) { Copy-Item -Path "$($ProfileAdmin)" -Destination "$($ProfileAdmin)_$(Get-Date -format "yyyy-MM-dd__HH-mm-ss").txt" }
Set-Content -Path $ProfileAdmin -Value "Set-Location C:\Users\`$(`$env:Username)"
Add-Content -Path $ProfileAdmin -Value ""
Add-Content -Path $ProfileAdmin -Value "# Prevent loading profile from network share"
Add-Content -Path $ProfileAdmin -Value "if (`$Profile.CurrentUserCurrentHost -ne $ProfileUserText) {"
Add-Content -Path $ProfileAdmin -Value "    `$Profile = $ProfileUserText"
Add-Content -Path $ProfileAdmin -Value "    if (Test-Path `"`$Profile`") { . `$Profile }"
Add-Content -Path $ProfileAdmin -Value "}"
</code>```

Body:
$profile is causing me some headaches. $Profile.GetType() resolves to String which is fine, but it has NoteProperty values:

$profile | Get-Member -Type NoteProperty

AllUsersAllHosts, AllUsersCurrentHost, CurrentUserAllHosts, CurrentUserCurrentHost

When I type $profile, the CurrentUserCurrentHost NoteProperty is returned. This is fine, but I need to change this value - it's complicated, but my corporate VPN uses a network profile and when I am online it tries to reference that location for my $profile meaning that every console startup takes 9 seconds (horribly slow). I can get that down to 1 sec if the profile is loaded locally, but that means changing these values. To do this, I put the following into the AllUsersAllHosts profile.ps1

$profile = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"

That's fine, but by doing this, I find that all of the NoteProperty values are deleted! So I tried:

$profile.CurrentUserCurrentHost = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"

But this fails, as the root value of $Profile continues to point at the network profile and Console startup is 9 seconds again!

I then also noticed the following weirdness:

$x = [string]$profile
$x -eq $profile

Ny main questions are:

• Why does $x return True even though $x has none of the NoteProperty values in $profile (as the objects are definitely not the same!)?

• How do I control what the root value of $profile is without destroying the NoteProperty values, and

• How can I update .CurrentUserAllHosts and .CurrentUserCurrentHost in such a way that the root value will also update accordingly? i.e. Even if I do the below, the root value of $profile remains unchanged (still points at the very slow network profile location):

Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersAllHosts" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersCurrentHost" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserAllHosts" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserCurrentHost" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"

Body:
As @mklement0 pointed out, I cannot bypass the functionality of $profile, but I can trick it. Without the below, all shells and scripts take 6.5 to 9 sec to start when I am remotely connected to my corporate VPN (part of that, about 3 seconds is my $profile functions etc). With the below, all consoles and scripts startup in 1 second (and that includes my $profile functions about 1000 lines of code). Putting this solution here in case of help to others.

Running the code at the bottom of this answer results in pushing the following into my $Profile.AllUsersAllHosts which will now always reference a profile at the default C:\ location (and correctly per host type as well - console, ISE, VSCode etc).

Set-Location C:\Users\$($env:Username)

# Prevent loading profile from network share
if ($Profile.CurrentUserCurrentHost -ne "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])") {
    $Profile = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])"
    if (Test-Path "$Profile") { . $Profile }
}

All I then need to do is delete any profiles on the network share and now I get 1 second load times whether connected remotely to the VPN or not, and whether I open a console or a script etc.

Write-Host ""
Write-Host "Do you want to update `$Profile.AllUsersAllHosts to always redirect to C:\Users\$($env:Username) ?"
Write-Host "This can significantly speed up PowerShell load times when working with a network share over a VPN."
Write-Host "Note that this is just a bypass to always use the *default* profile location on C:\."
Write-Host "   `$Profile.AllUsersAllHosts = C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
Write-Host "   `$Profile.CurrentHostCurrentUser = C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split("\"))[-1]_profile.ps1"
Write-Host ""

$ProfileAdmin = "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
# Use  (($Profile).split("\"))[-1]  to capture correct prefix PowerShell, VSCode. $ShellId does not work for VSCode etc
$ProfileUser = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split('\')[-1])"
$ProfileUserText = '"C:\Users\$($env:Username)\Documents\WindowsPowerShell\$(($Profile).split(`"\`")[-1])"'

Write-Host "Press any key to use `$Profile.AllUsersAllHosts to stop using a profile from a network share"
pause
# - Create $Profile.AllUsersAllHosts
# - Set-Location C:\Users\$($env:Username)   (override Admin defaulting into system32)
# - If the system decides that it will use C:\ have to check that so that we do not double-load $Profile!
# - If that condition is ok, set $Profile = "C:\Users\$($env:Username)\Documents\WindowsPowerShell\$($ShellId)_profile.ps1"
# - Then just dotsource $Profile as it's set to the C:\ drive as required.
if (!(Test-Path $(Split-Path $ProfileAdmin))) { mkdir $(Split-Path $ProfileAdmin) -Force }
if (!(Test-Path $(Split-Path $ProfileUser))) { mkdir $(Split-Path $ProfileUser) -Force }
Write-Host "`nCreating backup of existing profile ..."
If (Test-Path $ProfileAdmin) { Copy-Item -Path "$($ProfileAdmin)" -Destination "$($ProfileAdmin)_$(Get-Date -format "yyyy-MM-dd__HH-mm-ss").txt" }
Set-Content -Path $ProfileAdmin -Value "Set-Location C:\Users\`$(`$env:Username)"
Add-Content -Path $ProfileAdmin -Value ""
Add-Content -Path $ProfileAdmin -Value "# Prevent loading profile from network share"
Add-Content -Path $ProfileAdmin -Value "if (`$Profile.CurrentUserCurrentHost -ne $ProfileUserText) {"
Add-Content -Path $ProfileAdmin -Value "    `$Profile = $ProfileUserText"
Add-Content -Path $ProfileAdmin -Value "    if (Test-Path `"`$Profile`") { . `$Profile }"
Add-Content -Path $ProfileAdmin -Value "}"


来源: stackexchange

问:
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted
</code>```

application.properties

```<code>logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver
</code>```

pom.xml

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</code>```

V2__create_shipwreck.sql

```<code>-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));
</code>```

答:
Just add

```<code>spring.flyway.enabled=false
</code>```

in application.properties file if you do not want flyway to check the checksum every time you run the application.

ContentLicense: CC BY-SA 3.0

Body:
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted

application.properties

logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

V2__create_shipwreck.sql

-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));

Body:
Just add

spring.flyway.enabled=false

in application.properties file if you do not want flyway to check the checksum every time you run the application.

ContentLicense: CC BY-SA 4.0


问:
Convert object of objects to array
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

```<code>P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}
</code>```

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

答:
I try with Object.keys(obj).map(key => obj[key]) and it works
Thanks for your help

Title: Convert object of objects to array

Body:
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks


问:
LinQ Remove products based on Status
So I have a issue with a API showing drafted products.

So my solution is to iterate over the list before my view is set and remove any drafted products.

However i'm not familiar with LinQ so im not exactly sure how to go about this, Or what to Phrase id use to look into this more

Here are my attempts

Attempt 1: only removes 1 Product(If I say Any|All its just says cannot convert bool to product)

```<code>
  var listitem = (from itm in products where itm.status == "draft" select itm).FirstOrDefault();
                products.Remove(listitem);
  //Also tried something like

.Where(a => a.status == "draft")
</code>```

Attempt 2: Finds the item, But then removes everything

```<code>       foreach (var item in products)
                {
                    if (item.status == "draft")
                    {
                        products.Remove(item);
                    }
                }
</code>```

```<code>      productsListView.FlowItemsSource = products;
</code>```

Whats the correct way of doing this?

答:
I have a issue with a API showing drafted products. So my solution is to ... remove any drafted products.

Not sure what you want. Do you want to show only the drafted products? Or do you want to show all non-drafted products? Maybe you want to remove the drafted products from your original list?

Show only the drafted products

```<code>var draftedProducts = products.Where(product => product.Status == "draft);
</code>```

In words: from the original sequence of products, keep the products that have a value for property Status equal to "draft"

It is usually easier to understand if you follow the conventions: sequences (collections, lists, arrays) are plural nouns. Elements of the sequence are singular nouns. The part before => represents one element of the sequence, the part after => represents the expression that works on the element of the sequence

Show only non-drafted products

If you understand the previous attempt, this one won't be difficult to understand:

```<code> var nonDraftedProducts = products.Where(product => product.Status != "draft);
</code>```

Remove the drafted products from your original collection

It is important to understand: LINQ will never change your input sequences. LINQ will not add or remove items to the input sequences, nor will it change any of the properties.

If you want to remove items from your input sequences, you'll have to iterate over the LINQ result and remove the items.

```<code>var draftedProducts = products.Where(product => product.Status == "draft).ToList();
foreach (var draftedProduct in draftedProducts)
{
    products.Remove(draftedProduct);
}
</code>```

Or to remove them from a database:

```<code>using (var dbContext = new ProductsDbContext)
{
    var draftedProducts = dbContext.Products
        .Where(product => product.Status == "draft)
        .ToList();
    dbContext.Products.RemoveRange(draftedProducts);
}
</code>```

Or if you use SQL to access the Products:

```<code>var allProducts = myDatabase.GetAllProducts();
var draftedProducts = dbContext.Products
        .Where(product => product.Status == "draft)
        .ToList();
foreach (var draftedProduct in draftedProducts)
{
    myDatabase.RemoveProduct(draftedProduct);
}
</code>```

Title: LinQ Remove products based on Status

Body:
So I have a issue with a API showing drafted products.

So my solution is to iterate over the list before my view is set and remove any drafted products.

However i'm not familiar with LinQ so im not exactly sure how to go about this, Or what to Phrase id use to look into this more

Here are my attempts

Attempt 1: only removes 1 Product(If I say Any|All its just says cannot convert bool to product)

  var listitem = (from itm in products where itm.status == "draft" select itm).FirstOrDefault();
                products.Remove(listitem);
  //Also tried something like

.Where(a => a.status == "draft")

Attempt 2: Finds the item, But then removes everything

       foreach (var item in products)
                {
                    if (item.status == "draft")
                    {
                        products.Remove(item);
                    }
                }

      productsListView.FlowItemsSource = products;

Whats the correct way of doing this?

Body:
I have a issue with a API showing drafted products. So my solution is to ... remove any drafted products.

Not sure what you want. Do you want to show only the drafted products? Or do you want to show all non-drafted products? Maybe you want to remove the drafted products from your original list?

Show only the drafted products

var draftedProducts = products.Where(product => product.Status == "draft);

In words: from the original sequence of products, keep the products that have a value for property Status equal to "draft"

It is usually easier to understand if you follow the conventions: sequences (collections, lists, arrays) are plural nouns. Elements of the sequence are singular nouns. The part before => represents one element of the sequence, the part after => represents the expression that works on the element of the sequence

Show only non-drafted products

If you understand the previous attempt, this one won't be difficult to understand:

 var nonDraftedProducts = products.Where(product => product.Status != "draft);

Remove the drafted products from your original collection

It is important to understand: LINQ will never change your input sequences. LINQ will not add or remove items to the input sequences, nor will it change any of the properties.

If you want to remove items from your input sequences, you'll have to iterate over the LINQ result and remove the items.

var draftedProducts = products.Where(product => product.Status == "draft).ToList();
foreach (var draftedProduct in draftedProducts)
{
    products.Remove(draftedProduct);
}

Or to remove them from a database:

using (var dbContext = new ProductsDbContext)
{
    var draftedProducts = dbContext.Products
        .Where(product => product.Status == "draft)
        .ToList();
    dbContext.Products.RemoveRange(draftedProducts);
}

Or if you use SQL to access the Products:

var allProducts = myDatabase.GetAllProducts();
var draftedProducts = dbContext.Products
        .Where(product => product.Status == "draft)
        .ToList();
foreach (var draftedProduct in draftedProducts)
{
    myDatabase.RemoveProduct(draftedProduct);
}


问:
Where can i find a dataset of handwritten broken numbers or floats or digits?
I m looking for DATASET of HANDWRITTEN BROKEN NUMBERS or floats or digits which means for example a teacher s handwritten mark of students or anything like these images below

thank you in advance

example

答: You could use the MNIST dataset and then add some noise to it. Maybe openCV has some functions for you, like erode, dilate. Maybe some of Morphological Transformations could help you (Closing, for an example)


问:
Loading a xml to a class with Javascript
How can I load a XML file to class using Javascript?</p>

答:
This code will work for all kind of browsers

```<code>var url="file.xml"
var xmlDoc="";
if(window.XMLHttpRequest&&!window.ActiveXObject)
{
    var Gz=new XMLHttpRequest();Gz.open('GET',url,false);Gz.send(null);xmlDoc=Gz.responseXML;
}
else
{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.load(url);
}
</code>```

After using this, you can parse the tag and retrieve the data.

OwnerDisplayName: Lorenzo Jiménez

ContentLicense: CC BY-SA 2.5

Body:
This code will work for all kind of browsers

var url="file.xml"
var xmlDoc="";
if(window.XMLHttpRequest&&!window.ActiveXObject)
{
    var Gz=new XMLHttpRequest();Gz.open('GET',url,false);Gz.send(null);xmlDoc=Gz.responseXML;
}
else
{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.load(url);
}

After using this, you can parse the tag and retrieve the data.

OwnerDisplayName: praveenjayapal

LastEditorDisplayName: ScarletGarden


问:
Android - Custom Button gets stuck "Pressed"
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

```<code>private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}
</code>```

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,

答:
In your onTouch method, check for the event action.

If it's MotionEvent.ACTION_DOWN, then proceed as you have.

If it's ACTION_UP or ACTION_CANCEL, then call calcButton.setImageResource(R.drawable.calc_button_not_pressed);

http://developer.android.com/reference/android/view/MotionEvent.html

Body:
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,


问:
Values above the bars in a barchart in Matplotlib
I have the following code for a barchart in matplotlib

```<code>import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()
</code>```

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

答:
i is the index of x position, performance is height of the bar (y position). The first two parameters of plt.text are x and y positions of the text.

```<code>for i, performance in enumerate(performance):
    ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')
</code>```

Body:
I have the following code for a barchart in matplotlib

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

Body:
i is the index of x position, performance is height of the bar (y position). The first two parameters of plt.text are x and y positions of the text.

for i, performance in enumerate(performance):
    ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')


问:
Binary to BCD conversion
I was asked to convert 8 bits binary to 3 digits of BCD.

I saw online people use DIV but I do not understand that way at all, why would I divide by #0AH?

If I was asked to subtract 16 bits by 16 bits using 2 pairs of 8 bit registers, do I need to transfer it to 2's comp using CPL and +1 or just use the SUBB command ?

R4-7 are the registers

```<code>        MOV A, R5
        SUBB A, R7
        JNC L1
        DEC R4
L1:     MOV 20H,A
        CLR C
        MOV A, R4
        SUBB A, R6
        MOV 21H,A
        END
</code>```

答:
Question 1: Why do I need to DIV by #0AH to get the BCD of a binary value?

More often than not each integer value in a computer (and a microcontroller is a computer) is stored as binary, these days. So there is nothing special to do here. If you want the BCD (binary coded decimal), you will need the hundreds, the tens, and the ones separated in 4 bits each. For this you will need to divide by 10 (and save the remainder), and this can be coded as #0AH. However, I would not write this, but write #10 that shows much clearer what is ment.

Let's assume that the number to convert is in the accumulator A, and you want the result in register pair R0 (MSByte) and R1 (LSByte). You need more than one register, because you get 3 digits that will be 12 bits wide in total.

DIV will divide A by B, and give the integer quotient in A and the remainder in B.

```<code>    MOV   B,#10
    DIV   AB      ; floor(number / 10) in A, 1s in B
    MOV   R1,B    ; 1s are now in R1 (bits 3 to 0)
    MOV   B,#10
    DIV   AB      ; floor(number / 100) in A, 10s in B
    MOV   R0,A    ; 100s are now in R0 (bits 3 to 0)
    MOV   A,B     ; 10s are now in ACC (bits 3 to 0)
    SWAP  A       ; 10s are now in bits 7 to 4 in ACC
    ORL   A,R1
    MOV   R1,A    ; 10s and 1s are now in R1
</code>```

Question 2: Do I need to transfer [answerer: negate] the second operand by CPL and +1 or can I just use SUBB?

No, you just use SUBB. Before the first SUBB you will clear the carry flag.

Let's assume that the first operand (to subtract from, the "minuend") is in register pair R0 (MSByte) and R1 (LSByte), and the second operand (to subtract, the "subtrahend") is in register pair R2 (MSByte) and R3 (LSByte). The result (the "difference") should go in register pair R4 (MSByte) and R5 (LSByte).

```<code>    CLR   C
    MOV   A,R1
    SUBB  A,R3
    MOV   R5,A
    MOV   A,R0
    SUBB  A,R2    ; borrow bit from LSByte subtraction is taken into account
    MOV   R4,A
</code>```

Final note: Please use a simulator to try the code, if you like to see details not described here.

Title: Binary to BCD conversion

Body:
I was asked to convert 8 bits binary to 3 digits of BCD.

I saw online people use DIV but I do not understand that way at all, why would I divide by #0AH?

If I was asked to subtract 16 bits by 16 bits using 2 pairs of 8 bit registers, do I need to transfer it to 2's comp using CPL and +1 or just use the SUBB command ?

R4-7 are the registers

        MOV A, R5
        SUBB A, R7
        JNC L1
        DEC R4
L1:     MOV 20H,A
        CLR C
        MOV A, R4
        SUBB A, R6
        MOV 21H,A
        END

Body:
Question 1: Why do I need to DIV by #0AH to get the BCD of a binary value?

More often than not each integer value in a computer (and a microcontroller is a computer) is stored as binary, these days. So there is nothing special to do here. If you want the BCD (binary coded decimal), you will need the hundreds, the tens, and the ones separated in 4 bits each. For this you will need to divide by 10 (and save the remainder), and this can be coded as #0AH. However, I would not write this, but write #10 that shows much clearer what is ment.

Let's assume that the number to convert is in the accumulator A, and you want the result in register pair R0 (MSByte) and R1 (LSByte). You need more than one register, because you get 3 digits that will be 12 bits wide in total.

DIV will divide A by B, and give the integer quotient in A and the remainder in B.

    MOV   B,#10
    DIV   AB      ; floor(number / 10) in A, 1s in B
    MOV   R1,B    ; 1s are now in R1 (bits 3 to 0)
    MOV   B,#10
    DIV   AB      ; floor(number / 100) in A, 10s in B
    MOV   R0,A    ; 100s are now in R0 (bits 3 to 0)
    MOV   A,B     ; 10s are now in ACC (bits 3 to 0)
    SWAP  A       ; 10s are now in bits 7 to 4 in ACC
    ORL   A,R1
    MOV   R1,A    ; 10s and 1s are now in R1

Question 2: Do I need to transfer [answerer: negate] the second operand by CPL and +1 or can I just use SUBB?

No, you just use SUBB. Before the first SUBB you will clear the carry flag.

Let's assume that the first operand (to subtract from, the "minuend") is in register pair R0 (MSByte) and R1 (LSByte), and the second operand (to subtract, the "subtrahend") is in register pair R2 (MSByte) and R3 (LSByte). The result (the "difference") should go in register pair R4 (MSByte) and R5 (LSByte).

    CLR   C
    MOV   A,R1
    SUBB  A,R3
    MOV   R5,A
    MOV   A,R0
    SUBB  A,R2    ; borrow bit from LSByte subtraction is taken into account
    MOV   R4,A

Final note: Please use a simulator to try the code, if you like to see details not described here.


问:
How to handle App state change when our app is already in background due to prompts like SignIn with Google
Whenever prompts like SignIn with google appears on top of application, app goes in background.
Now if user manually closes app with google SignIn prompt on top, handle app state change is not possible right now.</p>

答:
you can use this approach for this case</p>

```<code>   componentDidMount() {
        const { navigation } = this.props;
        this.focusListener = navigation.addListener('didFocus',
            async () => {
                  this.progress()
                }
            });
    }

    async progress() {

    }

    componentWillUnmount() {
        this.focusListener.remove();
    }
</code>```

Body:
you can use this approach for this case

   componentDidMount() {
        const { navigation } = this.props;
        this.focusListener = navigation.addListener('didFocus',
            async () => {
                  this.progress()
                }
            });
    }

    async progress() {

    }

    componentWillUnmount() {
        this.focusListener.remove();
    }


问:
Unable to understand why the following JavaScript function is not working
I am new to Java Script and I am unable to understand why the following function is not working, what am I doing wrong here? Its prompting me to enter the var gender value but once I enter it is not executing any further. Given below the JavaScript code I am trying to run.

var gender = prompt('What is your gender..?');

function name(fname = 'Sayantan', mname, lname = 'Choudhury') {
  if (gender == male) {
    document.write('Hello Mr. ' + fname + ' ' + mname + ' ' + lname + '
');
  } else {
    document.write('Hello Mrs. ' + fname + ' ' + mname + ' ' + lname + '
');
  }
}

name('Mridula', 'Dutta', 'Chowdhury');
name('Mridula');```

答:
male is not variable here so you want to compare it with string like 'male'
You also should check by converting gender to lower case so it can support case insensitive.

also there is one more problem if you don't pass mname you will see undefined in-between first and last name.

var gender = prompt('Gender');
function name(fname = 'Sayantan', mname = '', lname = 'Choudhury') {
  let title = 'Mrs'
  if (gender.toLowerCase() === 'male') {
    title = 'Mr';
  }
  document.write('Hello'+ title + '. ' + fname + ' ' + mname + (mname ? ' ' : '') + lname + '
')
}

name('Mridula', 'Dutta', 'Chowdhury');
name('Mridula');```

Body:
male is not variable here so you want to compare it with string like 'male'
You also should check by converting gender to lower case so it can support case insensitive.

also there is one more problem if you don't pass mname you will see undefined in-between first and last name.

var gender = prompt('Gender');
function name(fname = 'Sayantan', mname = '', lname = 'Choudhury') {
  let title = 'Mrs'
  if (gender.toLowerCase() === 'male') {
    title = 'Mr';
  }
  document.write('Hello'+ title + '. ' + fname + ' ' + mname + (mname ? ' ' : '') + lname + '<br/>')
}

name('Mridula', 'Dutta', 'Chowdhury');
name('Mridula');


问:
Can I add users to a Gitlab private group with a Webhook?
Are account/organization level webhooks a thing in Gitlab? I'm creating a membership site, and when users enroll I'd like to trigger a webhook which adds them to a private Gitlab organization so that they can see all of the group's repositories. Is this possible with Gitlab? All I've been able to find are webhooks at the project level, i.e. when changes are pushed, commits are added, merge requests are started, etc.</p>

答:
You can use the Gitlab API to add members to projects/groups.

The webhooks you mentioned (changes pushed, merge requests started, etc.) are all events that are triggered within Gitlab and can be used to inform an external service.

The Gitlab API can be used the other way round to allow changes within Gitlab to occur by an external service


问:
ProGuard for Kotlin: JVM signature cannot be resolved
When activating ProGuard, I get the following error message that seems to stem from Kotlin Reflect.

```<code>kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Property 'selectedAccount' (JVM signature: getSelectedAccount()Lmy/app/package/data/model/Account;) not resolved in class my.app.package.data.SharedPrefsData
    at kotlin.reflect.jvm.internal.KDeclarationContainerImpl.findPropertyDescriptor(:115)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(:102)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(:27)
    at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(:92)
    at kotlin.reflect.jvm.internal.KPropertyImpl.getDescriptor(:105)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_javaField$1.invoke(:52)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_javaField$1.invoke(:27)
    at kotlin.reflect.jvm.internal.ReflectProperties$LazyVal.invoke(:62)
    at kotlin.reflect.jvm.internal.KPropertyImpl.getJavaField(:79)
    at kotlin.reflect.jvm.ReflectJvmMapping.getJavaField(:40)
    at kotlin.reflect.jvm.KCallablesJvm.a(:65)
    at com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt$a.<init>(:16)
    at com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt.a(:11)
    at my.app.package.data.SharedPrefsData.getSelectedAccountLiveData(:20)
</code>```

SharedPrefsData is a simple KotprefModel to store and load from SharedPreferences:

```<code>class SharedPrefsData(context: Context) : KotprefModel(context), ISharedPrefsData {

    override val kotprefName: String = "${context.packageName}_preferences_data"

    override var selectedAccount by gsonNullablePref<Account>()

    override fun getSelectedAccountLiveData(): LiveData<Account?> {
        return asLiveData(this::selectedAccount)
    }
}
</code>```

And this is what happens in KotprefLiveDataExtensionsKt

```<code>fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> {
    return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
        private val key: String

        init {
            value = property.get()
            property.isAccessible = true
            key = (property.getDelegate() as? PreferenceKey)?.key ?: property.name
            property.isAccessible = false
        }

        override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) {
            if (propertyName == key) {
                postValue(property.get())
            }
        }

        override fun onActive() {
            this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this)
        }

        override fun onInactive() {
            this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this)
        }
    }
}
</code>```

So there seems to be some Kotlin Reflection going on which is famous to cause problems with ProGuard.
But I am already keeping the involved model classes as well as the SharedPrefsData classes. The only ProGuard rules I can find on the KotPref Github are already applied here.

Right now I am using the following ProGuard rules:

```<code>-keep class kotlin.reflect.jvm.internal.** { *; }
-keep class kotlin.reflect.jvm.ReflectJvmMapping { *; }
-keep class com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt
-keep class kotlin.reflect.jvm.KCallablesJvm
-keep class my.app.package.data.model.Account { *; }
-keep class my.app.package.data.model.User { *; }
-keep class my.app.package.data.model.Team { *; }
-keep class my.app.package.data.SharedPrefsData { *; }
-keep class my.app.package.data.ISharedPrefsData { *; }
</code>```

But the error is still there. Any idea what to do here??

答:
Though the error does stem from a kotlin reflection problem as assumed, I fixed the issue by updating to the newest Kotpref version 2.10.0

This version does not use reflection anymore, which made the proguard rules obsolete.

Body:
When activating ProGuard, I get the following error message that seems to stem from Kotlin Reflect.

kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Property 'selectedAccount' (JVM signature: getSelectedAccount()Lmy/app/package/data/model/Account;) not resolved in class my.app.package.data.SharedPrefsData
    at kotlin.reflect.jvm.internal.KDeclarationContainerImpl.findPropertyDescriptor(:115)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(:102)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(:27)
    at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(:92)
    at kotlin.reflect.jvm.internal.KPropertyImpl.getDescriptor(:105)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_javaField$1.invoke(:52)
    at kotlin.reflect.jvm.internal.KPropertyImpl$_javaField$1.invoke(:27)
    at kotlin.reflect.jvm.internal.ReflectProperties$LazyVal.invoke(:62)
    at kotlin.reflect.jvm.internal.KPropertyImpl.getJavaField(:79)
    at kotlin.reflect.jvm.ReflectJvmMapping.getJavaField(:40)
    at kotlin.reflect.jvm.KCallablesJvm.a(:65)
    at com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt$a.<init>(:16)
    at com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt.a(:11)
    at my.app.package.data.SharedPrefsData.getSelectedAccountLiveData(:20)

SharedPrefsData is a simple KotprefModel to store and load from SharedPreferences:

class SharedPrefsData(context: Context) : KotprefModel(context), ISharedPrefsData {

    override val kotprefName: String = "${context.packageName}_preferences_data"

    override var selectedAccount by gsonNullablePref<Account>()

    override fun getSelectedAccountLiveData(): LiveData<Account?> {
        return asLiveData(this::selectedAccount)
    }
}

And this is what happens in KotprefLiveDataExtensionsKt

fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> {
    return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
        private val key: String

        init {
            value = property.get()
            property.isAccessible = true
            key = (property.getDelegate() as? PreferenceKey)?.key ?: property.name
            property.isAccessible = false
        }

        override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) {
            if (propertyName == key) {
                postValue(property.get())
            }
        }

        override fun onActive() {
            this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this)
        }

        override fun onInactive() {
            this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this)
        }
    }
}

So there seems to be some Kotlin Reflection going on which is famous to cause problems with ProGuard.
But I am already keeping the involved model classes as well as the SharedPrefsData classes. The only ProGuard rules I can find on the KotPref Github are already applied here.

Right now I am using the following ProGuard rules:

-keep class kotlin.reflect.jvm.internal.** { *; }
-keep class kotlin.reflect.jvm.ReflectJvmMapping { *; }
-keep class com.chibatching.kotpref.livedata.KotprefLiveDataExtensionsKt
-keep class kotlin.reflect.jvm.KCallablesJvm
-keep class my.app.package.data.model.Account { *; }
-keep class my.app.package.data.model.User { *; }
-keep class my.app.package.data.model.Team { *; }
-keep class my.app.package.data.SharedPrefsData { *; }
-keep class my.app.package.data.ISharedPrefsData { *; }

But the error is still there. Any idea what to do here??


答:
You Could use use onTouch. Then use the ACTION_OUTSIDE which is fired when the users touch moves out the the bound of the view.

Edit 1: to be more specific:

```<code>OnTouchListener(MotionEvent e) {
   switch(e.getAction()) {
      case MotionEvent.ACTION_OUTSIDE: // switch the image if the button
    }
}
</code>```

Title: Android - Custom Button gets stuck "Pressed"

Body:
You Could use use onTouch. Then use the ACTION_OUTSIDE which is fired when the users touch moves out the the bound of the view.

Edit 1: to be more specific:

OnTouchListener(MotionEvent e) {
   switch(e.getAction()) {
      case MotionEvent.ACTION_OUTSIDE: // switch the image if the button
    }
}


问:
git stash -> merge stashed change with current changes
I made some changes to my branch and realized I forgot I had stashed some other necessary changes to said branch.  What I want is a way to merge my stashed changes with the current changes.

Is there a way to do this?

Its more for convenience, I eventually gave up and committed first my current changes, then my stashed changes, but I would have preferred to get them in with one fell swoop.

答:
you can easily

Commit your current changes

Unstash your stash and resolve conflicts

Commit changes from stash

Soft reset to commit you are comming from (last correct commit)


问:
GitLab requires git@localhost password to push to a repo
I'm trying to get GitLab up and running on my server. I followed the installation instructions at the gitlab github page and everything went well.

The issue is, when I create a repo and try to

```<code>sudo git push -u origin master
</code>```

I am prompted for 'git@localhost's password: '

The git user doesn't have a password, so this is a problem.

Other people who have run into this problem suggested adding git to AllowedUsers in my sshd conf but I don't have an AllowedUsers field in there, so that doesn't seem to be an issue.

I'm still pretty new to ssh stuff so I believe its some sort of ssh key issue, though I tried to add all relevant ssh keys to /home/git/.ssh/authorized_keys and verified that there are no line breaks in the file.

Just FYI, my install completely passes the test provided in the gitlab wiki:

```<code>sudo -u gitlab bundle exec rake gitlab:app:status RAILS_ENV=production
</code>```

Any suggestions much appreciated!

EDIT

So, I finally got around this by just committing to a repo from a different machine.  As it was, I was SSHed into the same machine that gitlab was running on.  As soon as I tried to commit from a machine other than the host, it worked great.  So, that may be a solution for some people (it is for us, since we develop on seperate machines than our servers).

This is still an open-ended issue for anyone trying to host and develop on the same machine who has run into this.

答:
I had the a similar problem: Gitlab server is inside a docker container and every time when I tried to push changes, I had:
git@localhost's password:

the root cause was using "localhost" as a name. Right way is to check out the IP of the GitLab's container by:
$ docker inspect <container_id>

find the row:
"IPAddress": "172.17.0.2",

test it by:
ssh -T git@172.17.0.2
the answer should be like this. "Welcome to GitLab, @user_name!"

now it's necessary to fix repository's URL:
$ git remote set-url origin git@172.17.0.2:user_name/repo-name.git

after that the push command should work properly.

Body:
I'm trying to get GitLab up and running on my server. I followed the installation instructions at the gitlab github page and everything went well.

The issue is, when I create a repo and try to

sudo git push -u origin master

I am prompted for 'git@localhost's password: '

The git user doesn't have a password, so this is a problem.

Other people who have run into this problem suggested adding git to AllowedUsers in my sshd conf but I don't have an AllowedUsers field in there, so that doesn't seem to be an issue.

I'm still pretty new to ssh stuff so I believe its some sort of ssh key issue, though I tried to add all relevant ssh keys to /home/git/.ssh/authorized_keys and verified that there are no line breaks in the file.

Just FYI, my install completely passes the test provided in the gitlab wiki:

sudo -u gitlab bundle exec rake gitlab:app:status RAILS_ENV=production

Any suggestions much appreciated!

EDIT

So, I finally got around this by just committing to a repo from a different machine.  As it was, I was SSHed into the same machine that gitlab was running on.  As soon as I tried to commit from a machine other than the host, it worked great.  So, that may be a solution for some people (it is for us, since we develop on seperate machines than our servers).

This is still an open-ended issue for anyone trying to host and develop on the same machine who has run into this.


问:
How to change react-dates input css
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

```<code><SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>
</code>```

答:
You can create a custom styling file and import that one rather than importing the bundled styling coming with the package. Like this:

```<code>// NOTE: the order of these styles DO matter

// Will edit everything selected including everything between a range of dates
.CalendarDay__selected_span {
  background: #82e0aa; //background
  color: white; //text
  border: 1px solid $light-red; //default styles include a border
}

// Will edit selected date or the endpoints of a range of dates
.CalendarDay__selected {
  background: $dark-red;
  color: white;
}

// Will edit when hovered over. _span style also has this property
.CalendarDay__selected:hover {
  background: orange;
  color: white;
}

// Will edit when the second date (end date) in a range of dates
// is not yet selected. Edits the dates between your mouse and said date
.CalendarDay__hovered_span:hover,
.CalendarDay__hovered_span {
  background: brown;
}
</code>```

For more look the docs here.

Title: How to change react-dates input css

Body:
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

<SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>

Body:
You can create a custom styling file and import that one rather than importing the bundled styling coming with the package. Like this:

// NOTE: the order of these styles DO matter

// Will edit everything selected including everything between a range of dates
.CalendarDay__selected_span {
  background: #82e0aa; //background
  color: white; //text
  border: 1px solid $light-red; //default styles include a border
}

// Will edit selected date or the endpoints of a range of dates
.CalendarDay__selected {
  background: $dark-red;
  color: white;
}

// Will edit when hovered over. _span style also has this property
.CalendarDay__selected:hover {
  background: orange;
  color: white;
}

// Will edit when the second date (end date) in a range of dates
// is not yet selected. Edits the dates between your mouse and said date
.CalendarDay__hovered_span:hover,
.CalendarDay__hovered_span {
  background: brown;
}

For more look the docs here.


问:
How to deserialize JSON with RestTemplate when the request body is either a list or an object?
I am trying to deserialize JSON from consuming an API.
However the JSON body coming from the API is not consistent. Sometimes it comes as a list, and sometimes as a single item.

Example:

```<code>"Charge": [
            {
              "ChargeType": "EXPRESS 12:00",
              "ChargeAmount": 0.0
            },
            {
              "ChargeCode": "YK",
              "ChargeType": "12:00 PREMIUM",
              "ChargeAmount": 0.0
            },
          ]
</code>```

And in another case:

```<code>"Charge": {
            "ChargeType": "EXPRESS",
            "ChargeAmount": 8.5
          }
</code>```

I am using RestTemplate and DTOs.

My DTO is built like this.

```<code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Charges {

    @JsonProperty(value = "Currency")
    private String currency;

    @JsonProperty(value = "Charge")
    private List<Charge> charges;
}
</code>```

This fails on the case when it comes as an object:

```<code>com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<Charge>` out of START_OBJECT token
</code>```

Is there a way I can solve this without creating my Custom JSON Converter?
And if I have to create it, how can I do it?

答:
Solved by using:</p>

```<code> @JsonProperty(value = "Charge")
 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<Charge> charges;
</code>```

Body:
I am trying to deserialize JSON from consuming an API.
However the JSON body coming from the API is not consistent. Sometimes it comes as a list, and sometimes as a single item.

Example:

"Charge": [
            {
              "ChargeType": "EXPRESS 12:00",
              "ChargeAmount": 0.0
            },
            {
              "ChargeCode": "YK",
              "ChargeType": "12:00 PREMIUM",
              "ChargeAmount": 0.0
            },
          ]

And in another case:

"Charge": {
            "ChargeType": "EXPRESS",
            "ChargeAmount": 8.5
          }

I am using RestTemplate and DTOs.

My DTO is built like this.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Charges {

    @JsonProperty(value = "Currency")
    private String currency;

    @JsonProperty(value = "Charge")
    private List<Charge> charges;
}

This fails on the case when it comes as an object:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<Charge>` out of START_OBJECT token

Is there a way I can solve this without creating my Custom JSON Converter?
And if I have to create it, how can I do it?

Body:
Solved by using:

 @JsonProperty(value = "Charge")
 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<Charge> charges;


答:
You used wrong order of variables in ax.text. Use the following. Also, don't use performance variable twice. I used perf now

```<code>for i, perf in enumerate(performance):
    ax.text(i, perf + .25, str(perf), color='black',
            ha='center', fontweight='bold')
</code>```

Title: Values above the bars in a barchart in Matplotlib

Body:
You used wrong order of variables in ax.text. Use the following. Also, don't use performance variable twice. I used perf now

for i, perf in enumerate(performance):
    ax.text(i, perf + .25, str(perf), color='black',
            ha='center', fontweight='bold')


问:
Is it possible counting the records per hour in pl sql ? if possible please suggest query with simple example
Is it possible counting the records per hour in postgres ? if possible please suggest query with simple example.

Thanks in advance for your kind help.

答:
There are multiple system tables that can be used for this purpose. e.g

```<code>select * from pg_stat_all_tables where schemaname='public';
select * from pg_stat_database;
select * from pg_stat_activity;
</code>```

For more details please see the following link:MONITORING-STATS-VIEWS

Body:
There are multiple system tables that can be used for this purpose. e.g

select * from pg_stat_all_tables where schemaname='public';
select * from pg_stat_database;
select * from pg_stat_activity;

For more details please see the following link:MONITORING-STATS-VIEWS


问:
Angular strange behavior in production mode
When I'm building my project in production mode ng build --prod --output-path=../Angular --base-href=/autopoint/ --deploy-url=/autopoint/Angular/, a strange line at the top of the html before the  tag appears but when I'm running it with an ng serve, it is gone. Any ideas what this might be caused by?

_Layout.cshtml

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AutoPoint</title>
    <base href="/" />
    <link href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    @Styles.Render("~/Angular/Styles")
</head>
<body id="app">

@RenderBody()

    @Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/Angular/Scripts")
    @Scripts.RenderFormat("<script src='{0}' nomodule defer></script>", "~/Angular/ScriptsIE")
</body>
</html>
</code>```

Index.cshtml

```<code><app-root></app-root>
</code>```

答: Problem is solved. Invisible whitespace character.

Body:
When I'm building my project in production mode ng build --prod --output-path=../Angular --base-href=/autopoint/ --deploy-url=/autopoint/Angular/, a strange line at the top of the html before the  tag appears but when I'm running it with an ng serve, it is gone. Any ideas what this might be caused by?

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AutoPoint</title>
    <base href="/" />
    <link href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,600,800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    @Styles.Render("~/Angular/Styles")

@RenderBody()

    @Scripts.RenderFormat("", "~/Angular/Scripts")
    @Scripts.RenderFormat("", "~/Angular/ScriptsIE")

Index.cshtml

<app-root></app-root>


问:
Delphi 7 crashes after installing Delphi XE (BPL mixed paths)
After installing Delphi XE, my good-old Delphi 7 started to crash more often. Today, I have discovered that one of my BPLs was still loaded by D7 even if I deleted it from "c:\Program Files\Borland\Delphi7\Projects\Bpl".
After I have searched the entire disk I have discovered a copy of that BPL in "c:\Users\Public\Documents\RAD Studio\8.0\Bpl".

My question is: why is Delphi 7 looking in "c:\Users\Public\Documents\RAD Studio\8.0\Bpl"?
How can I convince it to look only in "c:\Program Files\Borland\Delphi7\Projects\Bpl" ?

答:
Delphi XE probably augments the PATH environment variable to include the Delphi XE Bpl folder. Delphi 7 doesn't know any better; it calls LoadLibrary just like everything else, and that searches the system path.

Follow the Delphi example and give your packages version-specific suffixes reflecting what version of Delphi they're for. You should be able to configure that in the project options, or else you can just have version-specific project files that already have the version suffixes in their names. That way, even if the Delphi XE version of the package is visible on the path, it won't have the right name, so Delphi 7 won't try to load it.


问:
How to get key value pairs in google vision ocr?
I have been using google vision API for retrieving the text from images, the output json file just contains the text and the coordinates of the text. Is there any way we can get key value pairs from google vision ocr?</p>

答: The way google vision ocr works is that it detects texts in blocks and in paragraphs inside these blocks. Provided your tables are in the same format, you can just manipulate the json output to give you key and value pairs. Aside from this, I do not think google vision ocr can do explicitly, what you're asking for. </p>


问:
Partial column sum of a matrix or nested list
The code listed below is an attempt to obtain a matrix with a partial column-sum of another, such that the rows, row[r], of the resultant matrix is the partial column-sum of the original matrix from row=0 to row=r.

For example,
given

```<code>A = [[0,0,0],
     [4,5,6],
     [7,8,9],
     [10,11,12]]
</code>```

I would like to obtain

```<code>B=[[0,0,0],
   [4,5,6],
   [11,13,15],
   [21,24,27]]
</code>```

Is there an alternative that allow me to eliminate the for-loop in the following code and which allows me to use pure list-comprehension instead?

Do you consider list-comprehension will be more computational efficient than for-loops or map/lambda provided that the actual matrices I'm working on are relatively large?

My current code is below:

```<code>import numpy as np
# Define matrices M and S
M= np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
H = np.array([0.1, 0.2, 0.3])
# Define matrix S with: S[0] = [0,0,0,0] and S[r>0][c] = M[r][c]xH[r]
S = np.array([[x if r != 0 else 0 for x in [M[r][c] * H[r] for c in range(0, len(M[r]))]] for r in range(len(M))])
# initialize matrix L
L = np.array(np.zeros((int(len(M)),int(len(M[0])))))
#Update Matrix L: L[r][c] = Sum[S[0][c] to S[i=r-1][c]]
for r in range(0, len(L)):
        L[r] = [sum([row[i] for row in S[0:r+1]]) for i in range(0,len(S[0]))]
print("S", S)
print("L", L)
</code>```

答:
When using numpy, the fastest way to do something is usually to use broadcasting, or vectorization. You can read more about this here, but basically this means to apply a function to an array of data all at once, rather than by iterating over the array by using a for-loop.

This may have been what you were alluding to when you talked about list-comprehensions, but these at heart are just a different way of writing for-loops.

The function you are looking for in this case is np.cumsum(), using axis=0 to indicate that we want to cumulatively sum over each column. This is a vectorized method of applying the logic you seek, and will be a lot faster than your for-loop solution on large matrices.

```<code>>>> A = np.array([[0,0,0],[4,5,6],[7,8,9],[10,11,12]])
>>> np.cumsum(A, axis=0)
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [11, 13, 15],
       [21, 24, 27]], dtype=int32)
</code>```

Below is a graph showing a comparison of the speed of this approach and the approach in your question, as matrix size increases, which shows that the vectorized approach tends towards being approximately 10,000 times faster.

Code to generate:

```<code>import perfplot
import numpy as np

def cdjb_cumsum(A):
    return np.cumsum(A, axis=0)

def ajbg_forloop(A):
    L = np.array(np.zeros((int(len(A)),int(len(A[0])))))
    for r in range(0, len(L)):
        L[r] = [sum([row[i] for row in A[0:r+1]]) for i in range(0,len(A[0]))]
    return L

perfplot.show(
    setup=lambda n: np.random.rand(n, n),
    n_range=[2**k for k in range(20)],
    kernels=[
        cdjb_cumsum, ajbg_forloop
        ],
    xlabel='Size of Array (n*n)',
    )
</code>```

Body:
The code listed below is an attempt to obtain a matrix with a partial column-sum of another, such that the rows, row[r], of the resultant matrix is the partial column-sum of the original matrix from row=0 to row=r.

For example,
given

A = [[0,0,0],
     [4,5,6],
     [7,8,9],
     [10,11,12]]

I would like to obtain

B=[[0,0,0],
   [4,5,6],
   [11,13,15],
   [21,24,27]]

Is there an alternative that allow me to eliminate the for-loop in the following code and which allows me to use pure list-comprehension instead?

Do you consider list-comprehension will be more computational efficient than for-loops or map/lambda provided that the actual matrices I'm working on are relatively large?

My current code is below:

import numpy as np
# Define matrices M and S
M= np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
H = np.array([0.1, 0.2, 0.3])
# Define matrix S with: S[0] = [0,0,0,0] and S[r>0][c] = M[r][c]xH[r]
S = np.array([[x if r != 0 else 0 for x in [M[r][c] * H[r] for c in range(0, len(M[r]))]] for r in range(len(M))])
# initialize matrix L
L = np.array(np.zeros((int(len(M)),int(len(M[0])))))
#Update Matrix L: L[r][c] = Sum[S[0][c] to S[i=r-1][c]]
for r in range(0, len(L)):
        L[r] = [sum([row[i] for row in S[0:r+1]]) for i in range(0,len(S[0]))]
print("S", S)
print("L", L)

Body:
When using numpy, the fastest way to do something is usually to use broadcasting, or vectorization. You can read more about this here, but basically this means to apply a function to an array of data all at once, rather than by iterating over the array by using a for-loop.

This may have been what you were alluding to when you talked about list-comprehensions, but these at heart are just a different way of writing for-loops.

The function you are looking for in this case is np.cumsum(), using axis=0 to indicate that we want to cumulatively sum over each column. This is a vectorized method of applying the logic you seek, and will be a lot faster than your for-loop solution on large matrices.

>>> A = np.array([[0,0,0],[4,5,6],[7,8,9],[10,11,12]])
>>> np.cumsum(A, axis=0)
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [11, 13, 15],
       [21, 24, 27]], dtype=int32)

Below is a graph showing a comparison of the speed of this approach and the approach in your question, as matrix size increases, which shows that the vectorized approach tends towards being approximately 10,000 times faster.

Code to generate:

import perfplot
import numpy as np

def cdjb_cumsum(A):
    return np.cumsum(A, axis=0)

def ajbg_forloop(A):
    L = np.array(np.zeros((int(len(A)),int(len(A[0])))))
    for r in range(0, len(L)):
        L[r] = [sum([row[i] for row in A[0:r+1]]) for i in range(0,len(A[0]))]
    return L

perfplot.show(
    setup=lambda n: np.random.rand(n, n),
    n_range=[2**k for k in range(20)],
    kernels=[
        cdjb_cumsum, ajbg_forloop
        ],
    xlabel='Size of Array (n*n)',
    )


问:
how to make vuetify select drop down working
I working with vuetify but I have notice that v-select drop down menu is not working,I have tried to google but and end up with nothing,Please kindly assist on this. I will be appreciate,Thanks</p>

```<code><v-select label="City" items="items" ></v-select>

data:function(){ items:["Mumbai","Capetown"]}
</code>```

答:
You need to pass ":items" instead of "items". By omitting the : in front of a property you are passing the prop as simple string.

Since you want it to be handled as object, you need to use ":item".

<v-select label="City" :items="items"></v-select>

Body:
I working with vuetify but I have notice that v-select drop down menu is not working,I have tried to google but and end up with nothing,Please kindly assist on this. I will be appreciate,Thanks

<v-select label="City" items="items" ></v-select>

data:function(){ items:["Mumbai","Capetown"]}


问:
Laravel - whereHas last relation is = 'manual'
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

```<code>$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

Or

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.

答:
My solution is to define a new relationship on the Lead table.

```<code>class Lead extends Model
{
    public function lastStatus()
    {
        return $this->statuses()->latest()->limit(1);
    }
}
</code>```

This way, the final query can be a bit simpler.

```<code>$leads = Lead::whereHas(‘lastStatus’, function ($query) use ($q) {
    $query->where(‘description’, ‘LIKE’, $q);
}
</code>```

Body:
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

Or

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.

Body:
My solution is to define a new relationship on the Lead table.

class Lead extends Model
{
    public function lastStatus()
    {
        return $this->statuses()->latest()->limit(1);
    }
}

This way, the final query can be a bit simpler.

$leads = Lead::whereHas(‘lastStatus’, function ($query) use ($q) {
    $query->where(‘description’, ‘LIKE’, $q);
}


问:
Merge JSON objects through unique field then print child node data
I have the following JSON:

```<code>data: {
    questions: "[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]},

    answers: "[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}},

    createdDate: "2020-02-14T07:43:02.000000Z"
}
</code>```

A tidy version of the above is:

Question (questions object)

title : "This is question 1"

ref" : "data_q1"

Answer (answers object)

ref" : "data_q1"

number : 2

So, for question 1 (with the ref: data_q1) the number (score) is 2.

What I'm trying to do, is to merge both questions answers together based on ref. I want to do this so that I can get the number. I.e. question and answer for data_q1 is 2.

I have the following:

```<code>// Get questions
var questionData = data.data.questions;
var questions = JSON.parse(questionData);

// get answers
var answerData = data.data.answers;
var answers = JSON.parse(answerData);
</code>```

What I've tried:

```<code>var answersInfo = answers.map( function(order) {
if( answers.ref === "RefIDHere"){
     var info = { "number": answers.number}
     return info;
 }
});
console.log(answersInfo);
</code>```

However, the issue with the above is, in answers.ref ===, I don't know what to pass because the questions and answers haven't been mapped together yet.

答:
Use filter:

let data = {
    questions: '[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]}]',
    answers: '[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}}]',
    createdDate: "2020-02-14T07:43:02.000000Z"
}

let getQuestionAndAnswer = (data, ref) => {
  let question = JSON.parse(data.questions).filter(v => v.ref === ref);
  let answer = JSON.parse(data.answers).filter(v => v.field.ref === ref);

  return {
      question,
      answer
    };
};

console.log(getQuestionAndAnswer(data, "data_q1"));```

Body:
I have the following JSON:

data: {
    questions: "[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]},

    answers: "[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}},

    createdDate: "2020-02-14T07:43:02.000000Z"
}

A tidy version of the above is:

Question (questions object)

title : "This is question 1"

ref" : "data_q1"

Answer (answers object)

ref" : "data_q1"

number : 2

So, for question 1 (with the ref: data_q1) the number (score) is 2.

What I'm trying to do, is to merge both questions answers together based on ref. I want to do this so that I can get the number. I.e. question and answer for data_q1 is 2.

I have the following:

// Get questions
var questionData = data.data.questions;
var questions = JSON.parse(questionData);

// get answers
var answerData = data.data.answers;
var answers = JSON.parse(answerData);

What I've tried:

var answersInfo = answers.map( function(order) {
if( answers.ref === "RefIDHere"){
     var info = { "number": answers.number}
     return info;
 }
});
console.log(answersInfo);

However, the issue with the above is, in answers.ref ===, I don't know what to pass because the questions and answers haven't been mapped together yet.


问:
SocketException: Address already in use MONGODB
i found this error when trying to run mongodb. I install it via homebrew. Please assist</p>

```<code>Agungs-MacBook-Pro:~ agungmahaputra$ mongod
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] MongoDB starting : pid=5189 port=27017 dbpath=/data/db 64-bit host=Agungs-MacBook-Pro.local
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] db version v3.6.0
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] git version: a57d8e71e6998a2d0afde7edc11bd23e5661c915
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2n  7 Dec 2017
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] allocator: system
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] modules: none
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] build environment:
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten]     distarch: x86_64
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten]     target_arch: x86_64
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] options: {}
2017-12-26T15:31:15.911+0700 E STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] now exiting
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] shutting down with code:48
Agungs-MacBook-Pro:~ agungmahaputra$
</code>```

答:
After running this commands below:

```<code>sudo lsof -iTCP -sTCP:LISTEN -n -P
</code>```

Search for mongod COMMAND and its PID and type,

```<code>sudo kill <mongo_command_pid>
</code>```

And restarting mongod, it still fails with the same error "SocketException: Address already in use MONGODB".

Server was restarted yesterday and then this happened.

Body:
i found this error when trying to run mongodb. I install it via homebrew. Please assist

Agungs-MacBook-Pro:~ agungmahaputra$ mongod
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] MongoDB starting : pid=5189 port=27017 dbpath=/data/db 64-bit host=Agungs-MacBook-Pro.local
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] db version v3.6.0
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] git version: a57d8e71e6998a2d0afde7edc11bd23e5661c915
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2n  7 Dec 2017
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] allocator: system
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] modules: none
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] build environment:
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten]     distarch: x86_64
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten]     target_arch: x86_64
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] options: {}
2017-12-26T15:31:15.911+0700 E STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] now exiting
2017-12-26T15:31:15.911+0700 I CONTROL  [initandlisten] shutting down with code:48
Agungs-MacBook-Pro:~ agungmahaputra$

Body:
After running this commands below:

sudo lsof -iTCP -sTCP:LISTEN -n -P

Search for mongod COMMAND and its PID and type,

sudo kill <mongo_command_pid>

And restarting mongod, it still fails with the same error "SocketException: Address already in use MONGODB".

Server was restarted yesterday and then this happened.


问:
How to properly handle a navigation stack with React Native tvOS / Android TV
I am using react-native-tvos to build a tvOS and Amazon FireStick app. However I am running into a problem with react-navigation. Screens that are added to the navigation stack are still active in the background. This causes the focus engine to get confused. Using the directional pad on the remote the focus will shift between the non-visible screen on the bottom of the stack and the currently displayed screen. I am looking for suggestions on how to solve this problem.

I have read that other people have experienced this problem with react-navigation and react-native-navigation. But I did not find solutions.

答:
If you are using react-native-tvos version, then follow this issue in their repo.

As for a temporary solution, I can recommend hiding your content yourself.
Take a look at my implementation:

```<code>import React from "react";
import { View } from "react-native";

// That's a HOC to know when the current Screen is focused
import withScreenFocusing from "../components/HOC/WithScreenFocusing";

const FocusHider = ({ isFocused, children }) => {
  return (
    <View style={{ display: isFocused ? "flex" : "none" }}>{children}</View>
  );
};

export default withScreenFocusing(FocusHider);
</code>```

And then use it as such:

```<code> <FocusHider>
   <YourAwesomeContent />
 </FocusHider>
</code>```

Just in case, the HOC I mentioned there is just useIsFocused from @react-navigation/native

Body:
If you are using react-native-tvos version, then follow this issue in their repo.

As for a temporary solution, I can recommend hiding your content yourself.
Take a look at my implementation:

import React from "react";
import { View } from "react-native";

// That's a HOC to know when the current Screen is focused
import withScreenFocusing from "../components/HOC/WithScreenFocusing";

const FocusHider = ({ isFocused, children }) => {
  return (
    <View style={{ display: isFocused ? "flex" : "none" }}>{children}</View>
  );
};

export default withScreenFocusing(FocusHider);

And then use it as such:

 <FocusHider>
   <YourAwesomeContent />
 </FocusHider>

Just in case, the HOC I mentioned there is just useIsFocused from @react-navigation/native