问:
Make the seaborn hue legend logarithmic
I have two independent linear variables and one dependent exponential one.

x = range(100)
y = range(100)
z = [2**i for i in range(100)]
df = pd.DataFrame({"x":x,"y":y,"z":z})

sns.scatterplot(
    x=df.x,
    y=df.y,
    hue=df.z
)
```

How can I make the hue scale logarithmic such that the pattern in the data is revealed?

Can I prevent the legend from showing large numbers in scientific notation?

Pyplot only contains setters for x and y axis scales, I only found how to change the legend to discrete values.

Title: Make the seaborn hue legend logarithmic

Body:
I have two independent linear variables and one dependent exponential one.

x = range(100)
y = range(100)
z = [2**i for i in range(100)]
df = pd.DataFrame({"x":x,"y":y,"z":z})

sns.scatterplot(
    x=df.x,
    y=df.y,
    hue=df.z
)

How can I make the hue scale logarithmic such that the pattern in the data is revealed?

Can I prevent the legend from showing large numbers in scientific notation?

Pyplot only contains setters for x and y axis scales, I only found how to change the legend to discrete values.


来源: stackexchange

问:
Coherence values do not agree when trying to calculate using different methods
I'm trying to see if I can obtain identical coherence values for two signals when computing them two different ways:

Method 1: I first compute the cross-correlation and the two auto-correlations. Then I take the DFT of the results to obtain the cross-spectral density and the power spectral densities, from which the coherence can be computed.

Method 2: I simply apply the coherence function from scipy.signal.

```<code>import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import correlate,coherence

t  = np.arange(0, 1, 0.001);
dt = t[1] - t[0]
fs=1/dt

f0=250
f1=400

x=np.cos(2*np.pi*f0*t)+np.cos(2*np.pi*f1*t)
y=np.cos(2*np.pi*f0*(t-.035))+np.cos(2*np.pi*f1*(t-.05))

fig, ax = plt.subplots(2,sharex=True)

# Coherence using method 1:
Rxx = correlate(x,x)
Pxx= abs(np.fft.rfft(Rxx))

Ryy = correlate(y,y)
Pyy = abs(np.fft.rfft(Ryy))

Rxy = correlate(x,y)
Pxy = abs(np.fft.rfft(Rxy))

f = np.fft.rfftfreq(len(Rxy))*fs
Coh1=np.divide(Pxy**2,np.multiply(Pxx,Pyy))

#Start at nonzero index, e.g. 50, since Pxx[0]=Pyy[0] where Coh[0] would be undefined
ax[0].plot(f[50:], Coh1[50:])
both equal zero
ax[0].set_xlabel('frequency [Hz]')
ax[0].set_ylabel('Coherence')

# Coherence using method 2:
f,Coh2=coherence(x,y)

ax[1].plot(f*fs,Coh2)
ax[1].set_xlabel('frequency [Hz]')
ax[1].set_ylabel('Coherence')

plt.show()
</code>```

I obtain the graphs shown below.

The results don't make sense to me. Not only are they different, but neither produces coherence values equal to one at frequencies 250 and 400. The second method should yield an undefined coherence except at 250 and 400.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to see if I can obtain identical coherence values for two signals when computing them two different ways:

Method 1: I first compute the cross-correlation and the two auto-correlations. Then I take the DFT of the results to obtain the cross-spectral density and the power spectral densities, from which the coherence can be computed.

Method 2: I simply apply the coherence function from scipy.signal.

import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import correlate,coherence

t  = np.arange(0, 1, 0.001);
dt = t[1] - t[0]
fs=1/dt

f0=250
f1=400

x=np.cos(2*np.pi*f0*t)+np.cos(2*np.pi*f1*t)
y=np.cos(2*np.pi*f0*(t-.035))+np.cos(2*np.pi*f1*(t-.05))

fig, ax = plt.subplots(2,sharex=True)

# Coherence using method 1:
Rxx = correlate(x,x)
Pxx= abs(np.fft.rfft(Rxx))

Ryy = correlate(y,y)
Pyy = abs(np.fft.rfft(Ryy))

Rxy = correlate(x,y)
Pxy = abs(np.fft.rfft(Rxy))

f = np.fft.rfftfreq(len(Rxy))*fs
Coh1=np.divide(Pxy**2,np.multiply(Pxx,Pyy))

#Start at nonzero index, e.g. 50, since Pxx[0]=Pyy[0] where Coh[0] would be undefined
ax[0].plot(f[50:], Coh1[50:])
both equal zero
ax[0].set_xlabel('frequency [Hz]')
ax[0].set_ylabel('Coherence')

# Coherence using method 2:
f,Coh2=coherence(x,y)

ax[1].plot(f*fs,Coh2)
ax[1].set_xlabel('frequency [Hz]')
ax[1].set_ylabel('Coherence')

plt.show()

I obtain the graphs shown below.

The results don't make sense to me. Not only are they different, but neither produces coherence values equal to one at frequencies 250 and 400. The second method should yield an undefined coherence except at 250 and 400.


问:
How to specified compileSdkVersion to build.gradle
As soon as I opened a project created through 'Create React Native App' with VS Code, the following error occurred:

The supplied phased action failed with an exception. A problem occurred configuring project ':expo'. compileSdkVersion is not specified. Please add it to build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = findProperty('android.buildToolsVersion') ?: '31.0.0'
        minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '21')
        compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '31')
        targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '31')
        if (findProperty('android.kotlinVersion')) {
            kotlinVersion = findProperty('android.kotlinVersion')
        }
        frescoVersion = findProperty('expo.frescoVersion') ?: '2.5.0'

        if (System.properties['os.arch'] == 'aarch64') {
            // For M1 Users we need to use the NDK 24 which added support for aarch64
            ndkVersion = '24.0.8215888'
        } else {
            // Otherwise we default to the side-by-side NDK version from AGP.
            ndkVersion = '21.4.7075529'
        }
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.2.1')
        classpath('com.facebook.react:react-native-gradle-plugin')
        classpath('de.undercouch:gradle-download-task:5.0.1')
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

def REACT_NATIVE_VERSION = new File(['node', '--print', "JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())

allprojects {
    configurations.all {
        resolutionStrategy {
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }

    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(['node', '--print', "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), '../dist'))
        }

        google()
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup 'com.facebook.react'
            }
        }
        maven { url 'https://www.jitpack.io' }
    }
}

</code>```

This is my build.gradle file.

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile

def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()

def reactNativeRoot = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath()

project.ext.react = [
    entryFile: ["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android"].execute(null, rootDir).text.trim(),
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
    hermesCommand: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc",
    cliPath: "${reactNativeRoot}/cli.js",
    composeSourceMapsPath: "${reactNativeRoot}/scripts/compose-source-maps.js",
]

