问:
How to create a box-shadow that covers the entire page?
the end result that I'm looking for is something like this:

http://osxdaily.com/wp-content/uploads/2011/08/icloud-background.jpg

Which was generated with this bkg title:

http://osxdaily.com/wp-content/uploads/2011/08/apple-shirt.jpg

Is it possible to apply a css3 box-shadow to get the desired output?

I tried:

```<code>box-shadow: inset 0 0 490px black;
</code>```

But that only covers a small part of the screen.

Thanks

答:
Shadow on whole page!</p>

```<code>box-shadow: 0 0 0 100000px rgba(0,0,0,.2);
</code>```

Body:
the end result that I'm looking for is something like this:

http://osxdaily.com/wp-content/uploads/2011/08/icloud-background.jpg

Which was generated with this bkg title:

http://osxdaily.com/wp-content/uploads/2011/08/apple-shirt.jpg

Is it possible to apply a css3 box-shadow to get the desired output?

I tried:

box-shadow: inset 0 0 490px black;

But that only covers a small part of the screen.

Thanks

Body:
Shadow on whole page!

box-shadow: 0 0 0 100000px rgba(0,0,0,.2);


来源: stackexchange

问:
Replace values outside range with NA using replace_with_na function
I have the following dataset

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60
</code>```

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60
</code>```

I've tried several things with replace_with_na_at function where this seemed most logical:

```<code>test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)
</code>```

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

答:
Yet another base R solution, this time with function is.na<-

```<code>is.na(test$b) <- with(test, b < 4 | b > 9)
is.na(test$c) <- with(test, c < 50 | c > 80)
</code>```

A package naniar solution with a pipe could be

```<code>library(naniar)
library(magrittr)

test %>%
  replace_with_na_at(
    .vars = 'b',
    condition = ~(.x < 4 | .x > 9)
  ) %>%
  replace_with_na_at(
    .vars = 'c',
    condition = ~(.x < 50 | .x > 80)
  )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following dataset

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60

I've tried several things with replace_with_na_at function where this seemed most logical:

test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

Body:
Yet another base R solution, this time with function is.na<-

is.na(test$b) <- with(test, b < 4 | b > 9)
is.na(test$c) <- with(test, c < 50 | c > 80)

A package naniar solution with a pipe could be

library(naniar)
library(magrittr)

test %>%
  replace_with_na_at(
    .vars = 'b',
    condition = ~(.x < 4 | .x > 9)
  ) %>%
  replace_with_na_at(
    .vars = 'c',
    condition = ~(.x < 50 | .x > 80)
  )


问:
Error 404 not found after running docker-compose with SpringBoot and MongoDB
My DockerFile is:

```<code>    FROM openjdk:8
VOLUME /tmp
ADD target/demo-0.0.1-SNAPSHOT.jar app.jar
#RUN bash -c 'touch /app.jar'
#EXPOSE 8080
ENTRYPOINT ["java","-Dspring.data.mongodb.uri=mongodb://mongo/players","-jar","/app.jar"]
</code>```

And the docker-compose is:

```<code>  version: "3"
services:
    spring-docker:
        build: .
        restart: always
        ports:
            - "8080:8080"
        depends_on:
            - db
    db:
        image: mongo
        volumes:
            - ./data:/data/db
        ports:
            - "27000:27017"
        restart: always
</code>```

I have docker Image and when I use docker-compose up, anything goes well without any error.
But in the Postman, when I use GET method with localhost:8080/player I do not have any out put, so I used the IP of docker-machine such as 192.168.99.101:8080, but I have error 404 Not found in the Postman.
what is my mistake?!

The docker-compose logs:

```<code>   $ docker-compose logs
Attaching to thesismongoproject_spring-docker_1, thesismongoproject_db_1
spring-docker_1  |
spring-docker_1  |   .   ____          _            __ _ _
spring-docker_1  |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
spring-docker_1  | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-docker_1  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
spring-docker_1  |   '  |____| .__|_| |_|_| |_\__, | / / / /
spring-docker_1  |  =========|_|==============|___/=/_/_/_/
spring-docker_1  |  :: Spring Boot ::        (v2.2.6.RELEASE)
spring-docker_1  |
spring-docker_1  | 2020-05-31 11:36:39.598  INFO 1 --- [           main] thesisM
ongoProject.Application           : Starting Application v0.0.1-SNAPSHOT on e81c
cff8ba0e with PID 1 (/demo-0.0.1-SNAPSHOT.jar started by root in /)
spring-docker_1  | 2020-05-31 11:36:39.620  INFO 1 --- [           main] thesisM
ongoProject.Application           : No active profile set, falling back to defau
lt profiles: default
spring-docker_1  | 2020-05-31 11:36:41.971  INFO 1 --- [           main] .s.d.r.
c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositori
es in DEFAULT mode.
spring-docker_1  | 2020-05-31 11:36:42.216  INFO 1 --- [           main] .s.d.r.
c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in
225ms. Found 4 MongoDB repository interfaces.
spring-docker_1  | 2020-05-31 11:36:44.319  INFO 1 --- [           main] o.s.b.w
.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

spring-docker_1  | 2020-05-31 11:36:44.381  INFO 1 --- [           main] o.apach
e.catalina.core.StandardService   : Starting service [Tomcat]
spring-docker_1  | 2020-05-31 11:36:44.381  INFO 1 --- [           main] org.apa
che.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.
33]
spring-docker_1  | 2020-05-31 11:36:44.619  INFO 1 --- [           main] o.a.c.c
.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationC
ontext
spring-docker_1  | 2020-05-31 11:36:44.619  INFO 1 --- [           main] o.s.web
.context.ContextLoader            : Root WebApplicationContext: initialization c
ompleted in 4810 ms
spring-docker_1  | 2020-05-31 11:36:46.183  INFO 1 --- [           main] org.mon
godb.driver.cluster               : Cluster created with settings {hosts=[db:270
17], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'
, maxWaitQueueSize=500}
spring-docker_1  | 2020-05-31 11:36:46.781  INFO 1 --- [null'}-db:27017] org.mon
godb.driver.connection            : Opened connection [connectionId{localValue:1
, serverValue:1}] to db:27017
spring-docker_1  | 2020-05-31 11:36:46.802  INFO 1 --- [null'}-db:27017] org.mon
godb.driver.cluster               : Monitor thread successfully connected to ser
ver with description ServerDescription{address=db:27017, type=STANDALONE, state=
CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 7]}, minWireVersion
=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30,
 roundTripTimeNanos=5468915}
spring-docker_1  | 2020-05-31 11:36:48.829  INFO 1 --- [           main] o.s.s.c
oncurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTas
kExecutor'
spring-docker_1  | 2020-05-31 11:36:49.546  INFO 1 --- [           main] o.s.b.w
.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with
context path ''
spring-docker_1  | 2020-05-31 11:36:49.581  INFO 1 --- [           main] thesisM
ongoProject.Application           : Started Application in 11.264 seconds (JVM r
unning for 13.615)
spring-docker_1  | 2020-05-31 11:40:10.290  INFO 1 --- [extShutdownHook] o.s.s.c
oncurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTa
skExecutor'
db_1             | 2020-05-31T11:36:35.623+0000 I  CONTROL  [main] Automatically
 disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none
'
db_1             | 2020-05-31T11:36:35.639+0000 W  ASIO     [main] No TransportL
ayer configured during NetworkInterface startup
db_1             | 2020-05-31T11:36:35.645+0000 I  CONTROL  [initandlisten] Mong
oDB starting : pid=1 port=27017 dbpath=/data/db 64-bit host=1a0e5bc0c503
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] db v
ersion v4.2.7
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] git
version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] Open
SSL version: OpenSSL 1.1.1  11 Sep 2018
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] allo
cator: tcmalloc
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] modu
les: none
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten] buil
d environment:
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
distmod: ubuntu1804
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
distarch: x86_64
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
target_arch: x86_64
db_1             | 2020-05-31T11:36:35.648+0000 I  CONTROL  [initandlisten] opti
ons: { net: { bindIp: "*" } }
db_1             | 2020-05-31T11:36:35.649+0000 I  STORAGE  [initandlisten] Dete
cted data files in /data/db created by the 'wiredTiger' storage engine, so setti
ng the active storage engine to 'wiredTiger'.
db_1             | 2020-05-31T11:36:35.650+0000 I  STORAGE  [initandlisten] wire
dtiger_open config: create,cache_size=256M,cache_overflow=(file_max=0M),session_
max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(f
ast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager
=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statis
tics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
db_1             | 2020-05-31T11:36:37.046+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:46670][1:0x7f393f9a0b00], txn-recover: Recovering log
 9 through 10
db_1             | 2020-05-31T11:36:37.231+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:231423][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 10 through 10
db_1             | 2020-05-31T11:36:37.294+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:294858][1:0x7f393f9a0b00], txn-recover: Main recovery
 loop: starting at 9/6016 to 10/256
