问:
standard_init_linux.go:178: exec user process caused "exec format error"
docker started throwing this error:

standard_init_linux.go:178: exec user process caused "exec format error"

whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CMD or ENTRYPOINT. here is the docker file I have been working with which worked perfectly until about an hour ago:

```<code>FROM buildpack-deps:jessie

ENV PATH /usr/local/bin:$PATH

ENV LANG C.UTF-8

RUN apt-get update && apt-get install -y --no-install-recommends \
        tcl \
        tk \
    && rm -rf /var/lib/apt/lists/*

ENV GPG_KEY 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
ENV PYTHON_VERSION 3.6.0

ENV PYTHON_PIP_VERSION 9.0.1

RUN set -ex \
    && buildDeps=' \
        tcl-dev \
        tk-dev \
    ' \
    && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
    \
    && wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \
    && wget -O python.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \
    && export GNUPGHOME="$(mktemp -d)" \
    && gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$GPG_KEY" \
    && gpg --batch --verify python.tar.xz.asc python.tar.xz \
    && rm -r "$GNUPGHOME" python.tar.xz.asc \
    && mkdir -p /usr/src/python \
    && tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \
    && rm python.tar.xz \
    \
    && cd /usr/src/python \
    && ./configure \
        --enable-loadable-sqlite-extensions \
        --enable-shared \
    && make -j$(nproc) \
    && make install \
    && ldconfig \
    \
    && if [ ! -e /usr/local/bin/pip3 ]; then : \
        && wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \
        && python3 /tmp/get-pip.py "pip==$PYTHON_PIP_VERSION" \
        && rm /tmp/get-pip.py \
    ; fi \
    && pip3 install --no-cache-dir --upgrade --force-reinstall "pip==$PYTHON_PIP_VERSION" \
    && [ "$(pip list |tac|tac| awk -F '[ ()]+' '$1 == "pip" { print $2; exit }')" = "$PYTHON_PIP_VERSION" ] \
    \
    && find /usr/local -depth \
        \( \
            \( -type d -a -name test -o -name tests \) \
            -o \
            \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
        \) -exec rm -rf '{}' + \
    && apt-get purge -y --auto-remove $buildDeps \
    && rm -rf /usr/src/python ~/.cache

RUN cd /usr/local/bin \
    && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
    && ln -s idle3 idle \
    && ln -s pydoc3 pydoc \
    && ln -s python3 python \
    && ln -s python3-config python-config

RUN pip install uwsgi

RUN mkdir /config

RUN mkdir /logs

ENV HOME /var/www

WORKDIR /config

ADD conf/requirements.txt /config

RUN pip install -r /config/requirements.txt

ADD conf/wsgi.py /config

ADD conf/wsgi.ini /config

ADD conf/__init__.py /config

ADD start.sh /bin/start.sh

RUN chmod +x /bin/start.sh

EXPOSE 8000

ENTRYPOINT ["start.sh", "uwsgi", "--ini", "wsgi.ini"]
</code>```

答:
This error could also occur if an image was built on a MacBook Pro with a Apple M1 Pro chip, which is ARM-based, so by default the Docker build command targets arm64.

Docker in fact detects the Apple M1 Pro platform as linux/arm64/v8

Specifying the platform to both the build command and version tag was enough:

```<code># Build for ARM64 (default)
docker build -t <image-name>:<version>-arm64 .

# Build for ARM64
docker build --platform=linux/arm64 -t <image-name>:<version>-arm64 .

# Build for AMD64
docker build --platform=linux/amd64 -t <image-name>:<version>-amd64 .
</code>```

Environment

Chip: Apple M1 Pro, 10 Cores (8 performance and 2 efficiency)

Docker version 20.10.12, build e91ed57

Body:
docker started throwing this error:

standard_init_linux.go:178: exec user process caused "exec format error"

whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CMD or ENTRYPOINT. here is the docker file I have been working with which worked perfectly until about an hour ago:

FROM buildpack-deps:jessie

ENV PATH /usr/local/bin:$PATH

ENV LANG C.UTF-8