apply from: new File(reactNativeRoot, "react.gradle")

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.binancetradingbot"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the CMake build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                cmake {
                    arguments "-DPROJECT_BUILD_DIR=$buildDir",
                        "-DREACT_ANDROID_DIR=${reactNativeRoot}/ReactAndroid",
                        "-DREACT_ANDROID_BUILD_DIR=${reactNativeRoot}/ReactAndroid/build",
                        "-DNODE_MODULES_DIR=$rootDir/../node_modules",
                        "-DANDROID_STL=c++_shared"
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the CMake build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            cmake {
                path "$projectDir/src/main/jni/CMakeLists.txt"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureCMakeDebug* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
            configureCMakeDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
    // Split option: 'foo,bar' -> ['foo', 'bar']
    def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
    // Trim all elements in place.
    for (i in 0..<options.size()) options[i] = options[i].trim();
    // `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
    options -= ""

    if (options.length > 0) {
        println "android.packagingOptions.$prop += $options ($options.length)"
        // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
        options.each {
            android.packagingOptions[prop] += it
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
    def frescoVersion = rootProject.ext.frescoVersion

    // If your app supports Android versions before Ice Cream Sandwich (API level 14)
    if (isGifEnabled || isWebpEnabled) {
        implementation "com.facebook.fresco:fresco:${frescoVersion}"
        implementation "com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}"
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation "com.facebook.fresco:animated-gif:${frescoVersion}"
    }

    if (isWebpEnabled) {
        // For webp support
        implementation "com.facebook.fresco:webpsupport:${frescoVersion}"
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation "com.facebook.fresco:animated-webp:${frescoVersion}"
        }
    }

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        //noinspection GradleDynamicVersion
        implementation("com.facebook.react:hermes-engine:+") { // From node_modules
            exclude group:'com.facebook.fbjni'
        }
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid"))
                    .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                    .using(project(":ReactAndroid:hermes-engine"))
                    .because("On New Architecture we're building Hermes from source")
        }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

</code>```

The second code I showed you is my app/build.gradle file.

Even if I searched on the Internet, I couldn't get a clear answer. How to specified compileSdkVersion to build.gradle?

I expecting How to specified compileSdkVersion to build.gradle

Body:
As soon as I opened a project created through 'Create React Native App' with VS Code, the following error occurred:

The supplied phased action failed with an exception. A problem occurred configuring project ':expo'. compileSdkVersion is not specified. Please add it to build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = findProperty('android.buildToolsVersion') ?: '31.0.0'
        minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '21')
        compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '31')
        targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '31')
        if (findProperty('android.kotlinVersion')) {
            kotlinVersion = findProperty('android.kotlinVersion')
        }
        frescoVersion = findProperty('expo.frescoVersion') ?: '2.5.0'

        if (System.properties['os.arch'] == 'aarch64') {
            // For M1 Users we need to use the NDK 24 which added support for aarch64
            ndkVersion = '24.0.8215888'
        } else {
            // Otherwise we default to the side-by-side NDK version from AGP.
            ndkVersion = '21.4.7075529'
        }
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.2.1')
        classpath('com.facebook.react:react-native-gradle-plugin')
        classpath('de.undercouch:gradle-download-task:5.0.1')
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

def REACT_NATIVE_VERSION = new File(['node', '--print', "JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())

allprojects {
    configurations.all {
        resolutionStrategy {
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }

    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(['node', '--print', "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), '../dist'))
        }

        google()
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup 'com.facebook.react'
            }
        }
        maven { url 'https://www.jitpack.io' }
    }
}

This is my build.gradle file.

apply plugin: "com.android.application"

import com.android.build.OutputFile

def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()

def reactNativeRoot = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath()

project.ext.react = [
    entryFile: ["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android"].execute(null, rootDir).text.trim(),
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
    hermesCommand: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc",
    cliPath: "${reactNativeRoot}/cli.js",
    composeSourceMapsPath: "${reactNativeRoot}/scripts/compose-source-maps.js",
]

apply from: new File(reactNativeRoot, "react.gradle")

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.binancetradingbot"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the CMake build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                cmake {
                    arguments "-DPROJECT_BUILD_DIR=$buildDir",
                        "-DREACT_ANDROID_DIR=${reactNativeRoot}/ReactAndroid",
                        "-DREACT_ANDROID_BUILD_DIR=${reactNativeRoot}/ReactAndroid/build",
                        "-DNODE_MODULES_DIR=$rootDir/../node_modules",
                        "-DANDROID_STL=c++_shared"
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the CMake build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            cmake {
                path "$projectDir/src/main/jni/CMakeLists.txt"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureCMakeDebug* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
            configureCMakeDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
    // Split option: 'foo,bar' -> ['foo', 'bar']
    def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
    // Trim all elements in place.
    for (i in 0..<options.size()) options[i] = options[i].trim();
    // `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
    options -= ""

    if (options.length > 0) {
        println "android.packagingOptions.$prop += $options ($options.length)"
        // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
        options.each {
            android.packagingOptions[prop] += it
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
    def frescoVersion = rootProject.ext.frescoVersion

    // If your app supports Android versions before Ice Cream Sandwich (API level 14)
    if (isGifEnabled || isWebpEnabled) {
        implementation "com.facebook.fresco:fresco:${frescoVersion}"
        implementation "com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}"
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation "com.facebook.fresco:animated-gif:${frescoVersion}"
    }

    if (isWebpEnabled) {
        // For webp support
        implementation "com.facebook.fresco:webpsupport:${frescoVersion}"
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation "com.facebook.fresco:animated-webp:${frescoVersion}"
        }
    }

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        //noinspection GradleDynamicVersion
        implementation("com.facebook.react:hermes-engine:+") { // From node_modules
            exclude group:'com.facebook.fbjni'
        }
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid"))
                    .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                    .using(project(":ReactAndroid:hermes-engine"))
                    .because("On New Architecture we're building Hermes from source")
        }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

The second code I showed you is my app/build.gradle file.

Even if I searched on the Internet, I couldn't get a clear answer. How to specified compileSdkVersion to build.gradle?

I expecting How to specified compileSdkVersion to build.gradle


问:
How to create an instruction in module pass calling gettimeofday()?
I want to insert the gettimeofday call statement at the specified location at compile time (llvm pass) , but I don not know how to create the instruction now. Any suggestions?</p>


问:
Failed to run dotnet restore
When trying to run dotnet restore in the root folder of my project, I get a following error:

```<code>C:\Program Files\dotnet\sdk\7.0.100\NuGet.targets(676,5): error : Unable to obtain lock file access on 'C:\Users\user\AppData\Local\Temp\NuGetScratch\lock' fo
r operations on 'C:\Users\user\AppData\Roaming\NuGet\NuGet.Config'. This may mean that a different user or administrator is holding this lock and that this pr
rashed and left an inaccessible lock file, in this case removing the file 'C:\Users\user\AppData\Local\Temp\NuGetScratch\lock' will allow NuGet to continue. [
C:\Users\user\Documents\Kurs C#\FirstProject\FirstProject\FirstProject.csproj]
</code>```

None of the solutions I've found in the Microsoft docs work. I've managed to find a possible solution here:
Dotnet commands fail when restoring Nuget packages in shell script
However, how exactly am I supposed to change these permissions?

Title: Failed to run dotnet restore

Body:
When trying to run dotnet restore in the root folder of my project, I get a following error:

C:\Program Files\dotnet\sdk\7.0.100\NuGet.targets(676,5): error : Unable to obtain lock file access on 'C:\Users\user\AppData\Local\Temp\NuGetScratch\lock' fo
r operations on 'C:\Users\user\AppData\Roaming\NuGet\NuGet.Config'. This may mean that a different user or administrator is holding this lock and that this pr
rashed and left an inaccessible lock file, in this case removing the file 'C:\Users\user\AppData\Local\Temp\NuGetScratch\lock' will allow NuGet to continue. [
C:\Users\user\Documents\Kurs C#\FirstProject\FirstProject\FirstProject.csproj]

None of the solutions I've found in the Microsoft docs work. I've managed to find a possible solution here:
Dotnet commands fail when restoring Nuget packages in shell script
However, how exactly am I supposed to change these permissions?


问:
GPU driver issue, android studio, HP Elitebook 840 G1
Laptop: HP Elitebook 840 G1
Ram: 12GB
Rom: 512GB

Graphic: Intel Integrated HD Graphics 4400

It's showing black screen on mobile and also, GPU driver issue.

I have install HAXM and also enable Hyper-V. But still not able to run emulator.


问:
Querying JPA Specification CriteriaBuilder with join column
This is my Deal entity :

```<code>@Data
@NoArgsConstructor
@Entity
@Table(name = "tbl_deal")
public class Deal {

    @Id
    @GeneratedValue(strategy = SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "quantity")
    private Integer quantity;

    @Column(name = "price", precision = 21, scale = 2)
    private BigDecimal price;

    @Column(name = "is_active")
    private Boolean isActive;

    @ManyToOne
    @JoinColumn(name = "branch")
    private Branch branch;
}
</code>```

This is my Branch entity :

```<code>@Data
@NoArgsConstructor
@Entity
@Table(name = "tbl_branch")
public class Branch {

    @Id
    @GeneratedValue(strategy = SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @NotNull
    @Size(min = 3, max = 254)
    @Column(name = "name", length = 254, nullable = false)
    private String name;

    @Column(nullable = false)
    private String phoneNumber;
}
</code>```

This is the helper method to build specification :

```<code>    private Specification<T> fieldLike(String fieldName, String value) {
        return (object, cq, cb) -> cb.like(
                cb.lower(object.get(fieldName)), "%" + value.toLowerCase() + "%"
        );
    }
</code>```

when I pass "branch.name" to this method while querying Deal entity, I get the following exception

org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [branch.name] on this ManagedType [com.xxx.Deal]; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [branch.name] on this ManagedType [com.xxx.Deal]

Body:
This is my Deal entity :

@Data
@NoArgsConstructor
@Entity
@Table(name = "tbl_deal")
public class Deal {

    @Id
    @GeneratedValue(strategy = SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "quantity")
    private Integer quantity;

    @Column(name = "price", precision = 21, scale = 2)
    private BigDecimal price;

    @Column(name = "is_active")
    private Boolean isActive;

    @ManyToOne
    @JoinColumn(name = "branch")
    private Branch branch;
}

This is my Branch entity :

@Data
@NoArgsConstructor
@Entity
@Table(name = "tbl_branch")
public class Branch {

    @Id
    @GeneratedValue(strategy = SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @NotNull
    @Size(min = 3, max = 254)
    @Column(name = "name", length = 254, nullable = false)
    private String name;

    @Column(nullable = false)
    private String phoneNumber;
}

This is the helper method to build specification :

    private Specification<T> fieldLike(String fieldName, String value) {
        return (object, cq, cb) -> cb.like(
                cb.lower(object.get(fieldName)), "%" + value.toLowerCase() + "%"
        );
    }

when I pass "branch.name" to this method while querying Deal entity, I get the following exception

org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [branch.name] on this ManagedType [com.xxx.Deal]; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [branch.name] on this ManagedType [com.xxx.Deal]


问:
How to get copied text content in android device by adb in PC side
I am developing android automation test tool.

I would like to know how to get copied text content (which is copied in android device) in PC side by adb.
Is there any good way to get this info?
I am using python and ppadb module, so I would like to know adb shell command to solve this question if it exists.

I tried the below command, but they did not work.

```<code>adb shell static final int TRANSACTION_getClipboardText 1
adb shell tatic final int TRANSACTION_setPrimaryClip = 1
</code>```

Body:
I am developing android automation test tool.

I would like to know how to get copied text content (which is copied in android device) in PC side by adb.
Is there any good way to get this info?
I am using python and ppadb module, so I would like to know adb shell command to solve this question if it exists.

I tried the below command, but they did not work.

adb shell static final int TRANSACTION_getClipboardText 1
adb shell tatic final int TRANSACTION_setPrimaryClip = 1


问:
Visual Studio Code commits untracked files (!). How to prevent this behaviour?
So I added a file containing sensitive information to my working folder.
When I committed using VS Code, I was shocked to see that that file, maked as untracked, was being committed.

My understanding of Git is that for files to be committed they must first be tracked and staged.

Is VS Code committing everything in the folder (unless you add it to .gitignore, which is not very working-friendly (as having to add all the new files to .gitignore is a pesky task...).

I may be missing something.

Thanks for your help!

I committed changed from within VS Code expecting only those changes in tracked files that had been staged to be committed. VS Code committed everything and pushed to repo sensitive untracked info.


问:
list index out of range
I created a Telegram bot with MySQL database. The user can insert and retrieve the orders from MySQL. The telegram bot will display the order details from MySQL when the user inputs the /select command. I have attached the MySQL table with two orders.

```<code>from datetime import datetime
import mysql.connector
import telebot

bot_token = ''

mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "telegram",
)

my_cursor = mydb.cursor()

bot = telebot.TeleBot(token=bot_token)

@bot.message_handler(commands=['select'])

def select_order(event):
    try:
        my_cursor.execute("SELECT * FROM mysql")
        res = my_cursor.fetchall() # fetch all the results
        mydb.commit()

        if(res):
            text = create_message_select_query(res)
            bot.send_message(event.chat.id, text)

        else:
            bot.send_message(event.chat.id, "No orders found inside the database.")

    except Exception as e:
        print(e)
        bot.send_message(event.chat.id, "Something Wrong happened... Check your code!")

def create_message_select_query(ans):
    text = " "
    for i in ans:
        id = i[0]
        product = i[1]
        quantity = i[2]
        date_edited = i[3]
        text += "<b>"+ str(id) +"</b> | " + "<b>"+ str(product) +"</b> | " + "<b>"+ str(quantity)+"</b> | " + "<b>"+ str(date_edited)+"</b>\n"
    message = "<b>Received  </b> Information about orders:\n\n"+text
    return message

bot.polling()
</code>```

I encountered an error list index out of range when I input the telegram command /select.
How do I fix the above error?

Title: list index out of range

Body:
I created a Telegram bot with MySQL database. The user can insert and retrieve the orders from MySQL. The telegram bot will display the order details from MySQL when the user inputs the /select command. I have attached the MySQL table with two orders.

from datetime import datetime
import mysql.connector
import telebot

bot_token = ''

mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "telegram",
)

my_cursor = mydb.cursor()

bot = telebot.TeleBot(token=bot_token)

@bot.message_handler(commands=['select'])

def select_order(event):
    try:
        my_cursor.execute("SELECT * FROM mysql")
        res = my_cursor.fetchall() # fetch all the results
        mydb.commit()

        if(res):
            text = create_message_select_query(res)
            bot.send_message(event.chat.id, text)

        else:
            bot.send_message(event.chat.id, "No orders found inside the database.")

    except Exception as e:
        print(e)
        bot.send_message(event.chat.id, "Something Wrong happened... Check your code!")

def create_message_select_query(ans):
    text = " "
    for i in ans:
        id = i[0]
        product = i[1]
        quantity = i[2]
        date_edited = i[3]
        text += ""+ str(id) +" | " + ""+ str(product) +" | " + ""+ str(quantity)+" | " + ""+ str(date_edited)+"\n"
    message = "Received   Information about orders:\n\n"+text
    return message

bot.polling()

I encountered an error list index out of range when I input the telegram command /select.
How do I fix the above error?


问:
How to convert Dockerfile-based python deployment on Google Cloud Run into an equivalent Procfile-based approach?
I executed this headless chrome with Cloud Run poc on Google Cloud Run and it worked fine. For that, I created main.py, requirements.txt file and Dockerfile as given in the article. Now, I'm trying to redo the same with Procfile and it's not working.

Here is the Procfile I created:

```<code>web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 30 --keep-alive 5 main:app
</code>```

When I deploy to cloud run, and invoke the service URL, I get the following error as I see in Logs Explorer:

```<code>selenium.common.exceptions.WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127
</code>```

The issue seems to be that the docker file installs the following dependencies and installs chrome before bringing up the server, which I'm unable to do with Procfile.

```<code>RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils

# Install Chrome
RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install
</code>```

I did try using 'release' process type in the Procfile as follows:

```<code>release: bash chrome.sh
web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 --keep-alive 5 main:app
</code>```

And, chrome.sh contains the same code to install dependencies and chrome:

```<code>apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils

# Install Chrome
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install
</code>```

But that didn't work and the dependencies and chrome did not get installed.

Any help on using Procfile to achieve the same results?

Body:
I executed this headless chrome with Cloud Run poc on Google Cloud Run and it worked fine. For that, I created main.py, requirements.txt file and Dockerfile as given in the article. Now, I'm trying to redo the same with Procfile and it's not working.

Here is the Procfile I created:

web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 30 --keep-alive 5 main:app

When I deploy to cloud run, and invoke the service URL, I get the following error as I see in Logs Explorer:

selenium.common.exceptions.WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127

The issue seems to be that the docker file installs the following dependencies and installs chrome before bringing up the server, which I'm unable to do with Procfile.

RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils

# Install Chrome
RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install

I did try using 'release' process type in the Procfile as follows:

release: bash chrome.sh
web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 --keep-alive 5 main:app

And, chrome.sh contains the same code to install dependencies and chrome:

apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils

# Install Chrome
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install

But that didn't work and the dependencies and chrome did not get installed.

Any help on using Procfile to achieve the same results?


问:
How to give write and execute permissions to newly created files inside a WSL distro from Windows?
The file permissions documentation for WSL in microsoft's page says:

The default umask is applied when creating a new file inside of a WSL
distribution from Windows. The default umask is 022, or in other words
it allows all permissions except write permissions to groups and
others.

I use sudo chmod -R a+rwx /path/to/folder on newly created directories. Since every article I've read about the aforementioned command say its a bad security practice, is there a better way to give write permissions to the default Windows user only for every newly created directories.


问:
error installing packages via conda (python3)
I am in a conda virtual environment and am getting a PackagesNotFoundError error when running

conda install --name myenv --file my_packages.txt where my_packages.txt is a text file with a python package name on each line.

but some packages that were giving me an error existed in the conda-forge environment (i had already --append conda-forge to my virtual environment), so I tried some of the failed packages individually, e.g.:

conda install -c conda-forge time

as well as all the other options that are listed here: https://anaconda.org/conda-forge/time
but am still getting the same PackagesNotFoundError each time.

Can anyone tell me why this is?

For extra context, the other packages I'm having issues with are: websockets, nest_asyncio, hmac, json, base64, etc.
But the time packages is very confusing since it clearly exists in conda-forge (^ link).

I can post the current channels listed via the error output in the comments since StackOverflow isn't letting me post so many links.

I am using:

conda 22.11.1 (from miniconda)

MacOS 13.0.1

Thank you.


问:
Array declaration in Pine Script
What is the different between and the usecases of these two way of declarations?

```<code>var _low = float(na)
</code>```

This will be interpreted as "series float"

```<code>var float[] _low = na
</code>```

This will be interpreted as undetermined type

I'm trying to run this code but it return error if I use the second way to declare the array

```<code>if showWeek and newTF
    _high := high
    _low := low
    _open := open
    weekH := drawWeekHline(high)
    weekL := drawWeekHline(low)
    weekO := drawWeekHline(open)
    int(na)
else
    int(na)
</code>```

Variable '_high' was declared with 'float[]' type. Cannot assign it expression of type 'series float'

Title: Array declaration in Pine Script

Body:
What is the different between and the usecases of these two way of declarations?

var _low = float(na)

This will be interpreted as "series float"

var float[] _low = na

This will be interpreted as undetermined type

I'm trying to run this code but it return error if I use the second way to declare the array

if showWeek and newTF
    _high := high
    _low := low
    _open := open
    weekH := drawWeekHline(high)
    weekL := drawWeekHline(low)
    weekO := drawWeekHline(open)
    int(na)
else
    int(na)

Variable '_high' was declared with 'float[]' type. Cannot assign it expression of type 'series float'


问:
Hi all, I try to modify a static website hosted by github pages, but I have the following error:
Logon failed, use ctrl+c to cancel basic credential prompt. remote: Support for password authentication was removed on August 13, 2021. remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication. fatal: Authentication failed for 'https://github.com/omnislashh/anim_site.git/'
Any help, please? I have an SSH key for my computer already, so I don't understand why I can't push the modifications for this project.

I trying to folow the documentation, push and enter passwords asked, and even SSH just in case.


问:
husky / lint-staged not running custom command or printing errors
I am trying to upgrade from husky@4.8 and lint-staged@11.2 to husky@8.0 and lint-staged@@13.1 for my Nx repo. It seems that the only configuration I used to need was the following in package.json:

```<code>"scripts: {
    "lint:fix": "ng lint -- --fix && npm run prettier:fix",
}
"husky": {
    "hooks": {
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.{ts,js,css,md,html}": "npm run lint:fix",
    "relative": true
  }
</code>```

This no longer works with the new husky and lint-staged. I followed this tutorial and installed husky: npx husky-init && npm install, installed lint-staged: npm install --save-dev lint-staged, modified the .husky/pre-commit file:

```<code>#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
</code>```

and added the .lintstagedrc.json file:

```<code>{
  "*.ts": [
    "prettier --write",
    "eslint"
  ],
  "*.html": [
    "eslint",
    "prettier --write"
  ],
  "*.scss": "prettier --write"
}
</code>```

When I make a new commit it seems to run. However it looks like this command either runs on every library or every staged file (I have a lot of libraries). When I change the file contents to:

```<code>{
    "*.{js,ts,json,scss,md}": ["npm run lint:fix"]
}
</code>```

it takes a while to run (though it seems to run and fix the linting) AND I don't get the output of my ng lint -- --fix command. If I go into the .husky/pre-commit file and change npx lint-staged to npm run lint:fix, it runs the ng lint -- --fix command, fixes what it can and prints out linting errors. However, the error doesn't prevent the commit and I have to commit any new changes that the linter fixed. With the old versions I didn't need to do this. Also I didn't need to commit a .husky/pre-commit file into my repo. (I see some workarounds that have a postinstall script that generates this file for the user).

How can I utilize lint-stage and husky newest versions to run my custom npm command so I can call ng lint like in the older versions and block commits on errors? Should I just use the older versions? Also what benefit do the newer versions provide?

Body:
I am trying to upgrade from husky@4.8 and lint-staged@11.2 to husky@8.0 and lint-staged@@13.1 for my Nx repo. It seems that the only configuration I used to need was the following in package.json:

"scripts: {
    "lint:fix": "ng lint -- --fix && npm run prettier:fix",
}
"husky": {
    "hooks": {
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.{ts,js,css,md,html}": "npm run lint:fix",
    "relative": true
  }

This no longer works with the new husky and lint-staged. I followed this tutorial and installed husky: npx husky-init && npm install, installed lint-staged: npm install --save-dev lint-staged, modified the .husky/pre-commit file:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged

and added the .lintstagedrc.json file:

{
  "*.ts": [
    "prettier --write",
    "eslint"
  ],
  "*.html": [
    "eslint",
    "prettier --write"
  ],
  "*.scss": "prettier --write"
}

When I make a new commit it seems to run. However it looks like this command either runs on every library or every staged file (I have a lot of libraries). When I change the file contents to:

{
    "*.{js,ts,json,scss,md}": ["npm run lint:fix"]
}

it takes a while to run (though it seems to run and fix the linting) AND I don't get the output of my ng lint -- --fix command. If I go into the .husky/pre-commit file and change npx lint-staged to npm run lint:fix, it runs the ng lint -- --fix command, fixes what it can and prints out linting errors. However, the error doesn't prevent the commit and I have to commit any new changes that the linter fixed. With the old versions I didn't need to do this. Also I didn't need to commit a .husky/pre-commit file into my repo. (I see some workarounds that have a postinstall script that generates this file for the user).

How can I utilize lint-stage and husky newest versions to run my custom npm command so I can call ng lint like in the older versions and block commits on errors? Should I just use the older versions? Also what benefit do the newer versions provide?


问:
webpagetest agent, how to start, stop and configure it?
The installation instructions for the universal webpagetest agent is here:

https://github.com/WPO-Foundation/wptagent-install

However, here is no documentation on how to:

start the agent

stop the agent

see if the agent is running

configure the agent (e.g. set the WPT_SEVER and WPT_KEY) post install.


问:
KIVY + PYTHON Class import issue
Any ideas on this error? The class exists not in the "main.py" but in the "dashboard.py" view and then I want to use in the dashboard.kv view file.  When I put this class in main.py it works fine, but I do not want to clutter my main with all the code. I have tried multiple ways of importing it, but still the same error...

First import try:

Here is how I am importing custom widget into the dashboard.kv from dashbutton.kv

Here is how I am importing dashboard.py to main.py:

Title: KIVY + PYTHON Class import issue


问:
inject respository into service in symfony
i have OrderRepository that i registered and i used it as dependency injection in my OrderService but i get this error.
symfony version is 2.8

```<code>Type error: Argument 1 passed to OrderBundle\Services\OrderService::__construct() must be an instance of OrderBundle\Entity\Repository\OrderRepository, instance of Doctrine\ORM\EntityRepository given, called in /var/www/html/app/cache/dev/appDevDebugProjectContainer.php on line 13296
</code>```

and this is my service.yml configurations:

```<code>x.order.repository:
  class: OrderBundle\Entity\Repository\OrderRepository
  factory: [ '@doctrine.orm.entity_manager', getRepository ]
  arguments:
      - OrderBundle\Entity\Order

x.order.service:
  class: OrderBundle\Services\OrderService
  arguments:
    - '@x.order.repository'
</code>```

could you please give me soltion fo this problem?

Body:
i have OrderRepository that i registered and i used it as dependency injection in my OrderService but i get this error.
symfony version is 2.8

Type error: Argument 1 passed to OrderBundle\Services\OrderService::__construct() must be an instance of OrderBundle\Entity\Repository\OrderRepository, instance of Doctrine\ORM\EntityRepository given, called in /var/www/html/app/cache/dev/appDevDebugProjectContainer.php on line 13296

and this is my service.yml configurations:

x.order.repository:
  class: OrderBundle\Entity\Repository\OrderRepository
  factory: [ '@doctrine.orm.entity_manager', getRepository ]
  arguments:
      - OrderBundle\Entity\Order

x.order.service:
  class: OrderBundle\Services\OrderService
  arguments:
    - '@x.order.repository'

could you please give me soltion fo this problem?


问:
Please can someone help me display a list on a pygame screen where each item can be displayed under each other?
I’m trying to display my list on a pygame window
[‘172773:Jerry, 27722:Harry, 23:Josh]

And I want to display the ítems line by line if this is possible
Many thanks

I tried using ways which would work in Python Idle, but they didn’t work


问:
is there a setuptools interface to pyproject.toml?
Does setuptools provide an interface to the pyproject.toml from within the setup.py? for example...

pyproject.toml

[build-system]
requires = ["setuptools>=58.2.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my_module"
version = "0.0.1"
requires-python = ">=3.10"
[tool.setuptools]
include-package-data = true
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
my_module = ["py.typed", "*.pyi", "**/*.pyi"]
```
<h3>setup.py</h3>
<pre class="lang-py prettyprint-override"><code>from setuptools import setup, Extension
from pathlib import Path

PROJECT_NAME = 'my_module' # can I access the project.name
PACKAGE_DIR = 'src' # or project.tool.setuptools.packages.find.where
root = Path(__file__).parent / PACKAGE_DIR

extension_modules = [
    Extension(
        f"{PROJECT_NAME}.api",
        [file.as_posix() for file in root.rglob("*.cpp")],
    ),
]

setup(ext_modules=extension_modules)

</code>```

Body:
Does setuptools provide an interface to the pyproject.toml from within the setup.py? for example...

pyproject.toml

[build-system]
requires = ["setuptools>=58.2.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my_module"
version = "0.0.1"
requires-python = ">=3.10"
[tool.setuptools]
include-package-data = true
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
my_module = ["py.typed", "*.pyi", "**/*.pyi"]

setup.py

from setuptools import setup, Extension
from pathlib import Path

PROJECT_NAME = 'my_module' # can I access the project.name
PACKAGE_DIR = 'src' # or project.tool.setuptools.packages.find.where
root = Path(__file__).parent / PACKAGE_DIR

extension_modules = [
    Extension(
        f"{PROJECT_NAME}.api",
        [file.as_posix() for file in root.rglob("*.cpp")],
    ),
]

setup(ext_modules=extension_modules)


问:
Make Selector to listen to two variables not only one
i'm using Selector to listen to changes of data but i have two arguments not one i made reaserch and i found i can use tuples like this

```<code>Selector<Foo, Tuple2<Bar, Baz>>(
  selector: (_, foo) => Tuple2(foo.bar, foo.baz),
  builder: (_, data, __) {
    return Text('${data.item1}  ${data.item2}');
  }
)
</code>```

and they explained like this In that example, builder will be called again only if foo.bar OR foo.baz changes.
what i want is to make the selector behave like this builder will be called again only if foo.bar AND foo.baz changes.
how to implement that

flutter dart

Body:
i'm using Selector to listen to changes of data but i have two arguments not one i made reaserch and i found i can use tuples like this

Selector<Foo, Tuple2<Bar, Baz>>(
  selector: (_, foo) => Tuple2(foo.bar, foo.baz),
  builder: (_, data, __) {
    return Text('${data.item1}  ${data.item2}');
  }
)

and they explained like this In that example, builder will be called again only if foo.bar OR foo.baz changes.
what i want is to make the selector behave like this builder will be called again only if foo.bar AND foo.baz changes.
how to implement that

flutter dart


问:
C++ UTF-8 Reading text file, counting characters and outputing results to another file. ‘ gets saved as nothing, but is counted. ā and € appears
I have a task in C++ to read from a UTF-8 text file, count the characters, and save the character + count in a tsv.

I use everywhere wstring, wifstream, and wofstream.
In the terminal, there are many empty spaces when checking everything, but when outputting to tsv everything is overall fine except for 3 things.

‘ when saved appears as nothing, but its amount is counted correctly.

From nowhere ā and € appear. They are counted as the same amount, but they are not present in the original text at all.

What might be the cause of these issues?

The code is a bit crude but looks like this currently

```<code>#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    vector <wchar_t> characters;
    vector <int> counter;
    string filename;
    string param;
    cout << "Please input the filename: ";
    cin >> filename;
    cout << "Please, if you want to convert everything to lowercase, input 'lower', else input 'No': ";
    cin >> param;
    wifstream inFile;
    wofstream endFile("dancing_men_char_frequency.tsv");
    inFile.open(filename);
    wstring Tfile;
    int checker;
    //inFile >> Tfile;
    while(getline(inFile, Tfile)) {

        //wcout << Tfile;
        //sort(Tfile.begin(), Tfile.end());
        if(param == "lower"){
            transform(
                Tfile.begin(), Tfile.end(),
                Tfile.begin(),
            towlower);
        }
        for(int i = 0; i < Tfile.length(); i++){

            if(find(characters.begin(), characters.end(), Tfile[i]) != characters.end())
            {

                if(isblank(Tfile[i])){}else{
                    checker = 0;
                    while(characters[checker] != Tfile[i]){
                        checker++;
                    }
                    counter[checker] += 1;
                }

            }else{

                if(isblank(Tfile[i])){}else{
                    characters.push_back(Tfile[i]);
                    counter.push_back(1);
                }

            }
        }

    }
    int sum = 0;
    for(int i = 0; i < characters.size(); i++){

        wcout << characters[i] << " ";
        cout << counter[i] << " " << i << endl;
        sum += counter[i];
        endFile << characters[i] << '\t' << counter[i] << '\n';

    }
    cout << sum << endl;
    //wcout << Tfile;
    //sort(Tfile.begin(), Tfile.end());
    //wcout << Tfile;
    endFile.close();
    inFile.close();
    return 0;
}

</code>```

Body:
I have a task in C++ to read from a UTF-8 text file, count the characters, and save the character + count in a tsv.

I use everywhere wstring, wifstream, and wofstream.
In the terminal, there are many empty spaces when checking everything, but when outputting to tsv everything is overall fine except for 3 things.

‘ when saved appears as nothing, but its amount is counted correctly.

From nowhere ā and € appear. They are counted as the same amount, but they are not present in the original text at all.

What might be the cause of these issues?

The code is a bit crude but looks like this currently

#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    vector <wchar_t> characters;
    vector <int> counter;
    string filename;
    string param;
    cout << "Please input the filename: ";
    cin >> filename;
    cout << "Please, if you want to convert everything to lowercase, input 'lower', else input 'No': ";
    cin >> param;
    wifstream inFile;
    wofstream endFile("dancing_men_char_frequency.tsv");
    inFile.open(filename);
    wstring Tfile;
    int checker;
    //inFile >> Tfile;
    while(getline(inFile, Tfile)) {

        //wcout << Tfile;
        //sort(Tfile.begin(), Tfile.end());
        if(param == "lower"){
            transform(
                Tfile.begin(), Tfile.end(),
                Tfile.begin(),
            towlower);
        }
        for(int i = 0; i < Tfile.length(); i++){

            if(find(characters.begin(), characters.end(), Tfile[i]) != characters.end())
            {

                if(isblank(Tfile[i])){}else{
                    checker = 0;
                    while(characters[checker] != Tfile[i]){
                        checker++;
                    }
                    counter[checker] += 1;
                }

            }else{

                if(isblank(Tfile[i])){}else{
                    characters.push_back(Tfile[i]);
                    counter.push_back(1);
                }

            }
        }

    }
    int sum = 0;
    for(int i = 0; i < characters.size(); i++){

        wcout << characters[i] << " ";
        cout << counter[i] << " " << i << endl;
        sum += counter[i];
        endFile << characters[i] << '\t' << counter[i] << '\n';

    }
    cout << sum << endl;
    //wcout << Tfile;
    //sort(Tfile.begin(), Tfile.end());
    //wcout << Tfile;
    endFile.close();
    inFile.close();
    return 0;
}


问:
Set up nginx to route subdomains to specific ports in home server (e.g. for Nextcloud)
I have a home server.

Local IP: 192.168.0.6
And assume public IP: 1.2.3.4

On the server I have Docker and NGINX installed.

Let's say that I also own a domain: mydomain.com.

I would like to have local and remote access to my Nextcloud Web UI using following subdomain: nextcloud.mydomain.com as Nextcloud requires an actual domain for initial setup.

This subdomain (nextcloud.mydomain.com) currently has it's A record set to 1.2.3.4 (my public IP). Is it correct approach or should I go with a different approach such as CNAME records for the main domain (mydomain.com)? Not sure on this one.

My general question is how can I configure NGINX in a way that it will point nextcloud.mydomain.com to my Nextcloud container instance.

I was able to access Nextcloud Web UI locally through 192.168.0.6:8443 so I assume that this is the port that NGINX should route to from the subdomain.

My Nextcloud instance exists as a docker container set up with default attributes:

```<code>--publish 80:80 \
--publish 8080:8080 \
--publish 8443:8443 \
</code>```

I haven't configured NGINX yet at all to not mess anything.

I would be grateful for any explanation what steps I should take and if my understanding of the entire concept is correct.

Body:
I have a home server.

Local IP: 192.168.0.6
And assume public IP: 1.2.3.4

On the server I have Docker and NGINX installed.

Let's say that I also own a domain: mydomain.com.

I would like to have local and remote access to my Nextcloud Web UI using following subdomain: nextcloud.mydomain.com as Nextcloud requires an actual domain for initial setup.

This subdomain (nextcloud.mydomain.com) currently has it's A record set to 1.2.3.4 (my public IP). Is it correct approach or should I go with a different approach such as CNAME records for the main domain (mydomain.com)? Not sure on this one.

My general question is how can I configure NGINX in a way that it will point nextcloud.mydomain.com to my Nextcloud container instance.

I was able to access Nextcloud Web UI locally through 192.168.0.6:8443 so I assume that this is the port that NGINX should route to from the subdomain.

My Nextcloud instance exists as a docker container set up with default attributes:

--publish 80:80 \
--publish 8080:8080 \
--publish 8443:8443 \

I haven't configured NGINX yet at all to not mess anything.

I would be grateful for any explanation what steps I should take and if my understanding of the entire concept is correct.


问:
how do i make an external variable optional? (gcc, c)
I made a library that contains a main that calls every function in a section, and I want it to work even if the section is empty. How do i do  that?

my code so far is

inside header:

```<code>#define CONCAT(x,y) x##y
#define CONCATE(x,y) CONCAT(x,y)
#define make_init static void (CONCATE(*init,__COUNTER__))()__attribute__((section("my_init"), unused))=
</code>```

inside main.c:

```<code>make_init 0;

extern void(*__start_my_init)();
extern void(*__stop_my_init)();

int main() {
    for (void(**initfunc)() = &__start_my_init; initfunc < &__stop_my_init; ++initfunc)
        if (*initfunc) (*preinitfunc)();
    return 0;
}
</code>```

it compiles fine, but when i link the library to a program and i don't do another

```<code>make_init foo;
</code>```

or another function, the linker says that __start_my_init and __stop_my_init are undefined.

on the other hand, if i don't make it extern it only adds the function inside the library (0) inside the section and not the ones defined in the program that uses the library.

how do i go about making making the section contain a 0 by default and add the functions defined in the program that is linked with the library inside the same section?`

Body:
I made a library that contains a main that calls every function in a section, and I want it to work even if the section is empty. How do i do  that?

my code so far is

inside header:

#define CONCAT(x,y) x##y
#define CONCATE(x,y) CONCAT(x,y)
#define make_init static void (CONCATE(*init,__COUNTER__))()__attribute__((section("my_init"), unused))=

inside main.c:

make_init 0;

extern void(*__start_my_init)();
extern void(*__stop_my_init)();

int main() {
    for (void(**initfunc)() = &__start_my_init; initfunc < &__stop_my_init; ++initfunc)
        if (*initfunc) (*preinitfunc)();
    return 0;
}

it compiles fine, but when i link the library to a program and i don't do another

make_init foo;

or another function, the linker says that __start_my_init and __stop_my_init are undefined.

on the other hand, if i don't make it extern it only adds the function inside the library (0) inside the section and not the ones defined in the program that uses the library.

how do i go about making making the section contain a 0 by default and add the functions defined in the program that is linked with the library inside the same section?`


问:
How can I resolve the error "undefined reference to `yyerror'"?
I've been following the youtube video https://www.youtube.com/watch?v=fFRxWtRibC8

I've created the lexer.l file with the following:

```<code>%{
    /* definitions */
    #include "parser.tab.h"
%}
    /* rules */
%%

[0-9]+ {yylval.num = atoi(yytext); return NUMBER; }
\n {return EOL;}
. {}

%%

yywrap() {}

int main() {
    yylex();

    return 0;
}

</code>```

and the parser.y file with the following:

```<code>%{
    /* definitions */
%}

%union{
    int num;
    char sym;
}

%token EOL
%token<num> NUMBER
%type<num> exp
%token PLUS

/* rules */
%%

input:
    exp EOL  {printf("%d\n", $1); }
|   EOL;
exp:
    NUMBER { $$ = $1; }
|   exp PLUS exp { $$ = $1 + $3; }
;

%%

int main() {
    yyparse();

    return 0;
}

void yyerror (char* s) {
    printf ("ERROR: %s\n", s);

    return 0;
}
</code>```

When running the command "gcc lex.yy.c parser.tab.c", I'm getting the following error:
undefined reference to `yyerror'
collect2.exe: error: ld returned 1 exit status

Body:
I've been following the youtube video https://www.youtube.com/watch?v=fFRxWtRibC8

I've created the lexer.l file with the following:

%{
    /* definitions */
    #include "parser.tab.h"
%}
    /* rules */
%%

[0-9]+ {yylval.num = atoi(yytext); return NUMBER; }
\n {return EOL;}
. {}

%%

yywrap() {}

int main() {
    yylex();

    return 0;
}

and the parser.y file with the following:

%{
    /* definitions */
%}

%union{
    int num;
    char sym;
}

%token EOL
%token<num> NUMBER
%type<num> exp
%token PLUS

/* rules */
%%

input:
    exp EOL  {printf("%d\n", $1); }
|   EOL;
exp:
    NUMBER { $$ = $1; }
|   exp PLUS exp { $$ = $1 + $3; }
;

%%

int main() {
    yyparse();

    return 0;
}

void yyerror (char* s) {
    printf ("ERROR: %s\n", s);

    return 0;
}

When running the command "gcc lex.yy.c parser.tab.c", I'm getting the following error:
undefined reference to `yyerror'
collect2.exe: error: ld returned 1 exit status


问:
How to insert html form inputs in mysql database express
I am working in database project. my objective is to insert data coming from html form into mysql database.

I successfully connected to my database

```<code>
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'IVI'
});

connection.connect(function(err){
    if (err){throw err;}
    else{console.log("Connected");}
});

module.exports = connection;
</code>```

I am created html file contains a form to make the user insert values

```<code><body>
    <h2>Add Package</h2>
    <form action="/add" method="post">
        <label for="package_number">package number:</label>
        <input type="number" name="package_number" id="package_number"> <br>

        <label for="weight">weight:</label>
        <input type="number" name="weight" id="weight"> <br>

        <label for="destination">destination:</label>
        <input type="text" name="destination" id="destination"><br>

        <label for="dimensions">dimensions:</label>
        <input type="text" name="dimensions" id="dimensions"><br>

        <label for="category">category:</label>
        <select name="category" id="">
            <option value="Regular">Regular</option>
            <option value="Fragile">Fragile</option>
            <option value="Liquid">Liquid</option>
            <option value="Chemical">Chemical</option>
        </select> <br>

        <label for="insurance_amount">insurance_amount:</label>
        <input type="number" name="insurance_amount" id="insurance_amount"><br>

        <label for="delivery_date">delivery_date:</label>
        <input type="text" name="delivery_date" id="delivery_date"> <br>
        <input type="submit" value="add">
    </form>
</body>
</code>```

and I used this post method to get the values from the form and insert it to my database

```<code>server.post('/add', (req,res)=>{
    var pn = req.body.package_number;
    var w = req.body.weight;
    var d = req.body.destination;
    var dimensions = req.body.dimensions;
    var c = req.body.category;
    var ia = req.body.insurance_amount;
    var dd = req.body.delivery_date;

    var q = `insert into package values(${pn},${w},"${d}","${dimensions}","${c}",${ia},"${dd}")`

    db.query(q,(e,d)=>{
        if (e){
            throw e
        }
        else{
            res.redirect('/admin/reports')
        }
    })
</code>```

but I got this error

TypeError: Cannot read properties of undefined (reading 'package_number')

I will be happy if someone can help me finding the solution for the problem.

Body:
I am working in database project. my objective is to insert data coming from html form into mysql database.

I successfully connected to my database

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'IVI'
});

connection.connect(function(err){
    if (err){throw err;}
    else{console.log("Connected");}
});

module.exports = connection;

I am created html file contains a form to make the user insert values

Add Package

    <form action="/add" method="post">
        package number:
        <input type="number" name="package_number" id="package_number">

        weight:
        <input type="number" name="weight" id="weight">

        destination:
        <input type="text" name="destination" id="destination">

        dimensions:
        <input type="text" name="dimensions" id="dimensions">

        category:
        <select name="category" id="">
            <option value="Regular">Regular</option>
            <option value="Fragile">Fragile</option>
            <option value="Liquid">Liquid</option>
            <option value="Chemical">Chemical</option>
        </select>

        insurance_amount:
        <input type="number" name="insurance_amount" id="insurance_amount">

        delivery_date:
        <input type="text" name="delivery_date" id="delivery_date">

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

and I used this post method to get the values from the form and insert it to my database

server.post('/add', (req,res)=>{
    var pn = req.body.package_number;
    var w = req.body.weight;
    var d = req.body.destination;
    var dimensions = req.body.dimensions;
    var c = req.body.category;
    var ia = req.body.insurance_amount;
    var dd = req.body.delivery_date;

    var q = `insert into package values(${pn},${w},"${d}","${dimensions}","${c}",${ia},"${dd}")`

    db.query(q,(e,d)=>{
        if (e){
            throw e
        }
        else{
            res.redirect('/admin/reports')
        }
    })

but I got this error

TypeError: Cannot read properties of undefined (reading 'package_number')

I will be happy if someone can help me finding the solution for the problem.


问:
Installing Jekyll theme for a website on a shared hosting plan
On my shared hosting plan I am trying to get a personal website to work, simple 2-page site based on a theme that I bought on jekyllthemes. As I'm obviously new at this I followed blogposts on this topic but I always get stuck, so I'd like someone more experienced that could possibly tell me what am I doing wrong. I'm using the cheapest shared hosting plan on hawkhost (if that's important to mention).

Here are the segmented steps I took trying to install this, hope it's easy to follow and figure out what I did and where was I wrong;

a) cPanel -> Setup Ruby App

Ruby version 3.1

App Directory: jekyll_site

App Domain: testweb

b) Testing www.mysite.com/testweb

blank page with "It works! Ruby 3.1.2" message

c) cPanel Terminal