db_1             | 2020-05-31T11:36:37.447+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:447346][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 9 through 10
db_1             | 2020-05-31T11:36:37.564+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:564841][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 10 through 10
db_1             | 2020-05-31T11:36:37.645+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:645216][1:0x7f393f9a0b00], txn-recover: Set global re
covery timestamp: (0, 0)
db_1             | 2020-05-31T11:36:37.681+0000 I  RECOVERY [initandlisten] Wire
dTiger recoveryTimestamp. Ts: Timestamp(0, 0)
db_1             | 2020-05-31T11:36:37.703+0000 I  STORAGE  [initandlisten] Time
stamp monitor starting
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten]
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten] ** W
ARNING: Access control is not enabled for the database.
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten] **
        Read and write access to data and configuration is unrestricted.
db_1             | 2020-05-31T11:36:37.705+0000 I  CONTROL  [initandlisten]
db_1             | 2020-05-31T11:36:37.712+0000 I  SHARDING [initandlisten] Mark
ing collection local.system.replset as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.722+0000 I  STORAGE  [initandlisten] Flow
 Control is enabled on this deployment.
db_1             | 2020-05-31T11:36:37.722+0000 I  SHARDING [initandlisten] Mark
ing collection admin.system.roles as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.724+0000 I  SHARDING [initandlisten] Mark
ing collection admin.system.version as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.726+0000 I  SHARDING [initandlisten] Mark
ing collection local.startup_log as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.729+0000 I  FTDC     [initandlisten] Init
ializing full-time diagnostic data capture with directory '/data/db/diagnostic.d
ata'
db_1             | 2020-05-31T11:36:37.740+0000 I  SHARDING [LogicalSessionCache
Refresh] Marking collection config.system.sessions as collection version: <unsha
rded>
db_1             | 2020-05-31T11:36:37.748+0000 I  SHARDING [LogicalSessionCache
Reap] Marking collection config.transactions as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.748+0000 I  NETWORK  [listener] Listening
 on /tmp/mongodb-27017.sock
db_1             | 2020-05-31T11:36:37.748+0000 I  NETWORK  [listener] Listening
 on 0.0.0.0
