问:
apache2: Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down
I am trying a very simple tutorial explaining how convert  docker-compose to minishift ( Minishift and Kompose. I tried to converted and push the docker-compose.yml example

```<code>version: "2"

services:

  redis-master:
    image: k8s.gcr.io/redis:e2e
    ports:
      - "6379"

  redis-slave:
    image: gcr.io/google_samples/gb-redisslave:v1
    ports:
      - "6379"
    environment:
      - GET_HOSTS_FROM=dns

  frontend:
    image: gcr.io/google-samples/gb-frontend:v4
    ports:
      - "80:80"
    environment:
      - GET_HOSTS_FROM=dns
    labels:
      kompose.service.type: LoadBalancer
</code>```

I successfully compose and push as I can see from these logs:

```<code>C:\Users\Cast\docker-compose-to-minishift>kompose-windows-amd64 up --provider=openshift
[36mINFO[0m We are going to create OpenShift DeploymentConfigs, Services and PersistentVolumeClaims for your Dockerized application.
If you need different kind of resources, use the 'kompose convert' and 'oc create -f' commands instead.

[36mINFO[0m Deploying application in "myproject" namespace
[36mINFO[0m Successfully created Service: frontend
[36mINFO[0m Successfully created Service: redis-master
[36mINFO[0m Successfully created Service: redis-slave
[36mINFO[0m Successfully created DeploymentConfig: frontend
[36mINFO[0m Successfully created ImageStream: frontend
[36mINFO[0m Successfully created DeploymentConfig: redis-master
[36mINFO[0m Successfully created ImageStream: redis-master
[36mINFO[0m Successfully created DeploymentConfig: redis-slave
[36mINFO[0m Successfully created ImageStream: redis-slave

Your application has been deployed to OpenShift. You can run 'oc get dc,svc,is,pvc' for details.

C:\Users\Cast\docker-compose-to-minishift>oc get dc
NAME           REVISION   DESIRED   CURRENT   TRIGGERED BY
frontend       0          1         0         config,image(frontend:v4)
redis-master   1          1         1         config,image(redis-master:e2e)
redis-slave    1          1         1         config,image(redis-slave:v1)
</code>```

Nevertheless, I couldn't reach the web application and looking at the logs I found "The container frontend is crashing frequently. It must wait before it will be restarted again" and clicking in details:

```<code>AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.13. Set the 'ServerName' directive globally to suppress this message
(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
</code>```

Searching around I found someone suggestion to change from port 80 to some not root privileged port (eg. 8080). So I changed it in my docker-compose, deleted manualy  the namespace myproject, recreated it  in OpenShift Web Console and I tried to run once again. Exactly same exception with same message.

In case it is relevant, I have another cmd window with

```<code>C:\Users\Cast\docker-compose-to-minishift>kubectl proxy --port=8080
Starting to serve on 127.0.0.1:8080
</code>```

I am quite begginer on moving from docker-compose to minishift (first time using Kompose tool to be honest).

My main question: why I still get same issue if I have alread changed the ports from 80:80 to 8080:8080 in docker-compose

```<code>  frontend:
    image: gcr.io/google-samples/gb-frontend:v4
    ports:
      - "8080:8080"
</code>```

Secondary question: what I have to check to see why I can't start the pront-end service? It is quite limited the exception provided.

*** edited

converted docker-compose by kompose (only front-end files)

frontend-imagestream

```<code>apiVersion: v1
kind: ImageStream
metadata:
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  tags:
  - annotations: null
    from:
      kind: DockerImage
      name: gcr.io/google-samples/gb-frontend:v4
    generation: null
    importPolicy: {}
    name: v4
status:
  dockerImageRepository: ""
</code>```

frontend-service

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: C:\tools\kompose-windows-amd64.exe convert --provider=openshift
    kompose.service.type: LoadBalancer
    kompose.version: 1.19.0 (f63a961c)
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  ports:
  - name: "8080"
    port: 8080
    targetPort: 8080
  selector:
    io.kompose.service: frontend
  type: LoadBalancer
status:
  loadBalancer: {}
</code>```

frontend-deploymentconfig

```<code>apiVersion: v1
kind: DeploymentConfig
metadata:
  annotations:
    kompose.cmd: C:\tools\kompose-windows-amd64.exe convert --provider=openshift
    kompose.service.type: LoadBalancer
    kompose.version: 1.19.0 (f63a961c)
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  replicas: 1
  selector:
    io.kompose.service: frontend
  strategy:
    resources: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        io.kompose.service: frontend
    spec:
      containers:
      - env:
        - name: GET_HOSTS_FROM
          value: dns
        image: ' '
        name: frontend
        ports:
        - containerPort: 8080
        resources: {}
      restartPolicy: Always
  test: false
  triggers:
  - type: ConfigChange
  - imageChangeParams:
      automatic: true
      containerNames:
      - frontend
      from:
        kind: ImageStreamTag
        name: frontend:v4
    type: ImageChange
status: {}
</code>```

Added all logs (I removed Redis and left only FrontEnd service since it was the only causing issue):

```<code>Windows PowerShell
Copyright (C) Microsoft Corporation. Todos os direitos reservados.

Experimente a nova plataforma cruzada PowerShell https://aka.ms/pscore6

PS C:\Windows\system32> cd C:\to_learn\docker-compose-to-minishift\first-try
PS C:\to_learn\docker-compose-to-minishift\first-try> kompose-windows-amd64 up --provider=openshift
[36mINFO[0m We are going to create OpenShift DeploymentConfigs, Services and PersistentVolumeClaims for your Dockerized application.
If you need different kind of resources, use the 'kompose convert' and 'oc create -f' commands instead.

[36mINFO[0m Deploying application in "myproject" namespace
[36mINFO[0m Successfully created Service: frontend
[36mINFO[0m Successfully created DeploymentConfig: frontend
[36mINFO[0m Successfully created ImageStream: frontend

Your application has been deployed to OpenShift. You can run 'oc get dc,svc,is,pvc' for details.
PS C:\to_learn\docker-compose-to-minishift\first-try> oc expose service/frontend
route.route.openshift.io/frontend exposed
PS C:\to_learn\docker-compose-to-minishift\first-try> minishift openshift service frontend --namespace=myproject
|-----------|----------|----------------------|-------------------------------------------------|--------|
| NAMESPACE |   NAME   |       NODEPORT       |                    ROUTE-URL                    | WEIGHT |
|-----------|----------|----------------------|-------------------------------------------------|--------|
| myproject | frontend | 192.168.99.101:30215 | http://frontend-myproject.192.168.99.101.nip.io |        |
|-----------|----------|----------------------|-------------------------------------------------|--------|
PS C:\to_learn\docker-compose-to-minishift\first-try>
</code>```

And when I try to open http://frontend-myproject.192.168.99.101.nip.io in Chrome:

```<code>Application is not available
The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
...
</code>```

Edited (trying deploying another sample application)

```<code>C:\Users\Cast\docker-compose-to-minishift>kompose-windows-amd64 up --provider=openshift
[36mINFO[0m We are going to create OpenShift DeploymentConfigs, Services and PersistentVolumeClaims for your Dockerized application.
If you need different kind of resources, use the 'kompose convert' and 'oc create -f' commands instead.

[36mINFO[0m Deploying application in "myproject" namespace
[36mINFO[0m Successfully created Service: frontend
[36mINFO[0m Successfully created Service: redis-master
[36mINFO[0m Successfully created Service: redis-slave
[36mINFO[0m Successfully created DeploymentConfig: frontend
[36mINFO[0m Successfully created ImageStream: frontend
[36mINFO[0m Successfully created DeploymentConfig: redis-master
[36mINFO[0m Successfully created ImageStream: redis-master
[36mINFO[0m Successfully created DeploymentConfig: redis-slave
[36mINFO[0m Successfully created ImageStream: redis-slave

Your application has been deployed to OpenShift. You can run 'oc get dc,svc,is,pvc' for details.

C:\Users\Cast\docker-compose-to-minishift>oc get dc
NAME           REVISION   DESIRED   CURRENT   TRIGGERED BY
frontend       0          1         0         config,image(frontend:v4)
redis-master   1          1         1         config,image(redis-master:e2e)
redis-slave    1          1         1         config,image(redis-slave:v1)
</code>```0

Build Pending Status

答:
It happens when you use a non-root container like bitnami official images.

We used user:root and network_mode: host when it needs to get bind with host network.

```<code>  apache:
    image: bitnami/apache:2.4
    container_name: "apache"
    ports:
      - 80:80
    network_mode: host
    privileged: true
    user: root
    environment:
      DOCKER_HOST: "unix:///var/run/docker.sock"
    env_file:
      - .env
    volumes:
      - ./setup/apache/httpd.conf:/opt/bitnami/apache/conf/httpd.conf
</code>```

Body:
I am trying a very simple tutorial explaining how convert  docker-compose to minishift ( Minishift and Kompose. I tried to converted and push the docker-compose.yml example

version: "2"

services:

  redis-master:
    image: k8s.gcr.io/redis:e2e
    ports:
      - "6379"

  redis-slave:
    image: gcr.io/google_samples/gb-redisslave:v1
    ports:
      - "6379"
    environment:
      - GET_HOSTS_FROM=dns

  frontend:
    image: gcr.io/google-samples/gb-frontend:v4
    ports:
      - "80:80"
    environment:
      - GET_HOSTS_FROM=dns
    labels:
      kompose.service.type: LoadBalancer

I successfully compose and push as I can see from these logs:

C:\Users\Cast\docker-compose-to-minishift>kompose-windows-amd64 up --provider=openshift
[36mINFO[0m We are going to create OpenShift DeploymentConfigs, Services and PersistentVolumeClaims for your Dockerized application.
If you need different kind of resources, use the 'kompose convert' and 'oc create -f' commands instead.

[36mINFO[0m Deploying application in "myproject" namespace
[36mINFO[0m Successfully created Service: frontend
[36mINFO[0m Successfully created Service: redis-master
[36mINFO[0m Successfully created Service: redis-slave
[36mINFO[0m Successfully created DeploymentConfig: frontend
[36mINFO[0m Successfully created ImageStream: frontend
[36mINFO[0m Successfully created DeploymentConfig: redis-master
[36mINFO[0m Successfully created ImageStream: redis-master
[36mINFO[0m Successfully created DeploymentConfig: redis-slave
[36mINFO[0m Successfully created ImageStream: redis-slave

Your application has been deployed to OpenShift. You can run 'oc get dc,svc,is,pvc' for details.

C:\Users\Cast\docker-compose-to-minishift>oc get dc
NAME           REVISION   DESIRED   CURRENT   TRIGGERED BY
frontend       0          1         0         config,image(frontend:v4)
redis-master   1          1         1         config,image(redis-master:e2e)
redis-slave    1          1         1         config,image(redis-slave:v1)

Nevertheless, I couldn't reach the web application and looking at the logs I found "The container frontend is crashing frequently. It must wait before it will be restarted again" and clicking in details:

AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.13. Set the 'ServerName' directive globally to suppress this message
(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs

Searching around I found someone suggestion to change from port 80 to some not root privileged port (eg. 8080). So I changed it in my docker-compose, deleted manualy  the namespace myproject, recreated it  in OpenShift Web Console and I tried to run once again. Exactly same exception with same message.

In case it is relevant, I have another cmd window with

C:\Users\Cast\docker-compose-to-minishift>kubectl proxy --port=8080
Starting to serve on 127.0.0.1:8080

I am quite begginer on moving from docker-compose to minishift (first time using Kompose tool to be honest).

My main question: why I still get same issue if I have alread changed the ports from 80:80 to 8080:8080 in docker-compose

  frontend:
    image: gcr.io/google-samples/gb-frontend:v4
    ports:
      - "8080:8080"

Secondary question: what I have to check to see why I can't start the pront-end service? It is quite limited the exception provided.

*** edited

converted docker-compose by kompose (only front-end files)

frontend-imagestream

apiVersion: v1
kind: ImageStream
metadata:
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  tags:
  - annotations: null
    from:
      kind: DockerImage
      name: gcr.io/google-samples/gb-frontend:v4
    generation: null
    importPolicy: {}
    name: v4
status:
  dockerImageRepository: ""

frontend-service

apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: C:\tools\kompose-windows-amd64.exe convert --provider=openshift
    kompose.service.type: LoadBalancer
    kompose.version: 1.19.0 (f63a961c)
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  ports:
  - name: "8080"
    port: 8080
    targetPort: 8080
  selector:
    io.kompose.service: frontend
  type: LoadBalancer
status:
  loadBalancer: {}

frontend-deploymentconfig

apiVersion: v1
kind: DeploymentConfig
metadata:
  annotations:
    kompose.cmd: C:\tools\kompose-windows-amd64.exe convert --provider=openshift
    kompose.service.type: LoadBalancer
    kompose.version: 1.19.0 (f63a961c)
  creationTimestamp: null
  labels:
    io.kompose.service: frontend
  name: frontend
spec:
  replicas: 1
  selector:
    io.kompose.service: frontend
  strategy:
    resources: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        io.kompose.service: frontend
    spec:
      containers:
      - env:
        - name: GET_HOSTS_FROM
          value: dns
        image: ' '
        name: frontend
        ports:
        - containerPort: 8080
        resources: {}
      restartPolicy: Always
  test: false
  triggers:
  - type: ConfigChange
  - imageChangeParams:
      automatic: true
      containerNames:
      - frontend
      from:
        kind: ImageStreamTag
        name: frontend:v4
    type: ImageChange
status: {}

Added all logs (I removed Redis and left only FrontEnd service since it was the only causing issue):

Windows PowerShell
Copyright (C) Microsoft Corporation. Todos os direitos reservados.

Experimente a nova plataforma cruzada PowerShell https://aka.ms/pscore6

PS C:\Windows\system32> cd C:\to_learn\docker-compose-to-minishift\first-try
PS C:\to_learn\docker-compose-to-minishift\first-try> kompose-windows-amd64 up --provider=openshift
[36mINFO[0m We are going to create OpenShift DeploymentConfigs, Services and PersistentVolumeClaims for your Dockerized application.
If you need different kind of resources, use the 'kompose convert' and 'oc create -f' commands instead.

[36mINFO[0m Deploying application in "myproject" namespace
[36mINFO[0m Successfully created Service: frontend
[36mINFO[0m Successfully created DeploymentConfig: frontend
[36mINFO[0m Successfully created ImageStream: frontend

Your application has been deployed to OpenShift. You can run 'oc get dc,svc,is,pvc' for details.
PS C:\to_learn\docker-compose-to-minishift\first-try> oc expose service/frontend
route.route.openshift.io/frontend exposed
PS C:\to_learn\docker-compose-to-minishift\first-try> minishift openshift service frontend --namespace=myproject
|-----------|----------|----------------------|-------------------------------------------------|--------|
| NAMESPACE |   NAME   |       NODEPORT       |                    ROUTE-URL                    | WEIGHT |
|-----------|----------|----------------------|-------------------------------------------------|--------|
| myproject | frontend | 192.168.99.101:30215 | http://frontend-myproject.192.168.99.101.nip.io |        |
|-----------|----------|----------------------|-------------------------------------------------|--------|
PS C:\to_learn\docker-compose-to-minishift\first-try>

And when I try to open http://frontend-myproject.192.168.99.101.nip.io in Chrome:

Application is not available
The application is currently not serving requests at this endpoint. It may not have been started or is still starting.
...

Edited (trying deploying another sample application)

PS C:\to_learn\docker-compose-to-minishift\first-try>  nslookup x.127.0.0.1.xip.io
Servidor:  one.one.one.one
Address:  1.1.1.1

Não é resposta autoritativa:
Nome:    x.127.0.0.1.xip.io
Address:  127.0.0.1

PS C:\to_learn\docker-compose-to-minishift\first-try> oc version
oc v3.11.0+0cbc58b
kubernetes v1.11.0+d4cacc0
features: Basic-Auth SSPI Kerberos SPNEGO

Server https://192.168.99.101:8443
kubernetes v1.11.0+d4cacc0
PS C:\to_learn\docker-compose-to-minishift\first-try>  oc new-app --name='cotd' --labels name='cotd' php~https://github.com/devopswith-openshift/cotd.git -e SELECTOR=cats
--> Found image dc5aa55 (2 months old) in image stream "openshift/php" under tag "7.1" for "php"

    Apache 2.4 with PHP 7.1
    -----------------------
    PHP 7.1 available as container is a base platform for building and running various PHP 7.1 applications and frameworks. PHP is an HTML-embedded scripting language. PHP attempts to make it easy for developers to write dynamically generated web pages. PHP also offers built-in database integration for several commercial and non-commercial database management systems, so writing a database-enabled webpage with PHP is fairly simple. The most common use of PHP coding is probably as a replacement for CGI scripts.

    Tags: builder, php, php71, rh-php71

    * A source build using source code from https://github.com/devopswith-openshift/cotd.git will be created
      * The resulting image will be pushed to image stream tag "cotd:latest"
      * Use 'start-build' to trigger a new build
    * This image will be deployed in deployment config "cotd"
    * Ports 8080/tcp, 8443/tcp will be load balanced by service "cotd"
      * Other containers can access this service through the hostname "cotd"

--> Creating resources with label name=cotd ...
    imagestream.image.openshift.io "cotd" created
    buildconfig.build.openshift.io "cotd" created
    deploymentconfig.apps.openshift.io "cotd" created
    service "cotd" created
--> Success
    Build scheduled, use 'oc logs -f bc/cotd' to track its progress.
    Application is not exposed. You can expose services to the outside world by executing one or more of the commands below:
     'oc expose svc/cotd'
    Run 'oc status' to view your app.
PS C:\to_learn\docker-compose-to-minishift\first-try> oc expose svc/cotd
route.route.openshift.io/cotd exposed
PS C:\to_learn\docker-compose-to-minishift\first-try> oc status
In project myproject on server https://192.168.99.101:8443

http://cotd-myproject.192.168.99.101.nip.io to pod port 8080-tcp (svc/cotd)
  dc/cotd deploys istag/cotd:latest <-
    bc/cotd source builds https://github.com/devopswith-openshift/cotd.git on openshift/php:7.1
      build #1 pending for 11 minutes
    deployment #1 waiting on image or update

http://frontend-myproject.192.168.99.101.nip.io to pod port 8080 (svc/frontend)
  dc/frontend deploys istag/frontend:v4
    deployment #1 waiting on image or update

4 infos identified, use 'oc status --suggest' to see details.
PS C:\to_learn\docker-compose-to-minishift\first-try> oc status --suggest
In project myproject on server https://192.168.99.101:8443

http://cotd-myproject.192.168.99.101.nip.io to pod port 8080-tcp (svc/cotd)
  dc/cotd deploys istag/cotd:latest <-
    bc/cotd source builds https://github.com/devopswith-openshift/cotd.git on openshift/php:7.1
      build #1 pending for 12 minutes
    deployment #1 waiting on image or update

http://frontend-myproject.192.168.99.101.nip.io to pod port 8080 (svc/frontend)
  dc/frontend deploys istag/frontend:v4
    deployment #1 waiting on image or update

Info:
  * dc/cotd has no readiness probe to verify pods are ready to accept traffic or ensure deployment is successful.
    try: oc set probe dc/cotd --readiness ...
  * dc/cotd has no liveness probe to verify pods are still running.
    try: oc set probe dc/cotd --liveness ...
  * dc/frontend has no readiness probe to verify pods are ready to accept traffic or ensure deployment is successful.
    try: oc set probe dc/frontend --readiness ...
  * dc/frontend has no liveness probe to verify pods are still running.
    try: oc set probe dc/frontend --liveness ...

View details with 'oc describe <resource>/<name>' or list everything with 'oc get all'.
PS C:\to_learn\docker-compose-to-minishift\first-try>

Build Pending Status

Body:
It happens when you use a non-root container like bitnami official images.

We used user:root and network_mode: host when it needs to get bind with host network.

  apache:
    image: bitnami/apache:2.4
    container_name: "apache"
    ports:
      - 80:80
    network_mode: host
    privileged: true
    user: root
    environment:
      DOCKER_HOST: "unix:///var/run/docker.sock"
    env_file:
      - .env
    volumes:
      - ./setup/apache/httpd.conf:/opt/bitnami/apache/conf/httpd.conf


来源: stackexchange

问:
How to get a Sagemaker notebook onto GitHub?
I have a Sagemaker notebook that I would like to move to a GitHub repository. I thought perhaps I should download the files locally, then I can easily push to git. But I cannot figure out how to download the folder to my local computer. Then I though, perhaps there is a way using the AWS CLI to move directly from Sagemaker to git? I've made many google searches that are unable to answer my question.</p>

答:
Building off the answer given by @mokugo-devops, I was able to link my existing notebook to my GitHub account.

First, I followed the directions posted in the link provided in his answer to set up my GitHub repo with my AWS account on the CLI, then I used the following command to edit my existing notebook:

```<code>aws sagemaker  update-notebook-instance \
--notebook-instance-name <value> \
--default-code-repository <saved-github-repo-name-in-AWS>
</code>```

my notebook instance is now linked my GitHub repo.

ContentLicense: CC BY-SA 4.0

Body:
Building off the answer given by @mokugo-devops, I was able to link my existing notebook to my GitHub account.

First, I followed the directions posted in the link provided in his answer to set up my GitHub repo with my AWS account on the CLI, then I used the following command to edit my existing notebook:

aws sagemaker  update-notebook-instance \
--notebook-instance-name <value> \
--default-code-repository <saved-github-repo-name-in-AWS>

my notebook instance is now linked my GitHub repo.


问:
How can I use an outer query variable in a nested sub query using update?
```<code>update fee_schedule fs set fs.branch_id=
(
SELECT  branch_id  FROM   (SELECT  branch_id
                                       ,updated_ts
                                       ,gr_number
                                      ,row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts desc) AS sno
                                FROM   admission_log ) x
                       WHERE  x.gr_number = fs.gr_number and to_char(x.updated_ts,'yyyymm') < fs.schedule_month
                       and rownum=1
                       order by sno
)
where fs.branch_id is null ;
</code>```

SQL Error: ORA-00907: missing right parenthesis
  00907. 00000 -  "missing right parenthesis"

The same thing I tried using:

```<code>update fee_schedule fs set fs.branch_id=
(
select c.branch_id
      from (select b.branch_id,updated_ts,
                   row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
                   from admission_log b
                   where b.gr_number = fs.gr_number and to_char(b.updated_ts,'yyyymm') <  fs.schedule_month ) c
      where c.sno = 1
)
where fs.branch_id is null ;
</code>```

And I found this error:

SQL Error: ORA-00904: "FS"."SCHEDULE_MONTH": invalid identifier

答:
You can use keep:

```<code>update fee_schedule fs
    set fs.branch_id =
            (select max(b.branch_id) keep (dense_rank first order by updated_ts desc)
              from admission_log al
                   where al.gr_number = fs.gr_number and
                         to_char(al.updated_ts, 'yyyymm') < fs.schedule_month
            )
where fs.branch_id is null ;
</code>```

This structure is equivalent to a "first()" aggregation function and is handy to get around Oracle's scoping limit on correlated subqueries.

Body:
update fee_schedule fs set fs.branch_id=
(
SELECT  branch_id  FROM   (SELECT  branch_id
                                       ,updated_ts
                                       ,gr_number
                                      ,row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts desc) AS sno
                                FROM   admission_log ) x
                       WHERE  x.gr_number = fs.gr_number and to_char(x.updated_ts,'yyyymm') < fs.schedule_month
                       and rownum=1
                       order by sno
)
where fs.branch_id is null ;

SQL Error: ORA-00907: missing right parenthesis
  00907. 00000 -  "missing right parenthesis"

The same thing I tried using:

update fee_schedule fs set fs.branch_id=
(
select c.branch_id
      from (select b.branch_id,updated_ts,
                   row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
                   from admission_log b
                   where b.gr_number = fs.gr_number and to_char(b.updated_ts,'yyyymm') <  fs.schedule_month ) c
      where c.sno = 1
)
where fs.branch_id is null ;

And I found this error:

SQL Error: ORA-00904: "FS"."SCHEDULE_MONTH": invalid identifier

Body:
You can use keep:

update fee_schedule fs
    set fs.branch_id =
            (select max(b.branch_id) keep (dense_rank first order by updated_ts desc)
              from admission_log al
                   where al.gr_number = fs.gr_number and
                         to_char(al.updated_ts, 'yyyymm') < fs.schedule_month
            )
where fs.branch_id is null ;

This structure is equivalent to a "first()" aggregation function and is handy to get around Oracle's scoping limit on correlated subqueries.


问:
PowerShell: How to compare 2 CSVs and export desired results to a new CSV?
I'm new to PowerShell and I'm trying to write a script that will help me parse large amounts of user session statistics. I have 2 CSVs:

currentmonth.csv

```<code>UserName;Hours
User1;0,5
User2;120
User3;1
</code>```

... and ...

previousmonth.csv

```<code>UserName;Hours
User1;2
User2;100
</code>```

I want to compare currentmonth.csv against previousmonth.csv and if an user (ex. User3) is not present in CSV for the previous month, give value for hours as "0" and save the processed data in a new CSV (ex. parsedmonth.csv).

Desired output:

```<code>UserName;Hours
User1;0,5
User2;120
User3;0
</code>```

What would be the simplest way to achieve this?

答:
Try something like this:</p>

```<code># Load the 2 CSV files
$currentmonth = import-csv .\currentmonth.csv -delimiter ';'
$previousmonth = import-csv .\previousmonth.csv -delimiter ';'

# Variable to hold output
$op = @()

foreach($entry in $currentmonth)
{
    # Loop through all entries in the current month and check against previous month
    if($previousmonth.username -contains $entry.username)
    {
        # If found, add the entry to the output variable
        $op += $entry
    }
    else
    {
        # If not found, create a temp object to hold values and add to output variable
        $tmp = new-object object
        $tmp | add-member -type noteproperty -name UserName $entry.UserName
        $tmp | add-member -type noteproperty -name Hours 0
        $op += $tmp
    }
}

# Write output variable to CSV file
$op | export-csv .\monthcheckresults.csv -notype
</code>```

Body:
I'm new to PowerShell and I'm trying to write a script that will help me parse large amounts of user session statistics. I have 2 CSVs:

currentmonth.csv

UserName;Hours
User1;0,5
User2;120
User3;1

... and ...

previousmonth.csv

UserName;Hours
User1;2
User2;100

I want to compare currentmonth.csv against previousmonth.csv and if an user (ex. User3) is not present in CSV for the previous month, give value for hours as "0" and save the processed data in a new CSV (ex. parsedmonth.csv).

Desired output:

UserName;Hours
User1;0,5
User2;120
User3;0

What would be the simplest way to achieve this?

Body:
Try something like this:

# Load the 2 CSV files
$currentmonth = import-csv .\currentmonth.csv -delimiter ';'
$previousmonth = import-csv .\previousmonth.csv -delimiter ';'

# Variable to hold output
$op = @()

foreach($entry in $currentmonth)
{
    # Loop through all entries in the current month and check against previous month
    if($previousmonth.username -contains $entry.username)
    {
        # If found, add the entry to the output variable
        $op += $entry
    }
    else
    {
        # If not found, create a temp object to hold values and add to output variable
        $tmp = new-object object
        $tmp | add-member -type noteproperty -name UserName $entry.UserName
        $tmp | add-member -type noteproperty -name Hours 0
        $op += $tmp
    }
}

# Write output variable to CSV file
$op | export-csv .\monthcheckresults.csv -notype


问:
how to resolve Unchecked Input for Loop Condition checkmarx issue in java
I am getting Unchecked Input for Loop Condition checkmarx issue.

I tried recommended code handling but its not working for me.

Checkmarx report's description :

```<code>Method transformPojoCommon at line 334 of
to_web/src/com/toweb/bd/TrainCategoriesBD.java gets user input from
element TC_TRAIN_CAT_NAME . This element’s value flows through the
code without being validated, and is eventually used in a loop
condition in getParentTrainTypes at line 162 of
to_web/src/com/toweb/dao/TrainCategoriesDAO.java. This constitutes an
Unchecked Input for Loop Condition.
</code>```

I tried below code:

```<code>valdiateRequestInput(ESAPI.encoder().
   canonicalize(request.getParameter(TOWebRequestConstants.TC_OBJID).trim()));
</code>```

```<code>private String valdiateRequestInput(String currentPage) {
    try {
        currentPage = ESAPI.validator().getValidInput("HTTP parameter value: ", currentPage, "HTTPParameterValue", 2000, true);
    } catch (Exception e1) {
        log.error("failed to validate HTTP parameter value ", e1);
        throw new IllegalArgumentException("failed to validate HTTP parameter value "+currentPage, e1);
    }
    return currentPage;
}
</code>```

答:
I have fixed these issues by using ESAPI.validator().getValidInteger() or ESAPI.validator().getValidDouble() based on the return type.

Hope this solution will help you too.

Body:
I am getting Unchecked Input for Loop Condition checkmarx issue.

I tried recommended code handling but its not working for me.

Checkmarx report's description :

Method transformPojoCommon at line 334 of
to_web/src/com/toweb/bd/TrainCategoriesBD.java gets user input from
element TC_TRAIN_CAT_NAME . This element’s value flows through the
code without being validated, and is eventually used in a loop
condition in getParentTrainTypes at line 162 of
to_web/src/com/toweb/dao/TrainCategoriesDAO.java. This constitutes an
Unchecked Input for Loop Condition.

I tried below code:

valdiateRequestInput(ESAPI.encoder().
   canonicalize(request.getParameter(TOWebRequestConstants.TC_OBJID).trim()));

private String valdiateRequestInput(String currentPage) {
    try {
        currentPage = ESAPI.validator().getValidInput("HTTP parameter value: ", currentPage, "HTTPParameterValue", 2000, true);
    } catch (Exception e1) {
        log.error("failed to validate HTTP parameter value ", e1);
        throw new IllegalArgumentException("failed to validate HTTP parameter value "+currentPage, e1);
    }
    return currentPage;
}


问:
Problem with configuring crystal report XI with postgre database
We are using Crystal Report XI with DB2 data base for our Application .Now we have new request to develop a report from some other application which has postgre data base.

So same thing we tried with postgre data base that what we did in DB2 data base.

We installed the postgre odbc driver and Test the connection was successfull. But when i tried open from crystal report design, I dont find postgre data source in the list.

What are all the steps needs to do, to connect Crystal Report XI with Postgre database?

Please help me what I am missing here.

Thanks,
Naveen

答:
Perhaps you configured a 64-bit ODBC DSN.
Crystal is a 32-bit application.
You need to configure a 32-bit DSN.</p>


问:
error: "fatal: I don't handle protocol ``git` when using bundle install
I have the following line in my GemFile :

gem 'rails', :git => 'git://github.com/rails/rails.git'

I get the following error:

```<code>Fetching git://github.com/rails/rails.git
fatal: I don't handle protocol ''git'
Git error: command `git clone 'git://github.com/rails/rails.git'...
</code>```

but when I run gem install 'rails' it works fine.

basically when running the clone command, bundler adds the single quotes around the git:// address which throws the error.

I am working on windows. Any ideas why I am getting this error?

Cheers

答:
Try this instead in your Gemfile:

```<code>gem 'rails', :git => "https://github.com/rails/rails.git"
</code>```

git:// can sometimes be blocked by firewalls. Though in your case that's probably not the issue. Try double quotes instead.

ContentLicense: CC BY-SA 3.0

Body:
I have the following line in my GemFile :

gem 'rails', :git => 'git://github.com/rails/rails.git'

I get the following error:

Fetching git://github.com/rails/rails.git
fatal: I don't handle protocol ''git'
Git error: command `git clone 'git://github.com/rails/rails.git'...

but when I run gem install 'rails' it works fine.

basically when running the clone command, bundler adds the single quotes around the git:// address which throws the error.

I am working on windows. Any ideas why I am getting this error?

Cheers

Body:
Try this instead in your Gemfile:

gem 'rails', :git => "https://github.com/rails/rails.git"

git:// can sometimes be blocked by firewalls. Though in your case that's probably not the issue. Try double quotes instead.


问:
With AG Grid, prevent row click event when cell is clicked?
I'd like to stop event propagation on all cell clicks since I'm using onRowClicked to do some actions. When a user clicks on something inside a cell (like an input field), I don't want the row click to be triggered.

Any thoughts?

I'm using Angular 2/4 for this.

答:
None of the past suggestions worked for me. AG Grid may have changed the API behavior. Even event.stopPropagation() on onCellClicked would not stop onRowClicked from firing.

What I ultimately did was to remove onRowClicked altogether and handle everything in onCellClicked. onRowClicked does not have an attribute on which column the click event generated from, onCellClicked does!

function cellClickedHandler(e) {
  if (e.column.colId === 'col1') {
    // Handle specific cell
  } else {
    // Handle all other cells, similar to rowClicked
  }
}
```


问:
Displaying Data From Database With Vb.net with combobox
I face an error in my syntax which is indicating near the AND Operator

If ComboBox1.Text = "" And ComboBox2.Text = "" Then
    MsgBox("Please Fill In The Details")
Else
    Try
        con.Open()
        Select Case ComboBox1.Text
            Case "Students Info"
                Dim a = "SELECT * FROM studentdb1 WHERE class = " & ComboBox2.SelectedText & " AND WHERE date_registered BETWEEN " & date1.Text & " AND " & date2.Text & ""
                displayTable(a)
        End Select

        con.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End If
```

<p>I created a class called <code>displayTable</code> to use command passed through the parameter to display into the datagridview</p>

<pre class="lang-vb prettyprint-override"><code>Public Sub displayTable(x As String)
    Dim command2 As New SqlClient.SqlCommand
    command2 = con.CreateCommand
    command2.CommandText = x
    command2.ExecuteNonQuery()

    Dim dt As New DataTable
    Dim da As New SqlDataAdapter(command2)
    da.Fill(dt)
    datagrid1.DataSource = dt
End Sub
</code>```

答:
As mentions in the comments by Vijay:

remove "WHERE" ( AND WHERE date_registered BETWEEN) followed by AND

But I have some other things I would like to point out:

command2.ExecuteNonQuery() will give you only the count of affected rows. You don't need it.

Try to use CommandParameters (you proberly need to redesign your code)

    Dim sqlString = "SELECT * FROM studentdb1 WHERE class = @Class AND date_registered BETWEEN @StartDate AND @EndDate"
    Dim command2 As New SqlClient.SqlCommand
    command2 = con.CreateCommand
    command2.CommandText = sqlString
    command2.Parameters.Add("@Class", SqlDbType.VarChar).Value = ComboBox2.SelectedText
    command2.Parameters.Add("@StartDate", SqlDbType.Date).Value = date1.Text
    command2.Parameters.Add("@EndDate", SqlDbType.Date).Value = date2.Text
```

Body:
I face an error in my syntax which is indicating near the AND Operator

If ComboBox1.Text = "" And ComboBox2.Text = "" Then
    MsgBox("Please Fill In The Details")
Else
    Try
        con.Open()
        Select Case ComboBox1.Text
            Case "Students Info"
                Dim a = "SELECT * FROM studentdb1 WHERE class = " & ComboBox2.SelectedText & " AND WHERE date_registered BETWEEN " & date1.Text & " AND " & date2.Text & ""
                displayTable(a)
        End Select

        con.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End If

I created a class called displayTable to use command passed through the parameter to display into the datagridview

Public Sub displayTable(x As String)
    Dim command2 As New SqlClient.SqlCommand
    command2 = con.CreateCommand
    command2.CommandText = x
    command2.ExecuteNonQuery()

    Dim dt As New DataTable
    Dim da As New SqlDataAdapter(command2)
    da.Fill(dt)
    datagrid1.DataSource = dt
End Sub


问:
Deno: How to substitute npm scripts (package.json)
Since it is not necessary to have package.json file with deno, how can I as a developer have a similar experience just as we have with npm scripts in package.json?

答:
deno install

You can create executable, aliased scripts with deno install.

It will provide a thin shell/cmd wrapper for the specified main module and CLI arguments. Example:

```<code>deno install --root . -n serve --allow-read --allow-net https://deno.land/std@0.54.0/http/file_server.ts
</code>```

The result is a serve script, similar to npm "scripts": { "serve": ... }:

```<code>./bin/serve # run `serve` script (~ npm run serve)
</code>```

If the project's bin folder is added to PATH environment, the command shortens up to serve.

What deno install does

creates bin folder, if not existent

adds serve/serve.cmd file with following content (Windows here):
```<code>% generated by deno install %
</code>```

@deno.exe "run" "--allow-read" "--allow-net" "https://deno.land/std@0.54.0/http/file_server.ts" %*
```</p>
<ul>
<li><code>-n</code> is the command name used later on (can be left out)</li>
<li><code>--root</code> specifies the <code>bin</code> root location (otherwise <code>~/.deno</code>)</li>
<li><code>-f</code> option overwrites an existent alias</li>
</ul>
<p><em>Side note</em>: Any <code>.js</code>/<code>.ts</code> script is a valid reference - source code location (local/URL) does not matter. If external shell scripts are to be included, you can also run them inside a subprocess.</p>
<h3>Example: Custom <code>npm run build</code></h3>
```// ./scripts/build.ts

// create subprocess
const p = Deno.run({
  cmd: ["deno", "cache", "-r", "--unstable", "main.ts"],
});

await p.status();
```
```deno install --root . --allow-run scripts\build.ts

./bin/build # execute build script
```
<h2>Built-in <code>deno</code> commands</h2>
<p>Deno already comes with built-in solutions for common ecosystem tasks, e.g. <code>bundle</code>, <code>fmt</code>, <code>test</code> and <code>lint</code> later on (see <code>deno help</code>). You can invoke these commands directly - no need to define custom scripts:</p>
```deno test
deno fmt
deno cache -r main.ts # similar to `npm run build` / `tsc`
# ...
```

Body:
deno install

You can create executable, aliased scripts with deno install.

It will provide a thin shell/cmd wrapper for the specified main module and CLI arguments. Example:

deno install --root . -n serve --allow-read --allow-net https://deno.land/std@0.54.0/http/file_server.ts

The result is a serve script, similar to npm "scripts": { "serve": ... }:

./bin/serve # run `serve` script (~ npm run serve)

If the project's bin folder is added to PATH environment, the command shortens up to serve.

What deno install does

creates bin folder, if not existent

adds serve/serve.cmd file with following content (Windows here):

% generated by deno install %

@deno.exe "run" "--allow-read" "--allow-net" "https://deno.land/std@0.54.0/http/file_server.ts" %*
```

-n is the command name used later on (can be left out)

--root specifies the bin root location (otherwise ~/.deno)

-f option overwrites an existent alias

Side note: Any .js/.ts script is a valid reference - source code location (local/URL) does not matter. If external shell scripts are to be included, you can also run them inside a subprocess.

Example: Custom npm run build

// ./scripts/build.ts

// create subprocess
const p = Deno.run({
  cmd: ["deno", "cache", "-r", "--unstable", "main.ts"],
});

await p.status();

deno install --root . --allow-run scripts\build.ts

./bin/build # execute build script

Built-in deno commands

Deno already comes with built-in solutions for common ecosystem tasks, e.g. bundle, fmt, test and lint later on (see deno help). You can invoke these commands directly - no need to define custom scripts:

deno test
deno fmt
deno cache -r main.ts # similar to `npm run build` / `tsc`
# ...


问:
Adding decimal hours using DATEADD in Oracle SQL
I have the following piece of query which works fine for adding hours to a time value:

```<code>to_char(date_add('h', trunc(o.tt_real)::integer, d.pickup_date::timestamp),'HH24:MI') injection_time
</code>```

In the above tt_real is an integer. Now lets assume I have a tt with decimal hours like this 2.98, 3.55 etc. Can someone suggest an updated version of the above query to incorporate decimal hours ?
An example of the output expected
10:30 + 2.25 = 12:45

答: rather add minutes instead of hours: (o.tt_real*60)::integer

Body:
I have the following piece of query which works fine for adding hours to a time value:

to_char(date_add('h', trunc(o.tt_real)::integer, d.pickup_date::timestamp),'HH24:MI') injection_time

In the above tt_real is an integer. Now lets assume I have a tt with decimal hours like this 2.98, 3.55 etc. Can someone suggest an updated version of the above query to incorporate decimal hours ?
An example of the output expected
10:30 + 2.25 = 12:45


问:
Copy Sharepoint data to SQL Server and then use the data for reporting purpose
I have data in sharepoint which has 104 columns and 708 rows. This data is basically contains information about enterprise. The senior management wants to view different charts by using these data such as bar chart, pie chart, tabular, bubble chart etc., There are no specific number of charts as they can plot any column against anything. For instance grouping of applications by criticality in a pie chart.

In order to create these n number of reports what we thought is to transfer the sharepoint list to sql server (using SSIS) and then use sql server reporting services (SSRS) to generate those reports and then use an ASP .net front end to contain the reports.

The very first important question is whether we can transfer sharepoint list to SQL Server using SSIS. Is this possible?

答:
I think it is possible to pull SharePoint data using SSIS but I have never done it personally. If you are using SSIS 2008, following links might help you.

SharePoint List Source and Destination

Extracting and Loading SharePoint Data in SQL Server Integration Services


问:
Apache cannot bind :443 address for SSL even though port 443 is unused
I recently installed Apache 2.4.20 with SSL enabled using openssl 1.0.2j.

After updating the httpd.conf and httpd-ssl.conf files and trying to start Apache while listening to port 443, I get the following error:

```<code>(13)Permission denied: -----: make_sock: could not bind to address [::]:443
(13)Permission denied: -----: make_sock: could not bind to address 0.0.0.0:443
no listening sockets available, shutting down
</code>```

Here is what I have for config:

httpd.conf:

```<code>Listen 51000
#Listen 443
#Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf
</code>```

httpd-ssl.conf

```<code>Listen 443
</code>```

If I comment out this line in the httpd-ssl.conf file, my apache starts up fine:

```<code>attempting to start apache
done
</code>```

However with it I get the socket error every time.

I ran the following as root:

```<code>netstat -tlpn | grep :443
</code>```

Returned nothing.

```<code>lsof -i tcp:443
</code>```

Returned nothing.

I've read somewhere that only root can bind to addresses below 1024, but I don't know the validity of that statement. Apache is not being run here as root - would that be the issue?

答:
If you are using docker with docker-compose,

It happens when we use a non-root container like bitnami official images.

We used user:root and network_mode: host when it needs to get bind with host network.

```<code>  apache:
    image: bitnami/apache:2.4
    container_name: "apache"
    ports:
      - 80:80
    network_mode: host
    privileged: true
    user: root
    environment:
      DOCKER_HOST: "unix:///var/run/docker.sock"
    env_file:
      - .env
    volumes:
      - ./setup/apache/httpd.conf:/opt/bitnami/apache/conf/httpd.conf
</code>```

Hope it helps!

Body:
I recently installed Apache 2.4.20 with SSL enabled using openssl 1.0.2j.

After updating the httpd.conf and httpd-ssl.conf files and trying to start Apache while listening to port 443, I get the following error:

(13)Permission denied: -----: make_sock: could not bind to address [::]:443
(13)Permission denied: -----: make_sock: could not bind to address 0.0.0.0:443
no listening sockets available, shutting down

Here is what I have for config:

httpd.conf:

Listen 51000
#Listen 443
#Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf

httpd-ssl.conf

Listen 443

If I comment out this line in the httpd-ssl.conf file, my apache starts up fine:

attempting to start apache
done

However with it I get the socket error every time.

I ran the following as root:

netstat -tlpn | grep :443

Returned nothing.

lsof -i tcp:443

Returned nothing.

I've read somewhere that only root can bind to addresses below 1024, but I don't know the validity of that statement. Apache is not being run here as root - would that be the issue?

Body:
If you are using docker with docker-compose,

It happens when we use a non-root container like bitnami official images.

We used user:root and network_mode: host when it needs to get bind with host network.

  apache:
    image: bitnami/apache:2.4
    container_name: "apache"
    ports:
      - 80:80
    network_mode: host
    privileged: true
    user: root
    environment:
      DOCKER_HOST: "unix:///var/run/docker.sock"
    env_file:
      - .env
    volumes:
      - ./setup/apache/httpd.conf:/opt/bitnami/apache/conf/httpd.conf

Hope it helps!


问:
VB6 How to pass variables to different form
I am starting with 1 form and 1 class. The idea is to set some class members and then call those members from a different form. I can't even set the values for some reason. We have a project done in VB6 and unfortunately, there is no chance to upgrade and am stuck on VB6.

Form1:

```<code>Public SomeClassObj As New SomeClass

Private Sub Command1_Click()
  Set SomeClassObj.Test1 = 1
  Set SomeClassObj.Test2 = 2
  Call SomeClassObj.Test
End Sub
</code>```

Class SomeClass:

```<code>Public Test1 As Integer
Public Test2 As Integer

Public Sub Test()
  MsgBox Test1
  MsgBox Test2
End Sub
</code>```

The error I get is "invalid use of property" and stops on Command1_Click: ".Test1 ="

Can someone please tell me what I'm doing wrong?

答: You should remove Set keywords - you are not assigning objects/references.

Body:
I am starting with 1 form and 1 class. The idea is to set some class members and then call those members from a different form. I can't even set the values for some reason. We have a project done in VB6 and unfortunately, there is no chance to upgrade and am stuck on VB6.

Form1:

Public SomeClassObj As New SomeClass

Private Sub Command1_Click()
  Set SomeClassObj.Test1 = 1
  Set SomeClassObj.Test2 = 2
  Call SomeClassObj.Test
End Sub

Class SomeClass:

Public Test1 As Integer
Public Test2 As Integer

Public Sub Test()
  MsgBox Test1
  MsgBox Test2
End Sub

The error I get is "invalid use of property" and stops on Command1_Click: ".Test1 ="

Can someone please tell me what I'm doing wrong?


问:
Cannot replace a string in Dart
I'm re-writing a simple application to calculate averages, however I have a hard time with a TextField.

I set the TextField to be able to replace a comma to a period if a locale is en_US, otherwise it should replace a period to a comma if locale is different than en_US. However, replaceAll() method doesn't seem to work.

Sorry for the code quality, but I will fix it after I see where's the problem.

Code:

import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';

class ArithmeticAverageScreen extends StatefulWidget {
  @override
  _ArithmeticAverageScreenState createState() => _ArithmeticAverageScreenState();
}

class _ArithmeticAverageScreenState extends State<ArithmeticAverageScreen> {
  var _grades = List<Widget>();

  var _textFieldController = TextEditingController();
  var _gradesList = List<String>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('arithmetic_average_title').tr(),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: ListView(
          children: <Widget>[
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.help),
                      title: Text('arithmetic_average_help').tr(),
                      subtitle: Text('arithmetic_average_help_content').tr(),
                    )
                  ],
                ),
              )
            ),
            SizedBox(height: 16.0),
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
                    SizedBox(height: 16.0),
                    Row(
                      children: <Widget>[
                        Container(
                          width: 60.0,
                          child: TextField(
                            controller: _textFieldController,
                            inputFormatters: [ WhitelistingTextInputFormatter(RegExp("[0-9,.]")) ],

                            decoration: InputDecoration(
                              hintText: '5',
                              labelText: 'arithmetic_average_grade'.tr()
                            ),
                          ),
                        ),
                        SizedBox(width: 20.0,),
                        RaisedButton(
                          onPressed: () {
                            if (_textFieldController.text == '') {
                              showDialog(
                                context: context,
                                builder: (context) {
                                  return AlertDialog(
                                    content: Text('arithmetic_average_type_number').tr(),
                                  );
                                }
                              );
                            }
                            else {

                              String locale = Localizations.localeOf(context).toString();

                                if (locale == 'en_US') {
                                  if (_textFieldController.text.contains(',')) {

                                    print('True');
                                    _textFieldController.text.replaceAll(',', '.');
                                  }
                                }
                                else if (locale == 'pl_PL') {
                                  if (_textFieldController.text.contains('.')) {
                                    _textFieldController.text.replaceAll('.', ',');
                                  }
                                }
                              setState(() {
                                _gradesList.add(_textFieldController.text);
                                print(_gradesList);

                                _grades.add(Text(_textFieldController.text));
                              });
                            }
                          },
                          color: Colors.teal[300],
                          textColor: Colors.white,
                          child: Text('arithmetic_average_add_button').tr(),
                        ),
                      ],
                    ),
                    SizedBox(height: 16.0,),
                    Wrap(
                      children: _grades,
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      )
    );
  }
}
```

答:
In the following line, you are not updating the text of the text field so replace the following

_textFieldController.text.replaceAll(',', '.');
```

<p>with this</p>

<pre class="lang-dart prettyprint-override"><code>_textFieldController.text = _textFieldController.text.replaceAll(',', '.')
</code>```

Title: Cannot replace a string in Dart

Body:
In the following line, you are not updating the text of the text field so replace the following

_textFieldController.text.replaceAll(',', '.');

with this

_textFieldController.text = _textFieldController.text.replaceAll(',', '.')


问:
can I get the tap position over a Text View?
a Text view is like:

```<code>Text("hello world")
.onTapGesture{
...}
</code>```

can I get the tab position ,so that to infer which word is tapped.

答:
Here is an approach how to get tap location in Text view coordinate space:

```<code>Text("hello world")
.gesture(DragGesture(minimumDistance: 0).onEnded { value in
    print("Position: \(value.location)") // in local coordinates
})
</code>```

Body:
a Text view is like:

Text("hello world")
.onTapGesture{
...}

can I get the tab position ,so that to infer which word is tapped.

Body:
Here is an approach how to get tap location in Text view coordinate space:

Text("hello world")
.gesture(DragGesture(minimumDistance: 0).onEnded { value in
    print("Position: \(value.location)") // in local coordinates
})


问:
object testkit is not a member of package akka
I am trying to run the example code of Akka FSM but I've met some error

```<code>[info] Loading project definition from /home/akka/fsm/project

[info] Loading settings for project root from build.sbt ...
[info] Set current project to fsm (in build file:/home/akka/fsm/)
[info] Executing in batch mode. For better performance use sbt's shell
[info] Compiling 1 Scala source to /home/akka/fsm/target/scala-2.13/classes ...
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:9:13: object testkit is not a member of package akka
[error] import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit }
[error]             ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:11:13: object testkit is not a member of package akka
[error] import akka.testkit._
[error]             ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:43:26: not found: type MyFavoriteTestFrameWorkPlusAkkaTestKit
[error] class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
[error]                          ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:203:33: value must is not a member of String
[error]   "simple finite state machine" must {
[error]                                 ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:205:32: value in is not a member of String
[error]     "demonstrate NullFunction" in {
[error]                                ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:214:23: value in is not a member of String
[error]     "batch correctly" in {
[error]                       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:215:21: not found: value system
[error]       val buncher = system.actorOf(Props(classOf[Buncher], this))
[error]                     ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:219:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(42, 43)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:223:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(44)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:224:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(45)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:227:34: value in is not a member of String
[error]     "not batch if uninitialized" in {
[error]                                  ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:228:21: not found: value system
[error]       val buncher = system.actorOf(Props(classOf[Buncher], this))
[error]                     ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:230:7: not found: value expectNoMsg
[error]       expectNoMsg
[error]       ^
[error] 13 errors found
</code>```

My code is like:

```<code>import language.postfixOps

import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit }
import akka.util.ByteString
import akka.testkit._

//#test-code
import akka.actor.Props
import scala.collection.immutable

object FSMDocSpec {
  // messages and data types
  //#test-code
  import akka.actor.ActorRef
  //#simple-events
  // received events
  final case class SetTarget(ref: ActorRef)
  final case class Queue(obj: Any)
  case object Flush

  // sent events
  final case class Batch(obj: immutable.Seq[Any])
  //#simple-events
  //#simple-state
  // states
  sealed trait State
  case object Idle extends State
  case object Active extends State

  sealed trait Data
  case object Uninitialized extends Data
  final case class Todo(target: ActorRef, queue: immutable.Seq[Any]) extends Data
  //#simple-state
  //#test-code
}

class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
  import FSMDocSpec._

  //#fsm-code-elided
  //#simple-imports
  import akka.actor.{ ActorRef, FSM }
  import scala.concurrent.duration._
  //#simple-imports
  //#simple-fsm
  class Buncher extends FSM[State, Data] {

    //#fsm-body
    startWith(Idle, Uninitialized)

    //#when-syntax
    when(Idle) {
      case Event(SetTarget(ref), Uninitialized) =>
        stay.using(Todo(ref, Vector.empty))
    }
    //#when-syntax

    //#transition-elided
    onTransition {
      case Active -> Idle =>
        stateData match {
          case Todo(ref, queue) => ref ! Batch(queue)
          case _                => // nothing to do
        }
    }
    //#transition-elided
    //#when-syntax

    when(Active, stateTimeout = 1 second) {
      case Event(Flush | StateTimeout, t: Todo) =>
        goto(Idle).using(t.copy(queue = Vector.empty))
    }
    //#when-syntax

    //#unhandled-elided
    whenUnhandled {
      // common code for both states
      case Event(Queue(obj), t @ Todo(_, v)) =>
        goto(Active).using(t.copy(queue = v :+ obj))

      case Event(e, s) =>
        log.warning("received unhandled request {} in state {}/{}", e, stateName, s)
        stay
    }
    //#unhandled-elided
    //#fsm-body

    initialize()
  }
  //#simple-fsm
  object DemoCode {
    trait StateType
    case object SomeState extends StateType
    case object Processing extends StateType
    case object Error extends StateType
    case object Idle extends StateType
    case object Active extends StateType

    class Dummy extends FSM[StateType, Int] {
      class X
      val newData = 42
      object WillDo
      object Tick

      //#modifier-syntax
      when(SomeState) {
        case Event(msg, _) =>
          goto(Processing).using(newData).forMax(5 seconds).replying(WillDo)
      }
      //#modifier-syntax

      //#transition-syntax
      onTransition {
        case Idle -> Active => startTimerWithFixedDelay("timeout", Tick, 1 second)
        case Active -> _    => cancelTimer("timeout")
        case x -> Idle      => log.info("entering Idle from " + x)
      }
      //#transition-syntax

      //#alt-transition-syntax
      onTransition(handler _)

      def handler(from: StateType, to: StateType): Unit = {
        // handle it here ...
      }
      //#alt-transition-syntax

      //#stop-syntax
      when(Error) {
        case Event("stop", _) =>
          // do cleanup ...
          stop()
      }
      //#stop-syntax

      //#transform-syntax
      when(SomeState)(transform {
        case Event(bytes: ByteString, read) => stay.using(read + bytes.length)
      }.using {
        case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
          goto(Processing)
      })
      //#transform-syntax

      //#alt-transform-syntax
      val processingTrigger: PartialFunction[State, State] = {
        case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
          goto(Processing)
      }

      when(SomeState)(transform {
        case Event(bytes: ByteString, read) => stay.using(read + bytes.length)
      }.using(processingTrigger))
      //#alt-transform-syntax

      //#termination-syntax
      onTermination {
        case StopEvent(FSM.Normal, state, data)         => // ...
        case StopEvent(FSM.Shutdown, state, data)       => // ...
        case StopEvent(FSM.Failure(cause), state, data) => // ...
      }
      //#termination-syntax

      //#unhandled-syntax
      whenUnhandled {
        case Event(x: X, data) =>
          log.info("Received unhandled event: " + x)
          stay
        case Event(msg, _) =>
          log.warning("Received unknown event: " + msg)
          goto(Error)
      }
      //#unhandled-syntax

    }

    //#logging-fsm
    import akka.actor.LoggingFSM
    class MyFSM extends LoggingFSM[StateType, Data] {
      //#body-elided
      override def logDepth = 12
      onTermination {
        case StopEvent(FSM.Failure(_), state, data) =>
          val lastEvents = getLog.mkString("\n\t")
          log.warning(
            "Failure in state " + state + " with data " + data + "\n" +
            "Events leading up to this point:\n\t" + lastEvents)
      }
      // ...
      //#body-elided
    }
    //#logging-fsm

  }
  //#fsm-code-elided

  "simple finite state machine" must {

    "demonstrate NullFunction" in {
      class A extends FSM[Int, Null] {
        val SomeState = 0
        //#NullFunction
        when(SomeState)(FSM.NullFunction)
        //#NullFunction
      }
    }

    "batch correctly" in {
      val buncher = system.actorOf(Props(classOf[Buncher], this))
      buncher ! SetTarget(testActor)
      buncher ! Queue(42)
      buncher ! Queue(43)
      expectMsg(Batch(immutable.Seq(42, 43)))
      buncher ! Queue(44)
      buncher ! Flush
      buncher ! Queue(45)
      expectMsg(Batch(immutable.Seq(44)))
      expectMsg(Batch(immutable.Seq(45)))
    }

    "not batch if uninitialized" in {
      val buncher = system.actorOf(Props(classOf[Buncher], this))
      buncher ! Queue(42)
      expectNoMsg
    }
  }
}
//#test-code
</code>```

build.sbt is like:

```<code>lazy val root = (project in file(".")).settings (
  name := "fsm",
  version := "1.0",
  scalaVersion := "2.13.1",
  scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation"),
  resolvers += "Typesafe Repository" at "https://repo.typesafe.com/typesafe/releases/",
  //libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.0.1" % Test,
  //libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.0",
  libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.1.2" % "test",
  libraryDependencies += "com.typesafe.akka" %% "akka-testkit" % "2.6.5" % Test,
  libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.6.5"
)
</code>```

I am following the guidance at:
https://doc.akka.io/docs/akka/current/fsm.html
but I can't get this code run.

I suspect that I do wrong in the build.sbt file but I've got nothing through a whole day searching and trying. Same error is looming around and I wonder what's wrong here.

答:
You should move FSMDocSpec.scala to the src/test/scala directory, instead of src/main/scala. This will put test-scoped dependencies on the classpath while compiling that file.

In your build.sbt, the scalatest and akka-testkit dependencies are specified to be scoped to the test configuration:

```<code>libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.1.2" % "test",
libraryDependencies += "com.typesafe.akka" %% "akka-testkit" % "2.6.5" % Test,
</code>```

This is the correct way to specify dependencies that are only used when running tests, and not at runtime for the main application, so it's not an error in your sbt configuration. These dependencies will only be available when running in the test configuration, which is used when compiling and running tests. They won't be on the classpath when compiling and running the main application, which allows you to exclude unnecessary libraries from your production application. The string "test" and constant Test are equivalent, so you could choose either one and use it for both dependencies to be consistent, but it's not important to do so.

The test source code itself must be inside src/test/scala. The src/main/scala directory should only be used for the main application code, and will be compiled without the test dependencies on the classpath.

There are more details in the sbt documentation, for example in "Scoping by the configuration axis".

Body:
I am trying to run the example code of Akka FSM but I've met some error

[info] Loading project definition from /home/akka/fsm/project

[info] Loading settings for project root from build.sbt ...
[info] Set current project to fsm (in build file:/home/akka/fsm/)
[info] Executing in batch mode. For better performance use sbt's shell
[info] Compiling 1 Scala source to /home/akka/fsm/target/scala-2.13/classes ...
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:9:13: object testkit is not a member of package akka
[error] import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit }
[error]             ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:11:13: object testkit is not a member of package akka
[error] import akka.testkit._
[error]             ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:43:26: not found: type MyFavoriteTestFrameWorkPlusAkkaTestKit
[error] class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
[error]                          ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:203:33: value must is not a member of String
[error]   "simple finite state machine" must {
[error]                                 ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:205:32: value in is not a member of String
[error]     "demonstrate NullFunction" in {
[error]                                ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:214:23: value in is not a member of String
[error]     "batch correctly" in {
[error]                       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:215:21: not found: value system
[error]       val buncher = system.actorOf(Props(classOf[Buncher], this))
[error]                     ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:219:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(42, 43)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:223:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(44)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:224:7: not found: value expectMsg
[error]       expectMsg(Batch(immutable.Seq(45)))
[error]       ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:227:34: value in is not a member of String
[error]     "not batch if uninitialized" in {
[error]                                  ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:228:21: not found: value system
[error]       val buncher = system.actorOf(Props(classOf[Buncher], this))
[error]                     ^
[error] /home/akka/fsm/src/main/scala/FSMDocSpec.scala:230:7: not found: value expectNoMsg
[error]       expectNoMsg
[error]       ^
[error] 13 errors found

My code is like:

import language.postfixOps

import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit }
import akka.util.ByteString
import akka.testkit._

//#test-code
import akka.actor.Props
import scala.collection.immutable

object FSMDocSpec {
  // messages and data types
  //#test-code
  import akka.actor.ActorRef
  //#simple-events
  // received events
  final case class SetTarget(ref: ActorRef)
  final case class Queue(obj: Any)
  case object Flush

  // sent events
  final case class Batch(obj: immutable.Seq[Any])
  //#simple-events
  //#simple-state
  // states
  sealed trait State
  case object Idle extends State
  case object Active extends State

  sealed trait Data
  case object Uninitialized extends Data
  final case class Todo(target: ActorRef, queue: immutable.Seq[Any]) extends Data
  //#simple-state
  //#test-code
}

class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit {
  import FSMDocSpec._

  //#fsm-code-elided
  //#simple-imports
  import akka.actor.{ ActorRef, FSM }
  import scala.concurrent.duration._
  //#simple-imports
  //#simple-fsm
  class Buncher extends FSM[State, Data] {

    //#fsm-body
    startWith(Idle, Uninitialized)

    //#when-syntax
    when(Idle) {
      case Event(SetTarget(ref), Uninitialized) =>
        stay.using(Todo(ref, Vector.empty))
    }
    //#when-syntax

    //#transition-elided
    onTransition {
      case Active -> Idle =>
        stateData match {
          case Todo(ref, queue) => ref ! Batch(queue)
          case _                => // nothing to do
        }
    }
    //#transition-elided
    //#when-syntax

    when(Active, stateTimeout = 1 second) {
      case Event(Flush | StateTimeout, t: Todo) =>
        goto(Idle).using(t.copy(queue = Vector.empty))
    }
    //#when-syntax

    //#unhandled-elided
    whenUnhandled {
      // common code for both states
      case Event(Queue(obj), t @ Todo(_, v)) =>
        goto(Active).using(t.copy(queue = v :+ obj))

      case Event(e, s) =>
        log.warning("received unhandled request {} in state {}/{}", e, stateName, s)
        stay
    }
    //#unhandled-elided
    //#fsm-body

    initialize()
  }
  //#simple-fsm
  object DemoCode {
    trait StateType
    case object SomeState extends StateType
    case object Processing extends StateType
    case object Error extends StateType
    case object Idle extends StateType
    case object Active extends StateType

    class Dummy extends FSM[StateType, Int] {
      class X
      val newData = 42
      object WillDo
      object Tick

      //#modifier-syntax
      when(SomeState) {
        case Event(msg, _) =>
          goto(Processing).using(newData).forMax(5 seconds).replying(WillDo)
      }
      //#modifier-syntax

      //#transition-syntax
      onTransition {
        case Idle -> Active => startTimerWithFixedDelay("timeout", Tick, 1 second)
        case Active -> _    => cancelTimer("timeout")
        case x -> Idle      => log.info("entering Idle from " + x)
      }
      //#transition-syntax

      //#alt-transition-syntax
      onTransition(handler _)

      def handler(from: StateType, to: StateType): Unit = {
        // handle it here ...
      }
      //#alt-transition-syntax

      //#stop-syntax
      when(Error) {
        case Event("stop", _) =>
          // do cleanup ...
          stop()
      }
      //#stop-syntax

      //#transform-syntax
      when(SomeState)(transform {
        case Event(bytes: ByteString, read) => stay.using(read + bytes.length)
      }.using {
        case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
          goto(Processing)
      })
      //#transform-syntax

      //#alt-transform-syntax
      val processingTrigger: PartialFunction[State, State] = {
        case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 =>
          goto(Processing)
      }

      when(SomeState)(transform {
        case Event(bytes: ByteString, read) => stay.using(read + bytes.length)
      }.using(processingTrigger))
      //#alt-transform-syntax

      //#termination-syntax
      onTermination {
        case StopEvent(FSM.Normal, state, data)         => // ...
        case StopEvent(FSM.Shutdown, state, data)       => // ...
        case StopEvent(FSM.Failure(cause), state, data) => // ...
      }
      //#termination-syntax

      //#unhandled-syntax
      whenUnhandled {
        case Event(x: X, data) =>
          log.info("Received unhandled event: " + x)
          stay
        case Event(msg, _) =>
          log.warning("Received unknown event: " + msg)
          goto(Error)
      }
      //#unhandled-syntax

    }

    //#logging-fsm
    import akka.actor.LoggingFSM
    class MyFSM extends LoggingFSM[StateType, Data] {
      //#body-elided
      override def logDepth = 12
      onTermination {
        case StopEvent(FSM.Failure(_), state, data) =>
          val lastEvents = getLog.mkString("\n\t")
          log.warning(
            "Failure in state " + state + " with data " + data + "\n" +
            "Events leading up to this point:\n\t" + lastEvents)
      }
      // ...
      //#body-elided
    }
    //#logging-fsm

  }
  //#fsm-code-elided

  "simple finite state machine" must {

    "demonstrate NullFunction" in {
      class A extends FSM[Int, Null] {
        val SomeState = 0
        //#NullFunction
        when(SomeState)(FSM.NullFunction)
        //#NullFunction
      }
    }

    "batch correctly" in {
      val buncher = system.actorOf(Props(classOf[Buncher], this))
      buncher ! SetTarget(testActor)
      buncher ! Queue(42)
      buncher ! Queue(43)
      expectMsg(Batch(immutable.Seq(42, 43)))
      buncher ! Queue(44)
      buncher ! Flush
      buncher ! Queue(45)
      expectMsg(Batch(immutable.Seq(44)))
      expectMsg(Batch(immutable.Seq(45)))
    }

    "not batch if uninitialized" in {
      val buncher = system.actorOf(Props(classOf[Buncher], this))
      buncher ! Queue(42)
      expectNoMsg
    }
  }
}
//#test-code

build.sbt is like:

lazy val root = (project in file(".")).settings (
  name := "fsm",
  version := "1.0",
  scalaVersion := "2.13.1",
  scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation"),
  resolvers += "Typesafe Repository" at "https://repo.typesafe.com/typesafe/releases/",
  //libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.0.1" % Test,
  //libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.0",
  libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.1.2" % "test",
  libraryDependencies += "com.typesafe.akka" %% "akka-testkit" % "2.6.5" % Test,
  libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.6.5"
)

I am following the guidance at:
https://doc.akka.io/docs/akka/current/fsm.html
but I can't get this code run.

I suspect that I do wrong in the build.sbt file but I've got nothing through a whole day searching and trying. Same error is looming around and I wonder what's wrong here.

Body:
You should move FSMDocSpec.scala to the src/test/scala directory, instead of src/main/scala. This will put test-scoped dependencies on the classpath while compiling that file.

In your build.sbt, the scalatest and akka-testkit dependencies are specified to be scoped to the test configuration:

libraryDependencies +=  "org.scalatest" %% "scalatest" % "3.1.2" % "test",
libraryDependencies += "com.typesafe.akka" %% "akka-testkit" % "2.6.5" % Test,

This is the correct way to specify dependencies that are only used when running tests, and not at runtime for the main application, so it's not an error in your sbt configuration. These dependencies will only be available when running in the test configuration, which is used when compiling and running tests. They won't be on the classpath when compiling and running the main application, which allows you to exclude unnecessary libraries from your production application. The string "test" and constant Test are equivalent, so you could choose either one and use it for both dependencies to be consistent, but it's not important to do so.

The test source code itself must be inside src/test/scala. The src/main/scala directory should only be used for the main application code, and will be compiled without the test dependencies on the classpath.

There are more details in the sbt documentation, for example in "Scoping by the configuration axis".


问:
How can I return a specific element out of an array in Javascript?
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})
</code>```

And the returned array in the console looks like this:

```<code>[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]
</code>```

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

```<code>const ip = devices.find('00:17:88:65:f4:4d');
</code>```

But this would only return the full element, if the syntax was correct.

Body:
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})

And the returned array in the console looks like this:

[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

const ip = devices.find('00:17:88:65:f4:4d');

But this would only return the full element, if the syntax was correct.

Body:
Here is how you can do it in the classic way:

var devices = [
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]

for(var i = 0; i < devices.length; i++) {
  if(devices[i].mac == "00:17:88:65:f4:4d") {
    return devices[i].ip;
  }
}


问:
How to measure the elapsed time of ASYNC sent HTTPRequest with Java 11 standard HTTPClient?
In one method, I create and send some HTTPRequests async, and add the CF to a list:

// HTTPClient is Java11 standard, package java.net.http;
CompletableFuture<HttpResponse<String>> httpResponseCF = this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
list.add(httpResponseCF);
```

<p>Later, in another method, I periodically check every 1second if some of my async sent HTTPRequests have already received:</p>

<pre class="lang-java prettyprint-override"><code>for(CompletableFuture<HttpResponse<String>> httpResponseCF : list){
  if (httpResponseCF.isDone()) {
    //print out: The time between sending HTTPRequest and receiving HTTPResponse is 25ms
  }
}
</code>```

The question is, how to measure the exact elapsed request-time?

答:
Something like the following should do the trick:

```<code>long start = System.nanoTime();
CompletableFuture<HttpResponse<String>> httpResponseCF =
    this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString()).
    whenComplete((r,t) -> System.out.println("elapsed ns: "
                           + (System.nanoTime() - start)));
</code>```

Disclaimer: I haven't actually compiled the above...
It's also not the exact time but the best approximation you can get. As with everything, the exact time is impossible to measure.

Body:
In one method, I create and send some HTTPRequests async, and add the CF to a list:

// HTTPClient is Java11 standard, package java.net.http;
CompletableFuture<HttpResponse<String>> httpResponseCF = this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
list.add(httpResponseCF);

Later, in another method, I periodically check every 1second if some of my async sent HTTPRequests have already received:

for(CompletableFuture<HttpResponse<String>> httpResponseCF : list){
  if (httpResponseCF.isDone()) {
    //print out: The time between sending HTTPRequest and receiving HTTPResponse is 25ms
  }
}

The question is, how to measure the exact elapsed request-time?

Body:
Something like the following should do the trick:

long start = System.nanoTime();
CompletableFuture<HttpResponse<String>> httpResponseCF =
    this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString()).
    whenComplete((r,t) -> System.out.println("elapsed ns: "
                           + (System.nanoTime() - start)));

Disclaimer: I haven't actually compiled the above...
It's also not the exact time but the best approximation you can get. As with everything, the exact time is impossible to measure.


问:
Two constraint height conflict UIView
I have UIView, which I have configured programmaticaly.
I tried to change height of MultiSelectsInputView (root view), but instead of changing I've got debug message:

```<code>MainApp[5765:768019] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x28204d360 MainApp.MultiSelectsInputView:0x159c08830.height == 300   (active)>",
    "<NSLayoutConstraint:0x2820880a0 MainApp.MultiSelectsInputView:0x159c08830.height == 275   (active)>"
)
</code>```

I'm setting constraints like this

```<code> func constraintHeight(constant: CGFloat) {
        translatesAutoresizingMaskIntoConstraints = false
        heightAnchor.constraint(equalToConstant: constant).isActive = true
 }
</code>```

Why does it conflict with itself?

答:
As per the error you set the height twice - once with constant value 300 and again with value 275, and both of these are active simultaneously. These two constraints conflict with each other and so only one can be active at a time.

Looking at the code it appears that you have called constraintHeight() method twice with different values. If you need to change the height of your view, you should first deactivate older height constraint.

Keep a reference to height constraints, so that you can activate / deactivate them later.

```<code>var heightConstraint: NSLayoutConstraint?

heightConstraint = view.heightAnchor.constraint(equalToConstant: constant)
// To activate or deactivate toggle the boolean isActive property
heightConstraint?.isActive = true // Activate height constraint
heightConstraint?.isActive = false // Deactivate height constraint
</code>```

Title: Two constraint height conflict UIView

Body:
I have UIView, which I have configured programmaticaly.
I tried to change height of MultiSelectsInputView (root view), but instead of changing I've got debug message:

MainApp[5765:768019] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x28204d360 MainApp.MultiSelectsInputView:0x159c08830.height == 300   (active)>",
    "<NSLayoutConstraint:0x2820880a0 MainApp.MultiSelectsInputView:0x159c08830.height == 275   (active)>"
)

I'm setting constraints like this

 func constraintHeight(constant: CGFloat) {
        translatesAutoresizingMaskIntoConstraints = false
        heightAnchor.constraint(equalToConstant: constant).isActive = true
 }

Why does it conflict with itself?

Body:
As per the error you set the height twice - once with constant value 300 and again with value 275, and both of these are active simultaneously. These two constraints conflict with each other and so only one can be active at a time.

Looking at the code it appears that you have called constraintHeight() method twice with different values. If you need to change the height of your view, you should first deactivate older height constraint.

Keep a reference to height constraints, so that you can activate / deactivate them later.

var heightConstraint: NSLayoutConstraint?

heightConstraint = view.heightAnchor.constraint(equalToConstant: constant)
// To activate or deactivate toggle the boolean isActive property
heightConstraint?.isActive = true // Activate height constraint
heightConstraint?.isActive = false // Deactivate height constraint


问:
How Messages Are Delivered to Consumer in RabbitMQ
I am currently developing an application which uses RabbitMQ Message broker. I have a confusion on how the message delivery work and I already went through their official docs but could not clarify my concern.

Say my application can take messages from two queues, For the queue A , producer directly push messages to this queue and the queue B gets message via an exchange. My question is if there are messages coming from queue A and queue B at the same time to the consumer, how would the consumer consume these messages? Sequentially or by creating multiple parallel threads?.

And if my main thread is responsible for reading the message, will making the main thread go to sleep stops consuming messages from the queue? I mean will rabbitMQ stop pushing messages to the consumer as long as the main thread is a sleep? I am not using the consumer acks as of now and trying to see if message consuming can be stopped by making the main thread go to sleep for a desired amount of time.

答:
A RabbitMQ consumer can only consume messages from a single queue. There are two mechanisms by which a RabbitMQ consumer consumes a message from the queue

Push mechanism - In this type, the rabbitmq-server takes the responsibility of pushing the message to the consumer, whenever there is a message in the queue. The number of messages to be sent to the consumer can be controlled using the basic_qos configuration. The message can be automatically acknowledged or can be acknowledged by the consumer.

Pull mechanism - In this type, it is the job of the consumer to request the rabbitmq-server for the message. Only one message can be requested at a time.

When a consumer connects using the push mechanism, the consumer runs an IO loop, so when you run a long-running job, there are chances that the long-running job can hinder the consumer heartbeat to the rabbitmq server. One way of handling this is to run the long-running job on a separate thread.


答:
if the syntax was correct

Well, your first step would be to fix that.  Perhaps:

```<code>const element = devices.find(d => d.mac === '00:17:88:65:f4:4d');
</code>```

Now you should have the element you're looking for (or null).

this would only return the full element

If you only want one property of that element, return that property:

```<code>return element ? element.ip : '';
</code>```

Here I arbitrarily picked an empty string as a default return value if a matching element is not found.  You can replace that with any default you'd like, or leave the return value undefined.

Note that there's two instances of find here, which may cause confusion.  The imported find is called on its own and returns a Promise.  And in the callback for that Promise is where we use .find on an array:

```<code>const find = require('local-devices');

find().then(devices => {
  const element = devices.find(d => d.mac === '00:17:88:65:f4:4d');
  console.log(element ? element.ip : '');
});
</code>```

Whether you return from the promise callback and use that resolved promise elsewhere, or use the resulting value directly in this callback, is up to your needs.  A single function won't be able to enclose the whole operation and synchronously return the value you want, but that function can return the promise which resolve to the value or can accept a callback to invoke when the promise resolves.

Title: How can I return a specific element out of an array in Javascript?

Body:
if the syntax was correct

Well, your first step would be to fix that.  Perhaps:

const element = devices.find(d => d.mac === '00:17:88:65:f4:4d');

Now you should have the element you're looking for (or null).

this would only return the full element

If you only want one property of that element, return that property:

return element ? element.ip : '';

Here I arbitrarily picked an empty string as a default return value if a matching element is not found.  You can replace that with any default you'd like, or leave the return value undefined.

Note that there's two instances of find here, which may cause confusion.  The imported find is called on its own and returns a Promise.  And in the callback for that Promise is where we use .find on an array:

const find = require('local-devices');

find().then(devices => {
  const element = devices.find(d => d.mac === '00:17:88:65:f4:4d');
  console.log(element ? element.ip : '');
});

Whether you return from the promise callback and use that resolved promise elsewhere, or use the resulting value directly in this callback, is up to your needs.  A single function won't be able to enclose the whole operation and synchronously return the value you want, but that function can return the promise which resolve to the value or can accept a callback to invoke when the promise resolves.