问:
How to find the right and the down bound of the screen
I want to create a program that if you click the up button, the window goes 50pixel up and so on. I am almost finished now, I want that the window cant go outside the current screen size. I want to do that in the Inner class.

`

```<code>class Listener extends WindowAdapter implements ActionListener{

        @Override
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Dimension hHeight = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension wWidth = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(wWidth.width - getSize().width / 2, (hHeight.height - getSize().height) / 2);
            double width= wWidth.getWidth();
            if (e.getActionCommand().equals("UP") & yPosition > 0) {
                yPosition -= 10;
            }
            if (e.getActionCommand().equals("RIGHT") & xPosition <= width) {
                xPosition += 100;
            }
            if (e.getActionCommand().equals("DOWN")) {
                yPosition += 10;
            }
            if (e.getActionCommand().equals("LEFT") & xPosition > 0) {
                xPosition -= 10;
            }
            setLocation(xPosition,yPosition);

        }
    }
</code>```

`

I make it for UP and LEFT for RIGHT and DOWN i don't manage it.

Body:
I want to create a program that if you click the up button, the window goes 50pixel up and so on. I am almost finished now, I want that the window cant go outside the current screen size. I want to do that in the Inner class.

`

class Listener extends WindowAdapter implements ActionListener{

        @Override
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Dimension hHeight = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension wWidth = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(wWidth.width - getSize().width / 2, (hHeight.height - getSize().height) / 2);
            double width= wWidth.getWidth();
            if (e.getActionCommand().equals("UP") & yPosition > 0) {
                yPosition -= 10;
            }
            if (e.getActionCommand().equals("RIGHT") & xPosition <= width) {
                xPosition += 100;
            }
            if (e.getActionCommand().equals("DOWN")) {
                yPosition += 10;
            }
            if (e.getActionCommand().equals("LEFT") & xPosition > 0) {
                xPosition -= 10;
            }
            setLocation(xPosition,yPosition);

        }
    }

`

I make it for UP and LEFT for RIGHT and DOWN i don't manage it.


来源: stackexchange

问:
Can we specify package structure relative to the generated directory in swagger?
Currently the issue is we have to generate two openapi specs A and B both of which use the some common models defined in package C.

Package A and B contain some objects with the same name for e.g. 'GetQuestionDetails' but the definition of this object is different in pacakge A and B.

I tried two approaches with openapi model generation:

Generate the model in different directories. This creates two copies of the common models defined in A and B.

Generate the model in same directory then the one copy of common model is generated but the object with the same name are getting replaced.

So we were wondering if we can specify the directory for some of the openapi models while their generation so that the model GetQuestionDetails is generated in two directories A/GetQuestionDetails and B/GetQuestionDetails and rest of the common models in other single directory or the root directory?

ContentLicense: CC BY-SA 4.0


问:
How to fix the Apache Flume Exception windows platform : Failed to instantiate SLF4J LoggerFactory?
How to fix the issue in Apache Flume in Window Platform ?

After successful installationa of hadoop and Flume in Windows Platform.Then Started the Hadoop and create the example.conf file run the command in powershell.

using this commands

```<code>flume-ng agent -n a1 -f example.conf -property "flume.root.logger=INFO,console;flume.monitoring.type=http;flume.monitoring.port=44123;"
</code>```

Then i get an error mentioned in below.

```<code>WARN: Config directory not set. Defaulting to F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\conf
Sourcing environment configuration script F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\conf\flume-env.ps1
Including Hadoop libraries found in (F:\hadoop-3.3.4) for DFS access
WARN: HBASE_HOME not found
WARN: HIVE_HOME not found
  Running FLUME agent :
    class: org.apache.flume.node.Application
    arguments: -n a1 -f "F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\flume_config_files\example.conf"
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
        at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:78)
        at org.apache.logging.slf4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:35)
        at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:53)
        at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:41)
        at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
        at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
        at org.apache.flume.node.Application.<clinit>(Application.java:73)
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
        at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:78)
        at org.apache.logging.slf4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:35)
        at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:53)
        at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:41)
        at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
        at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
        at org.apache.flume.node.Application.<clinit>(Application.java:73)
</code>```

Is there any possibility to solve the issue?

Body:
How to fix the issue in Apache Flume in Window Platform ?

After successful installationa of hadoop and Flume in Windows Platform.Then Started the Hadoop and create the example.conf file run the command in powershell.

using this commands

flume-ng agent -n a1 -f example.conf -property "flume.root.logger=INFO,console;flume.monitoring.type=http;flume.monitoring.port=44123;"

Then i get an error mentioned in below.

WARN: Config directory not set. Defaulting to F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\conf
Sourcing environment configuration script F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\conf\flume-env.ps1
Including Hadoop libraries found in (F:\hadoop-3.3.4) for DFS access
WARN: HBASE_HOME not found
WARN: HIVE_HOME not found
  Running FLUME agent :
    class: org.apache.flume.node.Application
    arguments: -n a1 -f "F:\apache-flume-1.11.0-bin\apache-flume-1.11.0-bin\flume_config_files\example.conf"
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
        at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:78)
        at org.apache.logging.slf4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:35)
        at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:53)
        at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:41)
        at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
        at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
        at org.apache.flume.node.Application.<clinit>(Application.java:73)
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
        at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:78)
        at org.apache.logging.slf4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:35)
        at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:53)
        at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:41)
        at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
        at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
        at org.apache.flume.node.Application.<clinit>(Application.java:73)

Is there any possibility to solve the issue?


问:
Could not resolve com.android.tools.build:gradle:7.2.1
Having this build issue trying to run a react native app:

A problem occurred configuring root project 'testttt'.

Could not determine the dependencies of null.

Could not resolve all task dependencies for configuration ':classpath'.

Could not resolve com.android.tools.build:gradle:7.2.1.

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

buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31

        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
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}
</code>```

Body:
Having this build issue trying to run a react native app:

A problem occurred configuring root project 'testttt'.

Could not determine the dependencies of null.

Could not resolve all task dependencies for configuration ':classpath'.

Could not resolve com.android.tools.build:gradle:7.2.1.

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

buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31

        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
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}


问:
Issue with borrowing in Rust
I'm starting to learn Rust, I apologize if the question seems trivial.

This is the code I have:

struct File {
    name: String,
    size: u32
}

struct Dir {
    name: String,
    files: Vec<File>,
    dirs: Vec<Dir>
}

impl Dir {
    fn get_subfolder(&mut self, subfolder: String) -> &Dir {
        let mut matched: Option<&Dir> = None;

        for elem in &self.dirs {
            if elem.name == subfolder {
                matched = Some(elem);
                break;
            }
        }

        match matched {
            Some(dir) => {
                return dir;
            },
            None => {
                let new_dir: Dir = Dir {name: subfolder, files: vec!(), dirs: vec!()};
                self.dirs.push(new_dir);
                return self.dirs.last().unwrap();
            }
        };
    }
}
```
<p>I get an error on <code>self.dirs.push(new_dir)</code>.</p>
```error[E0502]: cannot borrow `self.dirs` as mutable because it is also borrowed as immutable
  --> src\main.rs:29:17
   |
13 |     fn get_subfolder(&mut self, subfolder: String) -> &Dir {
   |                      - let's call the lifetime of this reference `'1`