db_1             | 2020-05-31T11:36:37.749+0000 I  NETWORK  [listener] waiting f
or connections on port 27017
db_1             | 2020-05-31T11:36:38.001+0000 I  SHARDING [ftdc] Marking colle
ction local.oplog.rs as collection version: <unsharded>
db_1             | 2020-05-31T11:36:46.536+0000 I  NETWORK  [listener] connectio
n accepted from 172.19.0.3:40656 #1 (1 connection now open)
db_1             | 2020-05-31T11:36:46.653+0000 I  NETWORK  [conn1] received cli
ent metadata from 172.19.0.3:40656 conn1: { driver: { name: "mongo-java-driver|l
egacy", version: "3.11.2" }, os: { type: "Linux", name: "Linux", architecture: "
amd64", version: "4.14.154-boot2docker" }, platform: "Java/Oracle Corporation/1.
8.0_252-b09" }
db_1             | 2020-05-31T11:40:10.302+0000 I  NETWORK  [conn1] end connecti
on 172.19.0.3:40656 (0 connections now open)
db_1             | 2020-05-31T11:40:10.523+0000 I  CONTROL  [signalProcessingThr
ead] got signal 15 (Terminated), will terminate after current cmd ends
db_1             | 2020-05-31T11:40:10.730+0000 I  NETWORK  [signalProcessingThr
ead] shutdown: going to close listening sockets...
db_1             | 2020-05-31T11:40:10.731+0000 I  NETWORK  [listener] removing
socket file: /tmp/mongodb-27017.sock
db_1             | 2020-05-31T11:40:10.731+0000 I  -        [signalProcessingThr
ead] Stopping further Flow Control ticket acquisitions.
db_1             | 2020-05-31T11:40:10.796+0000 I  CONTROL  [signalProcessingThr
ead] Shutting down free monitoring
db_1             | 2020-05-31T11:40:10.800+0000 I  FTDC     [signalProcessingThr
ead] Shutting down full-time diagnostic data capture
db_1             | 2020-05-31T11:40:10.803+0000 I  STORAGE  [signalProcessingThr
ead] Deregistering all the collections
db_1             | 2020-05-31T11:40:10.811+0000 I  STORAGE  [signalProcessingThr
ead] Timestamp monitor shutting down
db_1             | 2020-05-31T11:40:10.828+0000 I  STORAGE  [TimestampMonitor] T
imestamp monitor is stopping due to: interrupted at shutdown
db_1             | 2020-05-31T11:40:10.828+0000 I  STORAGE  [signalProcessingThr
ead] WiredTigerKVEngine shutting down
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down session sweeper thread
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down session sweeper thread
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down journal flusher thread
db_1             | 2020-05-31T11:40:10.916+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down journal flusher thread
db_1             | 2020-05-31T11:40:10.917+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down checkpoint thread
db_1             | 2020-05-31T11:40:10.917+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down checkpoint thread
db_1             | 2020-05-31T11:40:10.935+0000 I  STORAGE  [signalProcessingThr
ead] shutdown: removing fs lock...
db_1             | 2020-05-31T11:40:10.942+0000 I  CONTROL  [signalProcessingThr
ead] now exiting
db_1             | 2020-05-31T11:40:10.943+0000 I  CONTROL  [signalProcessingThr
ead] shutting down with code:0
</code>```

答: for solving this problem I must put @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class}) annotation </p>

Body:
My DockerFile is:

    FROM openjdk:8
VOLUME /tmp
ADD target/demo-0.0.1-SNAPSHOT.jar app.jar
#RUN bash -c 'touch /app.jar'
#EXPOSE 8080
ENTRYPOINT ["java","-Dspring.data.mongodb.uri=mongodb://mongo/players","-jar","/app.jar"]

And the docker-compose is:

  version: "3"
services:
    spring-docker:
        build: .
        restart: always
        ports:
            - "8080:8080"
        depends_on:
            - db
    db:
        image: mongo
        volumes:
            - ./data:/data/db
        ports:
            - "27000:27017"
        restart: always

I have docker Image and when I use docker-compose up, anything goes well without any error.
But in the Postman, when I use GET method with localhost:8080/player I do not have any out put, so I used the IP of docker-machine such as 192.168.99.101:8080, but I have error 404 Not found in the Postman.
what is my mistake?!

The docker-compose logs:

   $ docker-compose logs
Attaching to thesismongoproject_spring-docker_1, thesismongoproject_db_1
spring-docker_1  |
spring-docker_1  |   .   ____          _            __ _ _
spring-docker_1  |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
spring-docker_1  | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-docker_1  |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
spring-docker_1  |   '  |____| .__|_| |_|_| |_\__, | / / / /
spring-docker_1  |  =========|_|==============|___/=/_/_/_/
spring-docker_1  |  :: Spring Boot ::        (v2.2.6.RELEASE)
spring-docker_1  |
spring-docker_1  | 2020-05-31 11:36:39.598  INFO 1 --- [           main] thesisM
ongoProject.Application           : Starting Application v0.0.1-SNAPSHOT on e81c
cff8ba0e with PID 1 (/demo-0.0.1-SNAPSHOT.jar started by root in /)
spring-docker_1  | 2020-05-31 11:36:39.620  INFO 1 --- [           main] thesisM
ongoProject.Application           : No active profile set, falling back to defau
lt profiles: default
spring-docker_1  | 2020-05-31 11:36:41.971  INFO 1 --- [           main] .s.d.r.
c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositori
es in DEFAULT mode.
spring-docker_1  | 2020-05-31 11:36:42.216  INFO 1 --- [           main] .s.d.r.
c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in
225ms. Found 4 MongoDB repository interfaces.
spring-docker_1  | 2020-05-31 11:36:44.319  INFO 1 --- [           main] o.s.b.w
.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

spring-docker_1  | 2020-05-31 11:36:44.381  INFO 1 --- [           main] o.apach
e.catalina.core.StandardService   : Starting service [Tomcat]
spring-docker_1  | 2020-05-31 11:36:44.381  INFO 1 --- [           main] org.apa
che.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.
33]
spring-docker_1  | 2020-05-31 11:36:44.619  INFO 1 --- [           main] o.a.c.c
.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationC
ontext
spring-docker_1  | 2020-05-31 11:36:44.619  INFO 1 --- [           main] o.s.web
.context.ContextLoader            : Root WebApplicationContext: initialization c
ompleted in 4810 ms
spring-docker_1  | 2020-05-31 11:36:46.183  INFO 1 --- [           main] org.mon
godb.driver.cluster               : Cluster created with settings {hosts=[db:270
17], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'
, maxWaitQueueSize=500}
spring-docker_1  | 2020-05-31 11:36:46.781  INFO 1 --- [null'}-db:27017] org.mon
godb.driver.connection            : Opened connection [connectionId{localValue:1
, serverValue:1}] to db:27017
spring-docker_1  | 2020-05-31 11:36:46.802  INFO 1 --- [null'}-db:27017] org.mon
godb.driver.cluster               : Monitor thread successfully connected to ser
ver with description ServerDescription{address=db:27017, type=STANDALONE, state=
CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 7]}, minWireVersion
=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30,
 roundTripTimeNanos=5468915}
spring-docker_1  | 2020-05-31 11:36:48.829  INFO 1 --- [           main] o.s.s.c
oncurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTas
kExecutor'
spring-docker_1  | 2020-05-31 11:36:49.546  INFO 1 --- [           main] o.s.b.w
.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with
context path ''
spring-docker_1  | 2020-05-31 11:36:49.581  INFO 1 --- [           main] thesisM
ongoProject.Application           : Started Application in 11.264 seconds (JVM r
unning for 13.615)
spring-docker_1  | 2020-05-31 11:40:10.290  INFO 1 --- [extShutdownHook] o.s.s.c
oncurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTa
skExecutor'
db_1             | 2020-05-31T11:36:35.623+0000 I  CONTROL  [main] Automatically
 disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none
'
db_1             | 2020-05-31T11:36:35.639+0000 W  ASIO     [main] No TransportL
ayer configured during NetworkInterface startup
db_1             | 2020-05-31T11:36:35.645+0000 I  CONTROL  [initandlisten] Mong
oDB starting : pid=1 port=27017 dbpath=/data/db 64-bit host=1a0e5bc0c503
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] db v
ersion v4.2.7
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] git
version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] Open
SSL version: OpenSSL 1.1.1  11 Sep 2018
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] allo
cator: tcmalloc
db_1             | 2020-05-31T11:36:35.646+0000 I  CONTROL  [initandlisten] modu
les: none
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten] buil
d environment:
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
distmod: ubuntu1804
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
distarch: x86_64
db_1             | 2020-05-31T11:36:35.647+0000 I  CONTROL  [initandlisten]
target_arch: x86_64
db_1             | 2020-05-31T11:36:35.648+0000 I  CONTROL  [initandlisten] opti
ons: { net: { bindIp: "*" } }
db_1             | 2020-05-31T11:36:35.649+0000 I  STORAGE  [initandlisten] Dete
cted data files in /data/db created by the 'wiredTiger' storage engine, so setti
ng the active storage engine to 'wiredTiger'.
db_1             | 2020-05-31T11:36:35.650+0000 I  STORAGE  [initandlisten] wire
dtiger_open config: create,cache_size=256M,cache_overflow=(file_max=0M),session_
max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(f
ast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager
=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statis
tics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
db_1             | 2020-05-31T11:36:37.046+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:46670][1:0x7f393f9a0b00], txn-recover: Recovering log
 9 through 10
db_1             | 2020-05-31T11:36:37.231+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:231423][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 10 through 10
db_1             | 2020-05-31T11:36:37.294+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:294858][1:0x7f393f9a0b00], txn-recover: Main recovery
 loop: starting at 9/6016 to 10/256
db_1             | 2020-05-31T11:36:37.447+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:447346][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 9 through 10
db_1             | 2020-05-31T11:36:37.564+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:564841][1:0x7f393f9a0b00], txn-recover: Recovering lo
g 10 through 10
db_1             | 2020-05-31T11:36:37.645+0000 I  STORAGE  [initandlisten] Wire
dTiger message [1590924997:645216][1:0x7f393f9a0b00], txn-recover: Set global re
covery timestamp: (0, 0)
db_1             | 2020-05-31T11:36:37.681+0000 I  RECOVERY [initandlisten] Wire
dTiger recoveryTimestamp. Ts: Timestamp(0, 0)
db_1             | 2020-05-31T11:36:37.703+0000 I  STORAGE  [initandlisten] Time
stamp monitor starting
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten]
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten] ** W
ARNING: Access control is not enabled for the database.
db_1             | 2020-05-31T11:36:37.704+0000 I  CONTROL  [initandlisten] **
        Read and write access to data and configuration is unrestricted.
db_1             | 2020-05-31T11:36:37.705+0000 I  CONTROL  [initandlisten]
db_1             | 2020-05-31T11:36:37.712+0000 I  SHARDING [initandlisten] Mark
ing collection local.system.replset as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.722+0000 I  STORAGE  [initandlisten] Flow
 Control is enabled on this deployment.
db_1             | 2020-05-31T11:36:37.722+0000 I  SHARDING [initandlisten] Mark
ing collection admin.system.roles as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.724+0000 I  SHARDING [initandlisten] Mark
ing collection admin.system.version as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.726+0000 I  SHARDING [initandlisten] Mark
ing collection local.startup_log as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.729+0000 I  FTDC     [initandlisten] Init
ializing full-time diagnostic data capture with directory '/data/db/diagnostic.d
ata'
db_1             | 2020-05-31T11:36:37.740+0000 I  SHARDING [LogicalSessionCache
Refresh] Marking collection config.system.sessions as collection version: <unsha
rded>
db_1             | 2020-05-31T11:36:37.748+0000 I  SHARDING [LogicalSessionCache
Reap] Marking collection config.transactions as collection version: <unsharded>
db_1             | 2020-05-31T11:36:37.748+0000 I  NETWORK  [listener] Listening
 on /tmp/mongodb-27017.sock
db_1             | 2020-05-31T11:36:37.748+0000 I  NETWORK  [listener] Listening
 on 0.0.0.0
db_1             | 2020-05-31T11:36:37.749+0000 I  NETWORK  [listener] waiting f
or connections on port 27017
db_1             | 2020-05-31T11:36:38.001+0000 I  SHARDING [ftdc] Marking colle
ction local.oplog.rs as collection version: <unsharded>
db_1             | 2020-05-31T11:36:46.536+0000 I  NETWORK  [listener] connectio
n accepted from 172.19.0.3:40656 #1 (1 connection now open)
db_1             | 2020-05-31T11:36:46.653+0000 I  NETWORK  [conn1] received cli
ent metadata from 172.19.0.3:40656 conn1: { driver: { name: "mongo-java-driver|l
egacy", version: "3.11.2" }, os: { type: "Linux", name: "Linux", architecture: "
amd64", version: "4.14.154-boot2docker" }, platform: "Java/Oracle Corporation/1.
8.0_252-b09" }
db_1             | 2020-05-31T11:40:10.302+0000 I  NETWORK  [conn1] end connecti
on 172.19.0.3:40656 (0 connections now open)
db_1             | 2020-05-31T11:40:10.523+0000 I  CONTROL  [signalProcessingThr
ead] got signal 15 (Terminated), will terminate after current cmd ends
db_1             | 2020-05-31T11:40:10.730+0000 I  NETWORK  [signalProcessingThr
ead] shutdown: going to close listening sockets...
db_1             | 2020-05-31T11:40:10.731+0000 I  NETWORK  [listener] removing
socket file: /tmp/mongodb-27017.sock
db_1             | 2020-05-31T11:40:10.731+0000 I  -        [signalProcessingThr
ead] Stopping further Flow Control ticket acquisitions.
db_1             | 2020-05-31T11:40:10.796+0000 I  CONTROL  [signalProcessingThr
ead] Shutting down free monitoring
db_1             | 2020-05-31T11:40:10.800+0000 I  FTDC     [signalProcessingThr
ead] Shutting down full-time diagnostic data capture
db_1             | 2020-05-31T11:40:10.803+0000 I  STORAGE  [signalProcessingThr
ead] Deregistering all the collections
db_1             | 2020-05-31T11:40:10.811+0000 I  STORAGE  [signalProcessingThr
ead] Timestamp monitor shutting down
db_1             | 2020-05-31T11:40:10.828+0000 I  STORAGE  [TimestampMonitor] T
imestamp monitor is stopping due to: interrupted at shutdown
db_1             | 2020-05-31T11:40:10.828+0000 I  STORAGE  [signalProcessingThr
ead] WiredTigerKVEngine shutting down
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down session sweeper thread
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down session sweeper thread
db_1             | 2020-05-31T11:40:10.829+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down journal flusher thread
db_1             | 2020-05-31T11:40:10.916+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down journal flusher thread
db_1             | 2020-05-31T11:40:10.917+0000 I  STORAGE  [signalProcessingThr
ead] Shutting down checkpoint thread
db_1             | 2020-05-31T11:40:10.917+0000 I  STORAGE  [signalProcessingThr
ead] Finished shutting down checkpoint thread
db_1             | 2020-05-31T11:40:10.935+0000 I  STORAGE  [signalProcessingThr
ead] shutdown: removing fs lock...
db_1             | 2020-05-31T11:40:10.942+0000 I  CONTROL  [signalProcessingThr
ead] now exiting
db_1             | 2020-05-31T11:40:10.943+0000 I  CONTROL  [signalProcessingThr
ead] shutting down with code:0


问:
Retrieve specific keys and values from a nested dictionary and assign them into a new dictionary in python 3.X
I am currently new to python and my objective currently is to retrieve specific keys and values from a JSON data that I have converted into a dictionary format from a RESTful API and assign them to a new dictionary so that I can display them in a HTML template in flask in table form.

Below is the JSON data mentioned and I want to extract only the "dateRented", "username" in "user", "vehicleModel" and "vehicleBrand" in "vehicle".

```<code>[
  {
    "dateRented": "2020-05-22",
    "recordsID": 1,
    "user": {
      "firstname": "Ching",
      "imageName": "croppedCY",
      "password": "gAAAAABeuQsw-u6FTh3_2VZiXZGTuiJEhbBuLB4FwyPj5xKb33tkJ7HTH7YvZTWxi0MJ3UKqLQAd6LHoXgCahB1gC5qJo9wSHw==",
      "surname": "Loo",
      "userID": 10,
      "username": "CY"
    },
    "vehicle": {
      "colour": "White",
      "cost": 15,
      "latitude": null,
      "longitude": null,
      "rentalStatus": "True",
      "seats": 4,
      "user": null,
      "vehicleBrand": "Honda",
      "vehicleID": 4,
      "vehicleModel": "CRZ"
    }
  }
]
</code>```

答:
let's say your dictionary is called "my_data"

and you have a new dictionary called "new_dict"

You would do something like this:

```<code>new_dict["dateRented"] = my_data[0]["dateRented"]
new_dict["username"] = my_data[0]["user"]["username"]
new_dict["vehicleModel"] = my_data[0]["vehicle"]["vehicleModel"
new_dict["vehicleBrand"] = my_data[0]["vehicle"]["vehicleBrand"]
</code>```

Body:
I am currently new to python and my objective currently is to retrieve specific keys and values from a JSON data that I have converted into a dictionary format from a RESTful API and assign them to a new dictionary so that I can display them in a HTML template in flask in table form.

Below is the JSON data mentioned and I want to extract only the "dateRented", "username" in "user", "vehicleModel" and "vehicleBrand" in "vehicle".

[
  {
    "dateRented": "2020-05-22",
    "recordsID": 1,
    "user": {
      "firstname": "Ching",
      "imageName": "croppedCY",
      "password": "gAAAAABeuQsw-u6FTh3_2VZiXZGTuiJEhbBuLB4FwyPj5xKb33tkJ7HTH7YvZTWxi0MJ3UKqLQAd6LHoXgCahB1gC5qJo9wSHw==",
      "surname": "Loo",
      "userID": 10,
      "username": "CY"
    },
    "vehicle": {
      "colour": "White",
      "cost": 15,
      "latitude": null,
      "longitude": null,
      "rentalStatus": "True",
      "seats": 4,
      "user": null,
      "vehicleBrand": "Honda",
      "vehicleID": 4,
      "vehicleModel": "CRZ"
    }
  }
]

Body:
let's say your dictionary is called "my_data"

and you have a new dictionary called "new_dict"

You would do something like this:

new_dict["dateRented"] = my_data[0]["dateRented"]
new_dict["username"] = my_data[0]["user"]["username"]
new_dict["vehicleModel"] = my_data[0]["vehicle"]["vehicleModel"
new_dict["vehicleBrand"] = my_data[0]["vehicle"]["vehicleBrand"]


问:
ModuleNotFoundError: No module named 'sklearn.decomposition'
i want to import PCA from sklearn.decomposition, but following error occurs:
"ModuleNotFoundError: No module named 'sklearn.decomposition'". (just import sklearn works)

Does someone know how i can solve this problem?

I have installed the packages in Anaconda (conda version : 4.8.3)

答:
If the module installed, uninstall and install Sklearn again.
python -m pip install -U sklearn.


问:
How to show 2 items in one pagination of react native snap carousel
How to dispaly 2 items for one pagination(first dot) and if we swipe then next 2 items should display with showing second dot active.

And if it is odd then last item should display my own component in react native snap carousel.

答:
This is how I implemented to show 3 carousels. We can customize it in many ways</p>

```<code>import React from "react";
import { View, Dimensions, StyleSheet, Image } from "react-native";
import Carousel from "react-native-snap-carousel";

const windowWidth = Dimensions.get("window").width;

export default function MyCarousel() {
  const images = [
    { id: 1, image: require("../assets/home-slider-1.jpg") },
    { id: 2, image: require("../assets/home-slider-2.jpg") },
    { id: 3, image: require("../assets/home-slider-3.jpg") },
    { id: 4, image: require("../assets/home-slider-4.jpg") }
  ];

  // const imagesUri = [
  //   { id: 1, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 2, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 3, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 4, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } }
  // ];

  const _renderItem = ({ item }) => {
    return (
      <View style={styles.slide}>
        <Image
          source={item.image}
          style={styles.image}
          // resizeMode="center"
        ></Image>
      </View>
    );
  };

  return (
    <View style={styles.wrapper}>
      <Carousel
        data={images}
        renderItem={_renderItem}
        sliderWidth={windowWidth}
        itemWidth={windowWidth - 70}
        enableMomentum={false}
        lockScrollWhileSnapping
        autoplay
        useScrollView
        loop
        autoplayInterval={3000}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    height: 150
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff"
  },
  image: {
    flex: 1,
    height: "100%",
    width: "100%",
    alignItems: "center",
    justifyContent: "center"
  }
});
</code>```

Body:
This is how I implemented to show 3 carousels. We can customize it in many ways

import React from "react";
import { View, Dimensions, StyleSheet, Image } from "react-native";
import Carousel from "react-native-snap-carousel";

const windowWidth = Dimensions.get("window").width;

export default function MyCarousel() {
  const images = [
    { id: 1, image: require("../assets/home-slider-1.jpg") },
    { id: 2, image: require("../assets/home-slider-2.jpg") },
    { id: 3, image: require("../assets/home-slider-3.jpg") },
    { id: 4, image: require("../assets/home-slider-4.jpg") }
  ];

  // const imagesUri = [
  //   { id: 1, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 2, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 3, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } },
  //   { id: 4, image: { uri: 'https://i.imgur.com/gG5Egof.jpg' } }
  // ];

  const _renderItem = ({ item }) => {
    return (
      <View style={styles.slide}>
        <Image
          source={item.image}
          style={styles.image}
          // resizeMode="center"
        ></Image>
      </View>
    );
  };

  return (
    <View style={styles.wrapper}>
      <Carousel
        data={images}
        renderItem={_renderItem}
        sliderWidth={windowWidth}
        itemWidth={windowWidth - 70}
        enableMomentum={false}
        lockScrollWhileSnapping
        autoplay
        useScrollView
        loop
        autoplayInterval={3000}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    height: 150
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff"
  },
  image: {
    flex: 1,
    height: "100%",
    width: "100%",
    alignItems: "center",
    justifyContent: "center"
  }
});


答:
Data in the json file have object inside the list you can use loop to iterate through each object in the list then you can easily get the values using dict.get() method it will return the value if the given key exist otherwise it will return default value.

```<code>import json

with open('data.json') as fp:
    data = json.loads(fp.read())

for x in data:
    date_rented = x['dateRented']
    user_name = x['user'].get('username', '')
    vehicle_brand = x['vehicle'].get('vehicleBrand', '')
    vehicle_model = x['vehicle'].get('vehicleModel', '')
    print(date_rented, user_name, vehicle_brand, vehicle_model)
    #2020-05-22 CY Honda CRZ
</code>```

Title: Retrieve specific keys and values from a nested dictionary and assign them into a new dictionary in python 3.X

Body:
Data in the json file have object inside the list you can use loop to iterate through each object in the list then you can easily get the values using dict.get() method it will return the value if the given key exist otherwise it will return default value.

import json

with open('data.json') as fp:
    data = json.loads(fp.read())

for x in data:
    date_rented = x['dateRented']
    user_name = x['user'].get('username', '')
    vehicle_brand = x['vehicle'].get('vehicleBrand', '')
    vehicle_model = x['vehicle'].get('vehicleModel', '')
    print(date_rented, user_name, vehicle_brand, vehicle_model)
    #2020-05-22 CY Honda CRZ


问:
Multiply dataframe rows based on a datetime condition
I have the following example dataframe:

```<code>df = pd.DataFrame(columns=['Total_concentration'], index=pd.to_datetime([]))
df.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3], ['Total_concentration'])
</code>```

I would like to add a column "Total_flux" which is the "Total_concentration" column multiplied by 2 between the dates 2017-01-02 and 2017-01-03 and the "Total_concentration" column multiplied by 3 between the dates 2017-01-04 and 2017-01-05. I.e. the resulting dataframe would look like the following:

```<code>df2 = pd.DataFrame(columns=['Total_concentration','Total_flux'], index=pd.to_datetime([]))
df2.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1,1], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2,4], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1,3], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3,3], ['Total_concentration','Total_flux'])
</code>```

What is the most effective way to do this?

Body:
I have the following example dataframe:

df = pd.DataFrame(columns=['Total_concentration'], index=pd.to_datetime([]))
df.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3], ['Total_concentration'])

I would like to add a column "Total_flux" which is the "Total_concentration" column multiplied by 2 between the dates 2017-01-02 and 2017-01-03 and the "Total_concentration" column multiplied by 3 between the dates 2017-01-04 and 2017-01-05. I.e. the resulting dataframe would look like the following:

df2 = pd.DataFrame(columns=['Total_concentration','Total_flux'], index=pd.to_datetime([]))
df2.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1,1], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2,4], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1,3], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3,3], ['Total_concentration','Total_flux'])

What is the most effective way to do this?

Body:
Solution with slicing DataetimeIndex, then missing values are replaced by original column:

df.loc['2017-01-02':'2017-01-03', 'Total_flux'] = df.loc['2017-01-01':'2017-01-03', 'Total_concentration'] * 2
df.loc['2017-01-04':'2017-01-05', 'Total_flux'] = df.loc['2017-01-04':'2017-01-05', 'Total_concentration'] * 3

df['Total_flux'] = df['Total_flux'].fillna(df['Total_concentration'])
print (df)
                    Total_concentration  Total_flux
2017-01-01 12:00:00                   1           1
2017-01-02 12:00:00                   2           4
2017-01-03 12:00:00                   3           6
2017-01-04 12:00:00                   1           3
2017-01-05 12:00:00                   2           6
2017-01-06 12:00:00                   3           3

Or is possible use numpy.select for values used for multiple with DatetimeIndex.normalize and Series.between:

s = df.index.normalize().to_series()
df['Total_flux'] = (np.select([s.between('2017-01-02','2017-01-03'),
                               s.between('2017-01-04','2017-01-05')],
                               [2,3], default=1) * df['Total_concentration'])
print (df)
                    Total_concentration Total_flux
2017-01-01 12:00:00                   1          1
2017-01-02 12:00:00                   2          4
2017-01-03 12:00:00                   3          6
2017-01-04 12:00:00                   1          3
2017-01-05 12:00:00                   2          6
2017-01-06 12:00:00                   3          3


问:
How to add default code to every cpp file that I open in vim?
I've recently got started with competitive programming. I see a lot of competitors use vim in the competition.
I want to add default code to every CPP file that I might open in vim so that I don't have to type the following routine code and a few Macros as well every time. please help me. thanks in advance.</p>
```<code>#include <bits/stdc++.h>
using namespace std;
int main() {
             return 0;
}
</code>```

答: One possible solution would be to create the template file and read it using the :r command in vim. The next step would be using an autocommand on *.cpp files, whenever you create a new File. see :h autocmd-groups

Body:
I've recently got started with competitive programming. I see a lot of competitors use vim in the competition.
I want to add default code to every CPP file that I might open in vim so that I don't have to type the following routine code and a few Macros as well every time. please help me. thanks in advance.

#include <bits/stdc++.h>
using namespace std;
int main() {
             return 0;
}


问:
Mac App Store Rejection - App sandbox not enabled
I've submitted my app to the Mac App Store and it validated fine.  However, I keep getting Invalid Binary messages with the following;

App sandbox not enabled - The following executables must include the "com.apple.security.app-sandbox" entitlement with a Boolean value of true in the entitlements property list. Refer to the App Sandbox page for more information on sandboxing your app.

This is despite having the entitlements enabled in the app (both the app and the helper) with the following contents;

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
</dict>
</plist>
</code>```