RUN apt-get update && apt-get install -y --no-install-recommends \
        tcl \
        tk \
    && rm -rf /var/lib/apt/lists/*

ENV GPG_KEY 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
ENV PYTHON_VERSION 3.6.0

ENV PYTHON_PIP_VERSION 9.0.1

RUN set -ex \
    && buildDeps=' \
        tcl-dev \
        tk-dev \
    ' \
    && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
    \
    && wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \
    && wget -O python.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \
    && export GNUPGHOME="$(mktemp -d)" \
    && gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$GPG_KEY" \
    && gpg --batch --verify python.tar.xz.asc python.tar.xz \
    && rm -r "$GNUPGHOME" python.tar.xz.asc \
    && mkdir -p /usr/src/python \
    && tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \
    && rm python.tar.xz \
    \
    && cd /usr/src/python \
    && ./configure \
        --enable-loadable-sqlite-extensions \
        --enable-shared \
    && make -j$(nproc) \
    && make install \
    && ldconfig \
    \
    && if [ ! -e /usr/local/bin/pip3 ]; then : \
        && wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \
        && python3 /tmp/get-pip.py "pip==$PYTHON_PIP_VERSION" \
        && rm /tmp/get-pip.py \
    ; fi \
    && pip3 install --no-cache-dir --upgrade --force-reinstall "pip==$PYTHON_PIP_VERSION" \
    && [ "$(pip list |tac|tac| awk -F '[ ()]+' '$1 == "pip" { print $2; exit }')" = "$PYTHON_PIP_VERSION" ] \
    \
    && find /usr/local -depth \
        \( \
            \( -type d -a -name test -o -name tests \) \
            -o \
            \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
        \) -exec rm -rf '{}' + \
    && apt-get purge -y --auto-remove $buildDeps \
    && rm -rf /usr/src/python ~/.cache

RUN cd /usr/local/bin \
    && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
    && ln -s idle3 idle \
    && ln -s pydoc3 pydoc \
    && ln -s python3 python \
    && ln -s python3-config python-config

RUN pip install uwsgi

RUN mkdir /config

RUN mkdir /logs

ENV HOME /var/www

WORKDIR /config

ADD conf/requirements.txt /config

RUN pip install -r /config/requirements.txt

ADD conf/wsgi.py /config

ADD conf/wsgi.ini /config

ADD conf/__init__.py /config

ADD start.sh /bin/start.sh

RUN chmod +x /bin/start.sh

EXPOSE 8000

ENTRYPOINT ["start.sh", "uwsgi", "--ini", "wsgi.ini"]

Body:
This error could also occur if an image was built on a MacBook Pro with a Apple M1 Pro chip, which is ARM-based, so by default the Docker build command targets arm64.

Docker in fact detects the Apple M1 Pro platform as linux/arm64/v8

Specifying the platform to both the build command and version tag was enough:

# Build for ARM64 (default)
docker build -t <image-name>:<version>-arm64 .

# Build for ARM64
docker build --platform=linux/arm64 -t <image-name>:<version>-arm64 .

# Build for AMD64
docker build --platform=linux/amd64 -t <image-name>:<version>-amd64 .

Environment

Chip: Apple M1 Pro, 10 Cores (8 performance and 2 efficiency)

Docker version 20.10.12, build e91ed57


来源: stackexchange

问:
Catching Error in pipe() method of an Observable - rxjs/Axios
I refactored my http layer to go from a promised-based implementation to observables using rxjs. The problem that I am facing is that the code crashes whenever server response is 400 or 500,

```<code>Axios.request(config).pipe(map(((response: AxiosResponse) => response), catchError(e => {
    return new Observable(e);
})));
</code>```

The problem I am facing is that the error is not being handled by the catchError callback. I am looking for a way in which the error is handled by the catchError callback so that the response can be handled gracefully.

答:
I don't know your problem is this but you can do this:

```<code>import { EMPTY } from 'rxjs';

Axios.request(config).pipe(map(((response: AxiosResponse) => response),
catchError(() => EMPTY)));
</code>```

EMPTY is an object that is imported from rxjs libaray.

ContentLicense: CC BY-SA 4.0

Body:
I refactored my http layer to go from a promised-based implementation to observables using rxjs. The problem that I am facing is that the code crashes whenever server response is 400 or 500,

Axios.request(config).pipe(map(((response: AxiosResponse) => response), catchError(e => {
    return new Observable(e);
})));

The problem I am facing is that the error is not being handled by the catchError callback. I am looking for a way in which the error is handled by the catchError callback so that the response can be handled gracefully.

Body:
I don't know your problem is this but you can do this:

import { EMPTY } from 'rxjs';

Axios.request(config).pipe(map(((response: AxiosResponse) => response),
catchError(() => EMPTY)));

EMPTY is an object that is imported from rxjs libaray.


问:
Kotlin flow - Is flow created once for each collector?
I know Flow is cold, and ShaerdFlow is hot.

To test cold stream in Kotlin flow, I created below code. My plan is, create a flow that will emit String value and add two collectors on it. I expect that the only one collector will get emitted value, because it is a cold stream.

But the result was different, I found that two values are emitted!

Test code:

```<code>    val stringFlow: Flow<String> = flow<String> {
        for (i in 0..10) {
            Timber.d("Integer $i emitted ${currentCoroutineContext()}")
            emit("Integer $i")
            delay(500)
        }
    }
    // If I uncomment below line, only one flow will be emitted
    //.shareIn(coroutineScope, SharingStarted.Lazily)

    val job1 = coroutineScope.launch {
        stringFlow.collect {
            Timber.d("job1 collect 1 $it")
        }
    }
    val job2 = coroutineScope.launch {
        stringFlow.collect {
            Timber.d("job2 collect 2 $it")
        }
    }
</code>```

Result:

```<code>stringFlow: Integer 0 produced [StandaloneCoroutine{Active}@c2f624, Dispatchers.IO]
stringFlow: Integer 0 produced [StandaloneCoroutine{Active}@dd9f58d, Dispatchers.IO]
job1: job1 collect 1 Integer 0
job2: job2 collect 2 Integer 0
</code>```

How can I explain this situation? Can I say "flow will be created once for each collector?"

答:
Yes, it starts emitting a new flow/stream of items whenever we start collecting from it. This is described in the documentation:

The flow being cold means that the block is called every time a terminal operator is applied to the resulting flow.

It is the same for other cold flows as well. For example, flow created with flowOf() emits the same items whenever collected. Flow created with callbackFlow() attaches a callback whenever we collect. And so on.

I expect that the only one collector will get emitted value

If you meant to distribute work between multiple consumers, then I believe flows are not a good fit for this. They are more about observing for events or some data, but not for distributing of items between multiple producers and consumers. Use channels instead.

Body:
I know Flow is cold, and ShaerdFlow is hot.

To test cold stream in Kotlin flow, I created below code. My plan is, create a flow that will emit String value and add two collectors on it. I expect that the only one collector will get emitted value, because it is a cold stream.

But the result was different, I found that two values are emitted!

Test code:

    val stringFlow: Flow<String> = flow<String> {
        for (i in 0..10) {
            Timber.d("Integer $i emitted ${currentCoroutineContext()}")
            emit("Integer $i")
            delay(500)
        }
    }
    // If I uncomment below line, only one flow will be emitted
    //.shareIn(coroutineScope, SharingStarted.Lazily)

    val job1 = coroutineScope.launch {
        stringFlow.collect {
            Timber.d("job1 collect 1 $it")
        }
    }
    val job2 = coroutineScope.launch {
        stringFlow.collect {
            Timber.d("job2 collect 2 $it")
        }
    }

Result:

stringFlow: Integer 0 produced [StandaloneCoroutine{Active}@c2f624, Dispatchers.IO]
stringFlow: Integer 0 produced [StandaloneCoroutine{Active}@dd9f58d, Dispatchers.IO]
job1: job1 collect 1 Integer 0
job2: job2 collect 2 Integer 0

How can I explain this situation? Can I say "flow will be created once for each collector?"


问:
Parse the arguments of a git rebase command to determine the upstream, if one is specified
I'm trying to do this:

User runs git rebase-like [same arguments as rebase]

The script

determines the upstream if one is specified

pulls out other select options from the command

does stuff

then passes the original arguments on to rebase

This question is about 2.1 and 2.2. I expect the most reliable way to do this would be parsing with Git. But for now I'm taking a more manual command line parsing approach. Maybe you can think of a nice regex, or some bash cleverness?

(I've tried reading git-rebase source working back from $switch_to, and git-rebase--merge source working back from $base but I'm fairly new to shell scripts and can't tell whether there's a smallish piece of the source I could use.)

Here's what I have so far. It's limited: it's stricter about the order of arguments than git-rebase is. If [ <upstream> [<branch]] is used, it has to be at the end of the command. I can determine the specified upstream for

```<code>git rebase [...] --onto <newbase> [...]
</code>```

and for

```<code>git rebase <upstream> [<branch]
</code>```

but not for

```<code>git rebase <upstream> [<branch>] ...
</code>```

My script is not beautiful, and it's a brittle. I'd really like a way to get this more directly with Git. At the least I'd like to upgrade my script so it accepts arguments in any order. Ideas?

# !/bin/bash

NEWBASE QUIET UPSTREAM branch
# the "environment" for those env vars is the command line input
# I'm open to hearing arguments for lowercasing them

options () {
    local onto_index
    for ((i=1; i<=$#; i++)); do
      case "${!i}" in
        "--onto")
          newbase_index=$((i+1))
          NEWBASE="${!newbase_index}"
          ;;
        "-q"|"--quiet") QUIET=-q ;;
      esac
    done
}

opt_with_arg () {
    [[ \
        "$1" == "--fork" \
        || "$1" == "--onto" \
        || "$1" == "-s" \
        || "$1" == "-X" \
        || "$1" == "-x" \
        || "$1" == "-exec" \
    ]] \
    || [[ "$1" == "--root" ]]
    # though --root doesn't actually have an argument, including it here
    # is shorter than checking `opt_with_arg $1 || [[ $1 == "--root" ]]`
}

options "$@"

if [[ -n "$1" && "${!#}" != "-"* ]]; then
    [[ $# -gt 3 ]] && shift "$(($#-3))"
    opt_with_arg "$1" && shift 2
    [[ -n "$3" ]] && shift
    opt_with_arg "$1" && shift 2
    [[ "$1" == "-"* ]] && shift
    UPSTREAM="$1"
    #
    # possibilites after first shift:
    # (uppercase is what we want to preserve, lowercase we want to cut,
    # u is <upstream>, b is <branch>, x is <someoption>.)
    #    U,
    #    U B, X U, --root b, --opt_with_arg n,
    #    X U B, X X U, x --root b, x --opt_with_arg n, --opt_with_arg N U, --opt_with_arg n x
    # possibilites after second shift: U,
    #    U B, X U, x
    #    X U B, X X U, x --root b, x --opt_with_arg n
    # possibilites after third shift:
    #    U, x
    #    U B, X U, --root b, --opt_with_arg n
    # possibilites after fourth shift:
    #    U, x
    #    U B, X U
    # possibilites after fifth shift:
    #    U, U B
fi

branch="${NEWBASE:=$UPSTREAM}"
```

答:
Two new documentation elements can help inform your bash options parsing script:

First: revs come first before the pathspec among command line arguments, but Git documentation did not spell out that dashed options come before other args, which has been corrected with Git 2.36 (Q2 2022).

See commit c11f950 (17 Jan 2022) by Teng Long (dyrone).

(Merged by Junio C Hamano -- gitster -- in commit e704a44, 09 Feb 2022)

git-cli.txt: clarify "options first and then args"

Signed-off-by: Teng Long

There are some commands permit the user whether to provide options first before args, or the reverse order.

For example:

```<code>git push --dry-run <remote> <ref>
</code>```

And:

```<code>git push <remote> <ref> --dry-run
</code>```

Both of them is supported, but some commands do not, for instance:

```<code>git ls-remote --heads <remote>
</code>```

And:

```<code>git ls-remote <remote> --heads
</code>```

If <remote> only has one ref and it's name is "refs/heads/--heads", you will get the same result, otherwise will not.

This is because the former in the second example will parse "--heads" as an "option" which means to limit to only "refs/heads" when listing the remote references, the latter treat "--heads" as an argument which means to filter the result list with the given pattern.

Therefore, we want to specify a bit more in "gitcli.txt" about the way we recommend and help to resolve the ambiguity around some git command usage.

See related disscussions.

gitcli now includes in its man page:

Options come first and then args.
A subcommand may take dashed options (which may take their own
arguments, e.g. "--max-parents 2") and arguments.

You SHOULD
give dashed options first and then arguments.

Some commands may
accept dashed options after you have already gave non-option
arguments (which may make the command ambiguous), but you should
not rely on it (because eventually we may find a way to fix
these ambiguity by enforcing the "options then args" rule).

And, still with Git 2.36:

See commit 518e15d (20 Jan 2022) by René Scharfe (rscharfe).

(Merged by Junio C Hamano -- gitster -- in commit e66e990, 11 Feb 2022)

parse-options: document bracketing of argh

Signed-off-by: René Scharfe

parse-options.h

```<code> * `argh`::
 *   token to explain the kind of argument this option wants. Does not
 *   begin in capital letter, and does not end with a full stop.
 *   Should be wrapped by N_() for translation.
 *   Is automatically enclosed in brackets when printed, unless it
 *   contains any of the following characters: ()<>[]|
 *   E.g. "name" is shown as "<name>" to indicate that a name value
 *   needs to be supplied, not the literal string "name", but
 *   "<start>,<end>" and "(this|that)" are printed verbatim.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do this:

User runs git rebase-like [same arguments as rebase]

The script

determines the upstream if one is specified

pulls out other select options from the command

does stuff

then passes the original arguments on to rebase

This question is about 2.1 and 2.2. I expect the most reliable way to do this would be parsing with Git. But for now I'm taking a more manual command line parsing approach. Maybe you can think of a nice regex, or some bash cleverness?

(I've tried reading git-rebase source working back from $switch_to, and git-rebase--merge source working back from $base but I'm fairly new to shell scripts and can't tell whether there's a smallish piece of the source I could use.)

Here's what I have so far. It's limited: it's stricter about the order of arguments than git-rebase is. If [ <upstream> [<branch]] is used, it has to be at the end of the command. I can determine the specified upstream for

git rebase [...] --onto <newbase> [...]

and for

git rebase <upstream> [<branch]

but not for

git rebase <upstream> [<branch>] ...

My script is not beautiful, and it's a brittle. I'd really like a way to get this more directly with Git. At the least I'd like to upgrade my script so it accepts arguments in any order. Ideas?

# !/bin/bash

NEWBASE QUIET UPSTREAM branch
# the "environment" for those env vars is the command line input
# I'm open to hearing arguments for lowercasing them

options () {
    local onto_index
    for ((i=1; i<=$#; i++)); do
      case "${!i}" in
        "--onto")
          newbase_index=$((i+1))
          NEWBASE="${!newbase_index}"
          ;;
        "-q"|"--quiet") QUIET=-q ;;
      esac
    done
}

opt_with_arg () {
    [[ \
        "$1" == "--fork" \
        || "$1" == "--onto" \
        || "$1" == "-s" \
        || "$1" == "-X" \
        || "$1" == "-x" \
        || "$1" == "-exec" \
    ]] \
    || [[ "$1" == "--root" ]]
    # though --root doesn't actually have an argument, including it here
    # is shorter than checking `opt_with_arg $1 || [[ $1 == "--root" ]]`
}

options "$@"

if [[ -n "$1" && "${!#}" != "-"* ]]; then
    [[ $# -gt 3 ]] && shift "$(($#-3))"
    opt_with_arg "$1" && shift 2
    [[ -n "$3" ]] && shift
    opt_with_arg "$1" && shift 2
    [[ "$1" == "-"* ]] && shift
    UPSTREAM="$1"
    #
    # possibilites after first shift:
    # (uppercase is what we want to preserve, lowercase we want to cut,
    # u is <upstream>, b is <branch>, x is <someoption>.)
    #    U,
    #    U B, X U, --root b, --opt_with_arg n,
    #    X U B, X X U, x --root b, x --opt_with_arg n, --opt_with_arg N U, --opt_with_arg n x
    # possibilites after second shift: U,
    #    U B, X U, x
    #    X U B, X X U, x --root b, x --opt_with_arg n
    # possibilites after third shift:
    #    U, x
    #    U B, X U, --root b, --opt_with_arg n
    # possibilites after fourth shift:
    #    U, x
    #    U B, X U
    # possibilites after fifth shift:
    #    U, U B
fi

branch="${NEWBASE:=$UPSTREAM}"

Body:
Two new documentation elements can help inform your bash options parsing script:

First: revs come first before the pathspec among command line arguments, but Git documentation did not spell out that dashed options come before other args, which has been corrected with Git 2.36 (Q2 2022).

See commit c11f950 (17 Jan 2022) by Teng Long (dyrone).

(Merged by Junio C Hamano -- gitster -- in commit e704a44, 09 Feb 2022)

git-cli.txt: clarify "options first and then args"

Signed-off-by: Teng Long

There are some commands permit the user whether to provide options first before args, or the reverse order.

For example:

git push --dry-run <remote> <ref>

And:

git push <remote> <ref> --dry-run

Both of them is supported, but some commands do not, for instance:

git ls-remote --heads <remote>

And:

git ls-remote <remote> --heads

If <remote> only has one ref and it's name is "refs/heads/--heads", you will get the same result, otherwise will not.

This is because the former in the second example will parse "--heads" as an "option" which means to limit to only "refs/heads" when listing the remote references, the latter treat "--heads" as an argument which means to filter the result list with the given pattern.

Therefore, we want to specify a bit more in "gitcli.txt" about the way we recommend and help to resolve the ambiguity around some git command usage.

See related disscussions.

gitcli now includes in its man page:

Options come first and then args.
A subcommand may take dashed options (which may take their own
arguments, e.g. "--max-parents 2") and arguments.

You SHOULD
give dashed options first and then arguments.

Some commands may
accept dashed options after you have already gave non-option
arguments (which may make the command ambiguous), but you should
not rely on it (because eventually we may find a way to fix
these ambiguity by enforcing the "options then args" rule).

And, still with Git 2.36:

See commit 518e15d (20 Jan 2022) by René Scharfe (rscharfe).

(Merged by Junio C Hamano -- gitster -- in commit e66e990, 11 Feb 2022)

parse-options: document bracketing of argh

Signed-off-by: René Scharfe

parse-options.h

 * `argh`::
 *   token to explain the kind of argument this option wants. Does not
 *   begin in capital letter, and does not end with a full stop.
 *   Should be wrapped by N_() for translation.
 *   Is automatically enclosed in brackets when printed, unless it
 *   contains any of the following characters: ()<>[]|
 *   E.g. "name" is shown as "<name>" to indicate that a name value
 *   needs to be supplied, not the literal string "name", but
 *   "<start>,<end>" and "(this|that)" are printed verbatim.


问:
Angular *ngFor Howto stack element tag with left and right on respective sides?
Expected left to be stacked top left and right top right

[Need to stack elements with name left in left side and right in right side
Using single *ngFor div/ ul /table any means .....
Sample play around provided below]
https://stackblitz.com/edit/ngfor-index-example-wntaie?file=app%2Fapp.component.html

答:
Welcome @Rahul Krishnakumar!
Since we speak about list items, you can try this solution.

P.S accidently I just saved it to your stackblitz. Sorry about that.

https://stackblitz.com/edit/ngfor-index-example-b2ysbk?file=app%2Fapp.component.html

```<code><div>
  <ul>
  <li
    *ngFor="let course of courses; index as i"
    [ngClass]="courses[i].name == 'left' ? 'leftsec' : 'rightsec'"
  >
    {{ courses[i].name + ' ' + courses[i].id }}
  </li>
</ul>
</div>
</code>```

and the styling

```<code>.leftsec {
  float: left;
  padding: 10px;
  background-color: red;
}

.rightsec {
  float: right;
  padding: 10px;
  background-color: blue;
  color: white;
}

ul {
  list-style: none;
  display: flex;
  flex-flow: column wrap;
  height: 16em;
}

li {
  padding: 1em;
  margin: 2px;
}
</code>```

Body:
Welcome @Rahul Krishnakumar!
Since we speak about list items, you can try this solution.

P.S accidently I just saved it to your stackblitz. Sorry about that.

https://stackblitz.com/edit/ngfor-index-example-b2ysbk?file=app%2Fapp.component.html

<div>
  <ul>
  <li
    *ngFor="let course of courses; index as i"
    [ngClass]="courses[i].name == 'left' ? 'leftsec' : 'rightsec'"
  >
    {{ courses[i].name + ' ' + courses[i].id }}
  </li>
</ul>
</div>

and the styling

.leftsec {
  float: left;
  padding: 10px;
  background-color: red;
}

.rightsec {
  float: right;
  padding: 10px;
  background-color: blue;
  color: white;
}

ul {
  list-style: none;
  display: flex;
  flex-flow: column wrap;
  height: 16em;
}

li {
  padding: 1em;
  margin: 2px;
}


问:
brew start and brew restart wont start service
I installed mysql@5.7 using brew. After installing, I started the service using brew services start mysql@5.7. Checking using brew services shows its working fine.

In any attempt after the first though, the behavior is different. I run brew services start mysql@5.7 and I get:

```<code>Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; `/bin/launchctl bootstrap gui/505 /Users/Mahmoud/Library/LaunchAgents/homebrew.mxcl.mysql@5.7.plist` exited with 5.
</code>```

If I then try to restart the service, using brew services restart mysql@5.7 I get

```<code>Stopping `mysql@5.7`... (might take a while)
==> Successfully stopped `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)
==> Successfully started `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)
</code>```

but an inspection using brew services would show that the service has been stopped:

```<code>Name      Status  User File
mysql@5.7 stopped root ~/Library/LaunchAgents/homebrew.mxcl.mysql@5.7.plist
</code>```

Stopping the service manually using brew services stop mysql@5.7 and starting again hasn't worked as well.

Tried as well to uninstall using brew uninstall mysql@5.7 and re-installing using brew install mysql@5.7 but the problem persists. I tried looking all around but I don't see anyone having this same problem. Any ideas on how to fix this?

答:
I had this same issue today and noticed I already had data in the /usr/local/var/mysql/ directory, probably from a previous install.

I didn't care about losing anything within the directory so I removed it all rm -rf /usr/local/var/mysql and ran brew uninstall mysql@5.7 and brew install mysql@5.7.

When I next checked brew services list it was already running, something that didn't happen before and it was all working.

Body:
I installed mysql@5.7 using brew. After installing, I started the service using brew services start mysql@5.7. Checking using brew services shows its working fine.

In any attempt after the first though, the behavior is different. I run brew services start mysql@5.7 and I get:

Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; `/bin/launchctl bootstrap gui/505 /Users/Mahmoud/Library/LaunchAgents/homebrew.mxcl.mysql@5.7.plist` exited with 5.

If I then try to restart the service, using brew services restart mysql@5.7 I get

Stopping `mysql@5.7`... (might take a while)
==> Successfully stopped `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)
==> Successfully started `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)

but an inspection using brew services would show that the service has been stopped:

Name      Status  User File
mysql@5.7 stopped root ~/Library/LaunchAgents/homebrew.mxcl.mysql@5.7.plist

Stopping the service manually using brew services stop mysql@5.7 and starting again hasn't worked as well.

Tried as well to uninstall using brew uninstall mysql@5.7 and re-installing using brew install mysql@5.7 but the problem persists. I tried looking all around but I don't see anyone having this same problem. Any ideas on how to fix this?


问:
Select param when not null or another param
```<code>SELECT COALESCE(a.task_id,b.task_id) as
task_id,b.task_name as name
FROM table_a as a FULL OUTER JOIN table_b as b ON
a.task_id = b.task_id
</code>```

If b.task_name is null It will be

```<code>SELECT COALESCE(a.task_id,b.task_id) as
task_id,a.task_name as name
FROM table_a as a FULL OUTER JOIN table_b as b ON
a.task_id = b.task_id
</code>```

How to add where to select param from table a if not null or from another table if its be null when using fullouter join

Table_a:  primary_id,task_id, task_name = [{1,1,"name1ofa"}, {2,2,"name2ofa"}]

Talbe_b: primary_id,task_id, task_name = [{1,1,"name1ofb"}, {2,2,null}]

Expect selected query: [{1,"name1ofb"}, {2,"name2ofa"}]
I want is the priority of b.task_name to be higher than a.taske_name

答:
You can try to use INNER JOIN instead of FULL OUTER JOIN because you want to get a result that matches task_id from those tables.

Then COALESCE function will return the first non-null value in parameters, so you might use b.task_name be the first parameter

```<code>SELECT a.task_id ,
       COALESCE(b.task_name,a.task_name) as name
FROM table_a as a
INNER JOIN table_b as b
ON a.task_id = b.task_id
</code>```

Body:
SELECT COALESCE(a.task_id,b.task_id) as
task_id,b.task_name as name
FROM table_a as a FULL OUTER JOIN table_b as b ON
a.task_id = b.task_id

If b.task_name is null It will be

SELECT COALESCE(a.task_id,b.task_id) as
task_id,a.task_name as name
FROM table_a as a FULL OUTER JOIN table_b as b ON
a.task_id = b.task_id

How to add where to select param from table a if not null or from another table if its be null when using fullouter join

Table_a:  primary_id,task_id, task_name = [{1,1,"name1ofa"}, {2,2,"name2ofa"}]

Talbe_b: primary_id,task_id, task_name = [{1,1,"name1ofb"}, {2,2,null}]

Expect selected query: [{1,"name1ofb"}, {2,"name2ofa"}]
I want is the priority of b.task_name to be higher than a.taske_name

Body:
You can try to use INNER JOIN instead of FULL OUTER JOIN because you want to get a result that matches task_id from those tables.

Then COALESCE function will return the first non-null value in parameters, so you might use b.task_name be the first parameter

SELECT a.task_id ,
       COALESCE(b.task_name,a.task_name) as name
FROM table_a as a
INNER JOIN table_b as b
ON a.task_id = b.task_id


问:
Eclipse: large toolbar icons
Does anybody know how to use large toolbar icons? Edit: How do I do it?</p>

答:
In 2022 on linux with an UltraHD display:

set your system as zoom 100% (forget 200% or fractional hacks, it's slow and buggy)

only use font scaling : gsettings set org.gnome.desktop.interface text-scaling-factor 1.5

To launch Eclipse (with perfect text and icon size) from terminal, use :

```<code>GDK_SCALE=2 GDK_DPI_SCALE=0.5 ./eclipse
</code>```

OwnerDisplayName: George Bailey

Title: Eclipse: large toolbar icons

Body:
In 2022 on linux with an UltraHD display:

set your system as zoom 100% (forget 200% or fractional hacks, it's slow and buggy)

only use font scaling : gsettings set org.gnome.desktop.interface text-scaling-factor 1.5

To launch Eclipse (with perfect text and icon size) from terminal, use :

GDK_SCALE=2 GDK_DPI_SCALE=0.5 ./eclipse


问:
How to draw a gizmo in CesiumJS
How to draw a gizmo by giving it a position, orientation and eventually a scale in a CesiumJS application?

By gizmo I mean a 3-axes right-handed reference frame using (x,y,z) vectors, ideally depicted as (RGB) values, such as these, for example:

I wish I could depict the orientation of any object (e.g. a glTF) by placing such reference frame, for example, at the position of the object origin (e.g. using its longitude, latitude and elevation) and following its orientation, as defined by its heading, pitch and roll values which must follow the three given angles in their original order (heading first, pitch second and roll third) starting from the LTP-ENU (0,0,0) convention (x=0=east, y=0=north, z=0=upward).

The inspector is not an option.

答:
You can use DebugModelMatrixPrimitive.

Here 's Sandcastle

Sample code

```<code>const viewer = new Cesium.Viewer("cesiumContainer");

const position = Cesium.Cartesian3.fromDegrees(-107.0, 40.0, 300000.0);

const redSphere = viewer.entities.add({
    name: "Red sphere with black outline",
    position: position,
    ellipsoid: {
        radii: new Cesium.Cartesian3(300000.0, 300000.0, 300000.0),
        material: Cesium.Color.RED.withAlpha(0.5),
        outline: true,
        outlineColor: Cesium.Color.BLACK,
    },
});

const heading = Cesium.Math.toRadians(10);
const pitch = Cesium.Math.toRadians(50);
const roll = Cesium.Math.toRadians(0);

const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);

const frame = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr);

viewer.scene.primitives.add(new Cesium.DebugModelMatrixPrimitive({
    modelMatrix: frame,
    length: 800000,
    width: 3.0
}));

viewer.zoomTo(viewer.entities);
</code>```

Title: How to draw a gizmo in CesiumJS

Body:
You can use DebugModelMatrixPrimitive.

Here 's <a href="https://sandcastle.cesium.com/#c=dVPRbtsgFP0V5CciecRRVm1y02hdsmrSWq1Koz35hZibGBWDBThpO+XfB9iOnaz1AzL3nnPugXvJlTQW7TkcQKMbJOGAFmB4XZI/IYazKA/7hZKWcgk6i0bXmcxkHpiVMtxyJR235S2otu6PyinZalUuYacBDP40Sb6QJEafE79OE/+RZNQraWBPVQEanFTjh4C0ThwMoYzhv5lESNISUpRFK2DINOgDtwXaCJo/I1Vb4SxmUeyxnbX09BfCIASvjOIsRUESIU0Z5+nw7P0ZcOe09zxwHzcCJbWgORXpia+E0mT1Y0m8u1tRFRQn5KrDtz5TZHUN57HAvND5fn+7+BVgR7ceh9dfgPMud/3tP1BbEKtWLkylwZPEo9tWcZsXHyKvBkithPgQmJzVry6m5mdj6NHXWjkZ3DqMm/Jx0B4qbLVraV9srV2NrdKlIcWF1Frd8Rdgd56ATy31Fhq9dmhMDhJIpXnpAPt2eAYOl7Cpdw+KgXAH0/zlsUPidhxCR/s8ShuPcZ8VIHdu6FL0NQzCIHPgLCSmJGmCx9GZuTelyrXCF/M9uo7iaGbsq4B5p/WNl5XSFtVaYELGFspKuDEz402dP4MluTFe2UNn4yF1xvgecXbzzsNFuaDGuMy2FuKJv7mXMp+NHf4/qlDh7n/vQQv66mHFZH7fBAkhs7Hbvs+0SokN1RfK/wA" rel="nofollow noreferrer">Sandcastle

Sample code

const viewer = new Cesium.Viewer("cesiumContainer");

const position = Cesium.Cartesian3.fromDegrees(-107.0, 40.0, 300000.0);

const redSphere = viewer.entities.add({
    name: "Red sphere with black outline",
    position: position,
    ellipsoid: {
        radii: new Cesium.Cartesian3(300000.0, 300000.0, 300000.0),
        material: Cesium.Color.RED.withAlpha(0.5),
        outline: true,
        outlineColor: Cesium.Color.BLACK,
    },
});

const heading = Cesium.Math.toRadians(10);
const pitch = Cesium.Math.toRadians(50);
const roll = Cesium.Math.toRadians(0);

const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);

const frame = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr);

viewer.scene.primitives.add(new Cesium.DebugModelMatrixPrimitive({
    modelMatrix: frame,
    length: 800000,
    width: 3.0
}));

viewer.zoomTo(viewer.entities);


问:
What do you do on client side for WebGl Aquarium?
I am trying to work out how content is synchronized across multiple screens as shown by http://webglsamples.googlecode.com/hg/aquarium/README.html. (video at http://www.youtube.com/watch?v=64TcBiqmVko)

All I want to know is what code gets runs on the client side? From what I can tell is there is some websocket client side code that determines what is shown.

Can anyone point me to where this is?

TIA
JD.

答:
First, you must make sure that all initial data is identical on all machines. Then you set up different cameras on different machines (so you can put together "meta" screen). And run your simulation, but with synchronization for every frame (or every n-th frame).

Of if your simulation is non-deterministic then you have to synchronize simulation results needed for rendering every frame.


问:
Pandas dataframe, get the row and index for a column meeting certain conditions
I have the below df:

```<code>import pandas as pd
import numpy as np

output =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED'],['', 'DEV', 'AIRFLOW', 'TEST_TABLE', 'TEST_COL', 'COMMENT TEST'],]

df = pd.DataFrame(output[1:], columns=output[0])

query_list = []
empty_status_idx = []

for index, row in df.iterrows():
    if row['Status'] is None:
        sql = f"ALTER TABLE {row['Table']} ALTER {row['Column']} COMMENT {row['Comment']}; "
        # idx = np.where(df["Status"] is None)
        # idx = df.index[df['Status']]
        idx = df.iloc[df['Status']]
        empty_status_idx.append(idx)
        print(f'idx: {idx}')

        query_list.append(sql)
query_list
</code>```

I see the below error with idx:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

What I want to see if a list of the positions of None cells:

```<code>empty_status_idx = [0, 2]
</code>```

The above idx value I got from some of the answers from this stack overflow question

答:
You are overcomplicating it:</p>
```<code>empty_status_idx = df[df['Status'].isnull()].index.tolist()

Out[65]: [0, 2]
</code>```

Body:
I have the below df:

import pandas as pd
import numpy as np

output =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED'],['', 'DEV', 'AIRFLOW', 'TEST_TABLE', 'TEST_COL', 'COMMENT TEST'],]

df = pd.DataFrame(output[1:], columns=output[0])

query_list = []
empty_status_idx = []

for index, row in df.iterrows():
    if row['Status'] is None:
        sql = f"ALTER TABLE {row['Table']} ALTER {row['Column']} COMMENT {row['Comment']}; "
        # idx = np.where(df["Status"] is None)
        # idx = df.index[df['Status']]
        idx = df.iloc[df['Status']]
        empty_status_idx.append(idx)
        print(f'idx: {idx}')

        query_list.append(sql)
query_list

I see the below error with idx:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

What I want to see if a list of the positions of None cells:

empty_status_idx = [0, 2]

The above idx value I got from some of the answers from this stack overflow question

Body:
You are overcomplicating it:

empty_status_idx = df[df['Status'].isnull()].index.tolist()

Out[65]: [0, 2]


问:
How to find multiple elements in a list using linear search
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

```<code>product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()
</code>```

Here is the output:

```<code>Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2
</code>```

which should be:

```<code>The price for Milk in Axep are:
2
10
</code>```

答:
Set the found variable to False inside the if clause.

```<code>if found == True:
  print(f"The price for {product[position]} in {store[position]} are {price[position]}")
  found = False
</code>```

Explanation: After finding an element you are setting the found variable to True. But you are never setting it back to False. Thus in the subsequent iteration, the while loop's condition will evaluate to false.

```<code>while counter < len(price) and found == False:
</code>```

Thus it will not enter the while loop.

Note: You don't need to use the found variable. You can print the search result inside the first if clause like this:

```<code>while counter < len(price):
if product[counter] == enterProduct and store[counter] == enterStore:
  print(f"The price for {product[counter]} in {store[counter]} are {price[counter]}")
  # or insert the counter to another list for postprocessing.
</code>```

Body:
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()

Here is the output:

Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2

which should be:

The price for Milk in Axep are:
2
10

Body:
Set the found variable to False inside the if clause.

if found == True:
  print(f"The price for {product[position]} in {store[position]} are {price[position]}")
  found = False

Explanation: After finding an element you are setting the found variable to True. But you are never setting it back to False. Thus in the subsequent iteration, the while loop's condition will evaluate to false.

while counter < len(price) and found == False:

Thus it will not enter the while loop.

Note: You don't need to use the found variable. You can print the search result inside the first if clause like this:

while counter < len(price):
if product[counter] == enterProduct and store[counter] == enterStore:
  print(f"The price for {product[counter]} in {store[counter]} are {price[counter]}")
  # or insert the counter to another list for postprocessing.


问:
How to pass a parent ViewModel @Published property to a child ViewModel @Binding using MVVM
I'm using an approach similar to the one described on mockacoding - Dependency Injection in SwiftUI where my main ViewModel has the responsibility to create child viewModels.

In the code below I am not including the Factory, as it's very similar to the contents of the post above: it creates the ParentViewModel, passes to it dependencies and closures that construct the child view models.

struct Book { ... }    // It's a struct, not a class

struct ParentView: View {
  @StateObject var viewModel: ParentViewModel

  var body: some View {
    VStack {
      if viewModel.book.bookmarked {
        BookmarkedView(viewModel: viewModel.makeBookMarkedViewModel())
      } else {
        RegularView(viewModel: viewModel.makeBookMarkedViewModel())
      }
    }
  }
}

class ParentViewModel: ObservableObject {
  @Published var book: Book

  // THIS HERE - This is how I am passing the @Published to @Binding
  // Problem is I don't know if this is correct.
  //
  // Before, I was not using @Binding at all. All where @Published
  // and I just pass the reference. But doing that would cause for
  // the UI to NEVER update. That's why I changed it to use @Binding

  private var boundBook: Binding<Book> {
    Binding(get: { self.book }, set: { self.book = $0 })
  }

  // The Factory object passes down these closures
  private let createBookmarkedVM: (_ book: Binding<Book>) -> BookmarkedViewModel
  private let createRegularVM: (_ book: Binding<Book>) -> RegularViewModel

  init(...) {...}

  func makeBookmarkedViewModel() {
    createBookmarkedVM(boundBook)
  }
}

class BookmarkedView: View {
  @StateObject var viewModel: BookmarkedViewModel

  let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

  var body: some View {
    VStack {
      Text(book.title)        // <---- THIS IS THE PROBLEM. Not being updated

      Button("Remove bookmark") {
        viewModel.removeBookmark()
      }
    }
    .onReceive(timer) { _ in
      print("adding letter")    // <-- this gets called

      withAnimation {
        viewModel.addLetterToBookTitle()
      }
    }
  }
}

class BookmarkedViewModel: ObservableObject {
  @Binding var book: Book

  // ... some other dependencies passed by the Factory object
  init(...) { ... }

  public func removeBookmark() {
    // I know a class would be better than a struct, bear with me

    book = Book(title: book.title, bookmarked: false)
  }

  /// Adds an "a" to the title
  public func addLetterToBookTitle() {
    book = Book(title: book.title + "a", bookmarked: book.bookmarked)

    print("letter added")      // <-- this gets called as well
  }
}
```

From the code above, let's take a look at BookmarkedView. If I click the button and viewModel.removeBookmark() gets called, the struct is re-assigned and ParentView now renders RegularView.

This tells me that I successfully bound @Published book: Book from ParentViewModel to @Binding book: Book from BookmarkedViewModel, through its boundBook computed property. This felt like the most weird thing I had to make.

However, the problem is that even though addLetterToBookTitle() is also re-assigning the book with a new title, and it should update the Text(book.title), it's not happening. The same title is being displayed.

I can guarantee that the book title has change (because of some other components of the app I'm omitting for simplicity), but the title's visual is not being updated.

This is the first time I'm trying out these pattern of having a view model build child view models, so I appreciate I may be missing something fundamental. What am I missing?

EDIT:

I made an MVP example here: https://github.com/christopher-francisco/TestMVVM/tree/main/MVVMTest.xcodeproj

I'm looking for whether:

My take at child viewmodels is fundamentally wrong and I should start from scratch, or

I have misunderstood @Binding and @Published attributes, or

Anything really

答:
Like I said initially @Binding does not work in a class you have to use .sink to see the changes to an ObservableObject.

See below...

```<code>class MainViewModel: ObservableObject {
    @Published var timer = YourTimer()

    let store: Store
    let nManager: NotificationManager
    let wManager: WatchConnectionManager

    private let makeNotYetStartedViewModelClosure: (_ parentVM: MainViewModel) -> NotYetStartedViewModel
    private let makeStartedViewModelClosure: (_ parentVM: MainViewModel) -> StartedViewModel

    init(
        store: Store,
        nManager: NotificationManager,
        wManager: WatchConnectionManager,

        makeNotYetStartedViewModel: @escaping (_ patentVM: MainViewModel) -> NotYetStartedViewModel,
        makeStartedViewModel: @escaping (_ patentVM: MainViewModel) -> StartedViewModel
    ) {
        self.store = store
        self.nManager = nManager
        self.wManager = wManager

        self.makeNotYetStartedViewModelClosure = makeNotYetStartedViewModel
        self.makeStartedViewModelClosure = makeStartedViewModel
    }

}

// MARK: - child View Models
extension MainViewModel {

    func makeNotYetStartedViewModel() -> NotYetStartedViewModel {
        self.makeNotYetStartedViewModelClosure(self)
    }

    func makeStartedViewModel() -> StartedViewModel {
        self.makeStartedViewModelClosure(self)
    }
}
class NotYetStartedViewModel: ObservableObject {
    var parentVM: MainViewModel

    var timer: YourTimer{
        get{
            parentVM.timer
        }
        set{
            parentVM.timer = newValue
        }
    }

    var cancellable: AnyCancellable? = nil
    init(parentVM: MainViewModel) {
        self.parentVM = parentVM
        //Subscribe to the parent
        cancellable = parentVM.objectWillChange.sink(receiveValue: { [self] _ in
            //Trigger reload
            objectWillChange.send()
        })
    }

    func start() {
        // I'll make this into a class later on
        timer = YourTimer(remainingSeconds: timer.remainingSeconds, started: true)
    }
}
class StartedViewModel: ObservableObject {
    var parentVM: MainViewModel
    var timer: YourTimer{
        get{
            parentVM.timer
        }
        set{
            parentVM.timer = newValue
        }
    }

    var cancellable: AnyCancellable? = nil

    init(parentVM: MainViewModel) {
        self.parentVM = parentVM
        cancellable = parentVM.objectWillChange.sink(receiveValue: { [self] _ in
            //trigger reload
            objectWillChange.send()
        })
    }

    func tick() {
        // I'll make this into a class later on
        timer = YourTimer(remainingSeconds: timer.remainingSeconds - 1, started: timer.started)
    }

    func cancel() {
        timer = YourTimer()
    }
}
</code>```

But this is an overcomplicated setup, stick to class or struct. Also, maintain a single source of truth. That is basically the center of how SwiftUI works everything should be getting its value from a single source.

Body:
I'm using an approach similar to the one described on mockacoding - Dependency Injection in SwiftUI where my main ViewModel has the responsibility to create child viewModels.

In the code below I am not including the Factory, as it's very similar to the contents of the post above: it creates the ParentViewModel, passes to it dependencies and closures that construct the child view models.

struct Book { ... }    // It's a struct, not a class

struct ParentView: View {
  @StateObject var viewModel: ParentViewModel

  var body: some View {
    VStack {
      if viewModel.book.bookmarked {
        BookmarkedView(viewModel: viewModel.makeBookMarkedViewModel())
      } else {
        RegularView(viewModel: viewModel.makeBookMarkedViewModel())
      }
    }
  }
}

class ParentViewModel: ObservableObject {
  @Published var book: Book

  // THIS HERE - This is how I am passing the @Published to @Binding
  // Problem is I don't know if this is correct.
  //
  // Before, I was not using @Binding at all. All where @Published
  // and I just pass the reference. But doing that would cause for
  // the UI to NEVER update. That's why I changed it to use @Binding

  private var boundBook: Binding<Book> {
    Binding(get: { self.book }, set: { self.book = $0 })
  }

  // The Factory object passes down these closures
  private let createBookmarkedVM: (_ book: Binding<Book>) -> BookmarkedViewModel
  private let createRegularVM: (_ book: Binding<Book>) -> RegularViewModel

  init(...) {...}

  func makeBookmarkedViewModel() {
    createBookmarkedVM(boundBook)
  }
}

class BookmarkedView: View {
  @StateObject var viewModel: BookmarkedViewModel

  let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

  var body: some View {
    VStack {
      Text(book.title)        // <---- THIS IS THE PROBLEM. Not being updated

      Button("Remove bookmark") {
        viewModel.removeBookmark()
      }
    }
    .onReceive(timer) { _ in
      print("adding letter")    // <-- this gets called

      withAnimation {
        viewModel.addLetterToBookTitle()
      }
    }
  }
}

class BookmarkedViewModel: ObservableObject {
  @Binding var book: Book

  // ... some other dependencies passed by the Factory object
  init(...) { ... }

  public func removeBookmark() {
    // I know a class would be better than a struct, bear with me

    book = Book(title: book.title, bookmarked: false)
  }

  /// Adds an "a" to the title
  public func addLetterToBookTitle() {
    book = Book(title: book.title + "a", bookmarked: book.bookmarked)

    print("letter added")      // <-- this gets called as well
  }
}

From the code above, let's take a look at BookmarkedView. If I click the button and viewModel.removeBookmark() gets called, the struct is re-assigned and ParentView now renders RegularView.

This tells me that I successfully bound @Published book: Book from ParentViewModel to @Binding book: Book from BookmarkedViewModel, through its boundBook computed property. This felt like the most weird thing I had to make.

However, the problem is that even though addLetterToBookTitle() is also re-assigning the book with a new title, and it should update the Text(book.title), it's not happening. The same title is being displayed.

I can guarantee that the book title has change (because of some other components of the app I'm omitting for simplicity), but the title's visual is not being updated.

This is the first time I'm trying out these pattern of having a view model build child view models, so I appreciate I may be missing something fundamental. What am I missing?

EDIT:

I made an MVP example here: https://github.com/christopher-francisco/TestMVVM/tree/main/MVVMTest.xcodeproj

I'm looking for whether:

My take at child viewmodels is fundamentally wrong and I should start from scratch, or

I have misunderstood @Binding and @Published attributes, or

Anything really

Body:
Like I said initially @Binding does not work in a class you have to use .sink to see the changes to an ObservableObject.

See below...

class MainViewModel: ObservableObject {
    @Published var timer = YourTimer()

    let store: Store
    let nManager: NotificationManager
    let wManager: WatchConnectionManager

    private let makeNotYetStartedViewModelClosure: (_ parentVM: MainViewModel) -> NotYetStartedViewModel
    private let makeStartedViewModelClosure: (_ parentVM: MainViewModel) -> StartedViewModel

    init(
        store: Store,
        nManager: NotificationManager,
        wManager: WatchConnectionManager,

        makeNotYetStartedViewModel: @escaping (_ patentVM: MainViewModel) -> NotYetStartedViewModel,
        makeStartedViewModel: @escaping (_ patentVM: MainViewModel) -> StartedViewModel
    ) {
        self.store = store
        self.nManager = nManager
        self.wManager = wManager

        self.makeNotYetStartedViewModelClosure = makeNotYetStartedViewModel
        self.makeStartedViewModelClosure = makeStartedViewModel
    }

}

// MARK: - child View Models
extension MainViewModel {

    func makeNotYetStartedViewModel() -> NotYetStartedViewModel {
        self.makeNotYetStartedViewModelClosure(self)
    }

    func makeStartedViewModel() -> StartedViewModel {
        self.makeStartedViewModelClosure(self)
    }
}
class NotYetStartedViewModel: ObservableObject {
    var parentVM: MainViewModel

    var timer: YourTimer{
        get{
            parentVM.timer
        }
        set{
            parentVM.timer = newValue
        }
    }

    var cancellable: AnyCancellable? = nil
    init(parentVM: MainViewModel) {
        self.parentVM = parentVM
        //Subscribe to the parent
        cancellable = parentVM.objectWillChange.sink(receiveValue: { [self] _ in
            //Trigger reload
            objectWillChange.send()
        })
    }

    func start() {
        // I'll make this into a class later on
        timer = YourTimer(remainingSeconds: timer.remainingSeconds, started: true)
    }
}
class StartedViewModel: ObservableObject {
    var parentVM: MainViewModel
    var timer: YourTimer{
        get{
            parentVM.timer
        }
        set{
            parentVM.timer = newValue
        }
    }

    var cancellable: AnyCancellable? = nil

    init(parentVM: MainViewModel) {
        self.parentVM = parentVM
        cancellable = parentVM.objectWillChange.sink(receiveValue: { [self] _ in
            //trigger reload
            objectWillChange.send()
        })
    }

    func tick() {
        // I'll make this into a class later on
        timer = YourTimer(remainingSeconds: timer.remainingSeconds - 1, started: timer.started)
    }

    func cancel() {
        timer = YourTimer()
    }
}

But this is an overcomplicated setup, stick to class or struct. Also, maintain a single source of truth. That is basically the center of how SwiftUI works everything should be getting its value from a single source.


问:
avr-gcc calculation results varies with statement complexity
So i have this line of  C code that takes 10-bit ADC value on the ATmega2560 and scales it to be used later by counters. results should be between 44 and 4166 or something like that

```<code>uint16_t tcnt = (60 * 16000000)/((100 + adc_latest * 9) * 64 * 36);
</code>```

I compiled with avr-gcc and send the value of  tcnt to the serial to check it .. it was way outside the expected range

after checking my math and parenthesis multiple times i thought i would simplify and re-write it as follow

```<code>uint16_t tcnt = (416667) / (100 + adc_latest *9);
</code>```

this time i got the expected values

can anyone explain this behavior ? is this because there is a very large intermediate value involved ?

答:
I'm guessing you're working on a 16-bit processor, and that you've been bitten by integer overflow.

I'm guessing adc_latest is an int (16 bits), or perhaps a uint16_t.

And the constants 100, 9, 64, and 36 are all small enough to be represented as 16-bit int.  So the subexpression

```<code>(100 + adc_latest * 9) * 64 * 36
</code>```

will all be computed using 16-bit arithmetic.

Suppose adc_latest is 9000.  Then (100 + adc_latest * 9) * 64 * 36 is 20966400 — but that's not a number you can represent in 16 bits.  So it'll overflow, with undesired and perhaps undefined results.

In the numerator, though, the constant 16000000 is already too big to be represented in 16 bits, so the compiler will implicitly treat it as a long int.

When you rewrote it as

```<code>416667 / (100 + adc_latest * 9)
</code>```

you eliminated the overflow in the denominator, so everything worked.

If my suppositions here are correct, another fix would be

```<code>(60 * 16000000) / ((100 + adc_latest * 9L) * 64 * 36)
</code>```

The simple change of 9 to 9L will force everything in the denominator to be computed using long arithmetic also, eliminating overflow there and (I predict) resulting in a correct overall result.

This is all a consequence of the way expressions are evaluated "bottom up" in C.  Subexpressions get promoted to a larger, common type only when they have to be.  So in your original expression, you ended up with

```<code>long / int
</code>```

At that point, the int in the denominator got promoted to long — but by then it was too late; the overflow had already occurred.  The compiler did not notice that since the denominator was eventually going to be promoted to long, it might as well evaluate the whole denominator as a long.  It did not evaluate the whole denominator as a long, so overflow in the denominator occurred.

Addendum: I wrote, "When you rewrote it... you eliminated the overflow in the denominator", but that was an oversimplification.  The example I gave, with adc_latest = 9000, works out to 81900, which is still an overflow.  So that rewrite would work for most (but not all) values of adc_latest, those up to 7180 or so.  So the other rewrite, forcing the entire denominator to be evaluated in 32 bits, is preferable.

There's probably some other way of rearranging the expression so that you could evaluate the whole thing using 16-bit arithmetic, if for some reason you wanted to avoid 32-bit arithmetic, but I'm not going to try to work it out just now.

Body:
So i have this line of  C code that takes 10-bit ADC value on the ATmega2560 and scales it to be used later by counters. results should be between 44 and 4166 or something like that

uint16_t tcnt = (60 * 16000000)/((100 + adc_latest * 9) * 64 * 36);

I compiled with avr-gcc and send the value of  tcnt to the serial to check it .. it was way outside the expected range

after checking my math and parenthesis multiple times i thought i would simplify and re-write it as follow

uint16_t tcnt = (416667) / (100 + adc_latest *9);

this time i got the expected values

can anyone explain this behavior ? is this because there is a very large intermediate value involved ?

Body:
I'm guessing you're working on a 16-bit processor, and that you've been bitten by integer overflow.

I'm guessing adc_latest is an int (16 bits), or perhaps a uint16_t.

And the constants 100, 9, 64, and 36 are all small enough to be represented as 16-bit int.  So the subexpression

(100 + adc_latest * 9) * 64 * 36

will all be computed using 16-bit arithmetic.

Suppose adc_latest is 9000.  Then (100 + adc_latest * 9) * 64 * 36 is 20966400 — but that's not a number you can represent in 16 bits.  So it'll overflow, with undesired and perhaps undefined results.

In the numerator, though, the constant 16000000 is already too big to be represented in 16 bits, so the compiler will implicitly treat it as a long int.

When you rewrote it as

416667 / (100 + adc_latest * 9)

you eliminated the overflow in the denominator, so everything worked.

If my suppositions here are correct, another fix would be

(60 * 16000000) / ((100 + adc_latest * 9L) * 64 * 36)

The simple change of 9 to 9L will force everything in the denominator to be computed using long arithmetic also, eliminating overflow there and (I predict) resulting in a correct overall result.

This is all a consequence of the way expressions are evaluated "bottom up" in C.  Subexpressions get promoted to a larger, common type only when they have to be.  So in your original expression, you ended up with

long / int

At that point, the int in the denominator got promoted to long — but by then it was too late; the overflow had already occurred.  The compiler did not notice that since the denominator was eventually going to be promoted to long, it might as well evaluate the whole denominator as a long.  It did not evaluate the whole denominator as a long, so overflow in the denominator occurred.

Addendum: I wrote, "When you rewrote it... you eliminated the overflow in the denominator", but that was an oversimplification.  The example I gave, with adc_latest = 9000, works out to 81900, which is still an overflow.  So that rewrite would work for most (but not all) values of adc_latest, those up to 7180 or so.  So the other rewrite, forcing the entire denominator to be evaluated in 32 bits, is preferable.

There's probably some other way of rearranging the expression so that you could evaluate the whole thing using 16-bit arithmetic, if for some reason you wanted to avoid 32-bit arithmetic, but I'm not going to try to work it out just now.


问:
Only run task if another isn't UP-TO-DATE in gradle
I want to automatically add a serverRun task when doing functional tests in Gradle, so I add a dependency :

```<code>funcTestTask.dependsOn(serverRun)
</code>```

Which results in the task running whether or not the funcTestTask even runs

```<code>:compile
:serverRun
:funcTestTask (and associate compile tasks... etc)
:serverStop

OR

:compile UP-TO-DATE
:serverRun <-- unnecessary
:funcTestTask UP-TO-DATE
:serverStop
</code>```

The cost of starting the server is pretty high and I only want it to start if the functionalTest isn't UP-TO-DATE, I'd like to do or something :

```<code>if(!funcTestTask.isUpToDate) {
    funcTestTask.dependsOn(serverRun)
}
</code>```

So I know I can't know the up-to-date status of funcTestTask until all it's inputs/outputs are decided BUT can I inherit it's uptoDate checker?

```<code>serverRun.outputs.upToDateWhen(funcTestTask.upToDate)
</code>```

The alternative is to "doFirst" the ServerRun in the FuncTest, which I believe is generally frowned upon?

```<code>funcTestTask.doFirst { serverRun.execute() }
</code>```

Is there a way to conditionally run a task before another?

UPDATE 1

Tried settings inputs/outputs the same

```<code>serverRun.inputs.files(funcTestTask.inputs.files)
serverRun.outputs.files(funcTestTask.outputs.files)
</code>```

and this seems to rerun the server on recompiles (good), skips reruns after successful unchanged functional tests (also good), but wont rerun tests after a failed test like the following

```<code>:compile
:serverRun
:funcTestTask FAILED

then

:compile UP-TO-DATE
:serverRun UP-TO-DATE <-- wrong!
:funcTestTask FAILED
</code>```

答:
Assuming you have task1 and task2 which depends on task1 and you need to run task2 only if task1 is not up-to-date, the following example may be used:

```<code>task task1 {
  // task1 definition
}

task task2(dependsOn: task1) {
  onlyIf { task1.didWork }
}
</code>```

In this case task2 will run only when task1 is not up-to-date. It's important to use didWork only for tasks which are defined in dependsOn, in order to ensure that didWork is evaluated after that task (task1 in our example) had chance to run.

Body:
I want to automatically add a serverRun task when doing functional tests in Gradle, so I add a dependency :

funcTestTask.dependsOn(serverRun)

Which results in the task running whether or not the funcTestTask even runs

:compile
:serverRun
:funcTestTask (and associate compile tasks... etc)
:serverStop

OR

:compile UP-TO-DATE
:serverRun <-- unnecessary
:funcTestTask UP-TO-DATE
:serverStop

The cost of starting the server is pretty high and I only want it to start if the functionalTest isn't UP-TO-DATE, I'd like to do or something :

if(!funcTestTask.isUpToDate) {
    funcTestTask.dependsOn(serverRun)
}

So I know I can't know the up-to-date status of funcTestTask until all it's inputs/outputs are decided BUT can I inherit it's uptoDate checker?

serverRun.outputs.upToDateWhen(funcTestTask.upToDate)

The alternative is to "doFirst" the ServerRun in the FuncTest, which I believe is generally frowned upon?

funcTestTask.doFirst { serverRun.execute() }

Is there a way to conditionally run a task before another?

UPDATE 1

Tried settings inputs/outputs the same

serverRun.inputs.files(funcTestTask.inputs.files)
serverRun.outputs.files(funcTestTask.outputs.files)

and this seems to rerun the server on recompiles (good), skips reruns after successful unchanged functional tests (also good), but wont rerun tests after a failed test like the following

:compile
:serverRun
:funcTestTask FAILED

then

:compile UP-TO-DATE
:serverRun UP-TO-DATE <-- wrong!
:funcTestTask FAILED

Body:
Assuming you have task1 and task2 which depends on task1 and you need to run task2 only if task1 is not up-to-date, the following example may be used:

task task1 {
  // task1 definition
}

task task2(dependsOn: task1) {
  onlyIf { task1.didWork }
}

In this case task2 will run only when task1 is not up-to-date. It's important to use didWork only for tasks which are defined in dependsOn, in order to ensure that didWork is evaluated after that task (task1 in our example) had chance to run.


问:
How can I check if site is inside iframe in symfony?
Is it possible to check if a site is inside an iframe with symfony?
I do not want do it via JavaScript.</p>

答: Check the Symfony request for the Sec-Fetch-Site header.  That will indicate that it's in an iframe.</p>


问:
Why connection is not establishing on first time?
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me. </p>

```<code>HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();

if (respCode != HttpsURLConnection.HTTP_OK)
{
  throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
 else {
//read the content from server
}
</code>```

答:
1/ It is recommanded to use apache HttpClient rather than URLConnection (see http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html)

2/ for login and password, why not use Http Authentication ? both basic and digest are supported by android.

3/ as for you problem, you don't close the underlying outputStream.

you should do:

```<code>OutputStream os = con.getOutputStream();
DataOutputStream output = new DataOutputStream(os);
output.writeBytes(query);
output.close();
os.close();
</code>```

Body:
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me.

HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();

if (respCode != HttpsURLConnection.HTTP_OK)
{
  throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
 else {
//read the content from server
}

Body:
1/ It is recommanded to use apache HttpClient rather than URLConnection (see http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html)

2/ for login and password, why not use Http Authentication ? both basic and digest are supported by android.

3/ as for you problem, you don't close the underlying outputStream.

you should do:

OutputStream os = con.getOutputStream();
DataOutputStream output = new DataOutputStream(os);
output.writeBytes(query);
output.close();
os.close();


问:
Generate a unique list of pairs from a set of values that does not match previous n pairings
I'm working in python for this problem.

Given a list of values that can increase or decrease in size between iterations (it will be padded to always be even)

```<code>users = [1,2,3,4,5,6,7,8]
</code>```

Create a new random set of pairings for the users (order does not matter)

```<code>pairs_2 = [[2,5],[4,6],[3,8],[1,7]]
</code>```

and ensure that the pairing does not overlap with the previous n sets of pairs

```<code>pairs_1 = [[7,10],[3,5],[1,6],[2,8],[4,9]]
pairs_0 = [[2,4],[3,6],[1,5]]
</code>```

My current implementation just involves generating a random set of pairs and then doing a set intersection against the previous n pairings to see if it is unique or not, this obviously does not scale well nor guarantee a solution in any reasonable time.

I've also tried to instead generate all possible combinations of pairs, and then find the difference between that and all previous pairings, but then there is the problem of selecting exactly users/2 pairs from the list that contains all users. It feels like the first half of this solution is good as it guarantees only new pairs, but then requires some additional logic to select the pairs.

答:
```<code>import random
myList = [[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8]]
oldList = []

for e in range(0,len(myList)):
    oldList.append([])
    for d in range(0,len(myList[e]),2):
       while True:
           f = False
           a = random.choice(myList[e])
           myList[e].remove(a)
           #print(myList,e)
           b = random.choice(myList[e])
           myList[e].remove(b)
           #print(myList,e)
           for c in oldList:
               if [a,b] in c:
                   myList[e].append(a)
                   myList[e].append(b)
                   #print("Runned")
                   f = True
           if f:
               f = False
               continue
           oldList[e].append([a,b])
           break
print(oldList)
</code>```

All the result will be in oldList , It depend on which one you put in first

On your example , you should put in

```<code>myList = [[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8]]
</code>```

And the result will be:

```<code>[[[6, 3], [5, 4], [2, 1]], [[5, 2], [10, 8], [3, 4], [1, 9], [7, 6]], [[6, 1], [8, 5], [7, 3], [4, 2]]]
</code>```

And to get different pair out according to your example

```<code>pair_0 = oldList[0]
pair_1 = oldList[1]
pair_2 = oldList[2]
</code>```

and the result will be

```<code>pair_0 = [[6, 3], [5, 4], [2, 1]]
pair_1 = [[5, 2], [10, 8], [3, 4], [1, 9], [7, 6]]
pair_2 = [[6, 1], [8, 5], [7, 3], [4, 2]]
</code>```

Body:
I'm working in python for this problem.

Given a list of values that can increase or decrease in size between iterations (it will be padded to always be even)

users = [1,2,3,4,5,6,7,8]

Create a new random set of pairings for the users (order does not matter)

pairs_2 = [[2,5],[4,6],[3,8],[1,7]]

and ensure that the pairing does not overlap with the previous n sets of pairs

pairs_1 = [[7,10],[3,5],[1,6],[2,8],[4,9]]
pairs_0 = [[2,4],[3,6],[1,5]]

My current implementation just involves generating a random set of pairs and then doing a set intersection against the previous n pairings to see if it is unique or not, this obviously does not scale well nor guarantee a solution in any reasonable time.

I've also tried to instead generate all possible combinations of pairs, and then find the difference between that and all previous pairings, but then there is the problem of selecting exactly users/2 pairs from the list that contains all users. It feels like the first half of this solution is good as it guarantees only new pairs, but then requires some additional logic to select the pairs.

Body:
import random
myList = [[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8]]
oldList = []

for e in range(0,len(myList)):
    oldList.append([])
    for d in range(0,len(myList[e]),2):
       while True:
           f = False
           a = random.choice(myList[e])
           myList[e].remove(a)
           #print(myList,e)
           b = random.choice(myList[e])
           myList[e].remove(b)
           #print(myList,e)
           for c in oldList:
               if [a,b] in c:
                   myList[e].append(a)
                   myList[e].append(b)
                   #print("Runned")
                   f = True
           if f:
               f = False
               continue
           oldList[e].append([a,b])
           break
print(oldList)

All the result will be in oldList , It depend on which one you put in first

On your example , you should put in

myList = [[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8]]

And the result will be:

[[[6, 3], [5, 4], [2, 1]], [[5, 2], [10, 8], [3, 4], [1, 9], [7, 6]], [[6, 1], [8, 5], [7, 3], [4, 2]]]

And to get different pair out according to your example

pair_0 = oldList[0]
pair_1 = oldList[1]
pair_2 = oldList[2]

and the result will be

pair_0 = [[6, 3], [5, 4], [2, 1]]
pair_1 = [[5, 2], [10, 8], [3, 4], [1, 9], [7, 6]]
pair_2 = [[6, 1], [8, 5], [7, 3], [4, 2]]


问:
Why can't I deselect some packages in Buildroot, marked with -*-?
When I navigate through the Buildroot setup with make menuconfig (I'm using version 2021.11.x) I see some options that are marked -*- and cannot be deselected.

For example, under Target Packages -> Networking applications, cups is marked -*- but I would like to deselect it.

I tried editing the .config manually (probably not advisable?). Even after commenting out BR2_PACKAGE_CUPS=y it still shows cups marked -*- in menuconfig

I feel like I'm missing something obvious here.

答:
As mentioned in the comment to my question

That means that the option is a required dependency of some other option that you have selected. I think that if you press 'H' with the cursor on the option, it will tell you what that other option is.

H shows all the info you need about a package and showed me which package depends on cups. In my case, since I manually selected openjdk, cups was autoselected (and could not be deselected) because openjdk depends on cups.


问:
ContentStringFormat never changes by Setter Property in DataTrigger
In my user control I want to have label displaying Text from resource depending on viewmodel property Location value and with different format.
I implemented it by defining DataTrigger for each Location value

</Style>

```
<p>The problem is that format never changes from the first one (???) - HomeViewModel selected first - although text changing works.</p>
<p>I have</p>
```Home???
First???
Second???
Third???
```
<p>instead of</p>
```Home???
First+++
Second---
Third***
```

答:
There are a lot of discussions, using Labels and ContentStringFormat does not work like expected or desired:

WPF StringFormat on Label Content

StringFormat VS ContentStringFormat

...

The reason seems to be the template based implementation under the hood, since the content also could contain other data than strings. To solve your problem, my proposal is to use a TextBlock, which works quite smooth like this:

```<code><StackPanel>
    <CheckBox IsChecked="{Binding MyFlag}"/>
    <TextBlock HorizontalAlignment="Center" FontSize="40">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyFlag}" Value="False">
                        <Setter Property="Text" Value="{Binding Path=MyText, StringFormat='{}{0}+++'}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding MyFlag}" Value="True">
                        <Setter Property="Text" Value="{Binding Path=MyText, StringFormat='{}{0}???'}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</StackPanel>
</code>```

Body:
In my user control I want to have label displaying Text from resource depending on viewmodel property Location value and with different format.
I implemented it by defining DataTrigger for each Location value

</Style>

The problem is that format never changes from the first one (???) - HomeViewModel selected first - although text changing works.

I have

Home???
First???
Second???
Third???

instead of

Home???
First+++
Second---
Third***

Body:
There are a lot of discussions, using Labels and ContentStringFormat does not work like expected or desired:

WPF StringFormat on Label Content

StringFormat VS ContentStringFormat

...

The reason seems to be the template based implementation under the hood, since the content also could contain other data than strings. To solve your problem, my proposal is to use a TextBlock, which works quite smooth like this:

<StackPanel>
    <CheckBox IsChecked="{Binding MyFlag}"/>
    <TextBlock HorizontalAlignment="Center" FontSize="40">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyFlag}" Value="False">
                        <Setter Property="Text" Value="{Binding Path=MyText, StringFormat='{}{0}+++'}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding MyFlag}" Value="True">
                        <Setter Property="Text" Value="{Binding Path=MyText, StringFormat='{}{0}???'}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</StackPanel>


问:
Cannot find ROW_NUMBER() function in mysql 8.0.17?
I setup my web service by using package AppServ : Apache + PHP + MySQL, which is download from
https://www.appserv.org/en/

Mysql version is 8.0.17, and phpMyAdmin is 4.9.1

When I tried to use ROW_NUMBER() function inside phpMyAdmin, it always told me some errors.
Eventurally, I feel my Mysql might not include this function.

Is it possible? and how to verify it (mysql hasn't row_number()) and how to solve it?

答:
row is a reserved word in mysql 8.0.2+ according to the documentation.

This should work:

```<code>SELECT custid,
email,
ROW_NUMBER() OVER ( PARTITION BY email ORDER BY email ) AS `row`
FROM customers;
</code>```

Or you can ditch row for something non-problematic such as AS rn.

Notice that partitioning by email and ordering by it at the same time doesn't make much sense.

Fiddle

Body:
row is a reserved word in mysql 8.0.2+ according to the documentation.

This should work:

SELECT custid,
email,
ROW_NUMBER() OVER ( PARTITION BY email ORDER BY email ) AS `row`
FROM customers;

Or you can ditch row for something non-problematic such as AS rn.

Notice that partitioning by email and ordering by it at the same time doesn't make much sense.

Fiddle


问:
Can a snakemake rule depend on data in the file instead of its change state
I have data in a CSV file that frequently changes. The CSV file is a source for a snakefile rule. My issue is that I want this rule to run only when a certain value appears in the data of the CSV file and not every time when the file changes. Is it possible to let rule execution depend on specific patterns in the file that has changed and not on the fact that it changed?</p>

答:
An option could be to always run the conditional rule but running it in "dummy" mode if the value in your CSV is present. In mostly pseudocode:

```<code>rule run_if:
    input:
        'data.csv',
    output:
        'done.out',
    run:
        if 'some_value' is in data.csv:
            do stuff and write 'done.out'
        else:
            # Only update the file
            touch('done.out')
</code>```

It depends what happens after done.out is created/updated though.

In general, it is better to think of snakemake in terms of a chain of input/output files rather than in terms of which rules you want to run.

Body:
An option could be to always run the conditional rule but running it in "dummy" mode if the value in your CSV is present. In mostly pseudocode:

rule run_if:
    input:
        'data.csv',
    output:
        'done.out',
    run:
        if 'some_value' is in data.csv:
            do stuff and write 'done.out'
        else:
            # Only update the file
            touch('done.out')

It depends what happens after done.out is created/updated though.

In general, it is better to think of snakemake in terms of a chain of input/output files rather than in terms of which rules you want to run.


问:
Given a latitude and longitude, and distance, I want to find a bounding box
Given a latitude and longitude, and  distance, I want to find a bounding box where the distances are less than the given distance.

This questions was asked here: How to calculate the bounding box for a given lat/lng location?

I donot want this partcularly accurate, so I have modified and simplified it to

```<code>def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
    lat = math.radians(latitudeInDegrees)
    lon = math.radians(longitudeInDegrees)
    halfSide = 1000*halfSideInKm

    RADIUS_OF_EARTH  = 6371
    # Radius of the parallel at given latitude
    pradius = radius*math.cos(lat)

    latMin = lat - halfSide/radius
    latMax = lat + halfSide/radius
    lonMin = lon - halfSide/pradius
    lonMax = lon + halfSide/pradius
    rad2deg = math.degrees
    return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))
</code>```

But I cant understand how this is working, in particular this line makes no sense to me halfSide = 1000*halfSideInKm

答:
This code didn't quite work, it jumps between KM and M.

Fixed code, made names more PEP8 style, and added a simple box object:

```<code>class BoundingBox(object):
    def __init__(self, *args, **kwargs):
        self.lat_min = None
        self.lon_min = None
        self.lat_max = None
        self.lon_max = None

def get_bounding_box(latitude_in_degrees, longitude_in_degrees, half_side_in_miles):
    assert half_side_in_miles > 0
    assert latitude_in_degrees >= -90.0 and latitude_in_degrees  <= 90.0
    assert longitude_in_degrees >= -180.0 and longitude_in_degrees <= 180.0

    half_side_in_km = half_side_in_miles * 1.609344
    lat = math.radians(latitude_in_degrees)
    lon = math.radians(longitude_in_degrees)

    radius  = 6371
    # Radius of the parallel at given latitude
    parallel_radius = radius*math.cos(lat)

    lat_min = lat - half_side_in_km/radius
    lat_max = lat + half_side_in_km/radius
    lon_min = lon - half_side_in_km/parallel_radius
    lon_max = lon + half_side_in_km/parallel_radius
    rad2deg = math.degrees

    box = BoundingBox()
    box.lat_min = rad2deg(lat_min)
    box.lon_min = rad2deg(lon_min)
    box.lat_max = rad2deg(lat_max)
    box.lon_max = rad2deg(lon_max)

    return (box)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Given a latitude and longitude, and  distance, I want to find a bounding box where the distances are less than the given distance.

This questions was asked here: How to calculate the bounding box for a given lat/lng location?

I donot want this partcularly accurate, so I have modified and simplified it to

def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
    lat = math.radians(latitudeInDegrees)
    lon = math.radians(longitudeInDegrees)
    halfSide = 1000*halfSideInKm

    RADIUS_OF_EARTH  = 6371
    # Radius of the parallel at given latitude
    pradius = radius*math.cos(lat)

    latMin = lat - halfSide/radius
    latMax = lat + halfSide/radius
    lonMin = lon - halfSide/pradius
    lonMax = lon + halfSide/pradius
    rad2deg = math.degrees
    return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))

But I cant understand how this is working, in particular this line makes no sense to me halfSide = 1000*halfSideInKm

Body:
This code didn't quite work, it jumps between KM and M.

Fixed code, made names more PEP8 style, and added a simple box object:

class BoundingBox(object):
    def __init__(self, *args, **kwargs):
        self.lat_min = None
        self.lon_min = None
        self.lat_max = None
        self.lon_max = None

def get_bounding_box(latitude_in_degrees, longitude_in_degrees, half_side_in_miles):
    assert half_side_in_miles > 0
    assert latitude_in_degrees >= -90.0 and latitude_in_degrees  <= 90.0
    assert longitude_in_degrees >= -180.0 and longitude_in_degrees <= 180.0

    half_side_in_km = half_side_in_miles * 1.609344
    lat = math.radians(latitude_in_degrees)
    lon = math.radians(longitude_in_degrees)

    radius  = 6371
    # Radius of the parallel at given latitude
    parallel_radius = radius*math.cos(lat)

    lat_min = lat - half_side_in_km/radius
    lat_max = lat + half_side_in_km/radius
    lon_min = lon - half_side_in_km/parallel_radius
    lon_max = lon + half_side_in_km/parallel_radius
    rad2deg = math.degrees

    box = BoundingBox()
    box.lat_min = rad2deg(lat_min)
    box.lon_min = rad2deg(lon_min)
    box.lat_max = rad2deg(lat_max)
    box.lon_max = rad2deg(lon_max)

    return (box)


问:
How to remove flex in CSS
I am facing a problem in the alignment of two created grids in HTML.
I created Grids using bootstrap.
Below is the code for the

<!DOCTYPE html>

  <title>IRIS Flower Classification</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

        IRIS Flower Classification

        <form action="{{url_for('predict') }}" method=post>
            Sepal length:
            <input type="number" id="sepal_length" name="sepal_length" step=".1" value="">

            Sepal width:
            <input type="number" id="sepal width" name="sepal width" step=".1" value="">

            Petal length:
            <input type="number" id="Petal length" name="petal length" step=".1" value="">

            Petal width:
            <input type="number" id="Petal width" name="Petal width" step=".1" value="">

            <input type="submit" value="Predict">
        </form>

            Sample test data

                Species
                Sepal length
                Sepal width
                Petal length
                Petal width

                Setosa
                5.4
                3.9
                1.7
                0.4

                Versicolor
                6.2
                2.2
                4.5
                1.5

                Virginica
                5.7
                2.5
                5
                2

```

I am getting output as belowflex image

it is difficult for me to align both columns.
Can anyone tell me how can we create a column of a particular pixel in HTML?
Can anyone tell me how to remove flex?

答:
You can use grid system of bootstrap

<!DOCTYPE html>

  <title>IRIS Flower Classification</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

        IRIS Flower Classification

        <form action="{{url_for('predict') }}" method=post class="row">
            Sepal length:
            <input type="number" id="sepal_length" name="sepal_length" step=".1" value="" class="col-6 pull-right">

            Sepal width:
            <input type="number" id="sepal width" name="sepal width" step=".1" value="" class="col-6 pull-right">

            Petal length:
            <input type="number" id="Petal length" name="petal length" step=".1" value="" class="col-6 pull-right">

            Petal width:
            <input type="number" id="Petal width" name="Petal width" step=".1" value="" class="col-6 pull-right">

            <input type="submit" value="Predict">
        </form>

            Sample test data

                Species
                Sepal length
                Sepal width
                Petal length
                Petal width

                Setosa
                5.4
                3.9
                1.7
                0.4

                Versicolor
                6.2
                2.2
                4.5
                1.5

                Virginica
                5.7
                2.5
                5
                2

```

Title: How to remove flex in CSS

Body:
I am facing a problem in the alignment of two created grids in HTML.
I created Grids using bootstrap.
Below is the code for the

<!DOCTYPE html>

  <title>IRIS Flower Classification</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

        IRIS Flower Classification

        <form action="{{url_for('predict') }}" method=post>
            Sepal length:
            <input type="number" id="sepal_length" name="sepal_length" step=".1" value="">

            Sepal width:
            <input type="number" id="sepal width" name="sepal width" step=".1" value="">

            Petal length:
            <input type="number" id="Petal length" name="petal length" step=".1" value="">

            Petal width:
            <input type="number" id="Petal width" name="Petal width" step=".1" value="">

            <input type="submit" value="Predict">
        </form>

            Sample test data

                Species
                Sepal length
                Sepal width
                Petal length
                Petal width

                Setosa
                5.4
                3.9
                1.7
                0.4

                Versicolor
                6.2
                2.2
                4.5
                1.5

                Virginica
                5.7
                2.5
                5
                2

I am getting output as belowflex image

it is difficult for me to align both columns.
Can anyone tell me how can we create a column of a particular pixel in HTML?
Can anyone tell me how to remove flex?

Body:
You can use grid system of bootstrap

<!DOCTYPE html>
<html lang="en">
<head>
  <title>IRIS Flower Classification</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>

 <h2 class="heading text-center">
        IRIS Flower Classification
 </h2>

<div class="container-fluid">
  <div class="row">
    <div class="col-6">
        <form action="{{url_for('predict') }}" method=post class="row">
            <label type="text" for="Sepal_length" class="col-6">Sepal length:</label>
            <input type="number" id="sepal_length" name="sepal_length" step=".1" value="" class="col-6 pull-right"><br>
            <label type="text" for="Sepal width" class="col-6">Sepal width:</label>
            <input type="number" id="sepal width" name="sepal width" step=".1" value="" class="col-6 pull-right"><br>
            <label type="text" for="Petal length" class="col-6">Petal length:</label>
            <input type="number" id="Petal length" name="petal length" step=".1" value="" class="col-6 pull-right"><br>
            <label type="text" for="Petal width" class="col-6">Petal width:</label>
            <input type="number" id="Petal width" name="Petal width" step=".1" value="" class="col-6 pull-right"><br>
            <input type="submit" value="Predict">
        </form>
    </div>
    <div class="col-6">
        <h2 class="testdata">
            Sample test data
        </h2>
        <table class="table">
            <tr>
                <th>Species</th>
                <th>Sepal length</th>
                <th>Sepal width</th>
                <th>Petal length</th>
                <th>Petal width</th>
            </tr>
            <tr>
                <td>Setosa</td>
                <td>5.4</td>
                <td>3.9</td>
                <td>1.7</td>
                <td>0.4</td>
            </tr>
            <tr>
                <td>Versicolor</td>
                <td>6.2</td>
                <td>2.2</td>
                <td>4.5</td>
                <td>1.5</td>
            </tr>
            <tr>
                <td>Virginica</td>
                <td>5.7</td>
                <td>2.5</td>
                <td>5</td>
                <td>2</td>
            </tr>
        </table>
    </div>
  </div>
</div>

 <br>
    <div class="output">
        <img height="241px" width="203px" src="/static/img/{{ prediction_answer }}.png" alt="No Prediction">
    </div>
</body>
</html>