source /home/user/rubyvenv/jekyll__site/3.1/bin/activate (with single underscore I get "no such file or dir" warning, but works when double underscore)

terminal now points to: (jekyll_site:3.1)[user@dal206 ~]$

gem install bundler jekyll

Done installing documentation for webrick, unicode-display_width, terminal-table, safe_yaml, rouge, forwardable-extended, pathutil, mercenary, liquid, rexml, kramdown, kramdown-parser-gfm, ffi, rb-inotify, rb-fsevent, listen, jekyll-watch, sassc, jekyll-sass-converter, concurrent-ruby, i18n, http_parser.rb, eventmachine, em-websocket, colorator, public_suffix, addressable, jekyll after 22 seconds
29 gems installed

cd public_html

terminal now points to: (jekyll_site:3.1)[user@dal206 public_html]$

gem install bigdecimal

Done installing documentation for bigdecimal after 0 seconds 1 gem installed

jekyll new testweb

And after this, I get this error; /opt/alt/ruby31/share/rubygems/rubygems.rb:265:in find_spec_for_exe': can't find gem jekyll (>= 0.a) with executable jekyll (Gem::GemNotFoundException) from /opt/alt/ruby31/share/rubygems/rubygems.rb:284:in activate_bin_path'
from /home/user/bin/jekyll:25:in `


问:
How to set columns name dynamically in Exceljs using Nodejs?
I am using Exceljs library to export data from the database using Nodejs, Now I am trying to set the column Header name dynamically from columns=36 (i.e. AK) to till the end or until it has data. but nothing helps.

column name strictly needs to start from 36th (i.e. AK) column name

labels array are like this -

```<code>[
  'Type',
  'Competition',
  'IDB',
  'SOV Focus',
  'Medium',
  'Tone'
]
</code>```

So, I only need to print these in the header.

```<code>      con.query(query, id, function (err, result) {
      if (err) throw err;
      const labels = [];
      result.forEach((result) => {
        labels.push(result.label);
      });
      labels.forEach((label, index) => {
        const columnName = label;

        // Get the column using the column index (in this case, 1)
        const firstRow = worksheet.getRow(1);

        // Set the value of the first cell in the row to the dynamic column name
        firstRow.getCell(36, columnName);
      });
    });