Not sure what to check next.

答: I tracked down the problem to the Build Settings, Signing, CODE_SIGN_ENTITLEMENTS had multiple values. The values looked all the same, so I just re-entered the path for the entitlement file, the multiple values went away, and I no longer got the Sandbox not enabled error.

ContentLicense: CC BY-SA 3.0

Body:
I've submitted my app to the Mac App Store and it validated fine.  However, I keep getting Invalid Binary messages with the following;

App sandbox not enabled - The following executables must include the "com.apple.security.app-sandbox" entitlement with a Boolean value of true in the entitlements property list. Refer to the App Sandbox page for more information on sandboxing your app.

This is despite having the entitlements enabled in the app (both the app and the helper) with the following contents;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
</dict>
</plist>

Not sure what to check next.


问:
python fixed digits rounding
Is there an function in python 2 that can do this?

```<code>1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3
</code>```

Basically the second number says the precision of the number and the everything behind should be rounded.

Based on the comment i came up with this:

```<code>def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision
</code>```

But this is still wrong, because i don't know the size of the numbers.

答:
I found a solution:</p>

```<code>def round_to_precision(x, precision):
    fmt_string = '{:.' + str(precision) + 'g}'
    return float(fmt_string.format(x))

print round_to_precision(1234, 2)
print round_to_precision(1234, 3)
print round_to_precision(12.34, 3)
</code>```