...
16 |         for elem in &self.dirs {
   |                     ---------- immutable borrow occurs here
...
25 |                 return dir;
   |                        --- returning this value requires that `self.dirs` is borrowed for `'1`
...
29 |                 self.dirs.push(new_dir);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
```

From what i understand, the compiler is telling me that the vector dirs is borrowed when returning the dir reference in the Some(dir) arm of the match expression. And it tells me that the borrow lasts for as long as self lives (i.e. they have the same lifetimes).
It then complains that I'm borrowing dirs mutably in the other arm, None. But these two arms could never get executed in a single call, right? There's no way that an Option is both Some<T> and None, so I'm always either borrowing the vector for as long as self lives, or I'm borrowing it for just one line to append a new Dir to it.

What's going on here? Is my reasoning correct?

Edit: it seems that this is a limitation of the current borrow checker. Are there any "elegant" workarounds to this?
One that comes to mind is returning a copy of the object, but I can't really do that here.

Title: Issue with borrowing in Rust

Body:
I'm starting to learn Rust, I apologize if the question seems trivial.

This is the code I have:

struct File {
    name: String,
    size: u32
}

struct Dir {
    name: String,
    files: Vec<File>,
    dirs: Vec<Dir>
}

impl Dir {
    fn get_subfolder(&mut self, subfolder: String) -> &Dir {
        let mut matched: Option<&Dir> = None;

        for elem in &self.dirs {
            if elem.name == subfolder {
                matched = Some(elem);
                break;
            }
        }

        match matched {
            Some(dir) => {
                return dir;
            },
            None => {
                let new_dir: Dir = Dir {name: subfolder, files: vec!(), dirs: vec!()};
                self.dirs.push(new_dir);
                return self.dirs.last().unwrap();
            }
        };
    }
}

I get an error on self.dirs.push(new_dir).

error[E0502]: cannot borrow `self.dirs` as mutable because it is also borrowed as immutable
  --> src\main.rs:29:17
   |
13 |     fn get_subfolder(&mut self, subfolder: String) -> &Dir {
   |                      - let's call the lifetime of this reference `'1`
...
16 |         for elem in &self.dirs {
   |                     ---------- immutable borrow occurs here
...
25 |                 return dir;
   |                        --- returning this value requires that `self.dirs` is borrowed for `'1`
...
29 |                 self.dirs.push(new_dir);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

From what i understand, the compiler is telling me that the vector dirs is borrowed when returning the dir reference in the Some(dir) arm of the match expression. And it tells me that the borrow lasts for as long as self lives (i.e. they have the same lifetimes).
It then complains that I'm borrowing dirs mutably in the other arm, None. But these two arms could never get executed in a single call, right? There's no way that an Option is both Some<T> and None, so I'm always either borrowing the vector for as long as self lives, or I'm borrowing it for just one line to append a new Dir to it.

What's going on here? Is my reasoning correct?

Edit: it seems that this is a limitation of the current borrow checker. Are there any "elegant" workarounds to this?
One that comes to mind is returning a copy of the object, but I can't really do that here.


问:
How to find out the ownership of some unknown IP's obtained in packet captures provided by Azure Network Watcher?
I have an AKS Kubernetes cluster which holds a set of node pools which have a set of nodes created on them. My application is built on these nodes collectively which has a set of K8s pods and containers scheduled on them.

My objective:
To monitor and collect the network data obtained from packet captures provided by Azure Network Watcher service.

Details:

I have created packet captures for each node present on nodepools and trying to find out the communication between pods by looking for IP addresses assigned to different pods.

I used Wireshark to look into packet captures files and looked under Conversations to watch out for network data flowing inside a node.

The ultimate goal is to find out the port numbers on which these pods(IP addresses) are communicating to each other.

I could figure out most pod IP's belonging to K8s pods and was able to find out the connection between pods.

Problem:
As I have multiple subnets inside a Virtual network, my application pods use 2 of those subnets to get scheduled and pick IP addresses dynamically. Since there are a lot of IP's(from remaining subnets) present in those packet captures, I'm unable to figure out where those unknown IP's belong to.

Things I tried:

Some pod IP's were figured out by checking into pods in all the namespaces present in a cluster.

In addition, I checked if they belong to pod service IP's(like cluster IP's, External IP's), ingresses IP's etc but couldn't find the ownership.

Question:
How would I find the ownership of some IP addresses which take IP's from other subnets?


问:
create subset with specific variables
I've been trying to create two different subsets for white native british and 2nd generation Indians and Pakistanis in the understanding society date frame but havent been able to, I already made a UKborn subsets that works just fine, however I cant figure out how to do these two subsets

here's what I have so far

```<code>British <- subset(df, ukborn>0 & ukborn < 5)

df1 <- within(British, {
  White_native <- British$racel_dv == 1 & British$racel_dv == 2 & British$racel_dv == 4
  Second_Generation <- British$racel_dv == 9 & British$racel_dv ==10
})
</code>```

Title: create subset with specific variables

Body:
I've been trying to create two different subsets for white native british and 2nd generation Indians and Pakistanis in the understanding society date frame but havent been able to, I already made a UKborn subsets that works just fine, however I cant figure out how to do these two subsets

here's what I have so far

British <- subset(df, ukborn>0 & ukborn < 5)

df1 <- within(British, {
  White_native <- British$racel_dv == 1 & British$racel_dv == 2 & British$racel_dv == 4
  Second_Generation <- British$racel_dv == 9 & British$racel_dv ==10
})


问:
Is cross validation on a CalibratedClassiferCV sensible?
I wonder whether it is sensible to evaluate the score of a base estimator, say a Random Forest Classifier, using cross validation which is calibrated using cross validation beforehand. Consider the follwoing scenario

```<code>kfold = RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=SEED)

rfc = RandomForestClassifier()

calib = CalibratedClassifierCV(base_estimator=rfc, method="isotonic", cv=kfold)

scores = cross_validate(
        calib, X_train, y_train, cv=kfold,
        scoring=["accuracy", "recall", "roc_auc"]
    )
</code>```

Or is the cleaner way to fit the calibrated model based on the total training data and evaluate the score using the predictions? For instances,

```<code>calib.fit(X_train, y_train)

y_pred = calib.predict_proba(X_test)

accuracy_score(y_test, np.round(y_pred[:, 1])))
</code>```

Body:
I wonder whether it is sensible to evaluate the score of a base estimator, say a Random Forest Classifier, using cross validation which is calibrated using cross validation beforehand. Consider the follwoing scenario

kfold = RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=SEED)

rfc = RandomForestClassifier()

calib = CalibratedClassifierCV(base_estimator=rfc, method="isotonic", cv=kfold)

scores = cross_validate(
        calib, X_train, y_train, cv=kfold,
        scoring=["accuracy", "recall", "roc_auc"]
    )

Or is the cleaner way to fit the calibrated model based on the total training data and evaluate the score using the predictions? For instances,

calib.fit(X_train, y_train)

y_pred = calib.predict_proba(X_test)

accuracy_score(y_test, np.round(y_pred[:, 1])))


问:
Is there a way to estimate an Error Correction Model in Panel Data in R?
I have used many times the 'ecm' package in R to build Error Correction models, in single time-series. However, I was wondering if there is a package or a "walk around" way to build Error Correction Models in R ?

Simply using the 'ecm' package on panel data leads to overlapping between last and first time series observation points across different sections.


问:
Unable to consume Eventhub messages using Kafka API
I am trying to read messages from Azure Event Hub using kafka API. But I am unable to connect to the event hub. The bootstrap_connected() function always return false and the code stops there. It is not going to print message part.
Below is my code

```<code>from kafka import KafkaConsumer
from json import loads
consumer = KafkaConsumer(<EVENTHUB_NAME>,
                         bootstrap_servers='<NAME>.servicebus.windows.net:9093',
                         auto_offset_reset='earliest',
                         enable_auto_commit=True,
                         security_protocol='SASL_SSL',
                         sasl_mechanism='PLAIN',
                         sasl_plain_username=<CLIENT ID>,
                         sasl_plain_password=<CONNECTION_STRING>,
                         group_id=<CONSUMER_GROUP_NAME>,
                         api_version=(0, 11),
                         value_deserializer=lambda x: loads(x.decode('utf-8')))
print(consumer) #returns <kafka.consumer.group.KafkaConsumer object at 0x00000000012A8130>
x = consumer.bootstrap_connected() #returns False
print(x)
for message in consumer:
    message = message.value
    print('{} added'.format(message))
</code>```

I have followed the documentation but not sure why it is not connecting. I am able to use Azure's EventHubConsumerClient and able to receive the message. But my business logic requires to use Kafka Consumer Client. Please do help me in finding a solution for this!

Body:
I am trying to read messages from Azure Event Hub using kafka API. But I am unable to connect to the event hub. The bootstrap_connected() function always return false and the code stops there. It is not going to print message part.
Below is my code

from kafka import KafkaConsumer
from json import loads
consumer = KafkaConsumer(<EVENTHUB_NAME>,
                         bootstrap_servers='<NAME>.servicebus.windows.net:9093',
                         auto_offset_reset='earliest',
                         enable_auto_commit=True,
                         security_protocol='SASL_SSL',
                         sasl_mechanism='PLAIN',
                         sasl_plain_username=<CLIENT ID>,
                         sasl_plain_password=<CONNECTION_STRING>,
                         group_id=<CONSUMER_GROUP_NAME>,
                         api_version=(0, 11),
                         value_deserializer=lambda x: loads(x.decode('utf-8')))
print(consumer) #returns <kafka.consumer.group.KafkaConsumer object at 0x00000000012A8130>
x = consumer.bootstrap_connected() #returns False
print(x)
for message in consumer:
    message = message.value
    print('{} added'.format(message))

I have followed the documentation but not sure why it is not connecting. I am able to use Azure's EventHubConsumerClient and able to receive the message. But my business logic requires to use Kafka Consumer Client. Please do help me in finding a solution for this!


问:
How to fix "cannot access class sun.awt.AppContext (in module java.desktop)" in intelliJ
I am having the following error when calling the AppContext class:

```<code>Exception in thread "Thread-5" java.lang.IllegalAccessError: class [Class Name] (in unnamed module @0x6f1fba17) cannot access class sun.awt.AppContext (in module java.desktop) because module java.desktop does not export sun.awt to unnamed module @0x6f1fba17
    at [Class Name].run([Class Name].java:176)
</code>```

Line 176 contains the following line of code:

```<code>ApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
</code>```

I tried to uninstall java and reinstall it.

Also, I removed the use '--release' option as shown below:

Body:
I am having the following error when calling the AppContext class:

Exception in thread "Thread-5" java.lang.IllegalAccessError: class [Class Name] (in unnamed module @0x6f1fba17) cannot access class sun.awt.AppContext (in module java.desktop) because module java.desktop does not export sun.awt to unnamed module @0x6f1fba17
    at [Class Name].run([Class Name].java:176)

Line 176 contains the following line of code:

ApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);

I tried to uninstall java and reinstall it.

Also, I removed the use '--release' option as shown below:


问:
Lazy loading for twig and sonata
The problem i am facing is that not all the images are loading correctly. I have a page with about 25 photos and i want to load at start the first 10, so the user is not impacted by the lazy loading. The thing is, on refresh it sometimes shows me 3 random images out of 10, another time it will be 4 other photos, and so on. I cant see why their are not loading , because the code is the exact same either the image is showing or not.

I have tried different forms of lazy loading, they all work perfectly ,but if I try to load all of the 10 first images it just wont work. Here is my twig code:

```<code>`
{% extends '@SonataAdmin/CRUD/base_list_field.html.twig' %}

{% block field %}
<script> cookie = document.cookie
cookie = cookie.split(";")
 counter = cookie[0].split("=")