</code>```

But it is not working or throwing any errors.

Previously I used PHPSpreadhsheet in PHP but it was not able to handle huge data export and took much time to export data.

but in PHPspreadsheet it was so easy to set dynamic header names.

```<code> $sheet->setCellValueByColumnAndRow($col, 1, trim($labels[$k] ,  ','));
</code>```

How will I set columns/header names dynamically?

Body:
I am using Exceljs library to export data from the database using Nodejs, Now I am trying to set the column Header name dynamically from columns=36 (i.e. AK) to till the end or until it has data. but nothing helps.

column name strictly needs to start from 36th (i.e. AK) column name

labels array are like this -

[
  'Type',
  'Competition',
  'IDB',
  'SOV Focus',
  'Medium',
  'Tone'
]

So, I only need to print these in the header.

      con.query(query, id, function (err, result) {
      if (err) throw err;
      const labels = [];
      result.forEach((result) => {
        labels.push(result.label);
      });
      labels.forEach((label, index) => {
        const columnName = label;

        // Get the column using the column index (in this case, 1)
        const firstRow = worksheet.getRow(1);

        // Set the value of the first cell in the row to the dynamic column name
        firstRow.getCell(36, columnName);
      });
    });

But it is not working or throwing any errors.

Previously I used PHPSpreadhsheet in PHP but it was not able to handle huge data export and took much time to export data.

but in PHPspreadsheet it was so easy to set dynamic header names.

 $sheet->setCellValueByColumnAndRow($col, 1, trim($labels[$k] ,  ','));

How will I set columns/header names dynamically?


问:
cookies are blocked from keycloak localhost to my application localhost, cecause path was not an exact match or a superdirectory or request url path
I have a keycloak server running in localhost:8080 and a web app server written in ASP.NET MVC 4.7 running in https:localhost:44337,

the application uses the keycloak to authenticate and login, and after succesful login it should redirect to https:localhost:44337/home,
from dev tools i see that Sessions are passed correctly but it is blocked because "This cookie was blocked because its path was not an exact match for or a superdirectory of the request url's path".
Is this maybe because I am testing in localhost with different port? is this samesite issue?

How can I resolve this while developing locally and I dont have a domain?
It seems like by googling this error does not come out.


问:
How to use environment variable in sc create command?
I am trying to create a java process using below command

```<code>sc create JavaService binpath= "C:\\java-11-openjdk-11.0.15.9-1.windows.ojdkbuild.x86_64\\bin\\java.exe -jar C:\\data\\lib\\test-1.0.0.jar"
</code>```

I have set env varibales Var1=Key1, Var2=Key2 on the system using set command. How do I pass Var1 or Var2 in above command.

I tried with -D option but that does not pick env variables.

```<code>sc create JavaService binpath= "C:\\java-11-openjdk-11.0.15.9-1.windows.ojdkbuild.x86_64\\bin\\java.exe -DVar1 -DVar2 -jar C:\\data\\lib\\test-1.0.0.jar"
</code>```

Body:
I am trying to create a java process using below command

sc create JavaService binpath= "C:\\java-11-openjdk-11.0.15.9-1.windows.ojdkbuild.x86_64\\bin\\java.exe -jar C:\\data\\lib\\test-1.0.0.jar"

I have set env varibales Var1=Key1, Var2=Key2 on the system using set command. How do I pass Var1 or Var2 in above command.

I tried with -D option but that does not pick env variables.

sc create JavaService binpath= "C:\\java-11-openjdk-11.0.15.9-1.windows.ojdkbuild.x86_64\\bin\\java.exe -DVar1 -DVar2 -jar C:\\data\\lib\\test-1.0.0.jar"


问:
How to deal with incompatible shapes while trying to fit a model in Tensorflow Keras
So, I have done some modifications with the VGG16 neural network to make a linear-regression and classification model.
And at last I am writing the following code to compile and fit my data into the model to initiate training->

```<code>class Facetracker(Model):
#     The initialization function-
    def __init__(self,eyetracker,**kwargs):
        super().__init__(**kwargs)
        self.model = eyetracker #Instantiating the model

    def compile(self,opt,classlosss,localization_loss,**kwargs):
        super().compile(**kwargs)
        self.classloss = class_loss
        self.localization_loss = regress_loss
        self.opt = optimizer

        # Defining the training step
    def train_step(self,batch,**kwargs):
        X,y = batch #unpacking our data

        with tf.GradientTape() as tape:
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)

            # calculating total loss-
            total_loss = batch_localloss+0.5*batch_classloss
            grad = tape.gradient(total_loss,self.model.trainable_variables)
        optimizer.apply_gradients(zip(grad,self.model.trainable_variables))

        return{
            "total_loss":total_loss,
            "class_loss":batch_classloss,
            "localilzation_loss":batch_localloss

        }
    def test_step(self,batch):
        X,y = batch
        classes,coords = self.model(X,training=False)
        batch_classloss = self.classloss(y[0],classes)
        batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)

        total_loss = batch_localloss+0.5*batch_classloss

        return{
            "total_loss": total_loss,
            "class_loss": batch_classloss,
            "localilzation_loss": batch_localloss
        }
    # def call(self, X, **kwargs):
    #     return self.model(X,**kwargs)