Title: python fixed digits rounding

Body:
Is there an function in python 2 that can do this?

1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3

Basically the second number says the precision of the number and the everything behind should be rounded.

Based on the comment i came up with this:

def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision

But this is still wrong, because i don't know the size of the numbers.

Body:
I found a solution:

def round_to_precision(x, precision):
    fmt_string = '{:.' + str(precision) + 'g}'
    return float(fmt_string.format(x))

print round_to_precision(1234, 2)
print round_to_precision(1234, 3)
print round_to_precision(12.34, 3)


问:
Filtering an array of arrays JS
I'm trying to write a function, that accepts an array of arrays as argument and filtering this array under certain condition. I will explain this condition later.
For example I have such array:

```<code> const arr = [
  [1, 1, 20],
  [2, 1, 15],
  [3, 1.5, 15],
  [4, 1, 15],
  [5, 1, 20],
  [6, 1.5, 15],
  [7, 1, 25],
  [8, 1, 15],
  [9, 0, 15],
  [10, 0, 15],
  [11, 0, 15],
]
</code>```

and the condition. I want to filter it by the value of the third column, but only if it's at least three in a sequence. The function should accept two arguments (or more if needed): value and array
So for example

```<code> const filterByValue = (array, val) => { //definition
     return filtredArr
   }
</code>```

const newArr = filterByValue(array,15)
and now newArr should equal:

```<code> [
   [2, 1, 15],
   [3, 1.5, 15],
   [4, 1, 15],
   [8, 1, 15],
   [9, 0, 15],
   [10, 0, 15],
   [11, 0, 15],
 ]
</code>```

For now I only made:

```<code>const filterByValue = (arr, value) => {
      const newArr = arr.filter((elem, index) => elem[2] === value)
      return newArr
  }
</code>```

but this function returns

```<code>  [
     [2, 1, 15],
     [3, 1.5, 15],
     [4, 1, 15],
     [6, 1.5, 15],
     [8, 1, 15],
     [9, 0, 15],
     [10, 0, 15],
     [11, 0, 15],
  ]
</code>```

there shouldn't be [6,1.5,15]. I have no idea how it could be done to return only fragments of an array that contain at least three internal arrays in a row. Maybe any of you have any idea?

edit more explanation

This sequence means to me that I want only output which internal arrays that contain a set value in the third value (value argument in a function), but that they also have internal arrays that follow each other (at least three). Let's assume that the function accepts arr (first array in my post) and value = 15. The first internal array contains 20 as the third value, so it falls off. The second is okey, the third also and the fourth also - and should return in this situation 2,3,4 internal board (because they follow three in succession). Then the fifth value is 20, the sixth value is 15, but the next (seventh) value 25 again, so the function should not take into account the sixth table (because it is not followed by at least two tables that have the value 15). In the table 8,9,10,11 we have the value 15, and these are four tables (i.e. at least three). Therefore, the function should return an array containing the following tables 2,3,4 and 8,9,10,11. The sixth array contains the value 15, but not followed by two more that would have this value as well. The expected output is the second board in my post.

答:
Try with filter and conditions based on whether match the value or not.

const arr = [
  [1, 1, 20],
  [2, 1, 15],
  [3, 1.5, 15],
  [4, 1, 15],
  [5, 1, 20],
  [6, 1.5, 15],
  [7, 1, 25],
  [8, 1, 15],
  [9, 0, 15],
  [10, 0, 15],
  [11, 0, 15],
];

const filterByValue = (array, val) =>
  array.filter((ar, i, items) => {
    if (ar[2] !== val) {
      return true;
    } else {
      return items[i - 1][2] === val || items[i + 1][2] === val;
    }
  });