if(counter[1] == 0) {
var lazyloadImages = document.querySelectorAll("img.lazy");
        console.log(lazyloadImages.length)
        if(lazyloadImages.length >= 24) {
            counter[1] = parseInt(counter[1]) + 1
            cookie[0] = "counter=" + counter[1];
            cookie = cookie.join(";")
            document.cookie = cookie
            while (lazyloadImages.length > 15) {
                for (i = 0; i < 10; i++) {
                    if (typeof lazyloadImages[i].dataset !== "undefined") {
                        lazyloadImages[i].src = lazyloadImages[i].dataset.src;
                        lazyloadImages[i].classList.remove('lazy');
                    }
                }

                var lazyloadImages = document.querySelectorAll("img.lazy");
            }
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        var lazyloadImages = document.querySelectorAll("img.lazy");
        var lazyloadThrottleTimeout;

        function lazyload () {
            if(lazyloadThrottleTimeout) {
                clearTimeout(lazyloadThrottleTimeout);
            }

            lazyloadThrottleTimeout = setTimeout(function() {
                var scrollTop = window.pageYOffset;
                lazyloadImages.forEach(function(img) {
                    if(img.offsetTop < (window.innerHeight + scrollTop)) {
                        img.src = img.dataset.src;
                        img.classList.remove('lazy');
                    }
                });
                if(lazyloadImages.length == 0) {
                    document.removeEventListener("scroll", lazyload);
                    window.removeEventListener("resize", lazyload);
                    window.removeEventListener("orientationChange", lazyload);
                }
            }, 20);
        }

        document.addEventListener("scroll", lazyload);
        window.addEventListener("resize", lazyload);
        window.addEventListener("orientationChange", lazyload);
    });
</script>

<div style="text-align: center">
    <img style="width: 45%" class="lazy" data-src="{{ url('productImages', {id: object.mainImageId }) }}" loading="lazy" alt="image"/>
</div>
{% endblock %}
</code>```

`

Title: Lazy loading for twig and sonata

Body:
The problem i am facing is that not all the images are loading correctly. I have a page with about 25 photos and i want to load at start the first 10, so the user is not impacted by the lazy loading. The thing is, on refresh it sometimes shows me 3 random images out of 10, another time it will be 4 other photos, and so on. I cant see why their are not loading , because the code is the exact same either the image is showing or not.

I have tried different forms of lazy loading, they all work perfectly ,but if I try to load all of the 10 first images it just wont work. Here is my twig code:

`
{% extends '@SonataAdmin/CRUD/base_list_field.html.twig' %}

{% block field %}

{% endblock %}

`


问:
How to locally redirect from one website to another without HTML
I want my local browser to redirect one address to another address
(eg when entering youtube.com, redirect to google.com)

I tried to make it by editing the windows's host file but it didnt work.


问:
I am trying to deploy an ReScript project on vercel but the build fails
I have a portfolio app written in ReScript and  i am trying to deploy it live with vercel(i also tried other platforms) and i am failing the build phase saying
While resolving: @rescript/react@0.10.2
npm ERR! Found: bs-platform@4.0.18.</p>


问:
Can I emulate a different process.platform for unit tests?
I have a lot of functionality that should work both with posix and windows paths that I need to run some unit tests for, but running unit tests on actual Windows machine is a pain. Is there a way to emulate process.platform to be win32 and to all native path-related functionality to behave as if it was on Windows?

I don't need to actually read or write anything from or to filesystem in these tests, just to have path.join work.


问:
How to find WatchGuard SSL VPN version?
which version of watchguard ssl vpn uses SHA1 2A42AF641D4B59A5BC7DB461879AE3DC4D2B874D

tried in manny ways

Title: How to find WatchGuard SSL VPN version?


问:
vscode does not recognize terminal command ''make''
I created a make file to run a sdl2 window

Make file

```<code>all:
    g++ -I src/include -L src/lib -o main.cpp -lmingw32 -lSDL2main -lSDL2
</code>```

Opened a new terminal and the command ''make'' doesn't create my .exe file, it isn't really recognized at all

is there an easier way to use the cmd terminal to create an .exe file with sdl2?

I tried going the cmd path : g++ -o main main.cpp

and the result was:

main.cpp:2:10: fatal error: SDL2/SDL.h: No such file or directory
    2 | #include <SDL2/SDL.h>
      |          ^~~~~~~~~~~~
compilation terminated.
```

So apparently the problem is that my file doesn't include SDL.h even tho it is present in the SDL folder.

Also cmd straight out deleted my ''main.cpp' file.

Also tried mingw32-make in the terminal and it also deleted my main.cpp file and found the same errors.

Body:
I created a make file to run a sdl2 window

Make file

all:
    g++ -I src/include -L src/lib -o main.cpp -lmingw32 -lSDL2main -lSDL2

Opened a new terminal and the command ''make'' doesn't create my .exe file, it isn't really recognized at all

is there an easier way to use the cmd terminal to create an .exe file with sdl2?

I tried going the cmd path : g++ -o main main.cpp

and the result was:

main.cpp:2:10: fatal error: SDL2/SDL.h: No such file or directory
    2 | #include <SDL2/SDL.h>
      |          ^~~~~~~~~~~~
compilation terminated.

So apparently the problem is that my file doesn't include SDL.h even tho it is present in the SDL folder.

Also cmd straight out deleted my ''main.cpp' file.

Also tried mingw32-make in the terminal and it also deleted my main.cpp file and found the same errors.


问:
MVC Razor Call Method from Controller class. Download Txt File
I wrote a  public ActionResult BtnSearch_Click(object sender) method in the controller class. What it does is generate a DataTable from another method in the same class and appends all the values into a StringBuilder. The Values are logs from an EventLog(Eventviewerlog_name). The Method returns: return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/plain", "Eventlog.txt"); in hope, it will download a txt file after pressing the button in the .cshtml.

To pass the parameter from the viewmodel class, I used f.e. for bool: if(bool.Parse(Request["IsEvent"])). Please correct me if I am wrong...

Now for the primary question: I have a button in .cshtml, where I want the onclick to be the method public ActionResult BtnSearch_Click(object sender) where I pass all the properties like the bool IsEvent, which is defined in a RadioButton.
From other Stackoverflow posts, I found several things that do not work for me, such as:

```<code><button class="btn btn-primary" onclick="location.href='<%: Url.Action("BtnSearch_Click", "SupportController", new{sender = this}) %>'" >
</code>```

I don't know if I wrote it correctly, but the button <> brackets stop at the top-bracket I wrote a line above that one.

Body:
I wrote a  public ActionResult BtnSearch_Click(object sender) method in the controller class. What it does is generate a DataTable from another method in the same class and appends all the values into a StringBuilder. The Values are logs from an EventLog(Eventviewerlog_name). The Method returns: return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/plain", "Eventlog.txt"); in hope, it will download a txt file after pressing the button in the .cshtml.

To pass the parameter from the viewmodel class, I used f.e. for bool: if(bool.Parse(Request["IsEvent"])). Please correct me if I am wrong...

Now for the primary question: I have a button in .cshtml, where I want the onclick to be the method public ActionResult BtnSearch_Click(object sender) where I pass all the properties like the bool IsEvent, which is defined in a RadioButton.
From other Stackoverflow posts, I found several things that do not work for me, such as:

<button class="btn btn-primary" onclick="location.href='<%: Url.Action("BtnSearch_Click", "SupportController", new{sender = this}) %>'" >

I don't know if I wrote it correctly, but the button <> brackets stop at the top-bracket I wrote a line above that one.


问:
Cannot access Object/Array data in PHP function without getting error
I am currently working on a project with PHP, JavaScript and jQuery and have come across an issue.  I am trying to get the PHP function getCountryBorders() to return just the polygon information for a country but I cannot seem to access object data with object['property'] as it gives me the

Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21

Any help would be greatly appreciated.

Here is the code:

server.php:

```<code><?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
        if(isset($_POST['iso_a2'])) {
            $iso_a2 = $_POST['iso_a2'];
        }

        switch($action) {
            case 'populateSelect' : populateSelect();break;
            case 'getCountryBorders' : getCountryBorders($iso_a2);break;
        };
    };

    function populateSelect() {
        $data = file_get_contents('../../data.json');
        echo $data;
    }

    function getCountryBorders($iso_a2) {
        $data = file_get_contents('../../data.json');
        echo $data['features'];
    }
?>

//index.js
$('#document').ready(() => {
    $.ajax({
        url: 'libs/php/server.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'populateSelect'
        },
        success: (result) => {
            result['features'].forEach((country) => {
                $("<option>", {
                    value: country.properties.iso_a2,
                    text: country.properties.name
                }).appendTo('#countries');
            })
        }
    });
});

$('#countries').change(() => {
    console.log($('#countries').val());
});

$('#test').click(() => {
    alert('Clicked')
    $.ajax({
        url: 'libs/php/server.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'getCountryBorders',
            iso_a2: $('#countries').val()
        },
        success: (result) => {
            console.log(result);
        }
    });
});
</code>```

The issue is within the $('#test') ajax function.

Thank you,

Liam

I have tried looking at network responses but they just return

Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21

Body:
I am currently working on a project with PHP, JavaScript and jQuery and have come across an issue.  I am trying to get the PHP function getCountryBorders() to return just the polygon information for a country but I cannot seem to access object data with object['property'] as it gives me the

Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21

Any help would be greatly appreciated.

Here is the code:

server.php:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
        if(isset($_POST['iso_a2'])) {
            $iso_a2 = $_POST['iso_a2'];
        }

        switch($action) {
            case 'populateSelect' : populateSelect();break;
            case 'getCountryBorders' : getCountryBorders($iso_a2);break;
        };
    };

    function populateSelect() {
        $data = file_get_contents('../../data.json');
        echo $data;
    }

    function getCountryBorders($iso_a2) {
        $data = file_get_contents('../../data.json');
        echo $data['features'];
    }
?>

//index.js
$('#document').ready(() => {
    $.ajax({
        url: 'libs/php/server.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'populateSelect'
        },
        success: (result) => {
            result['features'].forEach((country) => {
                $("<option>", {
                    value: country.properties.iso_a2,
                    text: country.properties.name
                }).appendTo('#countries');
            })
        }
    });
});

$('#countries').change(() => {
    console.log($('#countries').val());
});

$('#test').click(() => {
    alert('Clicked')
    $.ajax({
        url: 'libs/php/server.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'getCountryBorders',
            iso_a2: $('#countries').val()
        },
        success: (result) => {
            console.log(result);
        }
    });
});

The issue is within the $('#test') ajax function.

Thank you,

Liam

I have tried looking at network responses but they just return

Fatal error: Uncaught TypeError: Cannot access offset of type string on string in C:\xampp\htdocs\worldmap\libs\php\server.php:21 Stack trace: #0 C:\xampp\htdocs\worldmap\libs\php\server.php(10): getCountryBorders('BS') #1 {main} thrown in C:\xampp\htdocs\worldmap\libs\php\server.php on line 21


问:
How to run cmd or powershell command from golang as admin?
How can cmd and powershell commands be executed from Go with admin privilege (run as admin)?
Note that the execution of cmd and powershell with admin privilege is clear, but how to specify that the commands executed by them also have admin privilege is questionable.
For example how can we run this powershell command in go as administrative:

```<code>Stop-Process -ID 11111 -Force
</code>```

or this command:

```<code>taskkill /IM example.exe /F
</code>```

Body:
How can cmd and powershell commands be executed from Go with admin privilege (run as admin)?
Note that the execution of cmd and powershell with admin privilege is clear, but how to specify that the commands executed by them also have admin privilege is questionable.
For example how can we run this powershell command in go as administrative:

Stop-Process -ID 11111 -Force

or this command:

taskkill /IM example.exe /F


问:
Using roles with Realtime Database (firebase)
I'm trying to write a project using Realtime Database (firebase)  and Angular. Lately I've been trying to learn how to use roles in a project (user, manager, admin, etc.). Did I understand correctly - in the case of using Realtime Database, it is impossible to create roles. Instead, you need to use the rules in the database:

rules: {
   "adminContent": {
       ".read": "auth.token.admin === true",
       ".write": "auth.token.admin === true",
     }
```