# Replacing the call function with a lambda function
lambda self,X,**kwargs: self.model(X,**kwargs)

# Subclassing our model-
print("Subclassing.....")
model = Facetracker(facetracker)
print("Compiling......")
model.compile(optimizer,classlosss=class_loss,localization_loss=localization_loss)

# Preparing the log directory
logdir="logdir"
tensorboard_callbacks = tf.keras.callbacks.TensorBoard(log_dir=logdir)
print("Fitting the model")
hist = model.fit(train.take(80),
                 epochs=16,
                 initial_epoch =8,
                 validation_data=val,
                 validation_steps =8,
                 validation_freq=2,
                 callbacks = [[tensorboard_callbacks]])
</code>```

This includes the class prepared for training the model and the last few lines are subclassing the model and fitting the prepared data into the model.
The error I now get seems pretty hefty to me and it goes like this->

```<code>  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
    hist = model.fit(train.take(80),
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'gradient_tape/sub_2/BroadcastGradientArgs' defined at (most recent call last):
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
      hist = model.fit(train.take(80),
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 498, in train_step
      grad = tape.gradient(total_loss,self.model.trainable_variables)
Node: 'gradient_tape/sub_2/BroadcastGradientArgs'
Incompatible shapes: [2,4] vs. [8]
         [[{{node gradient_tape/sub_2/BroadcastGradientArgs}}]] [Op:__inference_train_function_22026]
</code>```

It would be a great help if someone could examine this problem and help me get out of it. I have been quite struggling with it now.
Thanks in advance!!!

I has planned to initiate training with the code provided, but I firstly received an error for the call function and as I resolved it by converting it into  lambda function- This issue of incompatible shapes came up. I tries to adjust the integers in the input data and batch related fields but nothing worked.

Body:
So, I have done some modifications with the VGG16 neural network to make a linear-regression and classification model.
And at last I am writing the following code to compile and fit my data into the model to initiate training->

class Facetracker(Model):
#     The initialization function-
    def __init__(self,eyetracker,**kwargs):
        super().__init__(**kwargs)
        self.model = eyetracker #Instantiating the model

    def compile(self,opt,classlosss,localization_loss,**kwargs):
        super().compile(**kwargs)
        self.classloss = class_loss
        self.localization_loss = regress_loss
        self.opt = optimizer

        # Defining the training step
    def train_step(self,batch,**kwargs):
        X,y = batch #unpacking our data

        with tf.GradientTape() as tape:
            classes,coords = self.model(X,training=True)
            batch_classloss = self.classloss(y[0],classes)
            batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)

            # calculating total loss-
            total_loss = batch_localloss+0.5*batch_classloss
            grad = tape.gradient(total_loss,self.model.trainable_variables)
        optimizer.apply_gradients(zip(grad,self.model.trainable_variables))

        return{
            "total_loss":total_loss,
            "class_loss":batch_classloss,
            "localilzation_loss":batch_localloss

        }
    def test_step(self,batch):
        X,y = batch
        classes,coords = self.model(X,training=False)
        batch_classloss = self.classloss(y[0],classes)
        batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)

        total_loss = batch_localloss+0.5*batch_classloss

        return{
            "total_loss": total_loss,
            "class_loss": batch_classloss,
            "localilzation_loss": batch_localloss
        }
    # def call(self, X, **kwargs):
    #     return self.model(X,**kwargs)
# Replacing the call function with a lambda function
lambda self,X,**kwargs: self.model(X,**kwargs)

# Subclassing our model-
print("Subclassing.....")
model = Facetracker(facetracker)
print("Compiling......")
model.compile(optimizer,classlosss=class_loss,localization_loss=localization_loss)

# Preparing the log directory
logdir="logdir"
tensorboard_callbacks = tf.keras.callbacks.TensorBoard(log_dir=logdir)
print("Fitting the model")
hist = model.fit(train.take(80),
                 epochs=16,
                 initial_epoch =8,
                 validation_data=val,
                 validation_steps =8,
                 validation_freq=2,
                 callbacks = [[tensorboard_callbacks]])

This includes the class prepared for training the model and the last few lines are subclassing the model and fitting the prepared data into the model.
The error I now get seems pretty hefty to me and it goes like this->

  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
    hist = model.fit(train.take(80),
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'gradient_tape/sub_2/BroadcastGradientArgs' defined at (most recent call last):
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
      hist = model.fit(train.take(80),
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1409, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1051, in train_function
      return step_function(self, iterator)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1040, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1030, in run_step
      outputs = model.train_step(data)
    File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 498, in train_step
      grad = tape.gradient(total_loss,self.model.trainable_variables)
Node: 'gradient_tape/sub_2/BroadcastGradientArgs'
Incompatible shapes: [2,4] vs. [8]
         [[{{node gradient_tape/sub_2/BroadcastGradientArgs}}]] [Op:__inference_train_function_22026]

It would be a great help if someone could examine this problem and help me get out of it. I have been quite struggling with it now.
Thanks in advance!!!

I has planned to initiate training with the code provided, but I firstly received an error for the call function and as I resolved it by converting it into  lambda function- This issue of incompatible shapes came up. I tries to adjust the integers in the input data and batch related fields but nothing worked.


问:
How would I go about packaging a smaller subset of Math3
I only use a small subset of the org.apache.commons.math3... class tree and would like to package only what I need.

Is there any way to get a dependency tree that may help the process of repackaging manually?

The current download of 3.6.1 is 2.2MB and I'd like to reduce that size to ideally only the classes in the closure of what I use.