console.log(filterByValue(arr, 15));```

Title: Filtering an array of arrays JS

Body:
I'm trying to write a function, that accepts an array of arrays as argument and filtering this array under certain condition. I will explain this condition later.
For example I have such array:

 const arr = [
  [1, 1, 20],
  [2, 1, 15],
  [3, 1.5, 15],
  [4, 1, 15],
  [5, 1, 20],
  [6, 1.5, 15],
  [7, 1, 25],
  [8, 1, 15],
  [9, 0, 15],
  [10, 0, 15],
  [11, 0, 15],
]

and the condition. I want to filter it by the value of the third column, but only if it's at least three in a sequence. The function should accept two arguments (or more if needed): value and array
So for example

 const filterByValue = (array, val) => { //definition
     return filtredArr
   }

const newArr = filterByValue(array,15)
and now newArr should equal:

 [
   [2, 1, 15],
   [3, 1.5, 15],
   [4, 1, 15],
   [8, 1, 15],
   [9, 0, 15],
   [10, 0, 15],
   [11, 0, 15],
 ]

For now I only made:

const filterByValue = (arr, value) => {
      const newArr = arr.filter((elem, index) => elem[2] === value)
      return newArr
  }

but this function returns

  [
     [2, 1, 15],
     [3, 1.5, 15],
     [4, 1, 15],
     [6, 1.5, 15],
     [8, 1, 15],
     [9, 0, 15],
     [10, 0, 15],
     [11, 0, 15],
  ]

there shouldn't be [6,1.5,15]. I have no idea how it could be done to return only fragments of an array that contain at least three internal arrays in a row. Maybe any of you have any idea?

edit more explanation

This sequence means to me that I want only output which internal arrays that contain a set value in the third value (value argument in a function), but that they also have internal arrays that follow each other (at least three). Let's assume that the function accepts arr (first array in my post) and value = 15. The first internal array contains 20 as the third value, so it falls off. The second is okey, the third also and the fourth also - and should return in this situation 2,3,4 internal board (because they follow three in succession). Then the fifth value is 20, the sixth value is 15, but the next (seventh) value 25 again, so the function should not take into account the sixth table (because it is not followed by at least two tables that have the value 15). In the table 8,9,10,11 we have the value 15, and these are four tables (i.e. at least three). Therefore, the function should return an array containing the following tables 2,3,4 and 8,9,10,11. The sixth array contains the value 15, but not followed by two more that would have this value as well. The expected output is the second board in my post.


问:
pure HTML/JS how to direct visitor to certain web page based on their location
Thanks for your time. Just like the title, what I need to accomplish is that

Whenever someone in the South Korea visit my site http://awebsite.com/ they will automatically goes to http://awebsite.com/kr/index.html instead of http://awebsite.com/index.html (so basically the "kr" folder)

If its from South  Korea, then they will be automatically point towards /kr/ folder instead.

How to achieve the above?

Thank you

答: One way to achieve this is to use an IP detection API (for example, ip-api.com, there are many similar services) to detect the location of the client, and when South Korea is detected as the location of the client, use window.location.replace(...) as described in this answer.


问:
How can I create a Class file and JAR file without main function?
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here</p>

```<code>public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}
</code>```

答:
What do you want to do?

Create a class and an jar file out of this Java code so that you can use this in another Java program?

Then you have to compile it:

```<code>java NewLogFields.java
</code>```

Looks like you are unable to compile it at all. This could be because the interface ILogNotify (or the jar that contains this) is not in the classpath.

You can include the path/jar containing this interface in the classpath by using:

```<code>javac -cp .;path_to_jar_or_class NewLogFields.java
</code>```

where path_to_jar_or_class is the path to the folder or jar file that contains ILogNotify.
For example, this may be something like ./logNotify.jar or ./log/

Body:
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here

public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}

Body:
What do you want to do?

Create a class and an jar file out of this Java code so that you can use this in another Java program?

Then you have to compile it:

java NewLogFields.java

Looks like you are unable to compile it at all. This could be because the interface ILogNotify (or the jar that contains this) is not in the classpath.

You can include the path/jar containing this interface in the classpath by using:

javac -cp .;path_to_jar_or_class NewLogFields.java

where path_to_jar_or_class is the path to the folder or jar file that contains ILogNotify.
For example, this may be something like ./logNotify.jar or ./log/


问:
vuetify: Align Odd elements to left even elements to right in grid
I have a list of values where I need to place the even elements to the right, odd element to the left in a grid. But every element is getting aligned to the left itself.</p>

```<code>list = [1,2,3,4,5,6]

<v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6">{{l}}</v-col>
     </v-col>
</v-row>
</code>```

答:
Basically you can achieve this using the below code.</p>

```<code><v-col cols="6" v-for="(l,index) in list">
  {{l}}
</v-col>
</code>```

Body:
I have a list of values where I need to place the even elements to the right, odd element to the left in a grid. But every element is getting aligned to the left itself.

list = [1,2,3,4,5,6]

<v-row>
     <v-col cols="12" v-for="(l,index) in list">
        <v-col v-if="index%2==0" cols="6">{{l}}</v-col>
        <v-col v-else cols="6">{{l}}</v-col>
     </v-col>
</v-row>

Body:
Basically you can achieve this using the below code.

<v-col cols="6" v-for="(l,index) in list">
  {{l}}
</v-col>


问:
Pre-processing SHA256 Python implementation
I am working my way through the SHA256 implementation on wikipedia but have came up stuck. I have just tried to write the code for the message pre-processing and my length for the final message is 504 bits, not the 512 required.

Wikipedia: SHA256

Pre-processing:

append the bit '1' to the message

append k bits '0', where k is the minimum number >= 0 such that the resulting message
  length (modulo 512 in bits) is 448.

append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer
  (this will make the entire post-processed length a multiple of 512 bits)

I'm unsure where the flaw is, I've been over the code quite a few times.

```<code>def joe_sha256 ( input_string ):
    "Joe's SHA256 implementation"

    # Create a binary version of the input string
    binary_string = create_binary ( input_string )

    # Append '1' bit to the end as per the SHA256 specification
    appended_1_bit_string = append_bit_1 ( binary_string )

    # Append 'k' bits to allow for len(string) % 512 == 488
    appended_k_string = append_k_bit ( appended_1_bit_string )

    # Append length of message
    length_of_message = append_length_of_message ( binary_string )

    # Create final message
    final_message = appended_k_string + length_of_message

    print(len(final_message)) # This prints out 504, it should be 512!!!!

    return final_message # Just for testing.

def create_binary ( input_string ):
    "Takes a string and outputs its binary form"
    A = ''.join(format(ord(x), 'b').zfill(8) for x in input_string)
    return A

def append_bit_1 ( input_string ):
    "Appends the bit 1 to the binary form"
    input_string = input_string + '1'
    return input_string

def append_k_bit ( input_string ):
    "Makes sure the length of input will become X % 512 == 488"
    if len(input_string) % 512 == 488:
        return input_string
    else:
        while len(input_string) % 512 != 488:
            input_string = input_string + '0'
        return input_string

def append_length_of_message ( input_string ):
    ""
    # Get value
    hex = format(len(input_string),'x')

    # Construct the 64 bit number?
    final_num = ''
    length = 16-len(hex)
    for x in range(length):
        final_num = final_num + '0'

    final_num = final_num + hex

    return final_num
</code>```

答:
If you are considering hex as a variable, then

```<code>hex = format(len(input_string),'x')
</code>```

should be updated to

```<code>hex = format(len(input_string),'b')
</code>```

to get the correct result.

By doing this the result will become with respect to SHA.

Body:
I am working my way through the SHA256 implementation on wikipedia but have came up stuck. I have just tried to write the code for the message pre-processing and my length for the final message is 504 bits, not the 512 required.

Wikipedia: SHA256

Pre-processing:

append the bit '1' to the message

append k bits '0', where k is the minimum number >= 0 such that the resulting message
  length (modulo 512 in bits) is 448.

append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer
  (this will make the entire post-processed length a multiple of 512 bits)

I'm unsure where the flaw is, I've been over the code quite a few times.

def joe_sha256 ( input_string ):
    "Joe's SHA256 implementation"

    # Create a binary version of the input string
    binary_string = create_binary ( input_string )

    # Append '1' bit to the end as per the SHA256 specification
    appended_1_bit_string = append_bit_1 ( binary_string )

    # Append 'k' bits to allow for len(string) % 512 == 488
    appended_k_string = append_k_bit ( appended_1_bit_string )

    # Append length of message
    length_of_message = append_length_of_message ( binary_string )

    # Create final message
    final_message = appended_k_string + length_of_message

    print(len(final_message)) # This prints out 504, it should be 512!!!!

    return final_message # Just for testing.

def create_binary ( input_string ):
    "Takes a string and outputs its binary form"
    A = ''.join(format(ord(x), 'b').zfill(8) for x in input_string)
    return A

def append_bit_1 ( input_string ):
    "Appends the bit 1 to the binary form"
    input_string = input_string + '1'
    return input_string

def append_k_bit ( input_string ):
    "Makes sure the length of input will become X % 512 == 488"
    if len(input_string) % 512 == 488:
        return input_string
    else:
        while len(input_string) % 512 != 488:
            input_string = input_string + '0'
        return input_string

def append_length_of_message ( input_string ):
    ""
    # Get value
    hex = format(len(input_string),'x')

    # Construct the 64 bit number?
    final_num = ''
    length = 16-len(hex)
    for x in range(length):
        final_num = final_num + '0'

    final_num = final_num + hex

    return final_num

Body:
If you are considering hex as a variable, then

hex = format(len(input_string),'x')

should be updated to

hex = format(len(input_string),'b')

to get the correct result.

By doing this the result will become with respect to SHA.


问:
Spool output multiple tables involved in query
I am trying to find efficient ways to pull a large amount of data from a database, to put it on a cloud platform for analysis (for technical reasons there's no way of doing this in an automated way). For the big tables, I'd like to extract CSVs of a month's worth of data at a time; however, one huge table doesn't have dates, and the IDs have a prefix so I can't simply get a range of IDs. So I think I'd have to join onto another table. Something like this:

select * from big_table
inner join (
select * from table2 where date between to_date("'2020-04-01'","yyyy-mm-dd") and to_date("'2020-05-01'","yyyy-mm-dd") query_result
on big_table.id = query_result.id
```

Thing is, I want to be able to spool to CSV the results of both this query and the inner query into separate files. The inner query can take some time to run (approx 8 minutes), so ideally I'd want to run the whole query above and export to two locations, rather than run the above query and the inner query as separate tasks (thereby duplicating the work).

Is this possible?

答:
I don't think you can spool to two locations at the same time.  But you could create a temporary table and use that:

```<code>create temp table temp_table2 as
    select t2.*
    from table2 t2
    where date >= date '2020-04-01' and
          date < date '2020-05-01';
</code>```