Everything was very good until I read:

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken () method.

What does "your server" mean?  I am using Realtime Database and firebase authentication and this is not enough and I need server?
Maybe there is an easier way to add roles to the Realtime Database, I just haven't found it?

Body:
I'm trying to write a project using Realtime Database (firebase)  and Angular. Lately I've been trying to learn how to use roles in a project (user, manager, admin, etc.). Did I understand correctly - in the case of using Realtime Database, it is impossible to create roles. Instead, you need to use the rules in the database:

rules: {
   "adminContent": {
       ".read": "auth.token.admin === true",
       ".write": "auth.token.admin === true",
     }

Everything was very good until I read:

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken () method.

What does "your server" mean?  I am using Realtime Database and firebase authentication and this is not enough and I need server?
Maybe there is an easier way to add roles to the Realtime Database, I just haven't found it?


问:
Killing the container if the `docker run` command is killed
I am running a Docker container that has access to the host's Docker socket. It uses this privilege to start new, short-lived containers on its own, using docker run -it some_image some_command. Though there's no strict link here, we can call the original container the parent, and the other, short-lived containers children. What I'd like to happen is for the children containers to die if the parent dies, for example, by sending a SIGKILL to process started by docker run -it ....

The context is here to avoid the XY problem, but the same question is relevant in a non-nested scenario - if I run docker run -it image sleep 300, then kill this process, sleep 300 will carry on and the container will stay alive. What I want is for the docker run command to be "bound together" with the command it runs. I am looking to do this without access to the host, and without using docker compose. Is there any such way?

The options listed under the docker run docs don't seem to have anything like this. My best working approach would be to set up a trap for SIGTERM, run the children containers in detached mode (so I get their container IDs), and then docker kill them in the trap, but this seems more cumbersome than it should be (and I'm unsure if docker kill can be trapped).


问:
ApexCharts appearing on top of navbar, -z-50 or z-index:-999 is not solving the problem
i am facing an issue with apexchart charts they are appearing on top of my navbar which looks ugly this is how it is looking when appearing on top of the navbar while i scroll throw the website

i am using tailwind-react, i have tried setting it to -z-50 and a bunch of other minus z-index numbers, plus i tried giving it a standard CSS className and ID to set the z-index:-999; from the css file but still didn't solve the issue, i was wondering if any of you have found a solution to this issue..

