问:
JAVA_HOME is set to an invalid directory using Cygwin
I'm trying to build an android app using cordova, and I need the sdkmanager to set the permission. Also, I had to install Cygwin because it was need to use SDKman.

This is what I get in the terminal:

```<code>user@DESKTOP ~
$ echo $JAVA_HOME
/home/user/jdk

user@DESKTOP ~
$ java --version
openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)

user@DESKTOP ~
$ sdkmanager.bat

ERROR: JAVA_HOME is set to an invalid directory: /home/user/jdk

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

user@DESKTOP ~
$ whereis sdkmanager.bat
sdkmanager: /home/user/android_sdk/tools/bin/sdkmanager.bat
</code>```

Java itself seems to be working fine, but whenever I try to run the sdkmanager it doesn't find it.

Here is my .bashrc

#ANDROID SDK PATH
export ANDROID_HOME="$HOME/android_sdk"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/tools/bin:$PATH"
export PATH="$ANDROID_SDK_ROOT/platform-tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/build-tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/tools/bin:$PATH"
export JAVA_HOME="$HOME/jdk"
export PATH="$JAVA_HOME/bin:$PATH"

#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="$HOME/.sdkman"
[[ -s "$HOME/.sdkman/bin/sdkman-init.sh" ]] && source "$HOME/.sdkman/bin/sdkman-init.sh"
```
<p>And my file structure</p>
```android_sdk:
  - build-tools
  - cmdline-tools
  - platform-tools
  - tools

jdk:
  - bin
  - conf
  - include
  - ...

```

Body:
I'm trying to build an android app using cordova, and I need the sdkmanager to set the permission. Also, I had to install Cygwin because it was need to use SDKman.

This is what I get in the terminal:

user@DESKTOP ~
$ echo $JAVA_HOME
/home/user/jdk

user@DESKTOP ~
$ java --version
openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)

user@DESKTOP ~
$ sdkmanager.bat

ERROR: JAVA_HOME is set to an invalid directory: /home/user/jdk

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

user@DESKTOP ~
$ whereis sdkmanager.bat
sdkmanager: /home/user/android_sdk/tools/bin/sdkmanager.bat

Java itself seems to be working fine, but whenever I try to run the sdkmanager it doesn't find it.

Here is my .bashrc

#ANDROID SDK PATH
export ANDROID_HOME="$HOME/android_sdk"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/tools/bin:$PATH"
export PATH="$ANDROID_SDK_ROOT/platform-tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/build-tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/tools/bin:$PATH"
export JAVA_HOME="$HOME/jdk"
export PATH="$JAVA_HOME/bin:$PATH"

#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="$HOME/.sdkman"
[[ -s "$HOME/.sdkman/bin/sdkman-init.sh" ]] && source "$HOME/.sdkman/bin/sdkman-init.sh"

And my file structure

android_sdk:
  - build-tools
  - cmdline-tools
  - platform-tools
  - tools

jdk:
  - bin
  - conf
  - include
  - ...


来源: stackexchange

问:
What is allowing re-render when set state is setting the state to the same string?
I have setToken("unset") in the useCallback of the first button click which causes re-render of the parent and the child; because it's button text changes. This is correct but, how is a second click causing  the parent to re-render?

Third click does nothing as I expected the second to do (token is set to a value of "unset" on each click).

I have to change setToken('unset'); to if(token!=='unset'){setToken('unset');} and add token to the callback's dependencies to stop it re-rendering after the first re-render on first click. I thought React re-renders when useState value is updated and different than the previous value.

Why does React allow one extra re-render here? Why did React need me to do what I thought it was suppose to do?

Console:

Without Condition
With

render parent, token: a7ib0PcX9
render parent, token: a7ib0PcX9

render Logout
render Logout

clicked
clicked

render parent, token: unset
render parent, token: unset

render Logout
render Logout

clicked
clicked

render parent, token: unset
clicked

clicked
clicked

clicked

clicked

```<code>function Logout({ username, onLogout }) {
    console.log('render Logout');
    return (
        <>
            <button onClick={onLogout}>{username?('Logout '+username):'Buh Bye!'}</button>
        </>
    );
}
const MemoizedLogout = React.memo(Logout);