Then, you might want to create an index on this:

```<code>create index idx_temp_table2_id on table2(id);
</code>```

Then:

```<code>select bt.*
from big_table bt join
     temp_table2 t2
     on bt.id = t2.id;
</code>```

You would still need to spool them spearately.

Note:  A simple index on table2(date) might be sufficient to speed both queries.

Body:
I am trying to find efficient ways to pull a large amount of data from a database, to put it on a cloud platform for analysis (for technical reasons there's no way of doing this in an automated way). For the big tables, I'd like to extract CSVs of a month's worth of data at a time; however, one huge table doesn't have dates, and the IDs have a prefix so I can't simply get a range of IDs. So I think I'd have to join onto another table. Something like this:

select * from big_table
inner join (
select * from table2 where date between to_date("'2020-04-01'","yyyy-mm-dd") and to_date("'2020-05-01'","yyyy-mm-dd") query_result
on big_table.id = query_result.id

Thing is, I want to be able to spool to CSV the results of both this query and the inner query into separate files. The inner query can take some time to run (approx 8 minutes), so ideally I'd want to run the whole query above and export to two locations, rather than run the above query and the inner query as separate tasks (thereby duplicating the work).

Is this possible?

Body:
I don't think you can spool to two locations at the same time.  But you could create a temporary table and use that:

create temp table temp_table2 as
    select t2.*
    from table2 t2
    where date >= date '2020-04-01' and
          date < date '2020-05-01';

Then, you might want to create an index on this:

create index idx_temp_table2_id on table2(id);

Then:

select bt.*
from big_table bt join
     temp_table2 t2
     on bt.id = t2.id;

You would still need to spool them spearately.

Note:  A simple index on table2(date) might be sufficient to speed both queries.


问:
iOS: compare a slice of an image to library of options
I'm basically trying to work out how to take a slice of an image, say a screenshot of an iPhone home screen, slice out the first icon and compare it to a set array of images in a library.  Any help on where to start?</p>

答:
I'm no iPhone programmer, but I might be able to suggest a few things:

The SURF feature detection implemented in OpenCV should help you with this

There is a nice article on using OpenCV in Objective-C code.

A quick & dirty way might be to use the difference blend mode which should return the difference between the 1st image(top) and the 2nd image(bottom). If there is no difference the result will be completely black. So, the more black pixels in the difference result, potentially, the more similarities between the compared images.

I'm not an iOS developer, so I don't know if there is an image library that ships with sdk or if there's a free/opensource library for basic image processing. Still this should be trivial to implement:

e.g.

```<code>- (int)difference((int)topPixel,(int)bottomPixel)
{
    return abs(topPixel-bottomPixel);
}
</code>```

Note: Syntax might not be correct :)

HTH

Body:
I'm no iPhone programmer, but I might be able to suggest a few things:

The SURF feature detection implemented in OpenCV should help you with this

There is a nice article on using OpenCV in Objective-C code.

A quick & dirty way might be to use the difference blend mode which should return the difference between the 1st image(top) and the 2nd image(bottom). If there is no difference the result will be completely black. So, the more black pixels in the difference result, potentially, the more similarities between the compared images.

I'm not an iOS developer, so I don't know if there is an image library that ships with sdk or if there's a free/opensource library for basic image processing. Still this should be trivial to implement:

e.g.

- (int)difference((int)topPixel,(int)bottomPixel)
{
    return abs(topPixel-bottomPixel);
}

Note: Syntax might not be correct :)

HTH


问:
Better way to expose functions in NodeJS?
I have a directory where I am keeping all of my DAO files which contains methods to interact with MySQL server.

My DAO directory looks like this

```<code>| -- dao
  | -- user.dao.ts
  | -- employee.dao.ts
</code>```

I have my controllers directory that looks like this

```<code>| -- controller
  | -- user.controller.ts
  | -- employee.controller.ts
</code>```

Each DAO file contains functions which may have same names like:

function insertOne() {}

function insertMany() {}
```

<p>I am utilising these DAO functions in my controller file, I am importing multiple DAO files in one controller file as I want to use multiple DAO functions in one controller</p>

<p>I have two ways to export the functions from DAO files:</p>

<p>First Approach:</p>

<pre class="lang-js prettyprint-override"><code>export function insertOne() {}

export function insertMany() {}
</code>```

Second Approach:

function insertOne() {}

function insertMany() {}

export default {
  insertOne,
  insertMany
};
```

<p>I know it is better to export individual functions, as we can import only the functions that we need in that file, but in my case, the function names would clash, so, what should be the best approach to deal with this ?</p>

<p>If I use first approach I would do something like this in my controller</p>

<pre class="lang-js prettyprint-override"><code>import * as userDAO from "../dao/user.dao.ts";
import * as empDAO from "../dao/emp.dao.ts";

// import { insertOne } from "../dao/user.dao.ts"; // can't do this as name would clash

userDAO.insertOne();
empDAO.insertOne();
</code>```

If I use second approach I would do something like this in my controller

import userDAO from "../dao/user.dao.ts";
import empDAO from "../dao/emp.dao.ts";

userDAO.insertOne();
empDAO.insertOne();
```

Am I doing anything wrong by keeping the same name methods in every DAO file? Looking for suggestions and similar approaches I can add to my code.

答:
You can use the as syntax to rename named imports as well:

```<code>import {insertOne as userInsertOne} from "../dao/user.dao.ts";
import {insertOne as empInsertOne} from "../dao/emp.dao.ts";
//You can use shorter names if you want, of course...

userInsertOne();
empInsertOne();
</code>```

Body:
I have a directory where I am keeping all of my DAO files which contains methods to interact with MySQL server.

My DAO directory looks like this

| -- dao
  | -- user.dao.ts
  | -- employee.dao.ts

I have my controllers directory that looks like this

| -- controller
  | -- user.controller.ts
  | -- employee.controller.ts

Each DAO file contains functions which may have same names like:

function insertOne() {}

function insertMany() {}

I am utilising these DAO functions in my controller file, I am importing multiple DAO files in one controller file as I want to use multiple DAO functions in one controller

I have two ways to export the functions from DAO files:

First Approach:

export function insertOne() {}

export function insertMany() {}

Second Approach:

function insertOne() {}

function insertMany() {}

export default {
  insertOne,
  insertMany
};

I know it is better to export individual functions, as we can import only the functions that we need in that file, but in my case, the function names would clash, so, what should be the best approach to deal with this ?

If I use first approach I would do something like this in my controller

import * as userDAO from "../dao/user.dao.ts";
import * as empDAO from "../dao/emp.dao.ts";

// import { insertOne } from "../dao/user.dao.ts"; // can't do this as name would clash

userDAO.insertOne();
empDAO.insertOne();

If I use second approach I would do something like this in my controller

import userDAO from "../dao/user.dao.ts";
import empDAO from "../dao/emp.dao.ts";

userDAO.insertOne();
empDAO.insertOne();

Am I doing anything wrong by keeping the same name methods in every DAO file? Looking for suggestions and similar approaches I can add to my code.

Body:
You can use the as syntax to rename named imports as well:

import {insertOne as userInsertOne} from "../dao/user.dao.ts";
import {insertOne as empInsertOne} from "../dao/emp.dao.ts";
//You can use shorter names if you want, of course...

userInsertOne();
empInsertOne();


问:
Algorithm of checking if the number is prime
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

```<code>bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}
</code>```

Thanks in advance

答:
2 is the only even prime. So if you start you loop form 3 and increase i by 2, then you can cut off the loop by half.

And you can break as soon as you find the first divisor.

Assign the sqrt(num) into a variable so that it does not calculated on every iteration.

```<code>    if (num == 2)
    {
        return 1;
    }
    if (num % 2 == 0)
    {
        return 0;
    }
    int square_root = sqrt(num);
    for (int i = 3; i <= square_root; i += 2)
    {
        if (num % i == 0)
        {
            isPrime = 0;
            break;
        }
    }

</code>```

Body:
Hello everyone!

I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

Thanks in advance

Body:
2 is the only even prime. So if you start you loop form 3 and increase i by 2, then you can cut off the loop by half.

And you can break as soon as you find the first divisor.

Assign the sqrt(num) into a variable so that it does not calculated on every iteration.

    if (num == 2)
    {
        return 1;
    }
    if (num % 2 == 0)
    {
        return 0;
    }
    int square_root = sqrt(num);
    for (int i = 3; i <= square_root; i += 2)
    {
        if (num % i == 0)
        {
            isPrime = 0;
            break;
        }
    }


问:
Why Url without http or https not open in webkit
Here is the code implementation

```<code>let url = URL(string: "www.google.com")
 webView.load(URLRequest(url: url!))