export default App(){
 return(

 <navbar />
 <text />
 <picture />
 <apexChart />  //this appears on top of <navbar /> i have tried changing z-index from css and tailwind
 <moreText />

);
}```

thanks a lot in advance

Body:
i am facing an issue with apexchart charts they are appearing on top of my navbar which looks ugly this is how it is looking when appearing on top of the navbar while i scroll throw the website

i am using tailwind-react, i have tried setting it to -z-50 and a bunch of other minus z-index numbers, plus i tried giving it a standard CSS className and ID to set the z-index:-999; from the css file but still didn't solve the issue, i was wondering if any of you have found a solution to this issue..

export default App(){
 return(

 <navbar />
 <text />
 <picture />
 <apexChart />  //this appears on top of <navbar /> i have tried changing z-index from css and tailwind
 <moreText />

);
}

thanks a lot in advance


问:
concurrency in AWS Lambda function
I am just looking for confirmation that I understand the lambda settings correctly.
The minimum concurrency setting is 10, My lambda function takes 3000 ms.
So does that mean the maximum number of times my function can be called a minute is...

60 seconds / 3 seconds = 20 calls

20 x 10 concurrent = 200 function calls per minute.

thanks

Title: concurrency in AWS Lambda function


问:
Send AWS load balancer traffic to data interface of instances
I am using AWS classic load balancer to distribute traffic to instances present in a auto scale group.

Each instance has 3 interfaces (1 management, 2 data interface).

I want my loadbalancer to send traffic to data interface 1, but I have found any way to do this. Loadbalancer is sending traffic to management interface only.

```<code>Subnet CIDR:
Management: 10.0.1.0/24 -> Public
Data1: 10.0.2.0/24 -> Private
Data2: 10.0.3.0/24 -> Private
</code>```

Load balancer is present in public subnet, and instances are getting created in private subnet.

Route table
Public:Management subnet is associated, and internet gateway is attached.
Private: Data1 and Data2 subnet is associated and nat gateway is attached.

Body:
I am using AWS classic load balancer to distribute traffic to instances present in a auto scale group.

Each instance has 3 interfaces (1 management, 2 data interface).

I want my loadbalancer to send traffic to data interface 1, but I have found any way to do this. Loadbalancer is sending traffic to management interface only.

Subnet CIDR:
Management: 10.0.1.0/24 -> Public
Data1: 10.0.2.0/24 -> Private
Data2: 10.0.3.0/24 -> Private

Load balancer is present in public subnet, and instances are getting created in private subnet.

Route table
Public:Management subnet is associated, and internet gateway is attached.
Private: Data1 and Data2 subnet is associated and nat gateway is attached.


问:
ActivityTransitions API not calling BroadcastReceiver on Samsung Deivce
I implemented the Activity Transitions API with a PendingIntent and a BroadcastReceiver as seen below. The code works perfectly fine on a Pixel 3a. However, on a Samsung A32 and Samsung S22 Pro, the Broadcast receiver is never reached, eventhough the ActivityRecognition.getClient(mainActivity).requestActivityTransitionUpdates() succeeds and enters the onSuccessListener().

After a lot of time spent reading through the internet, I wasn't able to find any further information. Neither concerning the Activity Transitions API, nor concerning such problems on Samsung devices (e.g. not raching BroadcastReceiver). Some people hint to disabling battery saving features from Samsung, but the App runs currently only in foreground in the MainActivty thread, therefore I don't think my problem is related to that. Other point out that, for example Huawai devices, need a diffferent permission than the in the android docs specified one for the Activity Transition API. So currently I'm specifing those three permissions (and check them run-time with ContextCompat.checkSelfPermission()):

```<code>    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
</code>```

Code

Main class with

initalization function initController() called in the form of
mActivityTransitionController = ActivityTransitionController().also { it.initController(this@MainActivity) }

and the entrypoint onClickEnableOrDisableActivityRecognition():

class ActivityTransitionController() {
companion object {
internal val TRANSITION_RECEIVER_ACTION: String =
"MyMachineLearningStalkingProtection.TRANSITIONS_RECEIVER_ACTION"
}

    private var activityTrackingOn: Boolean = false

    private lateinit var activityTransitionList: List<ActivityTransition>
    private lateinit var mActivityTransitionPendingIntent: PendingIntent

    internal fun initController(mainActivity: MainActivity) {
        activityTrackingOn = false
        activityTransitionList = buildTransitionList()

        val intent = Intent(TRANSITION_RECEIVER_ACTION)
        mActivityTransitionPendingIntent =
            PendingIntent.getBroadcast(mainActivity, 0, intent, PendingIntent.FLAG_MUTABLE)

        Utils.makeSnackBar("Activity Recognition initialized!", mainActivity)
    }

    internal fun onClickEnableOrDisableActivityRecognition(mainActivity: MainActivity) {
        if (activityTrackingOn) {
            disableActivityTransitions(mainActivity)
        } else {
            enableActivityTransitions(mainActivity)
        }
    }

    private fun buildTransitionList(): ArrayList<ActivityTransition> {
        val list = ArrayList<ActivityTransition>()
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build()
        )
        return list
    }

    @SuppressLint("MissingPermission")
    internal fun disableActivityTransitions(mainActivity: MainActivity) {
        Log.d(Utils.MY_LOG_TAG, "disableActivityTransitions()")
        ActivityRecognition.getClient(mainActivity)
            .removeActivityTransitionUpdates(mActivityTransitionPendingIntent)
            .addOnSuccessListener {
                activityTrackingOn = false
                Utils.makeSnackBar("Transitions successfully unregistered.", mainActivity)
            }.addOnFailureListener {
                Utils.makeSnackBar("Transitions could NOT be unregistered.", mainActivity)
                Log.e(Utils.MY_LOG_TAG, "Transitions could not be unregistered $it")
            }
    }

    @SuppressLint("MissingPermission")
    internal fun enableActivityTransitions(mainActivity: MainActivity) {
        Log.d(Utils.MY_LOG_TAG, "enableActivityTransitions()")

        val request = ActivityTransitionRequest(activityTransitionList)
        ActivityRecognition.getClient(mainActivity)
            .requestActivityTransitionUpdates(request, mActivityTransitionPendingIntent)
            .addOnSuccessListener {
                Utils.makeSnackBar("Transitions Api was successfully registered", mainActivity)
                activityTrackingOn = true
            }
            .addOnFailureListener {
                Utils.makeSnackBar("Transitions Api could NOT be registered", mainActivity)
                Log.e(Utils.MY_LOG_TAG, "Transitions Api could NOT be registered. $it")
            }
    }

}
```
<hr />
<p><strong>Boradcast receiver</strong></p>
<ul>
<li>registerd in <code>MainActivity</code>'s <code>onStart()</code></li>
<li>unregisterd in <code>MainActivity</code>'s <code>onStop()</code></li>
</ul>
<pre class="lang-kt prettyprint-override"><code>
class ActivityTransitionReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val mainActivity = context as MainActivity
        val findViewById = mainActivity.findViewById<TextView>(R.id.txt_activity)
        val now = Calendar.getInstance().time.toString()
        val currentText = findViewById.text
        if (currentText.isEmpty()) {
            findViewById.text = "1##$now"
        } else {
            val split = currentText.split("##")
            val num = split[0].toInt() + 1
            findViewById.text = "$num##$now"
        }

        if (ActivityRecognitionResult.hasResult(intent)) {
            Log.d(Utils.MY_LOG_TAG, "RECOGNITION  called")
        }

        if (ActivityTransitionResult.hasResult(intent)) {
            Log.d(Utils.MY_LOG_TAG, "TRANSITION  called")
            val result = ActivityTransitionResult.extractResult(intent!!)
            for (event in result!!.transitionEvents) {
                val activityType = event.activityType
                val transitionType = event.transitionType
                val elapsedRealTimeNanos = event.elapsedRealTimeNanos
                val findViewById1 = mainActivity.findViewById<TextView>(R.id.txt_confidence)
                findViewById1.text ="${findViewById1.text} + $activityType + $transitionType"
            }
        }
    }
}
</code>```

With this code, the Pixel 3a is able to detect my activities as soon as I call the onClickEnableOrDisableActivityRecognition() entrypoint. On the Samsung devices however, nothing happens, the requestActivityTransitionUpdates() succeeds, though the broadcast receiver ActivityTransitionReceiver is never reached. Do you guys have any idea why I expereience this behaviour? Maybe you experienced similar behaviour with a BroadcastReceiver and were able to fix it?

On a short side note: I also tested if the ActivityRecognition API is available on the Samsung devices using code which is equivalent as described in the docs https://developers.google.com/android/guides/api-client#check-api-availability which succeeded.

If something is unclear, do not hesitate to ask for clarification. Thanks in advance!

Body:
I implemented the Activity Transitions API with a PendingIntent and a BroadcastReceiver as seen below. The code works perfectly fine on a Pixel 3a. However, on a Samsung A32 and Samsung S22 Pro, the Broadcast receiver is never reached, eventhough the ActivityRecognition.getClient(mainActivity).requestActivityTransitionUpdates() succeeds and enters the onSuccessListener().

After a lot of time spent reading through the internet, I wasn't able to find any further information. Neither concerning the Activity Transitions API, nor concerning such problems on Samsung devices (e.g. not raching BroadcastReceiver). Some people hint to disabling battery saving features from Samsung, but the App runs currently only in foreground in the MainActivty thread, therefore I don't think my problem is related to that. Other point out that, for example Huawai devices, need a diffferent permission than the in the android docs specified one for the Activity Transition API. So currently I'm specifing those three permissions (and check them run-time with ContextCompat.checkSelfPermission()):

    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

Code

Main class with

initalization function initController() called in the form of
mActivityTransitionController = ActivityTransitionController().also { it.initController(this@MainActivity) }

and the entrypoint onClickEnableOrDisableActivityRecognition():

class ActivityTransitionController() {
companion object {
internal val TRANSITION_RECEIVER_ACTION: String =
"MyMachineLearningStalkingProtection.TRANSITIONS_RECEIVER_ACTION"
}

    private var activityTrackingOn: Boolean = false

    private lateinit var activityTransitionList: List<ActivityTransition>
    private lateinit var mActivityTransitionPendingIntent: PendingIntent

    internal fun initController(mainActivity: MainActivity) {
        activityTrackingOn = false
        activityTransitionList = buildTransitionList()

        val intent = Intent(TRANSITION_RECEIVER_ACTION)
        mActivityTransitionPendingIntent =
            PendingIntent.getBroadcast(mainActivity, 0, intent, PendingIntent.FLAG_MUTABLE)

        Utils.makeSnackBar("Activity Recognition initialized!", mainActivity)
    }

    internal fun onClickEnableOrDisableActivityRecognition(mainActivity: MainActivity) {
        if (activityTrackingOn) {
            disableActivityTransitions(mainActivity)
        } else {
            enableActivityTransitions(mainActivity)
        }
    }

    private fun buildTransitionList(): ArrayList<ActivityTransition> {
        val list = ArrayList<ActivityTransition>()
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build()
        )
        list.add(
            ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build()
        )
        return list
    }

    @SuppressLint("MissingPermission")
    internal fun disableActivityTransitions(mainActivity: MainActivity) {
        Log.d(Utils.MY_LOG_TAG, "disableActivityTransitions()")
        ActivityRecognition.getClient(mainActivity)
            .removeActivityTransitionUpdates(mActivityTransitionPendingIntent)
            .addOnSuccessListener {
                activityTrackingOn = false
                Utils.makeSnackBar("Transitions successfully unregistered.", mainActivity)
            }.addOnFailureListener {
                Utils.makeSnackBar("Transitions could NOT be unregistered.", mainActivity)
                Log.e(Utils.MY_LOG_TAG, "Transitions could not be unregistered $it")
            }
    }

    @SuppressLint("MissingPermission")
    internal fun enableActivityTransitions(mainActivity: MainActivity) {
        Log.d(Utils.MY_LOG_TAG, "enableActivityTransitions()")

        val request = ActivityTransitionRequest(activityTransitionList)
        ActivityRecognition.getClient(mainActivity)
            .requestActivityTransitionUpdates(request, mActivityTransitionPendingIntent)
            .addOnSuccessListener {
                Utils.makeSnackBar("Transitions Api was successfully registered", mainActivity)
                activityTrackingOn = true
            }
            .addOnFailureListener {
                Utils.makeSnackBar("Transitions Api could NOT be registered", mainActivity)
                Log.e(Utils.MY_LOG_TAG, "Transitions Api could NOT be registered. $it")
            }
    }

}

Boradcast receiver

registerd in MainActivity's onStart()

unregisterd in MainActivity's onStop()

class ActivityTransitionReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val mainActivity = context as MainActivity
        val findViewById = mainActivity.findViewById<TextView>(R.id.txt_activity)
        val now = Calendar.getInstance().time.toString()
        val currentText = findViewById.text
        if (currentText.isEmpty()) {
            findViewById.text = "1##$now"
        } else {
            val split = currentText.split("##")
            val num = split[0].toInt() + 1
            findViewById.text = "$num##$now"
        }

        if (ActivityRecognitionResult.hasResult(intent)) {
            Log.d(Utils.MY_LOG_TAG, "RECOGNITION  called")
        }

        if (ActivityTransitionResult.hasResult(intent)) {
            Log.d(Utils.MY_LOG_TAG, "TRANSITION  called")
            val result = ActivityTransitionResult.extractResult(intent!!)
            for (event in result!!.transitionEvents) {
                val activityType = event.activityType
                val transitionType = event.transitionType
                val elapsedRealTimeNanos = event.elapsedRealTimeNanos
                val findViewById1 = mainActivity.findViewById<TextView>(R.id.txt_confidence)
                findViewById1.text ="${findViewById1.text} + $activityType + $transitionType"
            }
        }
    }
}

With this code, the Pixel 3a is able to detect my activities as soon as I call the onClickEnableOrDisableActivityRecognition() entrypoint. On the Samsung devices however, nothing happens, the requestActivityTransitionUpdates() succeeds, though the broadcast receiver ActivityTransitionReceiver is never reached. Do you guys have any idea why I expereience this behaviour? Maybe you experienced similar behaviour with a BroadcastReceiver and were able to fix it?

On a short side note: I also tested if the ActivityRecognition API is available on the Samsung devices using code which is equivalent as described in the docs https://developers.google.com/android/guides/api-client#check-api-availability which succeeded.

If something is unclear, do not hesitate to ask for clarification. Thanks in advance!


问:
Terraform import error retrieving Virtual Machine Scale Set created from an image
I'm trying to import a Linux VM Scale Set that was deployed in the Azure Portal from a custom shared image, also created in the portal. I'm using the following command:

terraform import module.vm_scaleset.azurerm_linux_virtual_machine_scale_set.vmscaleset /subscriptions/00000000-0000-0000-0000-000000000000
/resourceGroups/myrg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1

Import fails with the following error:

Error: retrieving Virtual Machine Scale Set "vmss1" (Resource Group "myrg"): properties.virtualMachineProfile.osProfile was nil

Below is my VM Scale set module code

```<code>data "azurerm_lb" "loadbalancer" {
  name                = var.lbName
  resource_group_name = var.rgName
}

data "azurerm_lb_backend_address_pool" "addresspool" {
  loadbalancer_id = data.azurerm_lb.loadbalancer.id
  name            = var.lbAddressPool
}

data "azurerm_shared_image" "scaleset_image" {
  provider            = azurerm.ist
  name                = var.scaleset_image_name
  gallery_name        = var.scaleset_image_gallery
  resource_group_name = var.scaleset_image_rgname
}