function AppLogout({ store }) {
    const [token, setToken] = useState('a7ib0PcX9');
    console.log('render parent,','token: '+token);
    const onLogout=useCallback(() => {
        console.log('clicked');
        store.username = undefined;
        setToken('unset');
    }, [store]);
    return (
        <div className="main">
            <header>
                <MemoizedLogout username={store.username} onLogout={onLogout}/>
            </header>
        </div>
    );
}
function App(){
    return (
        <>
            <AppLogout store={{username:'benz'}}/>
        </>
    );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have setToken("unset") in the useCallback of the first button click which causes re-render of the parent and the child; because it's button text changes. This is correct but, how is a second click causing  the parent to re-render?

Third click does nothing as I expected the second to do (token is set to a value of "unset" on each click).

I have to change setToken('unset'); to if(token!=='unset'){setToken('unset');} and add token to the callback's dependencies to stop it re-rendering after the first re-render on first click. I thought React re-renders when useState value is updated and different than the previous value.

Why does React allow one extra re-render here? Why did React need me to do what I thought it was suppose to do?

Console:

Without Condition
With

render parent, token: a7ib0PcX9
render parent, token: a7ib0PcX9

render Logout
render Logout

clicked
clicked

render parent, token: unset
render parent, token: unset

render Logout
render Logout

clicked
clicked

render parent, token: unset
clicked

clicked
clicked

clicked

clicked

function Logout({ username, onLogout }) {
    console.log('render Logout');
    return (
        <>
            <button onClick={onLogout}>{username?('Logout '+username):'Buh Bye!'}</button>
        </>
    );
}
const MemoizedLogout = React.memo(Logout);

function AppLogout({ store }) {
    const [token, setToken] = useState('a7ib0PcX9');
    console.log('render parent,','token: '+token);
    const onLogout=useCallback(() => {
        console.log('clicked');
        store.username = undefined;
        setToken('unset');
    }, [store]);
    return (

                <MemoizedLogout username={store.username} onLogout={onLogout}/>

    );
}
function App(){
    return (
        <>
            <AppLogout store={{username:'benz'}}/>
        </>
    );
}


问:
Prometheus : list docker and docker compose version of each node
I would like to list each version of "docker" and "docker compose" of each node?

How can I do this with prometheus?

I have cadvisor and NodeExporter on each node. Is it enough? witch configuration ?

Thanks for your answers.

I ever try with

```<code>container_tasks_state{job="cadvisor", name="cadvisor",state="running"}
</code>```

to extract container_label_com_docker_compose_version but I never succeeded because it's always the same result for each node and i know it's false.

Body:
I would like to list each version of "docker" and "docker compose" of each node?

How can I do this with prometheus?

I have cadvisor and NodeExporter on each node. Is it enough? witch configuration ?

Thanks for your answers.

I ever try with

container_tasks_state{job="cadvisor", name="cadvisor",state="running"}

to extract container_label_com_docker_compose_version but I never succeeded because it's always the same result for each node and i know it's false.


问:
The button is pressed, the action happens, but after a couple of seconds the action is canceled, Selenium, Python
The button is clicked, but the click action is canceled after 3 secs if the button was clicked with selenium python. But if, during the execution of the code, I click on the button myself with the mouse, then everything is executed correctly. What's wrong? Clicking through selenium is different from clicking with the mouse?

Tiktok detects that this is a bot? How to bypass it?

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

class Tiktok:
    def __init__(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument("--disable-extensions")
        self.options.add_argument("--disable-blink-features=AutomationControlled")
        self.options.add_experimental_option("excludeSwitches", ["enable-automation"])
        self.options.add_experimental_option('useAutomationExtension', False)
        self.driver = webdriver.Chrome(
            executable_path='firefoxdriver/chromedriver',
            options=self.options
        )
        self.action = ActionChains(self.driver)

    def start_chrome(self):
        self.driver.implicitly_wait(5)
        self.driver.get('https://www.tiktok.com/@tiktok')

        #click the subscribe button
        driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[2]/div/div[1]/div[1]/div[2]/div/div[1]/button').click()
</code>```

I tried to solve it with Keys.ENTER, ActionChains().

Body:
The button is clicked, but the click action is canceled after 3 secs if the button was clicked with selenium python. But if, during the execution of the code, I click on the button myself with the mouse, then everything is executed correctly. What's wrong? Clicking through selenium is different from clicking with the mouse?

Tiktok detects that this is a bot? How to bypass it?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

class Tiktok:
    def __init__(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument("--disable-extensions")
        self.options.add_argument("--disable-blink-features=AutomationControlled")
        self.options.add_experimental_option("excludeSwitches", ["enable-automation"])
        self.options.add_experimental_option('useAutomationExtension', False)
        self.driver = webdriver.Chrome(
            executable_path='firefoxdriver/chromedriver',
            options=self.options
        )
        self.action = ActionChains(self.driver)

    def start_chrome(self):
        self.driver.implicitly_wait(5)
        self.driver.get('https://www.tiktok.com/@tiktok')

        #click the subscribe button
        driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[2]/div/div[1]/div[1]/div[2]/div/div[1]/button').click()

I tried to solve it with Keys.ENTER, ActionChains().


问:
Python - ValueError: source code string cannot contain null bytes
I have a problem. I am using Windows 7 32x, Python 3.

When I try to import the numpy library in code, no matter what, I get an error. I don't remember how to solve it.

The code itself:

```<code>import numba

print('Hello World!')
</code>```

And here is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\User\Desktop\numba_test.py", line 1, in <module>
    import numba
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\__init__.py", line 38, in <module>
    from numba.core.decorators import (cfunc, generated_jit, jit, njit, stencil,
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\decorators.py", line 12, in <module>
    from numba.stencils.stencil import stencil
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\stencils\stencil.py", line 11, in <module>
    from numba.core import types, typing, utils, ir, config, ir_utils, registry
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\registry.py", line 4, in <module>
    from numba.core import utils, typing, dispatcher, cpu
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\dispatcher.py", line 13, in <module>
    from numba.core import (
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\compiler.py", line 6, in <module>
    from numba.core import (utils, errors, typing, interpreter, bytecode, postproc,
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\cpu.py", line 15, in <module>
    import numba.core.entrypoints
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\entrypoints.py", line 8, in <module>
    import importlib_metadata
ValueError: source code string cannot contain null bytes
</code>```

I have reinstalled numba several times, searched for solutions on the Internet, but all without success. Help what you can.

Body:
I have a problem. I am using Windows 7 32x, Python 3.

When I try to import the numpy library in code, no matter what, I get an error. I don't remember how to solve it.

The code itself:

import numba

print('Hello World!')

And here is the error:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\numba_test.py", line 1, in <module>
    import numba
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\__init__.py", line 38, in <module>
    from numba.core.decorators import (cfunc, generated_jit, jit, njit, stencil,
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\decorators.py", line 12, in <module>
    from numba.stencils.stencil import stencil
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\stencils\stencil.py", line 11, in <module>
    from numba.core import types, typing, utils, ir, config, ir_utils, registry
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\registry.py", line 4, in <module>
    from numba.core import utils, typing, dispatcher, cpu
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\dispatcher.py", line 13, in <module>
    from numba.core import (
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\compiler.py", line 6, in <module>
    from numba.core import (utils, errors, typing, interpreter, bytecode, postproc,
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\cpu.py", line 15, in <module>
    import numba.core.entrypoints
  File "C:\Users\User\AppData\Roaming\Python\Python37\site-packages\numba\core\entrypoints.py", line 8, in <module>
    import importlib_metadata
ValueError: source code string cannot contain null bytes

I have reinstalled numba several times, searched for solutions on the Internet, but all without success. Help what you can.


问:
K8s installation issue [ERROR Mem]: the system RAM (966 MB) is less than the minimum 1700 MB
Steps:
kubeadm init --apiserver-advertise-address= --pod-network-cidr=192.168.0.0/16
after executing above command it throw below issue

```<code>1-->[ERROR NumCPU]: the number of available CPUs 1 is less than the required 2
2-->[ERROR Mem]: the system RAM (966 MB) is less than the minimum 1700 MB

</code>```

and re execute below comment
kubeadm init --apiserver-advertise-address=172.31.92.76 --pod-network-cidr=192.168.0.0/16  --ignore-preflight-errors=NumCPU --ignore-preflight-errors=Mem
it seem this error

```<code>This error is likely caused by:
        - The kubelet is not running
        - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

</code>```
```<code>[preflight] Running pre-flight checks
        [WARNING NumCPU]: the number of available CPUs 1 is less than the required 2
        [WARNING Mem]: the system RAM (966 MB) is less than the minimum 1700 MB
error execution phase preflight: [preflight] Some fatal errors occurred:
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml]: /etc/kubernetes/manifests/kube-apiserver.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml]: /etc/kubernetes/manifests/kube-controller-manager.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml]: /etc/kubernetes/manifests/kube-scheduler.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-etcd.yaml]: /etc/kubernetes/manifests/etcd.yaml already exists
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher
root@ip-172-31-92-76:/home/ubuntu#

</code>```

how to over come this one

Body:
Steps:
kubeadm init --apiserver-advertise-address= --pod-network-cidr=192.168.0.0/16
after executing above command it throw below issue

1-->[ERROR NumCPU]: the number of available CPUs 1 is less than the required 2
2-->[ERROR Mem]: the system RAM (966 MB) is less than the minimum 1700 MB

and re execute below comment
kubeadm init --apiserver-advertise-address=172.31.92.76 --pod-network-cidr=192.168.0.0/16  --ignore-preflight-errors=NumCPU --ignore-preflight-errors=Mem
it seem this error

This error is likely caused by:
        - The kubelet is not running
        - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

[preflight] Running pre-flight checks
        [WARNING NumCPU]: the number of available CPUs 1 is less than the required 2
        [WARNING Mem]: the system RAM (966 MB) is less than the minimum 1700 MB
error execution phase preflight: [preflight] Some fatal errors occurred:
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml]: /etc/kubernetes/manifests/kube-apiserver.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml]: /etc/kubernetes/manifests/kube-controller-manager.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml]: /etc/kubernetes/manifests/kube-scheduler.yaml already exists
        [ERROR FileAvailable--etc-kubernetes-manifests-etcd.yaml]: /etc/kubernetes/manifests/etcd.yaml already exists
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher
root@ip-172-31-92-76:/home/ubuntu#

how to over come this one


问:
How to set the root view controller's status bar to be hidden?
I am trying to show an Open Ad from Google Admob in my SwiftUI app. I am not too familiar with UIKit and stuff...

I am keep getting this error in my console: " Status bar could not be hidden for full screen ad. Ensure that your app is configured to allow full screen ads to control the status bar. For example, consider whether you need to set the childViewControllerForStatusBarHidden property on your ad's rootViewController."

How do I solve this?

```<code>// Extending Application to get RootView..
extension UIApplication {
    func getRootViewController() -> UIViewController {

        guard let scene = self.connectedScenes.first as? UIWindowScene else {
            return .init()
        }

        guard let root = scene.windows.first?.rootViewController else {
            return .init()
        }

        return root
    }
}

final class OpenAd: NSObject, GADFullScreenContentDelegate {
    var appOpenAd: GADAppOpenAd?
    var loadTime = Date()

    func currentDeviceOrientation() -> UIInterfaceOrientation {
        let currentOrientation = UIDevice.current.orientation

        switch currentOrientation {
        case .unknown:
            return .unknown
        case .portrait:
            return .portrait
        case .portraitUpsideDown:
            return .portraitUpsideDown
        case .landscapeLeft:
            return .landscapeLeft
        case .landscapeRight:
            return .landscapeRight
        case .faceUp:
            return .portrait
        case .faceDown:
            return .portrait
        @unknown default:
            return .unknown
        }
    }

    func showAdForFirstLaunch() {
        let request = GADRequest()
        GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                          request: request,
                          orientation: UIInterfaceOrientation.portrait,
                          completionHandler: { (appOpenAdIn, _) in
            self.appOpenAd = appOpenAdIn
            self.appOpenAd?.fullScreenContentDelegate = self
            self.loadTime = Date()

            self.appOpenAd?.present(fromRootViewController: UIApplication.shared.getRootViewController())
        })
    }

    func requestAppOpenAd() {
        let request = GADRequest()
        GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                          request: request,
                          orientation: UIInterfaceOrientation.portrait,
                          completionHandler: { (appOpenAdIn, _) in
            self.appOpenAd = appOpenAdIn
            self.appOpenAd?.fullScreenContentDelegate = self
            self.loadTime = Date()
            print("[OPEN AD] Ad is ready")
        })
    }

    func tryToPresentAd() {
        if let gOpenAd = self.appOpenAd, wasLoadTimeLessThanNHoursAgo(thresholdN: 4) {
            gOpenAd.present(fromRootViewController: UIApplication.shared.getRootViewController())
        } else {
            self.requestAppOpenAd()
        }
    }

    func wasLoadTimeLessThanNHoursAgo(thresholdN: Int) -> Bool {
        let now = Date()
        let timeIntervalBetweenNowAndLoadTime = now.timeIntervalSince(self.loadTime)
        let secondsPerHour = 3600.0
        let intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour
        return intervalInHours < Double(thresholdN)
    }

    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("[OPEN AD] Failed: \(error)")
        requestAppOpenAd()
    }

    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        requestAppOpenAd()
        print("[OPEN AD] Ad dismissed")
    }
}
</code>```

Body:
I am trying to show an Open Ad from Google Admob in my SwiftUI app. I am not too familiar with UIKit and stuff...

I am keep getting this error in my console: " Status bar could not be hidden for full screen ad. Ensure that your app is configured to allow full screen ads to control the status bar. For example, consider whether you need to set the childViewControllerForStatusBarHidden property on your ad's rootViewController."

How do I solve this?

// Extending Application to get RootView..
extension UIApplication {
    func getRootViewController() -> UIViewController {

        guard let scene = self.connectedScenes.first as? UIWindowScene else {
            return .init()
        }

        guard let root = scene.windows.first?.rootViewController else {
            return .init()
        }

        return root
    }
}

final class OpenAd: NSObject, GADFullScreenContentDelegate {
    var appOpenAd: GADAppOpenAd?
    var loadTime = Date()

    func currentDeviceOrientation() -> UIInterfaceOrientation {
        let currentOrientation = UIDevice.current.orientation

        switch currentOrientation {
        case .unknown:
            return .unknown
        case .portrait:
            return .portrait
        case .portraitUpsideDown:
            return .portraitUpsideDown
        case .landscapeLeft:
            return .landscapeLeft
        case .landscapeRight:
            return .landscapeRight
        case .faceUp:
            return .portrait
        case .faceDown:
            return .portrait
        @unknown default:
            return .unknown
        }
    }

    func showAdForFirstLaunch() {
        let request = GADRequest()
        GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                          request: request,
                          orientation: UIInterfaceOrientation.portrait,
                          completionHandler: { (appOpenAdIn, _) in
            self.appOpenAd = appOpenAdIn
            self.appOpenAd?.fullScreenContentDelegate = self
            self.loadTime = Date()

            self.appOpenAd?.present(fromRootViewController: UIApplication.shared.getRootViewController())
        })
    }

    func requestAppOpenAd() {
        let request = GADRequest()
        GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                          request: request,
                          orientation: UIInterfaceOrientation.portrait,
                          completionHandler: { (appOpenAdIn, _) in
            self.appOpenAd = appOpenAdIn
            self.appOpenAd?.fullScreenContentDelegate = self
            self.loadTime = Date()
            print("[OPEN AD] Ad is ready")
        })
    }

    func tryToPresentAd() {
        if let gOpenAd = self.appOpenAd, wasLoadTimeLessThanNHoursAgo(thresholdN: 4) {
            gOpenAd.present(fromRootViewController: UIApplication.shared.getRootViewController())
        } else {
            self.requestAppOpenAd()
        }
    }

    func wasLoadTimeLessThanNHoursAgo(thresholdN: Int) -> Bool {
        let now = Date()
        let timeIntervalBetweenNowAndLoadTime = now.timeIntervalSince(self.loadTime)
        let secondsPerHour = 3600.0
        let intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour
        return intervalInHours < Double(thresholdN)
    }

    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("[OPEN AD] Failed: \(error)")
        requestAppOpenAd()
    }

    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        requestAppOpenAd()
        print("[OPEN AD] Ad dismissed")
    }
}