</code>```

Error
The URL can’t be shown

答: Https stands for Hyper Text Transfer protocol. It is used for communication between the client and the website server database. You can't connect to a website until and unless you communicate with it. In normal surfing, the browser adds https automatically for us in URL if it is not there but in the dev environment, you have to manually add it.</p>

Body:
Here is the code implementation

let url = URL(string: "www.google.com")
 webView.load(URLRequest(url: url!))

Error
The URL can’t be shown


问:
Can't update react-dom 15.6.1 to 16.x.x
I want to update my react app that I created with VS2017 to react 16 so I can use fragments. Updating the 'react' package works fine but I'm struggling with 'react-dom'.

Steps to reproduce (what I've done):

Open VS2017

Create new 'ASP.NET Core Web Application'

Select 'React.js and Redux'

Edit package.json like this:

```<code>"devDependencies": {
    "@types/react": "^16.3.14",
    "@types/react-dom": "^16.0.5",
    "react": "^16.3.2",
    "react-dom": "^16.3.2"
 }
</code>```

Edit a file in ClientApp (eg. ClientApp/boot-client.tsx)

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
console.log(React.version);
console.log(ReactDOM.version);
</code>```

Update npm packages (Right click on package.json -> Restore or 'npm install' in project directory)

Excpected output from those two console.log lines:

```<code>16.3.2
16.3.2
</code>```

Actual output:

```<code>16.3.2
15.6.1
</code>```

Now that the 'react-dom' version isn't 16.x.x I can't use fragments.
I checked following files and all versions seem to be correct (16.x.x)

```<code>npm_modules/@types/react/package.json
npm_modules/@types/react-dom/package.json
npm_modules/react/package.json
npm_modules/react-dom/package.json
</code>```

I can't figure out, what I'm doing wrong. Any help is appreciated.

答:
You can use this command in the command prompt after changing the directory by using cd to the client app folder of your project.

```<code>npm install --save react@^16.8.0 react-dom@^16.8.0
</code>```

With the above command, you can update react and react-dom to the desired versions.

Title: Can't update react-dom 15.6.1 to 16.x.x

Body:
I want to update my react app that I created with VS2017 to react 16 so I can use fragments. Updating the 'react' package works fine but I'm struggling with 'react-dom'.

Steps to reproduce (what I've done):

Open VS2017

Create new 'ASP.NET Core Web Application'

Select 'React.js and Redux'

Edit package.json like this:

"devDependencies": {
    "@types/react": "^16.3.14",
    "@types/react-dom": "^16.0.5",
    "react": "^16.3.2",
    "react-dom": "^16.3.2"
 }

Edit a file in ClientApp (eg. ClientApp/boot-client.tsx)

import * as React from 'react';
import * as ReactDOM from 'react-dom';
console.log(React.version);
console.log(ReactDOM.version);

Update npm packages (Right click on package.json -> Restore or 'npm install' in project directory)

Excpected output from those two console.log lines:

16.3.2
16.3.2

Actual output:

16.3.2
15.6.1

Now that the 'react-dom' version isn't 16.x.x I can't use fragments.
I checked following files and all versions seem to be correct (16.x.x)

npm_modules/@types/react/package.json
npm_modules/@types/react-dom/package.json
npm_modules/react/package.json
npm_modules/react-dom/package.json

I can't figure out, what I'm doing wrong. Any help is appreciated.

Body:
You can use this command in the command prompt after changing the directory by using cd to the client app folder of your project.

npm install --save react@^16.8.0 react-dom@^16.8.0

With the above command, you can update react and react-dom to the desired versions.


问:
Rails/NPM - Module build failed [ERR_PACKAGE_PATH_NOT_EXPORTED] for babel-loader
I have a Rails app and something recently changed in such a way that the rails server will start but when I load a page I get an NPM related error in the browser console. I did not set up NPM/VueJS in this app so need some help getting it running locally...

```<code>Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in /Users/meltemi/rails/myapp/node_modules/@babel/helper-compilation-targets/package.json
    at applyExports (internal/modules/cjs/loader.js:524:9)
    at resolveExports (internal/modules/cjs/loader.js:541:12)
    at Function.Module._findPath (internal/modules/cjs/loader.js:661:22)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:963:27)
    at Function.Module._load (internal/modules/cjs/loader.js:859:27)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/Users/meltemi/rails/myapp/node_modules/@babel/preset-env/lib/debug.js:8:33)
    at Module._compile (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/Users/meltemi/rails/myapp/node_modules/@babel/preset-env/lib/index.js:11:14)
    at Module._compile (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at requireModule (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/files/plugins.js:165:12)
    at loadPreset (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/files/plugins.js:83:17)
    at createDescriptor (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
    at /Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:109:50
    at Array.map (<anonymous>)
    at createDescriptors (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
    at createPresetDescriptors (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
    at presets (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
    at mergeChainOpts (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:320:26)
    at /Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:283:7
    at Generator.next (<anonymous>)
    at buildRootChain (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:90:27)
    at buildRootChain.next (<anonymous>)
    at loadPrivatePartialConfig (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/partial.js:95:62)
    at loadPrivatePartialConfig.next (<anonymous>)
</code>```

This is similar to an issue reported recently in this SO post but in that case NPM wasn't embedded in a Rails app. Regardless I tried their solution by removing node_modules (there is no package-lock.json) and running npm install but that led to more errors in the shell:

```<code>$ npm install
npm WARN deprecated postcss-cssnext@3.1.0: 'postcss-cssnext' has been deprecated in favor of 'postcss-preset-env'. Read more at https://moox.io/blog/deprecating-cssnext/
npm WARN deprecated mkdirp@0.5.4: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated popper.js@1.16.1: You can find the new Popper v2 at @popperjs/core, this package is dedicated to the legacy v1
npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm ERR! code 1
npm ERR! Command failed: git checkout ^2.4.0
npm ERR! error: pathspec '^2.4.0' did not match any file(s) known to git
npm ERR!
</code>```

This app is working in production so I'm not interested in updating outdated libraries at the moment. I'm not an NPM/JS guru so would appreciate any advice no matter how rudimentary this probably is.  Thanks!

Edit: Results of yarn install --check-files as per request

```<code>$ yarn install --check-files
yarn install v1.22.4
[1/5]   Validating package.json...
[2/5]   Resolving packages...
[3/5]   Fetching packages...
[4/5]   Linking dependencies...
[5/5]   Building fresh packages...
$ node -e "try { require('fs').symlinkSync('../../node_modules/@bower_components', 'vendor/assets/components', 'junction') } catch (e) { }"
✨  Done in 10.22s.
</code>```

答: this my case , just remove node_modules and package-lock.json and run npm installso npm run build working correctly.show here for this answer

Body:
I have a Rails app and something recently changed in such a way that the rails server will start but when I load a page I get an NPM related error in the browser console. I did not set up NPM/VueJS in this app so need some help getting it running locally...

Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in /Users/meltemi/rails/myapp/node_modules/@babel/helper-compilation-targets/package.json
    at applyExports (internal/modules/cjs/loader.js:524:9)
    at resolveExports (internal/modules/cjs/loader.js:541:12)
    at Function.Module._findPath (internal/modules/cjs/loader.js:661:22)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:963:27)
    at Function.Module._load (internal/modules/cjs/loader.js:859:27)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/Users/meltemi/rails/myapp/node_modules/@babel/preset-env/lib/debug.js:8:33)
    at Module._compile (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/Users/meltemi/rails/myapp/node_modules/@babel/preset-env/lib/index.js:11:14)
    at Module._compile (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (/Users/meltemi/rails/myapp/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at requireModule (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/files/plugins.js:165:12)
    at loadPreset (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/files/plugins.js:83:17)
    at createDescriptor (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
    at /Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:109:50
    at Array.map (<anonymous>)
    at createDescriptors (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
    at createPresetDescriptors (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
    at presets (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
    at mergeChainOpts (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:320:26)
    at /Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:283:7
    at Generator.next (<anonymous>)
    at buildRootChain (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/config-chain.js:90:27)
    at buildRootChain.next (<anonymous>)
    at loadPrivatePartialConfig (/Users/meltemi/rails/myapp/node_modules/@babel/core/lib/config/partial.js:95:62)
    at loadPrivatePartialConfig.next (<anonymous>)

This is similar to an issue reported recently in this SO post but in that case NPM wasn't embedded in a Rails app. Regardless I tried their solution by removing node_modules (there is no package-lock.json) and running npm install but that led to more errors in the shell:

$ npm install
npm WARN deprecated postcss-cssnext@3.1.0: 'postcss-cssnext' has been deprecated in favor of 'postcss-preset-env'. Read more at https://moox.io/blog/deprecating-cssnext/
npm WARN deprecated mkdirp@0.5.4: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated popper.js@1.16.1: You can find the new Popper v2 at @popperjs/core, this package is dedicated to the legacy v1
npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm ERR! code 1
npm ERR! Command failed: git checkout ^2.4.0
npm ERR! error: pathspec '^2.4.0' did not match any file(s) known to git
npm ERR!

This app is working in production so I'm not interested in updating outdated libraries at the moment. I'm not an NPM/JS guru so would appreciate any advice no matter how rudimentary this probably is.  Thanks!

Edit: Results of yarn install --check-files as per request

$ yarn install --check-files
yarn install v1.22.4
[1/5]   Validating package.json...
[2/5]   Resolving packages...
[3/5]   Fetching packages...
[4/5]   Linking dependencies...
[5/5]   Building fresh packages...
$ node -e "try { require('fs').symlinkSync('../../node_modules/@bower_components', 'vendor/assets/components', 'junction') } catch (e) { }"
✨  Done in 10.22s.