resource "azurerm_linux_virtual_machine_scale_set" "vmscaleset" {
  name                            = var.vmssName
  resource_group_name             = var.rgName
  location                        = var.location
  sku                             = var.vms_sku
  instances                       = var.vm_instances
  admin_username                  = azurerm_key_vault_secret.vmssusername.value
  admin_password                  = azurerm_key_vault_secret.vmsspassword.value
  disable_password_authentication = false
  zones                           = var.vmss_zones
  source_image_id                 = data.azurerm_shared_image.scaleset_image.id
  tags                            = module.vmss_tags.tags

  os_disk {
    storage_account_type = var.vmss_osdisk_storage
    caching              = "ReadWrite"
    create_option        = "FromImage"
  }

  data_disk {
    storage_account_type = "StandardSSD_LRS"
    caching              = "None"
    disk_size_gb         = 1000
    lun                  = 10
    create_option        = "FromImage"
  }

  network_interface {
    name                          = format("nic-%s-001", var.vmssName)
    primary                       = true
    enable_accelerated_networking = true

    ip_configuration {
      name                                   = "internal"
      load_balancer_backend_address_pool_ids = [data.azurerm_lb_backend_address_pool.addresspool.id]
      primary                                = true
      subnet_id                              = var.subnet_id
    }
  }

  lifecycle {
    ignore_changes = [
      tags
    ]
  }
}

</code>```

The source image was created from a Linux RHEL 8.6 VM that included a custom node.js script.
Examination of the Scale Set in the portal does indeed show that the virtualMachineProfile.osProfile is absent.

I haven't been able to find a solution on any forum. Is there any way to ignore the error and import the Scale Set anyway?

Body:
I'm trying to import a Linux VM Scale Set that was deployed in the Azure Portal from a custom shared image, also created in the portal. I'm using the following command:

terraform import module.vm_scaleset.azurerm_linux_virtual_machine_scale_set.vmscaleset /subscriptions/00000000-0000-0000-0000-000000000000
/resourceGroups/myrg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1

Import fails with the following error:

Error: retrieving Virtual Machine Scale Set "vmss1" (Resource Group "myrg"): properties.virtualMachineProfile.osProfile was nil

Below is my VM Scale set module code

data "azurerm_lb" "loadbalancer" {
  name                = var.lbName
  resource_group_name = var.rgName
}

data "azurerm_lb_backend_address_pool" "addresspool" {
  loadbalancer_id = data.azurerm_lb.loadbalancer.id
  name            = var.lbAddressPool
}

data "azurerm_shared_image" "scaleset_image" {
  provider            = azurerm.ist
  name                = var.scaleset_image_name
  gallery_name        = var.scaleset_image_gallery
  resource_group_name = var.scaleset_image_rgname
}

resource "azurerm_linux_virtual_machine_scale_set" "vmscaleset" {
  name                            = var.vmssName
  resource_group_name             = var.rgName
  location                        = var.location
  sku                             = var.vms_sku
  instances                       = var.vm_instances
  admin_username                  = azurerm_key_vault_secret.vmssusername.value
  admin_password                  = azurerm_key_vault_secret.vmsspassword.value
  disable_password_authentication = false
  zones                           = var.vmss_zones
  source_image_id                 = data.azurerm_shared_image.scaleset_image.id
  tags                            = module.vmss_tags.tags

  os_disk {
    storage_account_type = var.vmss_osdisk_storage
    caching              = "ReadWrite"
    create_option        = "FromImage"
  }

  data_disk {
    storage_account_type = "StandardSSD_LRS"
    caching              = "None"
    disk_size_gb         = 1000
    lun                  = 10
    create_option        = "FromImage"
  }

  network_interface {
    name                          = format("nic-%s-001", var.vmssName)
    primary                       = true
    enable_accelerated_networking = true

    ip_configuration {
      name                                   = "internal"
      load_balancer_backend_address_pool_ids = [data.azurerm_lb_backend_address_pool.addresspool.id]
      primary                                = true
      subnet_id                              = var.subnet_id
    }
  }

  lifecycle {
    ignore_changes = [
      tags
    ]
  }
}

The source image was created from a Linux RHEL 8.6 VM that included a custom node.js script.
Examination of the Scale Set in the portal does indeed show that the virtualMachineProfile.osProfile is absent.

I haven't been able to find a solution on any forum. Is there any way to ignore the error and import the Scale Set anyway?


问:
Java - Playing music one after another without breaks
I'm trying to play a music file, and then a second file which is a second part of the song. The problem is, the transition between the two is very lacking. After one part finishes playing, there's about a second of silence, and then the second part starts playing.

In best case, both files would play seamlessly one after another. I tried using a second MediaPlayer, preparing it beforehand so the only thing left is to start it, but it didn't help. Is there a way to start playing the second part earlier?

Here's the code:

```<code>// MediaPlayers are created as "music" and "musicfollow"

//setting up files for source
    AssetFileDescriptor anticip = getAssets().openFd("file1.ogg");
    AssetFileDescriptor afdass1 = getAssets().openFd("file2.ogg");

    //setting a new source for player
    music.reset();
    try {
        music.setDataSource(anticip.getFileDescriptor(), anticip.getStartOffset(),anticip.getLength());
        music.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //preparing follow-up music player
    musicfollow.reset();
    musicfollow.setLooping(true);
    try {
        musicfollow.setDataSource(afdass1.getFileDescriptor(), afdass1.getStartOffset(),afdass1.getLength());
        musicfollow.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //playing part 1
    music.start();

    //changing the MediaPlayer to follow-up player
    music.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            musicfollow.start();
        }
    });
}
</code>```

Body:
I'm trying to play a music file, and then a second file which is a second part of the song. The problem is, the transition between the two is very lacking. After one part finishes playing, there's about a second of silence, and then the second part starts playing.

In best case, both files would play seamlessly one after another. I tried using a second MediaPlayer, preparing it beforehand so the only thing left is to start it, but it didn't help. Is there a way to start playing the second part earlier?

Here's the code:

// MediaPlayers are created as "music" and "musicfollow"

//setting up files for source
    AssetFileDescriptor anticip = getAssets().openFd("file1.ogg");
    AssetFileDescriptor afdass1 = getAssets().openFd("file2.ogg");

    //setting a new source for player
    music.reset();
    try {
        music.setDataSource(anticip.getFileDescriptor(), anticip.getStartOffset(),anticip.getLength());
        music.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //preparing follow-up music player
    musicfollow.reset();
    musicfollow.setLooping(true);
    try {
        musicfollow.setDataSource(afdass1.getFileDescriptor(), afdass1.getStartOffset(),afdass1.getLength());
        musicfollow.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //playing part 1
    music.start();

    //changing the MediaPlayer to follow-up player
    music.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            musicfollow.start();
        }
    });
}


问:
Fastapi return the results of a query as application/json
hello i have the following function in fastapi python

```<code>    from fastapi.encoders import jsonable_encoder
    from fastapi.responses import JSONResponse
    from fastapi import Response
    import json
    import pyodbc
    import pandas as pd
    from fastapi import FastAPI
    from typing  import Optional
    from typing import Union

@app.get("/periodikes/sql_2")
def results_to_json():
    conn = pyodbc.connect('blah blah')
    cursor = conn.cursor()
    query_result = "select top 100 * from table"
    cursor.execute(query_result)
    datashet = cursor.fetchall()
    print(cursor.description)
    cursor.close()
    conn.close()
    json_compatible_item_data = jsonable_encoder(datashet)
    return JSONResponse(content=json_compatible_item_data)
</code>```

this get method results in ValueError: [ValueError('dictionary update sequence element #0 has length 32; 2 is required'), TypeError('vars() argument must have dict attribute')] what can i do to return the results of query as json with the name of the column and the value like this

```<code>{
    "crmIFE_ReturnCode": "203",
    "crmIFE_ActionID": "0F09630A1C754B408CAF3C0B47CD4577",
    "crmBA_ID": "0F09630A1C754B408CAF3C0B47CD4577",
 }
</code>```

Body:
hello i have the following function in fastapi python

    from fastapi.encoders import jsonable_encoder
    from fastapi.responses import JSONResponse
    from fastapi import Response
    import json
    import pyodbc
    import pandas as pd
    from fastapi import FastAPI
    from typing  import Optional
    from typing import Union

@app.get("/periodikes/sql_2")
def results_to_json():
    conn = pyodbc.connect('blah blah')
    cursor = conn.cursor()
    query_result = "select top 100 * from table"
    cursor.execute(query_result)
    datashet = cursor.fetchall()
    print(cursor.description)
    cursor.close()
    conn.close()
    json_compatible_item_data = jsonable_encoder(datashet)
    return JSONResponse(content=json_compatible_item_data)

this get method results in ValueError: [ValueError('dictionary update sequence element #0 has length 32; 2 is required'), TypeError('vars() argument must have dict attribute')] what can i do to return the results of query as json with the name of the column and the value like this

{
    "crmIFE_ReturnCode": "203",
    "crmIFE_ActionID": "0F09630A1C754B408CAF3C0B47CD4577",
    "crmBA_ID": "0F09630A1C754B408CAF3C0B47CD4577",
 }


问:
Firebase says initializeApp is not defined after adding libraries
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>List</title>
</head>
<body>
<table>
        <thead>
          <th>Name</th>
          <th>Email</th>
          <th>Message</th>
        </thead>
        <tbody id="tbody1">

        </tbody>
      </table>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-database.js"></script>

      <script id="MainScript">
//-----------Config------------//
        var firebaseConfig = {
  apiKey: "----------------------",
  authDomain: "-firebaseapp.com",
  databaseURL: -.firebaseio.com",
  projectId: "-9677d",
  storageBucket: "--.appspot.com",
  messagingSenderId: "-------3",
  appId: "------------------------"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

//----------Getting-The-Data-------------------//
function SelectAllData() {
    firebase.database().ref('People').on('value',
    function(AllRecords){
      AllRecords.forEach(
        function(CurrentRecord){
          var name = CurrentRecord.val().Name;
          var email = CurrentRecord.val().Email;
          var message = CurrentRecord.val().Message;
          AddItemsToTable(name,email,message);
        }
      );
    });
  }
  window.onload = SelectAllData;
//----------Filling-The-Table-----------------//
var stdNo = 0;
var tbody = document.getElementById('tbody1');
  function AddItemsToTable(Name,Email,Message) {
    var trow = document.createElement('tr');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    td1.innerHTML= sdtNo;
    td1.innerHTML= Name;
    td1.innerHTML= Email;
    td4.innerHTML= Message;
    trow.appendChild(td1);
    trow.appendChild(td2);
    trow.appendChild(td3);
    tbody.appendChild(trow);
  }
  function AddAllItemsToTable(Name){
    stdNo=0;
    tbody.innerHTML="";
    Name.forEach(element => {
        AddItemToTable(element.Name, element.Email, element.Message)
    });
  }
      </script>
</body>
</code>```