问:
How to find the character index of an XPath match with libxml2?
Given an XML file (stored in, say, sample.xml), and an XPath expression (say, //storyinfo), I want to get the character index in the XML file of the start of each node that results from evaluating the XPath expression.

A line number and a column number would also be fine.

What I've tried:

Given a sample XML like this one, stored in sample.xml:

<?xml version="1.0" encoding="utf-8"?>
<story>
  <storyinfo>
    <author>John Fleck</author>
    <datewritten>June 2, 2002</datewritten>
    <keyword>example keyword</keyword>
  </storyinfo>

    <headline>This is the headline</headline>
    <para>This is the body text.</para>

</story>
```
<p>I can get the "storyinfo" node using an XPath expression with libxml2, like so:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

int
main(void)
{
    int i, size;
    char *filename;
    xmlChar *xpath_expr;
    xmlDocPtr doc;
    xmlNodePtr node;
    xmlNodeSetPtr nodes;
    xmlXPathContextPtr xpath_ctx;
    xmlXPathObjectPtr xpath_obj;

    /* Read file. */
    filename = "sample.xml";
    doc = xmlParseFile(filename);
    if (doc == NULL) {
        fprintf(stderr, "Error: unable to parse file \"%s\"\n",
            filename);
        exit(1);
    }

    /* Evaluate XPath expression. */
    xpath_ctx = xmlXPathNewContext(doc);
    if (xpath_ctx == NULL) {
        fprintf(stderr, "Error: unable to create new XPath context\n");
        xmlFreeDoc(doc);
        exit(1);
    }
    xpath_expr = (xmlChar *)"//storyinfo";
    xpath_obj = xmlXPathEvalExpression(xpath_expr, xpath_ctx);
    if (xpath_obj == NULL) {
        fprintf(stderr,
            "Error: unable to evaluate XPath expression \"%s\"\n",
            xpath_expr);
        xmlXPathFreeContext(xpath_ctx);
        xmlFreeDoc(doc);
        exit(1);
    }

    /* Print XPath matches. */
    nodes = xpath_obj->nodesetval;
    size = (nodes) ? nodes->nodeNr : 0;
    for (i = 0; i < size; ++i) {
        node = nodes->nodeTab[i];
        printf("Match %d - Name: %s\n", i, node->name);
        printf("Match %d - Content: %s\n", i, node->content);
        printf("Match %d - Line: %d\n", i, node->line);
        printf("Match %d - Extra: %d\n", i, node->extra);
    }

    /* Cleanup. */
    xmlXPathFreeObject(xpath_obj);
    xmlXPathFreeContext(xpath_ctx);
    xmlFreeDoc(doc);

    return 0;
}
</code>```

Here I saw that in libxml2, the node has a field line, with a value of 3, which is the line number in which the node is located in the XML file. However, that is not helpful if the XML is all in a single line (which isn't uncommon).

What I want instead is the character index: in the sample.xml above, that would be 50. Either that, or a line and column number: in the example above, that would be line 3, column 3.

Body:
Given an XML file (stored in, say, sample.xml), and an XPath expression (say, //storyinfo), I want to get the character index in the XML file of the start of each node that results from evaluating the XPath expression.

A line number and a column number would also be fine.

What I've tried:

Given a sample XML like this one, stored in sample.xml:

<?xml version="1.0" encoding="utf-8"?>
<story>
  <storyinfo>
    <author>John Fleck</author>
    <datewritten>June 2, 2002</datewritten>
    <keyword>example keyword</keyword>
  </storyinfo>

    <headline>This is the headline</headline>
    <para>This is the body text.</para>

</story>

I can get the "storyinfo" node using an XPath expression with libxml2, like so:

#include <stdio.h>
#include <stdlib.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

int
main(void)
{
    int i, size;
    char *filename;
    xmlChar *xpath_expr;
    xmlDocPtr doc;
    xmlNodePtr node;
    xmlNodeSetPtr nodes;
    xmlXPathContextPtr xpath_ctx;
    xmlXPathObjectPtr xpath_obj;

    /* Read file. */
    filename = "sample.xml";
    doc = xmlParseFile(filename);
    if (doc == NULL) {
        fprintf(stderr, "Error: unable to parse file \"%s\"\n",
            filename);
        exit(1);
    }

    /* Evaluate XPath expression. */
    xpath_ctx = xmlXPathNewContext(doc);
    if (xpath_ctx == NULL) {
        fprintf(stderr, "Error: unable to create new XPath context\n");
        xmlFreeDoc(doc);
        exit(1);
    }
    xpath_expr = (xmlChar *)"//storyinfo";
    xpath_obj = xmlXPathEvalExpression(xpath_expr, xpath_ctx);
    if (xpath_obj == NULL) {
        fprintf(stderr,
            "Error: unable to evaluate XPath expression \"%s\"\n",
            xpath_expr);
        xmlXPathFreeContext(xpath_ctx);
        xmlFreeDoc(doc);
        exit(1);
    }

    /* Print XPath matches. */
    nodes = xpath_obj->nodesetval;
    size = (nodes) ? nodes->nodeNr : 0;
    for (i = 0; i < size; ++i) {
        node = nodes->nodeTab[i];
        printf("Match %d - Name: %s\n", i, node->name);
        printf("Match %d - Content: %s\n", i, node->content);
        printf("Match %d - Line: %d\n", i, node->line);
        printf("Match %d - Extra: %d\n", i, node->extra);
    }

    /* Cleanup. */
    xmlXPathFreeObject(xpath_obj);
    xmlXPathFreeContext(xpath_ctx);
    xmlFreeDoc(doc);

    return 0;
}

Here I saw that in libxml2, the node has a field line, with a value of 3, which is the line number in which the node is located in the XML file. However, that is not helpful if the XML is all in a single line (which isn't uncommon).

What I want instead is the character index: in the sample.xml above, that would be 50. Either that, or a line and column number: in the example above, that would be line 3, column 3.


问:
How can I configure jcabi-aspect to NOT print method return value?
I have a class that has @Loggable(DEBUG) which prints return value of public method like this:

class:

```<code>@Loggable(DEBUG)
public class FhirAccessTokenServiceImpl implements FhirAccessTokenService {

    private static final Logger LOG = LoggerFactory.getLogger(FhirAccessTokenServiceImpl.class);
    private static final String ACCESS_TOKEN_FIELD = "access_token";
    private static final Integer RETRY_COUNT = 3;

    private final String loginUrl;

    @Override
    public String getToken(ServerCredential<FhirServer> serverCredential) throws HealthDataConnectorServiceException {
        try {
            WebClient client = WebClient.create(String.format(loginUrl,
                    serverCredential.getServer().getAzureTenantId()));
            return client.post()
                    .accept(MediaType.APPLICATION_FORM_URLENCODED)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .body(this.getFormInserter(serverCredential))
                    .retrieve()
                    .bodyToMono(String.class)
                    .retry(RETRY_COUNT)
                    .map(this::getToken)
                    .block();
        } catch (WebClientException | JsonParseException e) {
            throw new HealthDataConnectorServiceException(String.format("Error occurred while getting token for " +
                    "fhir url: %s", serverCredential.getServer().getServerUrl()), e);
        }
    }
</code>```

and here is the log in AKS:

```<code>[HDC-FhirBundle]] n.p.d.h.c.s.i.FhirAccessTokenServiceImpl : #getToken('ServerCredential [server=FhirServer [fhirVersion=..354..'2022-12-19', lastModified='2022-12-19']]]'): 'eyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..1192..eyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' in 141.88ms
</code>```

(I modified 'eyaaaa... ' due to sensitive information)

How can I configure jcabi-aspects to NOT print this secret(token)?

Body:
I have a class that has @Loggable(DEBUG) which prints return value of public method like this:

class:

@Loggable(DEBUG)
public class FhirAccessTokenServiceImpl implements FhirAccessTokenService {

    private static final Logger LOG = LoggerFactory.getLogger(FhirAccessTokenServiceImpl.class);
    private static final String ACCESS_TOKEN_FIELD = "access_token";
    private static final Integer RETRY_COUNT = 3;

    private final String loginUrl;

    @Override
    public String getToken(ServerCredential<FhirServer> serverCredential) throws HealthDataConnectorServiceException {
        try {
            WebClient client = WebClient.create(String.format(loginUrl,
                    serverCredential.getServer().getAzureTenantId()));
            return client.post()
                    .accept(MediaType.APPLICATION_FORM_URLENCODED)
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .body(this.getFormInserter(serverCredential))
                    .retrieve()
                    .bodyToMono(String.class)
                    .retry(RETRY_COUNT)
                    .map(this::getToken)
                    .block();
        } catch (WebClientException | JsonParseException e) {
            throw new HealthDataConnectorServiceException(String.format("Error occurred while getting token for " +
                    "fhir url: %s", serverCredential.getServer().getServerUrl()), e);
        }
    }

and here is the log in AKS:

[HDC-FhirBundle]] n.p.d.h.c.s.i.FhirAccessTokenServiceImpl : #getToken('ServerCredential [server=FhirServer [fhirVersion=..354..'2022-12-19', lastModified='2022-12-19']]]'): 'eyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..1192..eyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' in 141.88ms

(I modified 'eyaaaa... ' due to sensitive information)

How can I configure jcabi-aspects to NOT print this secret(token)?


问:
Create installer for WindowsApplication C#
I try to create an installer for my WindowsApplication. I use the Publish and it work.

I use Visual Studio 2019 and .NET Framework 4.7.2.

The problem is when i run the installer the application also run.

I want (if possible) avoid this behavior..I want to run only the installer not also the application after install.

there is some settings to define?

Thanks


问:
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [4,0,0], thread: [586,0,0] Assertion `t >= 0 && t < n_classes` failed
I get this error when I run this command: !python Models/KiU-Net/LiTS/train.py (training my neural network on Google Colab Pro in Python and Windows 10).

I tried to run this command: !python Models/KiU-Net/LiTS/train.py -Xcompiler -fno-gnu-unique, but I still got the same error.

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/visdom/__init__.py", line 692, in _send
    return self._handle_post(
  File "/usr/local/lib/python3.8/dist-packages/visdom/__init__.py", line 656, in _handle_post
    r = self.session.post(url, data=data)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 578, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=666): Max retries exceeded with url: /update (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1fa000dee0>: Failed to establish a new connection: [Errno 111] Connection refused'))
epoch:0, step:0, loss1:1.171, loss2:1.417, loss3:1.201, loss4:1.182, loss:2.4318742752075195 time:0.077 min
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [15,0,0], thread: [303,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [7,0,0], thread: [304,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [7,0,0], thread: [817,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [15,0,0], thread: [48,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [22,0,0], thread: [47,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [11,0,0], thread: [845,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [8,0,0], thread: [562,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [4,0,0], thread: [586,0,0] Assertion `t >= 0 && t < n_classes` failed.
</code>```

This is the training file (train.py) where I train a convolutional neural network, calculating the loss (cross-entropy loss) and making backpropagation to update the weights:

```<code>import os
from time import time

import numpy as np

import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader

from visdom import Visdom

from dataset.dataset import Dataset

from loss.Dice import DiceLoss
from loss.ELDice import ELDiceLoss
from loss.WBCE import WCELoss
from loss.Jaccard import JaccardLoss
from loss.SS import SSLoss
from loss.Tversky import TverskyLoss
from loss.Hybrid import HybridLoss
from loss.BCE import BCELoss

from net.models import net

import parameter as para

viz = Visdom(port=666)
step_list = [0]
win = viz.line(X=np.array([0]), Y=np.array([1.0]), opts=dict(title='loss'))

os.environ['CUDA_VISIBLE_DEVICES'] = para.gpu
cudnn.benchmark = para.cudnn_benchmark

net = torch.nn.DataParallel(net).cuda()
net.train()

print(para.training_set_path)
train_ds = Dataset(os.path.join(para.train_ct_path, 'ct'), os.path.join(para.train_seg_path, 'seg'))

train_dl = DataLoader(train_ds, para.batch_size, True, num_workers=para.num_workers, pin_memory=para.pin_memory)

loss_func_list = [DiceLoss(), ELDiceLoss(), WCELoss(), JaccardLoss(), SSLoss(), TverskyLoss(), HybridLoss(), BCELoss()]
loss_func = loss_func_list[5]

opt = torch.optim.Adam(net.parameters(), lr=para.learning_rate, capturable=True)
#opt = torch.optim.Adam(net.parameters(), lr=para.learning_rate)

lr_decay = torch.optim.lr_scheduler.MultiStepLR(opt, para.learning_rate_decay)

alpha = para.alpha

start = time()

for epoch in range(para.Epoch):

    lr_decay.step()

    mean_loss = []

    for step, (ct, seg) in enumerate(train_dl):

        ct = ct.cuda()
        seg = seg.cuda()

        # print(f"seg unique: {torch.unique(seg)}")

        outputs = net(ct)
        # print(len(outputs))
        loss1 = loss_func(outputs[0], seg)
        loss2 = loss_func(outputs[1], seg)
        loss3 = loss_func(outputs[2], seg)
        loss4 = loss_func(outputs[3], seg)

        loss = (loss1 + loss2 + loss3) * alpha + loss4

        mean_loss.append(loss4.item())

        opt.zero_grad()
        loss.backward()
        #print("Capturing:", torch.cuda.is_current_stream_capturing())
        opt.step()

        if step % 5 == 0:

            step_list.append(step_list[-1] + 1)
            viz.line(X=np.array([step_list[-1]]), Y=np.array([loss4.item()]), win=win, update='append')

            print('epoch:{}, step:{}, loss1:{:.3f}, loss2:{:.3f}, loss3:{:.3f}, loss4:{:.3f}, loss:{} time:{:.3f} min'
                  .format(epoch, step, loss1.item(), loss2.item(), loss3.item(), loss4.item(), loss, (time() - start) / 60))

    mean_loss = sum(mean_loss) / len(mean_loss)

    if epoch % 50 == 0 :

        torch.save(net.state_dict(), '/content/drive/MyDrive/CS/Models/KiU-Net/LiTS/saved_networks/net{}-{:.3f}-{:.3f}.pth'.format(epoch, loss, mean_loss))

    if epoch % 40 == 0 and epoch != 0:
        alpha *= 0.8
</code>```

This is my model (net.py). It is a convolutional neural network (the input size is equal to the output size) to make a multiclass segmentation of 3 classes: background, liver, and tumor of medical images (LiTS, liver tumor segmentation benchmark):

```<code>import os
import sys
sys.path.append(os.path.split(sys.path[0])[0])

import torch
import torch.nn as nn
import torch.nn.functional as F

import parameter as para

class segnet(nn.Module):
    def __init__(self, training):
        super(segnet, self).__init__()
        self.training = training
        self.encoder1 = nn.Conv3d(1, 32, 3, stride=1, padding=1)  # b, 16, 10, 10
        self.encoder2 = nn.Conv3d(32, 64, 3, stride=1, padding=1)  # b, 8, 3, 3
        self.encoder3 = nn.Conv3d(64, 128, 3, stride=1, padding=1)
        self.encoder4 = nn.Conv3d(128, 256, 3, stride=1, padding=1)
        self.encoder5 = nn.Conv3d(256, 512, 3, stride=1, padding=1)

        self.decoder1 = nn.Conv3d(512, 256, 3, stride=1,padding=1)  # b, 16, 5, 5
        self.decoder2 = nn.Conv3d(256, 128, 3, stride=1, padding=1)  # b, 8, 15, 1
        self.decoder3 = nn.Conv3d(128, 64, 3, stride=1, padding=1)  # b, 1, 28, 28
        self.decoder4 = nn.Conv3d(64, 32, 3, stride=1, padding=1)
        self.decoder5 = nn.Conv3d(32, 3, 3, stride=1, padding=1) # self.decoder5 =   nn.Conv3d(32, 2, 3, stride=1, padding=1)
                                #(32, 3...
        self.map4 = nn.Sequential(
            nn.Conv3d(3, 3, 1, 1), #nn.Conv3d(2, 1, 1, 1) / nn.Conv3d(3, 3, 1, 1)
            nn.Upsample(scale_factor=(1, 1, 1), mode='trilinear'), # nn.Upsample(scale_factor=(1, 2, 2), mode='trilinear')
            nn.Sigmoid()
        )

        # 128*128 尺度下的映射
        self.map3 = nn.Sequential(
            nn.Conv3d(64, 3, 1, 1), #nn.Conv3d(64, 1, 1, 1) / nn.Conv3d(64, 3, 1, 1)
            nn.Upsample(scale_factor=(4, 4, 4), mode='trilinear'), #nn.Upsample(scale_factor=(4, 8, 8), mode='trilinear')
            nn.Sigmoid()
        )

        # 64*64 尺度下的映射
        self.map2 = nn.Sequential(
            nn.Conv3d(128, 3, 1, 1), #nn.Conv3d(128, 1, 1, 1) / nn.Conv3d(128, 3, 1, 1)
            nn.Upsample(scale_factor=(8, 8, 8), mode='trilinear'), #nn.Upsample(scale_factor=(8, 16, 16), mode='trilinear')
            nn.Sigmoid()
        )

        # 32*32 尺度下的映射
        self.map1 = nn.Sequential(
            nn.Conv3d(256, 3, 1, 1), #nn.Conv3d(256, 1, 1, 1) / nn.Conv3d(256, 3, 1, 1)
            nn.Upsample(scale_factor=(16, 16, 16), mode='trilinear'), #nn.Upsample(scale_factor=(16, 32, 32), mode='trilinear'),
            nn.Sigmoid()
        )

        self.soft = nn.Softmax(dim = 1) #self.soft = nn.Softmax(dim = 1)

    def forward(self, x):
        out = F.relu(F.max_pool3d(self.encoder1(x),2,2))
        t1 = out
        out = F.relu(F.max_pool3d(self.encoder2(out),2,2))
        t2 = out
        out = F.relu(F.max_pool3d(self.encoder3(out),2,2))
        t3 = out
        out = F.relu(F.max_pool3d(self.encoder4(out),2,2))
        t4 = out
        out = F.relu(F.max_pool3d(self.encoder5(out),2,2))

        # t2 = out
        out = F.relu(F.interpolate(self.decoder1(out),scale_factor=(2,2,2),mode ='trilinear'))
        # print(out.shape,t4.shape)
        out = torch.add(F.pad(out,[0,0,0,0,0,1]),t4)
        output1 = self.map1(out)
        out = F.relu(F.interpolate(self.decoder2(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t3)
        output2 = self.map2(out)
        out = F.relu(F.interpolate(self.decoder3(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t2)
        output3 = self.map3(out)
        out = F.relu(F.interpolate(self.decoder4(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t1)

        out = F.relu(F.interpolate(self.decoder5(out),scale_factor=(2,2,2),mode ='trilinear'))
        output4 = self.map4(out)
        # print(out.shape)
        # print(output1.shape,output2.shape,output3.shape,output4.shape)
        if self.training is True:
            return output1, output2, output3, output4
        else:
            return output4

def init(module):
    if isinstance(module, nn.Conv3d) or isinstance(module, nn.ConvTranspose3d):
        nn.init.kaiming_normal_(module.weight.data, 0.25)
        nn.init.constant_(module.bias.data, 0)

net = segnet(training=True)
# net = kiunet_org(training=True)
net.apply(init)

# 计算网络参数
print('net total parameters:', sum(param.numel() for param in net.parameters()))
</code>```

This is the file where I calculate cross-entropy loss (Tversky.py):

```<code>import torch
import torch.nn as nn
import torch.nn.functional as F

class TverskyLoss(nn.Module):

    def __init__(self):
        super().__init__()
        self.ce_loss = nn.CrossEntropyLoss(reduction='mean')

    def forward(self, pred, target):
        pred = pred.squeeze(dim=1) # pred.size() == target.size()
        output = self.ce_loss(pred, target.to(torch.int64))
        return output
</code>```

Body:
I get this error when I run this command: !python Models/KiU-Net/LiTS/train.py (training my neural network on Google Colab Pro in Python and Windows 10).

I tried to run this command: !python Models/KiU-Net/LiTS/train.py -Xcompiler -fno-gnu-unique, but I still got the same error.

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/visdom/__init__.py", line 692, in _send
    return self._handle_post(
  File "/usr/local/lib/python3.8/dist-packages/visdom/__init__.py", line 656, in _handle_post
    r = self.session.post(url, data=data)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 578, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=666): Max retries exceeded with url: /update (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1fa000dee0>: Failed to establish a new connection: [Errno 111] Connection refused'))
epoch:0, step:0, loss1:1.171, loss2:1.417, loss3:1.201, loss4:1.182, loss:2.4318742752075195 time:0.077 min
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [15,0,0], thread: [303,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [7,0,0], thread: [304,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [7,0,0], thread: [817,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [15,0,0], thread: [48,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [22,0,0], thread: [47,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [11,0,0], thread: [845,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [8,0,0], thread: [562,0,0] Assertion `t >= 0 && t < n_classes` failed.
../aten/src/ATen/native/cuda/NLLLoss2d.cu:104: nll_loss2d_forward_kernel: block: [4,0,0], thread: [586,0,0] Assertion `t >= 0 && t < n_classes` failed.

This is the training file (train.py) where I train a convolutional neural network, calculating the loss (cross-entropy loss) and making backpropagation to update the weights:

import os
from time import time

import numpy as np

import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader

from visdom import Visdom

from dataset.dataset import Dataset

from loss.Dice import DiceLoss
from loss.ELDice import ELDiceLoss
from loss.WBCE import WCELoss
from loss.Jaccard import JaccardLoss
from loss.SS import SSLoss
from loss.Tversky import TverskyLoss
from loss.Hybrid import HybridLoss
from loss.BCE import BCELoss

from net.models import net

import parameter as para

viz = Visdom(port=666)
step_list = [0]
win = viz.line(X=np.array([0]), Y=np.array([1.0]), opts=dict(title='loss'))

os.environ['CUDA_VISIBLE_DEVICES'] = para.gpu
cudnn.benchmark = para.cudnn_benchmark

net = torch.nn.DataParallel(net).cuda()
net.train()

print(para.training_set_path)
train_ds = Dataset(os.path.join(para.train_ct_path, 'ct'), os.path.join(para.train_seg_path, 'seg'))

train_dl = DataLoader(train_ds, para.batch_size, True, num_workers=para.num_workers, pin_memory=para.pin_memory)

loss_func_list = [DiceLoss(), ELDiceLoss(), WCELoss(), JaccardLoss(), SSLoss(), TverskyLoss(), HybridLoss(), BCELoss()]
loss_func = loss_func_list[5]

opt = torch.optim.Adam(net.parameters(), lr=para.learning_rate, capturable=True)
#opt = torch.optim.Adam(net.parameters(), lr=para.learning_rate)

lr_decay = torch.optim.lr_scheduler.MultiStepLR(opt, para.learning_rate_decay)

alpha = para.alpha

start = time()

for epoch in range(para.Epoch):

    lr_decay.step()

    mean_loss = []

    for step, (ct, seg) in enumerate(train_dl):

        ct = ct.cuda()
        seg = seg.cuda()

        # print(f"seg unique: {torch.unique(seg)}")

        outputs = net(ct)
        # print(len(outputs))
        loss1 = loss_func(outputs[0], seg)
        loss2 = loss_func(outputs[1], seg)
        loss3 = loss_func(outputs[2], seg)
        loss4 = loss_func(outputs[3], seg)

        loss = (loss1 + loss2 + loss3) * alpha + loss4

        mean_loss.append(loss4.item())

        opt.zero_grad()
        loss.backward()
        #print("Capturing:", torch.cuda.is_current_stream_capturing())
        opt.step()

        if step % 5 == 0:

            step_list.append(step_list[-1] + 1)
            viz.line(X=np.array([step_list[-1]]), Y=np.array([loss4.item()]), win=win, update='append')

            print('epoch:{}, step:{}, loss1:{:.3f}, loss2:{:.3f}, loss3:{:.3f}, loss4:{:.3f}, loss:{} time:{:.3f} min'
                  .format(epoch, step, loss1.item(), loss2.item(), loss3.item(), loss4.item(), loss, (time() - start) / 60))

    mean_loss = sum(mean_loss) / len(mean_loss)

    if epoch % 50 == 0 :

        torch.save(net.state_dict(), '/content/drive/MyDrive/CS/Models/KiU-Net/LiTS/saved_networks/net{}-{:.3f}-{:.3f}.pth'.format(epoch, loss, mean_loss))

    if epoch % 40 == 0 and epoch != 0:
        alpha *= 0.8

This is my model (net.py). It is a convolutional neural network (the input size is equal to the output size) to make a multiclass segmentation of 3 classes: background, liver, and tumor of medical images (LiTS, liver tumor segmentation benchmark):

import os
import sys
sys.path.append(os.path.split(sys.path[0])[0])

import torch
import torch.nn as nn
import torch.nn.functional as F

import parameter as para

class segnet(nn.Module):
    def __init__(self, training):
        super(segnet, self).__init__()
        self.training = training
        self.encoder1 = nn.Conv3d(1, 32, 3, stride=1, padding=1)  # b, 16, 10, 10
        self.encoder2 = nn.Conv3d(32, 64, 3, stride=1, padding=1)  # b, 8, 3, 3
        self.encoder3 = nn.Conv3d(64, 128, 3, stride=1, padding=1)
        self.encoder4 = nn.Conv3d(128, 256, 3, stride=1, padding=1)
        self.encoder5 = nn.Conv3d(256, 512, 3, stride=1, padding=1)

        self.decoder1 = nn.Conv3d(512, 256, 3, stride=1,padding=1)  # b, 16, 5, 5
        self.decoder2 = nn.Conv3d(256, 128, 3, stride=1, padding=1)  # b, 8, 15, 1
        self.decoder3 = nn.Conv3d(128, 64, 3, stride=1, padding=1)  # b, 1, 28, 28
        self.decoder4 = nn.Conv3d(64, 32, 3, stride=1, padding=1)
        self.decoder5 = nn.Conv3d(32, 3, 3, stride=1, padding=1) # self.decoder5 =   nn.Conv3d(32, 2, 3, stride=1, padding=1)
                                #(32, 3...
        self.map4 = nn.Sequential(
            nn.Conv3d(3, 3, 1, 1), #nn.Conv3d(2, 1, 1, 1) / nn.Conv3d(3, 3, 1, 1)
            nn.Upsample(scale_factor=(1, 1, 1), mode='trilinear'), # nn.Upsample(scale_factor=(1, 2, 2), mode='trilinear')
            nn.Sigmoid()
        )

        # 128*128 尺度下的映射
        self.map3 = nn.Sequential(
            nn.Conv3d(64, 3, 1, 1), #nn.Conv3d(64, 1, 1, 1) / nn.Conv3d(64, 3, 1, 1)
            nn.Upsample(scale_factor=(4, 4, 4), mode='trilinear'), #nn.Upsample(scale_factor=(4, 8, 8), mode='trilinear')
            nn.Sigmoid()
        )

        # 64*64 尺度下的映射
        self.map2 = nn.Sequential(
            nn.Conv3d(128, 3, 1, 1), #nn.Conv3d(128, 1, 1, 1) / nn.Conv3d(128, 3, 1, 1)
            nn.Upsample(scale_factor=(8, 8, 8), mode='trilinear'), #nn.Upsample(scale_factor=(8, 16, 16), mode='trilinear')
            nn.Sigmoid()
        )

        # 32*32 尺度下的映射
        self.map1 = nn.Sequential(
            nn.Conv3d(256, 3, 1, 1), #nn.Conv3d(256, 1, 1, 1) / nn.Conv3d(256, 3, 1, 1)
            nn.Upsample(scale_factor=(16, 16, 16), mode='trilinear'), #nn.Upsample(scale_factor=(16, 32, 32), mode='trilinear'),
            nn.Sigmoid()
        )

        self.soft = nn.Softmax(dim = 1) #self.soft = nn.Softmax(dim = 1)

    def forward(self, x):
        out = F.relu(F.max_pool3d(self.encoder1(x),2,2))
        t1 = out
        out = F.relu(F.max_pool3d(self.encoder2(out),2,2))
        t2 = out
        out = F.relu(F.max_pool3d(self.encoder3(out),2,2))
        t3 = out
        out = F.relu(F.max_pool3d(self.encoder4(out),2,2))
        t4 = out
        out = F.relu(F.max_pool3d(self.encoder5(out),2,2))

        # t2 = out
        out = F.relu(F.interpolate(self.decoder1(out),scale_factor=(2,2,2),mode ='trilinear'))
        # print(out.shape,t4.shape)
        out = torch.add(F.pad(out,[0,0,0,0,0,1]),t4)
        output1 = self.map1(out)
        out = F.relu(F.interpolate(self.decoder2(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t3)
        output2 = self.map2(out)
        out = F.relu(F.interpolate(self.decoder3(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t2)
        output3 = self.map3(out)
        out = F.relu(F.interpolate(self.decoder4(out),scale_factor=(2,2,2),mode ='trilinear'))
        # out = torch.add(out,t1)

        out = F.relu(F.interpolate(self.decoder5(out),scale_factor=(2,2,2),mode ='trilinear'))
        output4 = self.map4(out)
        # print(out.shape)
        # print(output1.shape,output2.shape,output3.shape,output4.shape)
        if self.training is True:
            return output1, output2, output3, output4
        else:
            return output4

def init(module):
    if isinstance(module, nn.Conv3d) or isinstance(module, nn.ConvTranspose3d):
        nn.init.kaiming_normal_(module.weight.data, 0.25)
        nn.init.constant_(module.bias.data, 0)

net = segnet(training=True)
# net = kiunet_org(training=True)
net.apply(init)

# 计算网络参数
print('net total parameters:', sum(param.numel() for param in net.parameters()))

This is the file where I calculate cross-entropy loss (Tversky.py):

import torch
import torch.nn as nn
import torch.nn.functional as F

class TverskyLoss(nn.Module):

    def __init__(self):
        super().__init__()
        self.ce_loss = nn.CrossEntropyLoss(reduction='mean')

    def forward(self, pred, target):
        pred = pred.squeeze(dim=1) # pred.size() == target.size()
        output = self.ce_loss(pred, target.to(torch.int64))
        return output


问:
How do I pass a user variable (@variable) as a column name in a select statement?
Here is my table:
enter image description here

My statement is returning this:
enter image description here

But I want it to return this:
enter image description here
enter image description here


问:
How do I pass an IP address to Google geolocation api?
I have a Django web app that deploys on Heroku, so I'm trying to get the actual user's IP, not the heroku server. Everything works fine when I run the project locally. When I deploy it to Heroku, it gives me the Heroku server location, even though I get the correct IP from x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'). Am I passing it incorrectly to google?</p>
```<code>def get_latitude_longitude(request):
   # Get the user's IP address
   x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
   if x_forwarded_for:
       ip_address = x_forwarded_for

   else:
       ip_address = request.META.get('REMOTE_ADDR')

   url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={settings.GOOGLE_API_KEY}&considerIp=true&ipAddress={ip_address}"
   # Make the request
   response = requests.post(url)

   # Check the response status code
   if response.status_code != 200:
       print(response)
   # Parse the response data
   data = response.json()
   latitude = data['location']['lat']
   longitude = data['location']['lng']
   accuracy = data['accuracy']
   return latitude, longitude, data, ip_address
</code>```

Body:
I have a Django web app that deploys on Heroku, so I'm trying to get the actual user's IP, not the heroku server. Everything works fine when I run the project locally. When I deploy it to Heroku, it gives me the Heroku server location, even though I get the correct IP from x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'). Am I passing it incorrectly to google?

def get_latitude_longitude(request):
   # Get the user's IP address
   x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
   if x_forwarded_for:
       ip_address = x_forwarded_for

   else:
       ip_address = request.META.get('REMOTE_ADDR')

   url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={settings.GOOGLE_API_KEY}&considerIp=true&ipAddress={ip_address}"
   # Make the request
   response = requests.post(url)

   # Check the response status code
   if response.status_code != 200:
       print(response)
   # Parse the response data
   data = response.json()
   latitude = data['location']['lat']
   longitude = data['location']['lng']
   accuracy = data['accuracy']
   return latitude, longitude, data, ip_address


问:
Kotlin extensions method
How can I write extension function in kotlin for such function:

```<code>public abstract fun <T : TargetValue> getAverage(metric: StatisticsMetric,
interval: DateInterval,
timeUnit: TimeUnit,
mode: GroupingMode /* = compiled code */,
result: (AsyncResult<kotlin.collections.Map<Info, T>, Error>) -> kotlin.Unit): kotlin.Unit
</code>```

To be able call it like  this:
TargetValueV2 : TargetValue

```<code>"This function about signature".asFlow(): Flow<MyCustomDataEvent>

        val flowResult = sdk.getAverage<TargetValueV2>(
            metric = TIME,
            interval = DateInterval(startDay, currentDate),
            timeUnit = DAY,
            mode = private
        ).asFlow()
</code>```

Title: Kotlin extensions method

Body:
How can I write extension function in kotlin for such function:

public abstract fun <T : TargetValue> getAverage(metric: StatisticsMetric,
interval: DateInterval,
timeUnit: TimeUnit,
mode: GroupingMode /* = compiled code */,
result: (AsyncResult<kotlin.collections.Map<Info, T>, Error>) -> kotlin.Unit): kotlin.Unit

To be able call it like  this:
TargetValueV2 : TargetValue

"This function about signature".asFlow(): Flow<MyCustomDataEvent>

        val flowResult = sdk.getAverage<TargetValueV2>(
            metric = TIME,
            interval = DateInterval(startDay, currentDate),
            timeUnit = DAY,
            mode = private
        ).asFlow()


问:
OpenOffice - How to get the quantity of register in a table that is filtered?
I applied a filter in a table on open office and I want to try to get the number of registers of column N that are empty, Do you any idea about this, any help be appreciated, Thanks!

I tried use =CONTAR.SIS( N6:N1048576;"<>") but not working as I expected, the number of registers is 33, and this count all rows including the hiding rows by the filter


问:
run two scripts with user data on first server boot
i want to run two scripts using cloud init user data

the first command is for set root password

`

```<code>#cloud-config
chpasswd:
 list: |
   root:o~s@grnet
</code>```

`

the second I want to set the password expired and force root to change the password.

How can I do that

i want to run two scripts

Body:
i want to run two scripts using cloud init user data

the first command is for set root password

`

#cloud-config
chpasswd:
 list: |
   root:o~s@grnet

`

the second I want to set the password expired and force root to change the password.

How can I do that

i want to run two scripts


问:
How do i make div refreshing to work properly
FIXED

I have options for user to select if he is Online, Away...etc
When i select Away for example, in mysql database i get away status. So, selecting status is working perfect. The problem is that i want when user select status, function submit_status gets called and $('#statusRefresh').load(' #statusRefresh'); should refresh the div where his current status is displayed, but when i select for example Away, the status stays Online, and when i select Busy, the status changes to Away, but when i refresh the page, status goes to Busy. It's like late by one step, showing me only previous status. Sometimes happens like when i select, nothing happens, remains the old status, and when i select another, i get previous. The problem should be something about refreshing that div in correct time (when i select status).

This is the list of all statuses:

```<code>public function getStatusText($value){
        if($value == '1'){
            echo '<i class="fas fa-check-circle text-success"></i> Online';
        }else if($value == '2'){
            echo '<i class="fas fa-clock text-warning"></i> Away';
        }else if($value == '3'){
            echo '<i class="fas fa-minus-circle text-danger"></i> Busy';
        }else if($value == '4'){
            echo '<i class="fas fa-times-circle text-info"></i> Invisible';
        }
    }
</code>```

This needs to be refreshed when i change status:

```<code><li class="list-group-item" data-bs-toggle="modal" data-bs-target="#statusModal"><div id="statusRefresh"><?php echo $user->getStatusText(escape($user->data()->status)); ?></div>
</code>```

This is how i select status:

```<code><div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-darkblue">
                <h5 class="modal-title" id="statusModalLabel">Status</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="d-grid gap-2">
                    <button type="button" onclick="submit_status(1)" class="btn btn-light border text-start"><i class="fas fa-check-circle text-success"></i> Online</button>
                    <button type="button" onclick="submit_status(2)" class="btn btn-light border text-start"><i class="fas fa-clock text-warning"></i> Away</button>
                    <button type="button" onclick="submit_status(3)" class="btn btn-light border text-start"><i class="fas fa-minus-circle text-danger"></i> Busy</button>
                    <button type="button" onclick="submit_status(4)" class="btn btn-light border text-start"><i class="fas fa-times-circle text-info"></i> Invisible</button>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This is how i call for refresh:

```<code>function submit_status(value){
    $.ajax({
        type: "POST",
        url: "index.php",
        data: {
            value : value,
            success: function (data) {
                $('#output').html(data);
                $('#statusModal').modal('hide');
                $('#statusRefresh').load(' #statusRefresh');
            }
        }
    });
}
</code>```

FIXED:

```<code>function submit_status(value){
    $.ajax({
        type: "POST",
        url: "index.php",
        data: { value: value },
        dataType: "html",
        success: function (data) {
            $('#output').html(data);
            $('#statusModal').modal('hide');
            $('#statusRefresh').load(' #statusRefresh');
        }
    });
}
</code>```

I didn't notice that i put success inside data...

Body:
FIXED

I have options for user to select if he is Online, Away...etc
When i select Away for example, in mysql database i get away status. So, selecting status is working perfect. The problem is that i want when user select status, function submit_status gets called and $('#statusRefresh').load(' #statusRefresh'); should refresh the div where his current status is displayed, but when i select for example Away, the status stays Online, and when i select Busy, the status changes to Away, but when i refresh the page, status goes to Busy. It's like late by one step, showing me only previous status. Sometimes happens like when i select, nothing happens, remains the old status, and when i select another, i get previous. The problem should be something about refreshing that div in correct time (when i select status).

This is the list of all statuses:

public function getStatusText($value){
        if($value == '1'){
            echo ' Online';
        }else if($value == '2'){
            echo ' Away';
        }else if($value == '3'){
            echo ' Busy';
        }else if($value == '4'){
            echo ' Invisible';
        }
    }

This needs to be refreshed when i change status:

<?php echo $user->getStatusText(escape($user->data()->status)); ?>

This is how i select status:

Status

                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>

                    <button type="button" onclick="submit_status(1)" class="btn btn-light border text-start"> Online</button>
                    <button type="button" onclick="submit_status(2)" class="btn btn-light border text-start"> Away</button>
                    <button type="button" onclick="submit_status(3)" class="btn btn-light border text-start"> Busy</button>
                    <button type="button" onclick="submit_status(4)" class="btn btn-light border text-start"> Invisible</button>

This is how i call for refresh:

function submit_status(value){
    $.ajax({
        type: "POST",
        url: "index.php",
        data: {
            value : value,
            success: function (data) {
                $('#output').html(data);
                $('#statusModal').modal('hide');
                $('#statusRefresh').load(' #statusRefresh');
            }
        }
    });
}

FIXED:

function submit_status(value){
    $.ajax({
        type: "POST",
        url: "index.php",
        data: { value: value },
        dataType: "html",
        success: function (data) {
            $('#output').html(data);
            $('#statusModal').modal('hide');
            $('#statusRefresh').load(' #statusRefresh');
        }
    });
}

I didn't notice that i put success inside data...


问:
whats is this icon in visual studio source control?
I have some files with these icons and i dont know what this means...
some help?


问:
How can I pass a a modified Command value to the Help() function of Cobra?
I'd like to be able to take the Long value of a Command from Cobra and modify it before it's returned to the user when [program] [command] --help is called.

While there's ample documentation, Cobra lacks examples to illustrate ways of modifying what's returned from the Help() function. As an exmaple, I'd like to include markdown within the Long value:

// other values
Long:    `This [feature](https://www.google.com) blah, blah blah.`
```
<p>And then use a custom parser - which I've already written - that removes the markdown before returning the string to the user:</p>
<pre class="lang-golang prettyprint-override"><code>// other help information

This feature blah, blah blah.
</code>```

Essentially: can someone provide an example of a function I can pass to SetHelpFunc() that will permit me to change this value?

Body:
I'd like to be able to take the Long value of a Command from Cobra and modify it before it's returned to the user when [program] [command] --help is called.

While there's ample documentation, Cobra lacks examples to illustrate ways of modifying what's returned from the Help() function. As an exmaple, I'd like to include markdown within the Long value:

// other values
Long:    `This [feature](https://www.google.com) blah, blah blah.`

And then use a custom parser - which I've already written - that removes the markdown before returning the string to the user:

// other help information

This feature blah, blah blah.

Essentially: can someone provide an example of a function I can pass to SetHelpFunc() that will permit me to change this value?


问:
Flutterflow Action Output variable error?
Hi I have the following custom action to retrieve a list of documents from my database:

```<code>CollectionReference contractH =
    FirebaseFirestore.instance.collection('contractsHandlers');
CollectionReference contractsCollection =
    FirebaseFirestore.instance.collection('contracts');

Future<List<ContractsRecord>> getContractsByUser(DocumentReference user) async {
  List<DocumentReference> contractsRef = List.empty();
  List<ContractsRecord> contracts = List.empty();

  try {
    await contractH
        .where('user', isEqualTo: user)
        .where('status', isEqualTo: 'active')
        .get()
        .then((value) => {
              value.docs.forEach((doc) {
                contractsRef.add(doc.get('contract'));
              })
            });

    await contractH
        .where('backupUser', isEqualTo: user)
        .where('status', isEqualTo: 'backup')
        .get()
        .then((value) => {
              value.docs.forEach((doc) {
                contractsRef.add(doc.get('contract'));
              })
            });
    await contractsCollection.get().then((value) => {
          value.docs.forEach((doc) {
            if (contractsRef.contains(doc.reference)) {
              contracts.add(doc.data() as ContractsRecord);
            }
          })
        });
  } catch (error) {}

  return contracts;
}
</code>```

it compiles and I have no errors in the project. But when I add an action output variable from the action tree like this "test" variable:

enter image description here

it causes the application to crash when I try to build it, giving me this error:

enter image description here

Any idea what is going on? if I don't set an output variable it compiles everything, but I need to use this variable

I have tried running the app without the variable and it runs but I need to have the variable since I need to use that list

Body:
Hi I have the following custom action to retrieve a list of documents from my database:

CollectionReference contractH =
    FirebaseFirestore.instance.collection('contractsHandlers');
CollectionReference contractsCollection =
    FirebaseFirestore.instance.collection('contracts');

Future<List<ContractsRecord>> getContractsByUser(DocumentReference user) async {
  List<DocumentReference> contractsRef = List.empty();
  List<ContractsRecord> contracts = List.empty();

  try {
    await contractH
        .where('user', isEqualTo: user)
        .where('status', isEqualTo: 'active')
        .get()
        .then((value) => {
              value.docs.forEach((doc) {
                contractsRef.add(doc.get('contract'));
              })
            });

    await contractH
        .where('backupUser', isEqualTo: user)
        .where('status', isEqualTo: 'backup')
        .get()
        .then((value) => {
              value.docs.forEach((doc) {
                contractsRef.add(doc.get('contract'));
              })
            });
    await contractsCollection.get().then((value) => {
          value.docs.forEach((doc) {
            if (contractsRef.contains(doc.reference)) {
              contracts.add(doc.data() as ContractsRecord);
            }
          })
        });
  } catch (error) {}

  return contracts;
}

it compiles and I have no errors in the project. But when I add an action output variable from the action tree like this "test" variable:

enter image description here

it causes the application to crash when I try to build it, giving me this error:

enter image description here

Any idea what is going on? if I don't set an output variable it compiles everything, but I need to use this variable

I have tried running the app without the variable and it runs but I need to have the variable since I need to use that list


问:
How to calculate a value on first trading day of January and fill column with value, then recalculate for February
I am trying to figure out how to do this calculation without using a loop (if possible).

On the first trading day in January, I want to calculate the number of shares to buy based on the account value (starting $10k) divided by the closing price.

vb_shares = account / vb_close

In this instance I want vb_shares to be 234 for the entire month of January so I can calculate PnL each day and adjust the account value accordingly.

Now, when the first trading day in February occurs, I want to look at the updated account value (lets say its 9,800) and do the "shares" calculation again and populate the column with that fixed value for the entire month of February.

```<code>            vb_close    long_vb    vb_shares    account
Date
2005-01-03  42.596287   1.0        0            10000
2005-01-04  41.755325   1.0        0            10000
2005-01-05  41.084076   1.0        0            10000
2005-01-06  41.385006   1.0        0            10000
2005-01-07  40.968349   1.0        0            10000
2005-01-10  41.454426   1.0        0            10000
2005-01-11  40.875774   1.0        0            10000
2005-01-12  40.929775   1.0        0            10000
2005-01-13  40.790901   1.0        0            10000
2005-01-14  41.269253   1.0        0            10000
</code>```

Body:
I am trying to figure out how to do this calculation without using a loop (if possible).

On the first trading day in January, I want to calculate the number of shares to buy based on the account value (starting $10k) divided by the closing price.

vb_shares = account / vb_close

In this instance I want vb_shares to be 234 for the entire month of January so I can calculate PnL each day and adjust the account value accordingly.

Now, when the first trading day in February occurs, I want to look at the updated account value (lets say its 9,800) and do the "shares" calculation again and populate the column with that fixed value for the entire month of February.

            vb_close    long_vb    vb_shares    account
Date
2005-01-03  42.596287   1.0        0            10000
2005-01-04  41.755325   1.0        0            10000
2005-01-05  41.084076   1.0        0            10000
2005-01-06  41.385006   1.0        0            10000
2005-01-07  40.968349   1.0        0            10000
2005-01-10  41.454426   1.0        0            10000
2005-01-11  40.875774   1.0        0            10000
2005-01-12  40.929775   1.0        0            10000
2005-01-13  40.790901   1.0        0            10000
2005-01-14  41.269253   1.0        0            10000


问:
How to write pre/post-scripts for Azure VMs?
I am trying to set up pre/post-scripts for our new patching system. The VMs need a tag added and turned on and then restarted and removed after. I don't have the roles to test just to get it done. Previous scripts I've seen to start our servers use functions-is this necessary? Very new to PowerShell and learning as I go so to speak curious about how the code looks/would run.</p>
```<code>##########################  ADDITION  ##################################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxx-xxxxx-xxxxx-xxx-xxxxxxxx-Credential $credentials
Set-AzContext -Subscription "xxxxx"

#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Get AVD's in the UAT or DEV environments
$rs = Get-AzVM | where {($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "DEV") -or ($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "UAT")}

#Add autoscaleignore tag to each machine
foreach($r in $rs){
    New-AZTag -Name $r.Name -ResouceGroupName $r.ResourceGroupName -Tag $tags
}

########################## POWER ON ####################################
#Get all machines the AutoScaleIgnore tag exists on
$asi = Get-AzVM | where {($_.Tags['AutoScaleIgnore'] -eq "") -or ($_.Tags['AutoScaleIgnore'] -eq "Patching")}

#Make sure all of those machines are turned on for patching
foreach($a in $asi){
    Start-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName -NoWait
}
########################################################################
</code>```
```<code>##############################  POST-SCRIPT  #############################
###############################  RESTART VM  #############################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx -Credential $credentials
Set-AzContext -Subscription "xxxxx"

$a = $env:computername
$a = Get-AzVM -Name $a
Restart-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName

################################  REMOVAL  ###############################
#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Remove autoscaleignore tag
$a = $env:computername
$a = Get-AzVM -Name $a
Update-AZTag -Name $a.Name -ResourceGroupName $a.ResourceGroupName -Tag $tags -Operation Delete

#########################################################################
</code>```

Body:
I am trying to set up pre/post-scripts for our new patching system. The VMs need a tag added and turned on and then restarted and removed after. I don't have the roles to test just to get it done. Previous scripts I've seen to start our servers use functions-is this necessary? Very new to PowerShell and learning as I go so to speak curious about how the code looks/would run.

##########################  ADDITION  ##################################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxx-xxxxx-xxxxx-xxx-xxxxxxxx-Credential $credentials
Set-AzContext -Subscription "xxxxx"

#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Get AVD's in the UAT or DEV environments
$rs = Get-AzVM | where {($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "DEV") -or ($_.Tags['AVD'] -eq "AVD" -and $_.Tags['Environment'] -eq "UAT")}

#Add autoscaleignore tag to each machine
foreach($r in $rs){
    New-AZTag -Name $r.Name -ResouceGroupName $r.ResourceGroupName -Tag $tags
}

########################## POWER ON ####################################
#Get all machines the AutoScaleIgnore tag exists on
$asi = Get-AzVM | where {($_.Tags['AutoScaleIgnore'] -eq "") -or ($_.Tags['AutoScaleIgnore'] -eq "Patching")}

#Make sure all of those machines are turned on for patching
foreach($a in $asi){
    Start-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName -NoWait
}
########################################################################

##############################  POST-SCRIPT  #############################
###############################  RESTART VM  #############################
$credentials = Import-Clixml -Path xxxxx
Connect-AzAccount -Tenant xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx -Credential $credentials
Set-AzContext -Subscription "xxxxx"

$a = $env:computername
$a = Get-AzVM -Name $a
Restart-AzVM -Name $a.name -ResourceGroupName $a.ResourceGroupName

################################  REMOVAL  ###############################
#Append 'AutoScaleIgnore' tag with 'Patching' value to $tags list
$tags += @{AutoScaleIgnore="Patching"}

#Remove autoscaleignore tag
$a = $env:computername
$a = Get-AzVM -Name $a
Update-AZTag -Name $a.Name -ResourceGroupName $a.ResourceGroupName -Tag $tags -Operation Delete

#########################################################################


问:
What do the feature importance numbers mean when doing elastic net feature importance
I have written some code that does some feature ranking in a dataset I have. And the result is a plot with the x-axis values being the names of the features and the y-values being numbers that go from 0 to 0.7

What do these specific numbers mean or represent? How do I interpret these as feature importance?

Here is a picture of the plot. I have added the 'Rank Weight' titles on the y-axis.


问:
Svelte react on dependency change rather than mere dependency assignment?
I'm having trouble with too much reaction that is causing expensive operations (like database queries) to be repeated unnecessarily when there has been no change to any dependencies.

Is there a way in Svelte to request reaction ONLY when a dependency has changed its value? With $:, Svelte reacts on assignment even if the assignment didn't change the value.

I find myself constantly coding reams of "lastVariableValue" type variables and manually comparing them to the new variable values and blocking reactive execution from proceeding further if there are no changes. This leads to a lot of what I feel like are rather unnecessary variables to store last values.

```<code>
let lastCurrentDateMode
let lastNodeName
let lastModelEntityId

$: (currentDateMode !== lastCurrentDateMode || entityNode?.name !== lastNodeName || modelEntity.modelEntityId != lastModelEntityId) && runQuery()

async function runQuery() {
  // do expensive query

  lastCurrentDateMode = currentDateMode
  lastNodeName = entityNode.name
  lastModelEntityId = modelEntity.modelEntityId
}

</code>```

It seems like there should be some way of telling Svelte to do this for us... react only if a dependent variable actually changes. That would reduce the above to just two lines of code.

Another method is to build my own conditional execution wrapper and use it everywhere throughout my code. Something like:

```<code>export const callfx = (_old, _vars, _function) => {
  if (Object.values(_vars).every(val => typeof val !== "undefined") && Object.entries(_vars).some(([name,val]) => JSON.stringify(_old[name]) !== JSON.stringify(val))) {
    _function.call()
  }

  Object.assign(_old,_vars)
}

// and imported into another component, where it used:

const _old={}
$: callfx(_old,{currentDateMode,entityNode,modelEntity},runQuery)
</code>```

This works and reduces the burden to one variable declaration per component (_old) and a single call line, but it feels like I'm trying to do something that should be built into the framework itself.

Body:
I'm having trouble with too much reaction that is causing expensive operations (like database queries) to be repeated unnecessarily when there has been no change to any dependencies.

Is there a way in Svelte to request reaction ONLY when a dependency has changed its value? With $:, Svelte reacts on assignment even if the assignment didn't change the value.

I find myself constantly coding reams of "lastVariableValue" type variables and manually comparing them to the new variable values and blocking reactive execution from proceeding further if there are no changes. This leads to a lot of what I feel like are rather unnecessary variables to store last values.

let lastCurrentDateMode
let lastNodeName
let lastModelEntityId

$: (currentDateMode !== lastCurrentDateMode || entityNode?.name !== lastNodeName || modelEntity.modelEntityId != lastModelEntityId) && runQuery()

async function runQuery() {
  // do expensive query

  lastCurrentDateMode = currentDateMode
  lastNodeName = entityNode.name
  lastModelEntityId = modelEntity.modelEntityId
}

It seems like there should be some way of telling Svelte to do this for us... react only if a dependent variable actually changes. That would reduce the above to just two lines of code.

Another method is to build my own conditional execution wrapper and use it everywhere throughout my code. Something like:

export const callfx = (_old, _vars, _function) => {
  if (Object.values(_vars).every(val => typeof val !== "undefined") && Object.entries(_vars).some(([name,val]) => JSON.stringify(_old[name]) !== JSON.stringify(val))) {
    _function.call()
  }

  Object.assign(_old,_vars)
}

// and imported into another component, where it used:

const _old={}
$: callfx(_old,{currentDateMode,entityNode,modelEntity},runQuery)

This works and reduces the burden to one variable declaration per component (_old) and a single call line, but it feels like I'm trying to do something that should be built into the framework itself.


问:
Why is jest failing to find a module?
I am running a test and I receive this problem:

```<code>Test suite failed to run OffersLanding.test.js

Cannot find module 'react-promise' from 'react-static-google-map.cjs.js'

However, Jest was able to find:
        './StaticMapContainer.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx',

'json', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
</code>```

The failing test looks like this:

```<code>import StaticMapContainer from "~/Components/StaticMapContainer";

return <StaticMapContainer {...props} />

</code>```

And StaticMapContainer looks like this:

```<code>import { StaticGoogleMap, Marker } from "react-static-google-map";

  return (
        <StaticGoogleMap>
           <Marker />
        </StaticGoogleMap>
    );
</code>```

Any idea for a workaround on this?

I tried adding these lines to the jest config but it didn't work:

```<code>    "moduleFileExtensions": [
      "js",
      "mjs",
      "cjs",
      "jsx",
      "ts",
      "tsx",
      "json",
      "node"
    ],
    "modulePaths": [ "<rootDir>"],
</code>```

Title: Why is jest failing to find a module?

Body:
I am running a test and I receive this problem:

Test suite failed to run OffersLanding.test.js

Cannot find module 'react-promise' from 'react-static-google-map.cjs.js'

However, Jest was able to find:
        './StaticMapContainer.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx',

'json', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

The failing test looks like this:

import StaticMapContainer from "~/Components/StaticMapContainer";

return <StaticMapContainer {...props} />

And StaticMapContainer looks like this:

import { StaticGoogleMap, Marker } from "react-static-google-map";

  return (
        <StaticGoogleMap>
           <Marker />
        </StaticGoogleMap>
    );

Any idea for a workaround on this?

I tried adding these lines to the jest config but it didn't work:

    "moduleFileExtensions": [
      "js",
      "mjs",
      "cjs",
      "jsx",
      "ts",
      "tsx",
      "json",
      "node"
    ],
    "modulePaths": [ "<rootDir>"],


问:
cant route traffic to backend with traefik kubernetes ingress
```<code>kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.ingress.kubernetes.io/router.middlewares: "{{ .Release.Namespace }}-{{ .Release.Name }}-middleware@kubernetescrd"
  name: "{{ .Release.Name }}-ingress"
  namespace: "{{ .Release.Namespace }}"
spec:
  tls:
    - hosts:
        - website
      secretName: "{{ .Release.Name }}-secret-tls"
  rules:
    - host: website
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-service
                port:
                  number: 80
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: api-nestjs-service
                port:
                  number: 8080
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: "{{ .Release.Name }}-middleware"
  namespace: "{{ .Release.Namespace }}"
spec:
  stripPrefix:
    forceSlash: false
    prefixes:
      - /api
</code>```

Am currently trying to make the / endpoint route towards the frontend, and the /api endpoint to the backend, where /api/a would just be /a
At the moment, I can get my frontend working completely fine, but I cant get the website to route to the backend, at all.
website.com/api/a will just show me a default website error, and because of this, its not redirecting to the backend.
Ive been trying to solve this for god knows how long, so any help would be appreciated

Body:
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.ingress.kubernetes.io/router.middlewares: "{{ .Release.Namespace }}-{{ .Release.Name }}-middleware@kubernetescrd"
  name: "{{ .Release.Name }}-ingress"
  namespace: "{{ .Release.Namespace }}"
spec:
  tls:
    - hosts:
        - website
      secretName: "{{ .Release.Name }}-secret-tls"
  rules:
    - host: website
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-service
                port:
                  number: 80
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: api-nestjs-service
                port:
                  number: 8080
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: "{{ .Release.Name }}-middleware"
  namespace: "{{ .Release.Namespace }}"
spec:
  stripPrefix:
    forceSlash: false
    prefixes:
      - /api

Am currently trying to make the / endpoint route towards the frontend, and the /api endpoint to the backend, where /api/a would just be /a
At the moment, I can get my frontend working completely fine, but I cant get the website to route to the backend, at all.
website.com/api/a will just show me a default website error, and because of this, its not redirecting to the backend.
Ive been trying to solve this for god knows how long, so any help would be appreciated


问:
Appending shapefiles to record
I am trying to append a record and its corresponding shape to a dictionary, but it is only appending the last value of each record

```<code>sf = shapefile.Reader(r"W:\Taiwo\ORE_TYPE_POLY\WCP_ORETYPE-polygon.shp")
polys = {}
for record, shape in zip(sf.iterRecords(), sf.iterShapes()):
    ore_type_code=record["Name"]
    polys[ore_type_code]=shape
</code>```

Results
polys

```<code>{'200': Shape #33: POLYGONZ,
 '201': Shape #7443: POLYGONZ,
 '202': Shape #13536: POLYGONZ,
 '203': Shape #25712: POLYGONZ,
 '204': Shape #32061: POLYGONZ,
 '205': Shape #34081: POLYGONZ,
 '206': Shape #35664: POLYGONZ,
 '207': Shape #44888: POLYGONZ,
 '209': Shape #45084: POLYGONZ,
 '210': Shape #54732: POLYGONZ}
</code>```

How can I ensure every values is appended instead of the last values of each keys?

Title: Appending shapefiles to record

Body:
I am trying to append a record and its corresponding shape to a dictionary, but it is only appending the last value of each record

sf = shapefile.Reader(r"W:\Taiwo\ORE_TYPE_POLY\WCP_ORETYPE-polygon.shp")
polys = {}
for record, shape in zip(sf.iterRecords(), sf.iterShapes()):
    ore_type_code=record["Name"]
    polys[ore_type_code]=shape

Results
polys

{'200': Shape #33: POLYGONZ,
 '201': Shape #7443: POLYGONZ,
 '202': Shape #13536: POLYGONZ,
 '203': Shape #25712: POLYGONZ,
 '204': Shape #32061: POLYGONZ,
 '205': Shape #34081: POLYGONZ,
 '206': Shape #35664: POLYGONZ,
 '207': Shape #44888: POLYGONZ,
 '209': Shape #45084: POLYGONZ,
 '210': Shape #54732: POLYGONZ}

How can I ensure every values is appended instead of the last values of each keys?


问:
How to show a normal UWP window with C++ WinRT Console Application template
I am trying to understand the full process of how does a UWP app work from scratch, so I want to reproduce the process with the C++ WinRT console application and want to create a window with XAML in it (just like a normal C++ WinRT blank page template). So far I have success with C++ WinRT Core application template, but not with the console application template. The code

struct XamlApp : public winrt::Windows::UI::Xaml::ApplicationT<XamlApp>
{
    void OnLaunched(winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs const&)
    {
        winrt::Windows::UI::Xaml::Window::Current().Content(winrt::UWPCore::MainPage());
        winrt::Windows::UI::Xaml::Window::Current().Activate();
    }

    // Inherited via ApplicationT
    virtual void use_make_function_to_create_this_object() override {}
};

int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
{
    winrt::init_apartment();
    winrt::Windows::UI::Xaml::Application::Start([](auto&&){ winrt::make<XamlApp>();});
}
```

This will successfully display a window using the Core Application template. But using the same code (but with the normal main function) with the Console Application template it fails with Windows.UI.Xaml.dll!00007FFAEFC26955: (caller: 00007FF720072F32) FailFast(1) tid(1680) 8000FFFF Catastrophic failure. Looking through the vcxproj files doesn't seem to provide any clue of what magic visual studio does for deploying the UWP app.

Body:
I am trying to understand the full process of how does a UWP app work from scratch, so I want to reproduce the process with the C++ WinRT console application and want to create a window with XAML in it (just like a normal C++ WinRT blank page template). So far I have success with C++ WinRT Core application template, but not with the console application template. The code

struct XamlApp : public winrt::Windows::UI::Xaml::ApplicationT<XamlApp>
{
    void OnLaunched(winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs const&)
    {
        winrt::Windows::UI::Xaml::Window::Current().Content(winrt::UWPCore::MainPage());
        winrt::Windows::UI::Xaml::Window::Current().Activate();
    }

    // Inherited via ApplicationT
    virtual void use_make_function_to_create_this_object() override {}
};

int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
{
    winrt::init_apartment();
    winrt::Windows::UI::Xaml::Application::Start([](auto&&){ winrt::make<XamlApp>();});
}

This will successfully display a window using the Core Application template. But using the same code (but with the normal main function) with the Console Application template it fails with Windows.UI.Xaml.dll!00007FFAEFC26955: (caller: 00007FF720072F32) FailFast(1) tid(1680) 8000FFFF Catastrophic failure. Looking through the vcxproj files doesn't seem to provide any clue of what magic visual studio does for deploying the UWP app.