This is my code. Above I censored my firebase config. Whenever I run this, it says stdNo is not defined. I am trying to display data from my firebase database into a table. My firebase database looks like this! My Firebase Database Setup

I have tried countless tutorials but none are helping. I always get this error.

```<code>Uncaught ReferenceError: sdtNo is not defined
    at AddItemsToTable (LIST.php:65:20)
    at LIST.php:50:11
    at DataSnapshot.ts:148:14
    at ke.inorderTraversal (SortedMap.ts:229:9)
    at We.inorderTraversal (SortedMap.ts:755:23)
    at Je.forEachChild (ChildrenNode.ts:350:29)
    at cn.forEach (DataSnapshot.ts:147:27)
    at LIST.php:45:18
    at EventRegistration.ts:133:12
    at Nt (util.ts:588:5)
</code>```

Body:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>List</title>

          Name
          Email
          Message

This is my code. Above I censored my firebase config. Whenever I run this, it says stdNo is not defined. I am trying to display data from my firebase database into a table. My firebase database looks like this! My Firebase Database Setup

I have tried countless tutorials but none are helping. I always get this error.

Uncaught ReferenceError: sdtNo is not defined
    at AddItemsToTable (LIST.php:65:20)
    at LIST.php:50:11
    at DataSnapshot.ts:148:14
    at ke.inorderTraversal (SortedMap.ts:229:9)
    at We.inorderTraversal (SortedMap.ts:755:23)
    at Je.forEachChild (ChildrenNode.ts:350:29)
    at cn.forEach (DataSnapshot.ts:147:27)
    at LIST.php:45:18
    at EventRegistration.ts:133:12
    at Nt (util.ts:588:5)


问:
Why does my Gitlab pipeline fail if someone else runs a plan between me doing a build and actually applying my own plan?
I Tried to run a manual apply (i.e plan) of a pipeline that I had run  a build for a few days earlier. But the manual apply failed...it said this

I'm pretty sure that this happened because I originally ran a build...then someone else created a build for the same repo and then applied it  in the time between me running the build and actually doing a manual apply....So I think there were 2 plans....but I still can't get in my head what had changed to the plan in the meantime to make my dependency lock file inconsistent..

can anybody help? I hope I've explained myself clearly

ci file is like this

```<code>image:
  name: $<redacted>

variables:
  PLAN: plan.tfplan

cache:
  paths:
    - .terraform

before_script:
  - export <redacted>
  - export <redacted>
  - export <redacted>
  - terraform --version
  - terraform init -upgrade

stages:
  - validate
  - plan
  - apply
  - destroy

validate:
  stage: validate
  only:
    - branches
  except:
    - master
    - main
  script:
    - terraform validate

plan:
  stage: plan
  script:
    - terraform plan -out=$PLAN
    - echo \`\`\`diff > plan.txt
    - terraform show -no-color ${PLAN} | tee -a plan.txt
    - echo \`\`\` >> plan.txt
    - sed -i -e 's/  +/+/g' plan.txt
    - sed -i -e 's/  ~/~/g' plan.txt
    - sed -i -e 's/  -/-/g' plan.txt
    - MESSAGE=$(cat plan.txt)
    - >-
      curl -X POST -g -H <token stuff>
      --data-urlencode "body=${MESSAGE}"
      "$<ci url project stuff>"
  artifacts:
    name: plan
    paths:
      - $PLAN
  only:
    - merge_requests

build:
  stage: plan
  script:
    - terraform plan -out=$PLAN
  artifacts:
    name: plan
    paths:
      - $PLAN
  only:
    - branches

.apply-template:
  script:
    - terraform apply -input=false $PLAN

Manual Apply:
  extends: .apply-template
  stage: apply
  dependencies:
    - build
  when: manual
  except:
    - schedules
  only:
    - master
    - main

Scheduled Apply:
  extends: .apply-template
  stage: apply
  dependencies:
    - build
  only:
    - schedules

destroy:
  stage: destroy
  script:
    - terraform destroy -auto-approve
  when: manual
  only:
    - master
    - main
</code>```

Body:
I Tried to run a manual apply (i.e plan) of a pipeline that I had run  a build for a few days earlier. But the manual apply failed...it said this

I'm pretty sure that this happened because I originally ran a build...then someone else created a build for the same repo and then applied it  in the time between me running the build and actually doing a manual apply....So I think there were 2 plans....but I still can't get in my head what had changed to the plan in the meantime to make my dependency lock file inconsistent..

can anybody help? I hope I've explained myself clearly

ci file is like this

image:
  name: $<redacted>

variables:
  PLAN: plan.tfplan

cache:
  paths:
    - .terraform

before_script:
  - export <redacted>
  - export <redacted>
  - export <redacted>
  - terraform --version
  - terraform init -upgrade

stages:
  - validate
  - plan
  - apply
  - destroy

validate:
  stage: validate
  only:
    - branches
  except:
    - master
    - main
  script:
    - terraform validate

plan:
  stage: plan
  script:
    - terraform plan -out=$PLAN
    - echo \`\`\`diff > plan.txt
    - terraform show -no-color ${PLAN} | tee -a plan.txt
    - echo \`\`\` >> plan.txt
    - sed -i -e 's/  +/+/g' plan.txt
    - sed -i -e 's/  ~/~/g' plan.txt
    - sed -i -e 's/  -/-/g' plan.txt
    - MESSAGE=$(cat plan.txt)
    - >-
      curl -X POST -g -H <token stuff>
      --data-urlencode "body=${MESSAGE}"
      "$<ci url project stuff>"
  artifacts:
    name: plan
    paths:
      - $PLAN
  only:
    - merge_requests

build:
  stage: plan
  script:
    - terraform plan -out=$PLAN
  artifacts:
    name: plan
    paths:
      - $PLAN
  only:
    - branches

.apply-template:
  script:
    - terraform apply -input=false $PLAN

Manual Apply:
  extends: .apply-template
  stage: apply
  dependencies:
    - build
  when: manual
  except:
    - schedules
  only:
    - master
    - main

Scheduled Apply:
  extends: .apply-template
  stage: apply
  dependencies:
    - build
  only:
    - schedules

destroy:
  stage: destroy
  script:
    - terraform destroy -auto-approve
  when: manual
  only:
    - master
    - main


问:
Clean and neat way of asking permissions in android, like in this screen. How can I achieve this?
I accidently found this app which asks permission in a very clean way in just one screen with just one button to grant it. Here is the link to the project: https://github.com/karma9874/AndroRAT
Here is a screen:

I looked all the source code,but I have found nothing related to this.


问:
Why does Dismax's bq (Boost Query) parameter filter results instead of just boosting them?
I'm using Solr 8.11.2. In order to boost documents with certain field values, I'm using Dismax's bq (Boost Query) parameter.

From what I've read, this should only influence the score of the search results returned by the rest of the query. What I see happening is that it filters all search results that don't have the field I'm boosting.

I'm using the following query, which returns all documents containing both words procedure and maintenance:

q=((+procedure+maintenance))&rows=10&start=0&wt=xml&q.op=AND&fl=id,score,alias,author,hash,collection,label,url,lastModified,path,extension,objectId,objectDtType,title,DocumentPK_s,Taal_s,Site_s,SharePointId_s&hl=true&hl.qt=highlightRH&hl.fl=content,description,label&hl.snippets=5&defType=dismax&bf=recip(max(0,ms(NOW-3MONTH,creationDate)),3.16e-11,1,1)&pf=content&sort=score DESC

But as soon as I append &bq=language:english^10000, which is supposed to boost documents where the field language is set to english, all documents where the field language doesn't exist are no longer part of the results.

Am I misunderstanding how this parameter is supposed to work? Is it a side effect?


问:
Python pip not working as expected in 3.4

C:\Python34\lib\site-packages_distutils_hack_init_.py", line 158, in pip_imported_during_build     cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None) AttributeError: 'module' object has no attribute 'walk_stack

I am getting this error in Python 3.4 when I try to use pip.

Can someone help?

I tried upgrading pip and it shows the same error.


问:
How can I use Kotlin/Native modules as shared libraries in Kotlin/Native projects?
Say I have the following project structure:

```<code>+- root
|
+--- common
|
+--- prog1
|
+--- prog2
</code>```

prog1 and prog2 are executable targets.  common contains code shared by prog1 and prog2.

My goal is to minimize aggregate binary size, so it would be nice if the native code generated from common were shared between prog1 and prog2 rather than copied into each.

Is there a way to emit a shared object (.dll/.so/.dylib) from common and build prog1 and prog2 in such a way that they link to it?

I have tried defining a sharedLib binary for the common module.  This successfully generates a shared object, but I could not find a way to make use of it in prog1 and prog2.

Body:
Say I have the following project structure:

+- root
|
+--- common
|
+--- prog1
|
+--- prog2

prog1 and prog2 are executable targets.  common contains code shared by prog1 and prog2.

My goal is to minimize aggregate binary size, so it would be nice if the native code generated from common were shared between prog1 and prog2 rather than copied into each.

Is there a way to emit a shared object (.dll/.so/.dylib) from common and build prog1 and prog2 in such a way that they link to it?

I have tried defining a sharedLib binary for the common module.  This successfully generates a shared object, but I could not find a way to make use of it in prog1 and prog2.


问:
error: request for member ‘fl’ in ‘mapx->cv::Mat::data’, which is of non-class type ‘uchar*’ {aka ‘unsigned char*’} #1
`

```<code>void create_perspecive_undistortion_LUT( Mat *mapx, Mat *mapy, struct ocam_model *ocam_model, float sf)
{
     int i, j;
     int width = mapx->cols; //New width
     int height = mapx->rows;//New height
     float *data_mapx = mapx->data.fl;
     //float data_mapx = mapx->data.at<float>(1, 1, 1);
     float *data_mapy = mapy->data.fl;
     //float data_mapy = mapy->data.at<float>(1, 1, 1);
     float Nxc = height/2.0;
     float Nyc = width/2.0;
     float Nz  = -width/sf;
     double M[3];
     double m[2];

     for (i=0; i<height; i++)
         for (j=0; j<width; j++)
         {
             M[0] = (i - Nxc);
             M[1] = (j - Nyc);
             M[2] = Nz;
             world2cam(m, M, ocam_model);
             *( data_mapx + i*width+j ) = (float) m[1];
             *( data_mapy + i*width+j ) = (float) m[0];
         }
}

</code>```

`
I was using a Jetson Xavier AGX with Ubuntu 18.04 and ROS Melodic and it's fine but then i need to update to Ubuntu 20.04 and ROS NOETIC and then this error happened. can anyone help?

i tried changing
float *data_mapx = mapx->data.fl;
float *data_mapy = mapy->data.fl;

to

float data_mapx = mapx->data.at<float>(1, 1, 1);
float data_mapy = mapy->data.at<float>(1, 1, 1);

but it doesn't work

Body:
`

void create_perspecive_undistortion_LUT( Mat *mapx, Mat *mapy, struct ocam_model *ocam_model, float sf)
{
     int i, j;
     int width = mapx->cols; //New width
     int height = mapx->rows;//New height
     float *data_mapx = mapx->data.fl;
     //float data_mapx = mapx->data.at<float>(1, 1, 1);
     float *data_mapy = mapy->data.fl;
     //float data_mapy = mapy->data.at<float>(1, 1, 1);
     float Nxc = height/2.0;
     float Nyc = width/2.0;
     float Nz  = -width/sf;
     double M[3];
     double m[2];

     for (i=0; i<height; i++)
         for (j=0; j<width; j++)
         {
             M[0] = (i - Nxc);
             M[1] = (j - Nyc);
             M[2] = Nz;
             world2cam(m, M, ocam_model);
             *( data_mapx + i*width+j ) = (float) m[1];
             *( data_mapy + i*width+j ) = (float) m[0];
         }
}

`
I was using a Jetson Xavier AGX with Ubuntu 18.04 and ROS Melodic and it's fine but then i need to update to Ubuntu 20.04 and ROS NOETIC and then this error happened. can anyone help?

i tried changing
float *data_mapx = mapx->data.fl;
float *data_mapy = mapy->data.fl;

to

float data_mapx = mapx->data.at<float>(1, 1, 1);
float data_mapy = mapy->data.at<float>(1, 1, 1);

but it doesn't work


问:
SonarQube doesn't see a sourcecode
I have a gitlab pipeline set up where it will invoke sonarqube for source code analysis. Unfortunately, SonarQube stubbornly claims 'The main branch has no lines of code.', but if I analyze the same code on gitlab-runner, the whole thing is displayed correctly and I can see the results of the analysis.

On gitlab-runner, I run the following command:

```<code>gitlab-runner exec shell sonarqube-analyze
</code>```

Wheren sonarqube-analyze is a name of gitlab-ci job

Title: SonarQube doesn't see a sourcecode

Body:
I have a gitlab pipeline set up where it will invoke sonarqube for source code analysis. Unfortunately, SonarQube stubbornly claims 'The main branch has no lines of code.', but if I analyze the same code on gitlab-runner, the whole thing is displayed correctly and I can see the results of the analysis.

On gitlab-runner, I run the following command:

gitlab-runner exec shell sonarqube-analyze

Wheren sonarqube-analyze is a name of gitlab-ci job


问:
DATAFRAME (Exception has occurred: ProgrammingError (psycopg2.ProgrammingError) can't adapt type 'dict')
I am having a "Exception has occurred: ProgrammingError (psycopg2.ProgrammingError) can't adapt type 'dict'" error message while using sqlalchemy and psycopg to inject a dataframe to a postgres database

I am writing a script to pull  inject a kobo dataFrame into a local postgres database. Everything seems to be working except the injection. It gives me an error message:

Exception has occurred: ProgrammingError (psycopg2.ProgrammingError) can't adapt type 'dict'

```<code>This is my code below. Please assist.

import psycopg2
import pandas as pd
from sqlalchemy import create_engine
import sqlalchemy
from sqlalchemy.types import String
import pykobo

# establish connections
conn_string = 'postgresql://postgres:openppp@localhost:5432/wpp_appeals'

db = create_engine(conn_string)
conn = db.connect()

URL_KOBO_API = "https://kf.kobotoolbox.org/api/v2"
MYTOKEN = "1e83cdede6c48a19ef210e417d6ca61b076db175"
km = pykobo.Manager(url_api=URL_KOBO_API, token=MYTOKEN)

uid = 'aQCxZ9BVrHe33pLMdtx3gV'
my_form = km.get_form(uid)

my_form.fetch_data()
df1 = my_form.data

df1.to_sql('appeals', con=conn, if_exists='append', index=False, dtype={
    'deviceid':sqlalchemy.String(),
    'TimeStartRecorded':sqlalchemy.VARCHAR(),
    'TimeEndRecorded':sqlalchemy.VARCHAR(),
    'today':sqlalchemy.VARCHAR(),
    'Appeals_Feedback':sqlalchemy.VARCHAR(),
    'Location':sqlalchemy.VARCHAR(),
    'gps_location':sqlalchemy.VARCHAR(),
    '_gps_location_latitude':sqlalchemy.VARCHAR(),
    '_gps_location_longitude':sqlalchemy.VARCHAR(),
    '_gps_location_altitude':sqlalchemy.VARCHAR(),
    '_gps_location_precision':sqlalchemy.VARCHAR(),
    'householdID':sqlalchemy.VARCHAR(),
    'hhNumber':sqlalchemy.VARCHAR(),
    'confirm1':sqlalchemy.VARCHAR(),
    'focalPointName':sqlalchemy.VARCHAR(),
    'validz':sqlalchemy.VARCHAR(),
    '_id':sqlalchemy.VARCHAR(),
    '_uuid':sqlalchemy.VARCHAR(),
    '_submission_time':sqlalchemy.VARCHAR(),
    '_validation_status':sqlalchemy.VARCHAR(),
    '_notes':sqlalchemy.VARCHAR(),
    '_status':sqlalchemy.VARCHAR(),
    '_submitted_by':sqlalchemy.VARCHAR(),
    '_tags':sqlalchemy.VARCHAR(),
    '_index':sqlalchemy.VARCHAR()})

conn = psycopg2.connect(conn_string
                        )

conn.autocommit = True

#conn.commit()
conn.close()
</code>```

Body:
I am having a "Exception has occurred: ProgrammingError (psycopg2.ProgrammingError) can't adapt type 'dict'" error message while using sqlalchemy and psycopg to inject a dataframe to a postgres database

I am writing a script to pull  inject a kobo dataFrame into a local postgres database. Everything seems to be working except the injection. It gives me an error message:

Exception has occurred: ProgrammingError (psycopg2.ProgrammingError) can't adapt type 'dict'

This is my code below. Please assist.

import psycopg2
import pandas as pd
from sqlalchemy import create_engine
import sqlalchemy
from sqlalchemy.types import String
import pykobo

# establish connections
conn_string = 'postgresql://postgres:openppp@localhost:5432/wpp_appeals'

db = create_engine(conn_string)
conn = db.connect()

URL_KOBO_API = "https://kf.kobotoolbox.org/api/v2"
MYTOKEN = "1e83cdede6c48a19ef210e417d6ca61b076db175"
km = pykobo.Manager(url_api=URL_KOBO_API, token=MYTOKEN)

uid = 'aQCxZ9BVrHe33pLMdtx3gV'
my_form = km.get_form(uid)

my_form.fetch_data()
df1 = my_form.data

df1.to_sql('appeals', con=conn, if_exists='append', index=False, dtype={
    'deviceid':sqlalchemy.String(),
    'TimeStartRecorded':sqlalchemy.VARCHAR(),
    'TimeEndRecorded':sqlalchemy.VARCHAR(),
    'today':sqlalchemy.VARCHAR(),
    'Appeals_Feedback':sqlalchemy.VARCHAR(),
    'Location':sqlalchemy.VARCHAR(),
    'gps_location':sqlalchemy.VARCHAR(),
    '_gps_location_latitude':sqlalchemy.VARCHAR(),
    '_gps_location_longitude':sqlalchemy.VARCHAR(),
    '_gps_location_altitude':sqlalchemy.VARCHAR(),
    '_gps_location_precision':sqlalchemy.VARCHAR(),
    'householdID':sqlalchemy.VARCHAR(),
    'hhNumber':sqlalchemy.VARCHAR(),
    'confirm1':sqlalchemy.VARCHAR(),
    'focalPointName':sqlalchemy.VARCHAR(),
    'validz':sqlalchemy.VARCHAR(),
    '_id':sqlalchemy.VARCHAR(),
    '_uuid':sqlalchemy.VARCHAR(),
    '_submission_time':sqlalchemy.VARCHAR(),
    '_validation_status':sqlalchemy.VARCHAR(),
    '_notes':sqlalchemy.VARCHAR(),
    '_status':sqlalchemy.VARCHAR(),
    '_submitted_by':sqlalchemy.VARCHAR(),
    '_tags':sqlalchemy.VARCHAR(),
    '_index':sqlalchemy.VARCHAR()})

conn = psycopg2.connect(conn_string
                        )

conn.autocommit = True

#conn.commit()
conn.close()