问:
Sorting list specific to operations and conditions
Two lists of numbers named l_a and l_b.
In the beginning, l_b will be empty and l_a will contain a certain amount of positive or negative numbers.
The objective is to sort l_a with the minimum of operation and the fastest possible.
only using the following operations and nothing else:

• sa
swap the first two elements of l_a (nothing will happen if there aren’t enough elements).

• sb
swap the first two elements of l_b (nothing will happen if there aren’t enough elements).

• sc
sa and sb at the same time.

• pa
take the first element from l_b and move it to the first position on the l_a list (nothing will happen if
l_b is empty).

• pb
take the first element from l_a and move it to the first position on the l_b list (nothing will happen if
l_a is empty).

• ra
rotate l_a toward the beginning, the first element will become the last.

• rb
rotate l_b toward the beginning, the first element will become the last.

• rr
ra and rb at the same time.

• rra
rotate l_a toward the end, the last element will become the first.

• rrb
rotate l_b toward the end, the last element will become the first.

• rrr
rra and rrb at the same time.

I have implemented all the operation above with a circular doubly linked list in C.
Now I just need to sort l_a but I have tried to modify the iterative quick sort algorithm to use it only with these operations and using the median of the list as a pivot
But I just can't do it , I have no idea on how to do it with a programming language(btw I use C).
I found the radix sort by Bit Shifting method and replacing all the numbers in the initial list with their respective ranks before giving the list to the radix sort so that
it transform the negative numbers into positive numbers.
My friend implemented the radix sort with bit shifting and indexing for optimization and circular doubly linked list that I just described above but the problem is that
on a list with 50 000 randoms numbers it take like 180 seconds and more than 200 000 operation witch is way too much because i need to sort it under 40 seconds and with a lot less operation.
So can you recommend me the best sorting algorithm for this situation or help me implement the iterative median pivot quick sort or optimize the radix sort that my friend have implemented.
Thank you.

The pseudo-code that I tried to create for the iterative median pivot quick sort mentionned above(I don't think it works):

```<code>WHILE stack A is not sorted
  IF stack A contains 3 or less elements
    Sort stack A using swap and rotate commands
    Mark a partition in stack A
  ELSE
    Calculate the median of all elements after the last partition in stack A
    Push the lower values onto stack B
    Maintain the higher values in stack A
  END IF
  IF stack B contains 3 or less elements
    Push all elements from stack B onto stack A
  ELSE
    Calculate the median of all elements up until the last partition in stack B
    Push the higher values onto stack A
    Maintain the lower values in stack B
  END IF
END WHILE
</code>```

the repo with the optimized radix sort(friend's code) :
https://github.com/LouisDupraz/Epitech_Push-Swap

my implementation of the doubly circular linked list and it's operation is the same as the one in the github repo.

Body:
Two lists of numbers named l_a and l_b.
In the beginning, l_b will be empty and l_a will contain a certain amount of positive or negative numbers.
The objective is to sort l_a with the minimum of operation and the fastest possible.
only using the following operations and nothing else:

• sa
swap the first two elements of l_a (nothing will happen if there aren’t enough elements).

• sb
swap the first two elements of l_b (nothing will happen if there aren’t enough elements).

• sc
sa and sb at the same time.

• pa
take the first element from l_b and move it to the first position on the l_a list (nothing will happen if
l_b is empty).

• pb
take the first element from l_a and move it to the first position on the l_b list (nothing will happen if
l_a is empty).

• ra
rotate l_a toward the beginning, the first element will become the last.

• rb
rotate l_b toward the beginning, the first element will become the last.

• rr
ra and rb at the same time.

• rra
rotate l_a toward the end, the last element will become the first.

• rrb
rotate l_b toward the end, the last element will become the first.

• rrr
rra and rrb at the same time.

I have implemented all the operation above with a circular doubly linked list in C.
Now I just need to sort l_a but I have tried to modify the iterative quick sort algorithm to use it only with these operations and using the median of the list as a pivot
But I just can't do it , I have no idea on how to do it with a programming language(btw I use C).
I found the radix sort by Bit Shifting method and replacing all the numbers in the initial list with their respective ranks before giving the list to the radix sort so that
it transform the negative numbers into positive numbers.
My friend implemented the radix sort with bit shifting and indexing for optimization and circular doubly linked list that I just described above but the problem is that
on a list with 50 000 randoms numbers it take like 180 seconds and more than 200 000 operation witch is way too much because i need to sort it under 40 seconds and with a lot less operation.
So can you recommend me the best sorting algorithm for this situation or help me implement the iterative median pivot quick sort or optimize the radix sort that my friend have implemented.
Thank you.

The pseudo-code that I tried to create for the iterative median pivot quick sort mentionned above(I don't think it works):

WHILE stack A is not sorted
  IF stack A contains 3 or less elements
    Sort stack A using swap and rotate commands
    Mark a partition in stack A
  ELSE
    Calculate the median of all elements after the last partition in stack A
    Push the lower values onto stack B
    Maintain the higher values in stack A
  END IF
  IF stack B contains 3 or less elements
    Push all elements from stack B onto stack A
  ELSE
    Calculate the median of all elements up until the last partition in stack B
    Push the higher values onto stack A
    Maintain the lower values in stack B
  END IF
END WHILE

the repo with the optimized radix sort(friend's code) :
https://github.com/LouisDupraz/Epitech_Push-Swap

my implementation of the doubly circular linked list and it's operation is the same as the one in the github repo.


来源: stackexchange

问:
Graphene OS (Android): Where does it store app's cache data?
I'm using an app for audiobooks that allows you to download the book onto your device for offline use. I'm trying to locate that file, but can't figure out how and where is it stored. /Android/data/ directory seems to be empty, and yet the book has been downloaded, and app details page show that it is indeed using some storage. Could it be some kind of DRM BS (even though the book has been purchased) ?

I've tried using file browsers but to no avail.

ContentLicense: CC BY-SA 4.0


问:
Return JSON object with string values in Thymeleaf data attribute
When a Java object has props with string values, the JSON does not render properly.

.html:

```<code><div
    th:if="${address}"
    data-qa="js-address-info"
    class="address"
    th:attr='data-street-data=|{"addressLine":${address?.addressLine1} }|'
    th:attr='data-zip-data=|{"zip":${address?.postalCode} }|'
></div>
</code>```

.js:

```<code>const data = $('.address').data()
console.log(data)
</code>```

Output:

```<code>zipData: Object { zip: 65414}

streetData: "{\"addressLine\": 643 Dogwood Lane }"
</code>```

See that the string value doesn't have quotes around it, and the quotes that are there are escaped.

I tried wrapping the value with quotes like:

```<code>"addressLine":${""" + address?.addressLine1 + """} }
</code>```

but that fails to even build.

Body:
When a Java object has props with string values, the JSON does not render properly.

.html:

.js:

const data = $('.address').data()
console.log(data)

Output:

zipData: Object { zip: 65414}

streetData: "{\"addressLine\": 643 Dogwood Lane }"

See that the string value doesn't have quotes around it, and the quotes that are there are escaped.

I tried wrapping the value with quotes like:

"addressLine":${""" + address?.addressLine1 + """} }

but that fails to even build.


问:
GRAFANA - Cannot read properties of undefined (reading 'toFixed')
We are using grafana to visualize data from some weather stations for a few months.

A member of my team developed a dashboard plugin for such a visualization.

For months we have had the visualization correctly, but today, we received an error in the upper left corner of one of the panels that we developed whose message is:

Cannot read properties of undefined (reading 'toFixed')

image to contextualize

Can anyone help me find a solution for this? please

I already tried deleting and recreating the panel, and verified that the database had the data that grafana queries.

I really appreciate any help!!


问:
HTML 5 <video src="path/to/file.mp4" ...> video file is loading very slowly, sometimes never
```<code> <video id="mash-video-player"
        src="videos/xyz.mp4"
        width="100%"
        height="100%"
        controls
        preload="metadata">
</video>
</code>```

When the selected video is "clicked", the above HTML is dynamically built and injected into a "video player"  and played back. The contents of the  are replaced every time a different video is clicked.

There are many videos in the folder that get listed for playback. The first one clicked (not the first one in the list), usually gets displayed and played almost instantly. From there on, it's a roll of the dice. Click on the next one and it might take 15 seconds. Might not ever be able to be played. Even if the same exact video file is clicked.

The original video files are around 100-300MB. I processed them down to 40-80MB. The video file size doesn't matter. The slow behavior is exactly the same.

One strange side-effect of this is that when it comes to refreshing the page to restart the webapp, the reload can take just as long or sometimes never get reloaded until I reboot the web server.

There are several stacko questions out there that have similar problems. I have reviewed and tried sensible solutions.

Encoding might be a problem, but these are MP4 video files, not very big.

```<code>% file xyz.mp4
xyz.mp4: ISO Media, MP4 v2 [ISO 14496-14]
</code>```

Some of the solutions talk about the metadata being at the end of the file. So there is qtfaststart, now defunct and replaced by qtfaststart2. This python app attempts to move the metadata to an optimal location. Apparently all my videos are "optimal". This is not a solution.

Other solutions talk about caching and such. But even though 300MB might take some time to shove through a python HTTP server, it shouldn't take more than a few seconds. Ultimately that might be the core of the problem: using a python HTTP server.

As a work-around, I am running the video in a profoundly old-fashioned window.open() context, but it works as expected: videos load fast and clean using a "file:///videos/xyz.mp4" URL.

```<code>Hardware/Software:
    Hardware: MacPro 3.7GHz Xeon, 32GB ram
    Browser: Brave Version 1.46.134
    Server: Python 3.9.2, HTTPServer, SimpleHTTPRequestHandler
</code>```

Client and server are both running on the same machine.

Any and all suggestions welcome.

Body:
 <video id="mash-video-player"
        src="videos/xyz.mp4"
        width="100%"
        height="100%"
        controls
        preload="metadata">
</video>

When the selected video is "clicked", the above HTML is dynamically built and injected into a "video player"  and played back. The contents of the  are replaced every time a different video is clicked.

There are many videos in the folder that get listed for playback. The first one clicked (not the first one in the list), usually gets displayed and played almost instantly. From there on, it's a roll of the dice. Click on the next one and it might take 15 seconds. Might not ever be able to be played. Even if the same exact video file is clicked.

The original video files are around 100-300MB. I processed them down to 40-80MB. The video file size doesn't matter. The slow behavior is exactly the same.

One strange side-effect of this is that when it comes to refreshing the page to restart the webapp, the reload can take just as long or sometimes never get reloaded until I reboot the web server.

There are several stacko questions out there that have similar problems. I have reviewed and tried sensible solutions.

Encoding might be a problem, but these are MP4 video files, not very big.

% file xyz.mp4
xyz.mp4: ISO Media, MP4 v2 [ISO 14496-14]

Some of the solutions talk about the metadata being at the end of the file. So there is qtfaststart, now defunct and replaced by qtfaststart2. This python app attempts to move the metadata to an optimal location. Apparently all my videos are "optimal". This is not a solution.

Other solutions talk about caching and such. But even though 300MB might take some time to shove through a python HTTP server, it shouldn't take more than a few seconds. Ultimately that might be the core of the problem: using a python HTTP server.

As a work-around, I am running the video in a profoundly old-fashioned window.open() context, but it works as expected: videos load fast and clean using a "file:///videos/xyz.mp4" URL.

Hardware/Software:
    Hardware: MacPro 3.7GHz Xeon, 32GB ram
    Browser: Brave Version 1.46.134
    Server: Python 3.9.2, HTTPServer, SimpleHTTPRequestHandler

Client and server are both running on the same machine.

Any and all suggestions welcome.


问:
PowerShell - Rename files with number prefix
I have the following code:

```<code>$FilesFolder = "$env:USERPROFILE\Desktop\FilesToRename"
foreach($item in $FilesFolder)
{
Get-ChildItem $FilesFolder | Rename-Item -NewName { "Test - " + $_.Name }
}
</code>```

It's a simple code, basically it adds the prefix Test -   to all files in the folder that is in the $FilesFolder variable.

The issue is that I would like each file in that folder to gain a numerical prefix, that is, if the folder has 3 files it would have a file with a 01 prefix, a file with a 02 prefix and another with a 03 prefix.

Which file will receive the prefix makes no difference in my case, I would just like each file to have a numeric prefix.

How can I do this?

Body:
I have the following code:

$FilesFolder = "$env:USERPROFILE\Desktop\FilesToRename"
foreach($item in $FilesFolder)
{
Get-ChildItem $FilesFolder | Rename-Item -NewName { "Test - " + $_.Name }
}

It's a simple code, basically it adds the prefix Test -   to all files in the folder that is in the $FilesFolder variable.

The issue is that I would like each file in that folder to gain a numerical prefix, that is, if the folder has 3 files it would have a file with a 01 prefix, a file with a 02 prefix and another with a 03 prefix.

Which file will receive the prefix makes no difference in my case, I would just like each file to have a numeric prefix.

How can I do this?


问:
I initialized a global variable and passed it through context API but the change in it's value won't reflect in other components, why?
In component Audioplayer.jsx I have an audio element in which its src value is gotten from a variable {audio} , this variable is assigned data gotten from an API. The variable was initialized and passed down to all components through context API in component App.jsx. Code below :

In App.jsx

```<code> let audio ;

    <SearchContext.Provider value={{audio}}>
            <Router>
                <Navbar />
                <Routes>
                  <Route path="/" element={<Home />} />
                  <Route
                    path="/artisteMusicOverview"
                    element={<ArtisteMusicOverview />}
                  />
                </Routes>
            </Router>
            <AudioPlayer />
            </SearchContext.Provider>
</code>```

In Audioplayer.jsx

```<code>  let { audio } = useContext(SearchContext);

/*assigning it the audio data from the API*/
  audio = chartData?.[songIndex]?.hub?.actions?.[1]?.uri;

 <audio ref={audioPlayer} src={audio} preload="metadata"></audio>
</code>```

What i want to do now is change the audio source from another component.

In component Song.jsx, I tried to change the audio source. Code below:

```<code>  let { audio } = useContext(SearchContext);

/*function to re-assign audio variable*/
  function changeSong() {
    audio = props.song;
  }
  changeSong();

<button onClick={changeSong}>{title}</button>
</code>```

When i log audio to the console i see that it has changed but it does not reflect in Audioplayer.jsx (the audio source). What do i do?

Body:
In component Audioplayer.jsx I have an audio element in which its src value is gotten from a variable {audio} , this variable is assigned data gotten from an API. The variable was initialized and passed down to all components through context API in component App.jsx. Code below :

In App.jsx

 let audio ;

    <SearchContext.Provider value={{audio}}>
            <Router>
                <Navbar />
                <Routes>
                  <Route path="/" element={<Home />} />
                  <Route
                    path="/artisteMusicOverview"
                    element={<ArtisteMusicOverview />}
                  />
                </Routes>
            </Router>
            <AudioPlayer />
            </SearchContext.Provider>

In Audioplayer.jsx

  let { audio } = useContext(SearchContext);

/*assigning it the audio data from the API*/
  audio = chartData?.[songIndex]?.hub?.actions?.[1]?.uri;

 <audio ref={audioPlayer} src={audio} preload="metadata"></audio>

What i want to do now is change the audio source from another component.

In component Song.jsx, I tried to change the audio source. Code below:

  let { audio } = useContext(SearchContext);

/*function to re-assign audio variable*/
  function changeSong() {
    audio = props.song;
  }
  changeSong();

<button onClick={changeSong}>{title}</button>

When i log audio to the console i see that it has changed but it does not reflect in Audioplayer.jsx (the audio source). What do i do?


问:
Getting data from Wordpress with API to React Native app with Expo
I hope this question isn't answered somewhere, but I've Googled for hours and I don't understand anything anymore. So... I'm a beginner with React Native and we are making apps with Expo. For the exam, I need to make an app with products from a database. I had to make this 'webshop database' in Wordpress. You can find the overview of products here: https://evivermeeren.com/2233-2/

To start, I need to make a simple page where I list all the items (the suitcases) in an overview. If I could get that and understand how that works, the rest will be fine. I just can't get my head around the whole getting information from an API thing. I mean, I get the concept, but I don't know how to put the info on my screen.

This is the example my teacher gave me. I can't ask my teacher, since his wife is having a baby so we need to figure this out by ourselves.

```<code>import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import MovieItem from '../components/MovieItem';

const MoviesScreen = ({ navigation }) => {

  const [movies, setMovies] = useState([]);

  const getMoviesByRating = async () => {
    try {
      const response = await fetch("https://moviesminidatabase.p.rapidapi.com/movie/order/byRating/", {
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "moviesminidatabase.p.rapidapi.com",
          "x-rapidapi-key": apiKey
        }
      })
      const json = await response.json();
      console.log(json);
      setMovies(json.results);
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    getMoviesByRating();//laad moviesByRating wanneer het scherm laadt
  }, []);

  return (
    <View style={styles.screen}>
      <FlatList
        data={movies}
        keyExtractor={item => item.imdb_id}//gebruik imdb_id als key voor de flatlist
        renderItem={({ item }) => (

          <Text>{item.rating} - {item.title}</Text>

        )}
      />
    </View >
  );
}

const styles = StyleSheet.create({
  screen: {
    padding: 50,
  }
});
export default MoviesScreen;
</code>```

This gives a list of movie items, by their rating. For my question, I just want to have a list of all my suitcases, I don't care in which order or even if it's just the title.

Because I work with WooCommerce, I need to use a customer key and a customer secret. I have those and I also have my API Key from my Wordpress website via Akismet. So it's important that I put this in the code too.

This is what I have now, but it shows nothing.

```<code>import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import productItem from '../components/products';

const HomeScreen = ({ navigation }) => {

    const [title, setTitle] = useState([]);

    const getTitle = async () => {
      try {
        const response = await fetch("https://evivermeeren.com/wp-json/wp/v2/posts/1629", {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "evivermeeren.com",
            "x-rapidapi-key": apiKey
          }
        })
        const json = await response.json();
        console.log(json);
        setTitle(json.results);
      } catch (error) {
        console.error(error);
      }
    }

    useEffect(() => {
        getTitle();
    }, []);

    return (
      <View style={styles.screen}>
        <FlatList
          data={title}
          keyExtractor={item => item.author}
          renderItem={({ item }) => (

            <Text>{item.title}</Text>

          )}
        />
      </View >
    );
  }

  const styles = StyleSheet.create({
    screen: {
      padding: 50,
    }
  });

  export default HomeScreen;
</code>```

This is the App.js file:

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import HomeScreen from './screens/Home.js';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

I just get a screen with 'home' at the top, the rest is empty.

Can someone PLEASE give me a proper explanation, or give me a link to a website, video... where this is explained in 'dumb-people-language'? I would be forever grateful! This assignment counts for 50% of my class and I really can't figure it out. If I could just have an example of my own website in an app, I will figure out the rest by myself. And yes, I sound desperate, but that is because I have been looking for the answer for 6 hours now and it just doesn't work! :(

Body:
I hope this question isn't answered somewhere, but I've Googled for hours and I don't understand anything anymore. So... I'm a beginner with React Native and we are making apps with Expo. For the exam, I need to make an app with products from a database. I had to make this 'webshop database' in Wordpress. You can find the overview of products here: https://evivermeeren.com/2233-2/

To start, I need to make a simple page where I list all the items (the suitcases) in an overview. If I could get that and understand how that works, the rest will be fine. I just can't get my head around the whole getting information from an API thing. I mean, I get the concept, but I don't know how to put the info on my screen.

This is the example my teacher gave me. I can't ask my teacher, since his wife is having a baby so we need to figure this out by ourselves.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import MovieItem from '../components/MovieItem';

const MoviesScreen = ({ navigation }) => {

  const [movies, setMovies] = useState([]);

  const getMoviesByRating = async () => {
    try {
      const response = await fetch("https://moviesminidatabase.p.rapidapi.com/movie/order/byRating/", {
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "moviesminidatabase.p.rapidapi.com",
          "x-rapidapi-key": apiKey
        }
      })
      const json = await response.json();
      console.log(json);
      setMovies(json.results);
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    getMoviesByRating();//laad moviesByRating wanneer het scherm laadt
  }, []);

  return (
    <View style={styles.screen}>
      <FlatList
        data={movies}
        keyExtractor={item => item.imdb_id}//gebruik imdb_id als key voor de flatlist
        renderItem={({ item }) => (

          <Text>{item.rating} - {item.title}</Text>

        )}
      />
    </View >
  );
}

const styles = StyleSheet.create({
  screen: {
    padding: 50,
  }
});
export default MoviesScreen;

This gives a list of movie items, by their rating. For my question, I just want to have a list of all my suitcases, I don't care in which order or even if it's just the title.

Because I work with WooCommerce, I need to use a customer key and a customer secret. I have those and I also have my API Key from my Wordpress website via Akismet. So it's important that I put this in the code too.

This is what I have now, but it shows nothing.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import productItem from '../components/products';

const HomeScreen = ({ navigation }) => {

    const [title, setTitle] = useState([]);

    const getTitle = async () => {
      try {
        const response = await fetch("https://evivermeeren.com/wp-json/wp/v2/posts/1629", {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "evivermeeren.com",
            "x-rapidapi-key": apiKey
          }
        })
        const json = await response.json();
        console.log(json);
        setTitle(json.results);
      } catch (error) {
        console.error(error);
      }
    }

    useEffect(() => {
        getTitle();
    }, []);

    return (
      <View style={styles.screen}>
        <FlatList
          data={title}
          keyExtractor={item => item.author}
          renderItem={({ item }) => (

            <Text>{item.title}</Text>

          )}
        />
      </View >
    );
  }

  const styles = StyleSheet.create({
    screen: {
      padding: 50,
    }
  });

  export default HomeScreen;

This is the App.js file:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import HomeScreen from './screens/Home.js';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I just get a screen with 'home' at the top, the rest is empty.

Can someone PLEASE give me a proper explanation, or give me a link to a website, video... where this is explained in 'dumb-people-language'? I would be forever grateful! This assignment counts for 50% of my class and I really can't figure it out. If I could just have an example of my own website in an app, I will figure out the rest by myself. And yes, I sound desperate, but that is because I have been looking for the answer for 6 hours now and it just doesn't work! :(


问:
Airflow logs are empty in UI
I have a DAG that ran for 2 hours but I can not see any log in the UI.
In addition, I can't see how many attempts there were (or if there were any at all).

In the airflow webserver pod (where the UI runs), I can see some logs, but they are not relevant and I can not find any that can indicate a problem.

In the airflow scheduler the only line that looks weird is this line:

```<code>[34mkubernetes_executor.py:[0m469} INFO[0m - Found 0 queued task instances[0m
</code>```

Why there are no logs in the UI?

Does it mean that they do not exist or do they exist somewhere (where?!) and the UI does not show them?

Let's say that there are no logs at all, where do i should search the root cause?

Title: Airflow logs are empty in UI

Body:
I have a DAG that ran for 2 hours but I can not see any log in the UI.
In addition, I can't see how many attempts there were (or if there were any at all).

In the airflow webserver pod (where the UI runs), I can see some logs, but they are not relevant and I can not find any that can indicate a problem.

In the airflow scheduler the only line that looks weird is this line:

[34mkubernetes_executor.py:[0m469} INFO[0m - Found 0 queued task instances[0m

Why there are no logs in the UI?

Does it mean that they do not exist or do they exist somewhere (where?!) and the UI does not show them?

Let's say that there are no logs at all, where do i should search the root cause?


问:
Is there a way to log or capture the unparsed request body in Jersey if I'm still using Jackson JSON parsing?
We're using Jersey with a Jackson object mapper to parse JSON input.  So, we're doing this:

```<code>@POST
@Path("/placeOrder")
@Consumes("application/json")
@Produces({MediaType.APPLICATION_JSON})
public Response placeOrder(OrderDetails orderDetails) {
</code>```

where OrderDetails is a parsed representation of the JSON body (parsed by the Jackson parser).  It works well, but we'd like to be able to log the input request body for debugging purposes.  It seems like I can do that with the LoggingFeature property:

```<code>        rc.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
                java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_TEXT, 10000));
</code>```

But that logs way too much information, including headers and the whole response.  I'd like to capture or log just the unparsed JSON request body, but I can't find a way to get at it in Jersey.

Body:
We're using Jersey with a Jackson object mapper to parse JSON input.  So, we're doing this:

@POST
@Path("/placeOrder")
@Consumes("application/json")
@Produces({MediaType.APPLICATION_JSON})
public Response placeOrder(OrderDetails orderDetails) {

where OrderDetails is a parsed representation of the JSON body (parsed by the Jackson parser).  It works well, but we'd like to be able to log the input request body for debugging purposes.  It seems like I can do that with the LoggingFeature property:

        rc.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
                java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_TEXT, 10000));

But that logs way too much information, including headers and the whole response.  I'd like to capture or log just the unparsed JSON request body, but I can't find a way to get at it in Jersey.


问:
Interpreting the test cases for fixed-point arithmetic
I am trying to learn more about fixed-point arithmetic via the test case on Clang here:

https://github.com/llvm/llvm-project/blob/main/clang/test/Frontend/fixed_point_div_const.c

https://github.com/llvm/llvm-project/blob/main/clang/test/Frontend/fixed_point_div.c

and I am stuck trying to figure out how to interpret these lines of checks that seem to be happening, for examples:

```<code>short _Accum sa_const = 1.0hk / 2.0hk;
// CHECK-DAG: @sa_const  = {{.*}}global i16 64, align 2
</code>```
```<code>// CHECK-LABEL: @sdiv_sasasa(
// CHECK-NEXT:  entry:
// CHECK-NEXT:    [[TMP0:%.*]] = load i16, i16* @sa, align 2
// CHECK-NEXT:    [[TMP1:%.*]] = load i16, i16* @sa, align 2
// CHECK-NEXT:    [[TMP2:%.*]] = call i16 @llvm.sdiv.fix.i16(i16 [[TMP0]], i16 [[TMP1]], i32 7)
// CHECK-NEXT:    store i16 [[TMP2]], i16* @sa, align 2
// CHECK-NEXT:    ret void
//
void sdiv_sasasa(void) {
  sa = sa / sa;
}
</code>```

I tried to search around and I arrived at this https://llvm.org/docs/CommandGuide/FileCheck.html, but it wasn't very clear to me how to interpret these strings in the comment. If I have to take a guess at what was written in the first code block provided here, i.e.:

```<code>// CHECK-DAG: @sa_const  = {{.*}}global i16 64, align 2
</code>```

This is checking if the bit patterns of @sa_const match whatever is describe with {{.*}}global i16 64, align 2. If that is the case, how should I interpret the string {{.*}}global i16 64, align 2? My guess is that this is a 16-bit integer that corresponds to value of 64? But then, what does align 2 mean?

Any suggestions/recommendations on how I could search for relevant materials that would help?

Body:
I am trying to learn more about fixed-point arithmetic via the test case on Clang here:

https://github.com/llvm/llvm-project/blob/main/clang/test/Frontend/fixed_point_div_const.c

https://github.com/llvm/llvm-project/blob/main/clang/test/Frontend/fixed_point_div.c

and I am stuck trying to figure out how to interpret these lines of checks that seem to be happening, for examples:

short _Accum sa_const = 1.0hk / 2.0hk;
// CHECK-DAG: @sa_const  = {{.*}}global i16 64, align 2

// CHECK-LABEL: @sdiv_sasasa(
// CHECK-NEXT:  entry:
// CHECK-NEXT:    [[TMP0:%.*]] = load i16, i16* @sa, align 2
// CHECK-NEXT:    [[TMP1:%.*]] = load i16, i16* @sa, align 2
// CHECK-NEXT:    [[TMP2:%.*]] = call i16 @llvm.sdiv.fix.i16(i16 [[TMP0]], i16 [[TMP1]], i32 7)
// CHECK-NEXT:    store i16 [[TMP2]], i16* @sa, align 2
// CHECK-NEXT:    ret void
//
void sdiv_sasasa(void) {
  sa = sa / sa;
}

I tried to search around and I arrived at this https://llvm.org/docs/CommandGuide/FileCheck.html, but it wasn't very clear to me how to interpret these strings in the comment. If I have to take a guess at what was written in the first code block provided here, i.e.:

// CHECK-DAG: @sa_const  = {{.*}}global i16 64, align 2

This is checking if the bit patterns of @sa_const match whatever is describe with {{.*}}global i16 64, align 2. If that is the case, how should I interpret the string {{.*}}global i16 64, align 2? My guess is that this is a 16-bit integer that corresponds to value of 64? But then, what does align 2 mean?

Any suggestions/recommendations on how I could search for relevant materials that would help?


问:
Upload a .xlsx file to Shiny and load in all the tabs as a list
I want to upload an .xlsx file to Shiny and load all the tabs in as a list.
In the example, I am expecting the object input_file to be a list of dataframes which are the tabs from the .xlsx file.
The example is selecting the first dataframe and then putting it in a flextable.
The code doesnt work, I get the error message, object of type 'closure' is not subsettable
Can anyone suggest anything to fix this?

```<code>library(shiny)
library(readxl)
library(flextable)
library(tidyverse)

ui<-shinyUI(fluidPage(
  titlePanel("Use readxl"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose xlsx file',
                accept = c(".xlsx")
      )
    ),
    mainPanel(

      htmlOutput ("ftable2")

    )
  )
)

)

server <- function(input, output){
  input_file<-reactive({
    if (is.null(input$file1)) {
      return("")
    }

    sapply(readxl::excel_sheets(input$file1$datapath), simplify = F, USE.NAMES = T,
           function(X) readxl::read_excel(input$file1$datapath, sheet = X))

  })

  output$ftable2<- renderUI( {
    req(input_file())

    input_file[[1]]%>%
      head(10)%>%
      flextable()%>%
      htmltools_value()
  })}
shinyApp(ui, server)
</code>```

Body:
I want to upload an .xlsx file to Shiny and load all the tabs in as a list.
In the example, I am expecting the object input_file to be a list of dataframes which are the tabs from the .xlsx file.
The example is selecting the first dataframe and then putting it in a flextable.
The code doesnt work, I get the error message, object of type 'closure' is not subsettable
Can anyone suggest anything to fix this?

library(shiny)
library(readxl)
library(flextable)
library(tidyverse)

ui<-shinyUI(fluidPage(
  titlePanel("Use readxl"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose xlsx file',
                accept = c(".xlsx")
      )
    ),
    mainPanel(

      htmlOutput ("ftable2")

    )
  )
)

)

server <- function(input, output){
  input_file<-reactive({
    if (is.null(input$file1)) {
      return("")
    }

    sapply(readxl::excel_sheets(input$file1$datapath), simplify = F, USE.NAMES = T,
           function(X) readxl::read_excel(input$file1$datapath, sheet = X))

  })

  output$ftable2<- renderUI( {
    req(input_file())

    input_file[[1]]%>%
      head(10)%>%
      flextable()%>%
      htmltools_value()
  })}
shinyApp(ui, server)


问:
Why won't my fieldsets expand vertically instead of overflowing their content?
I want to have three fieldsets that each contain several labels and an equal number of input or textarea elements. I want the fieldsets to expand to the necessary height to contain all of their contents. This works fine for a smaller and larger screen, but just after the breakpoint, these elements contained within the fieldsets overflow out into each other, as if the fieldsets are unable to expand.

Here is an image of the problem:

I have tried to change the height rules of the outer div (#submit), the form, and the fieldsets. I have tried setting the fieldset to overflow: auto, which technically works since the content can be seen with scroll bars, but that is not what I really want. I just want all of the content to be visible and to expand the fieldsets, form, and div container to accommodate all of that. Also bonus question: I want the input elements (not the textarea) to only be the height of one line while keeping the current layout; is this possible?

Here is the relevant html:

```<code><div id="submit">
            <h2>
              Submit an analysis
            </h2>
            <form action="" method="post">
              <fieldset id="album_information">
                <legend>
                  Album Information
                </legend>
                <label for="album_title">
                  Album title:
                </label>
                <input type="text"
                       id="album_title" name="album_title"
                       required="required">
                <label for="artist_title">
                  Artist title:
                </label>
                <input type="text"
                       id="artist_title" name="artist_title"
                       required="required"
                       list="artists">
                <datalist id="artists">
                  <option>death's dynamic shroud</option>
                  <option>Hallmark '87</option>
                  <option>telepath</option>
                  <option>猫 シ Corp.</option>
                </datalist>
                <label for="release_date">
                  Release date:
                </label>
                <input type="date"
                       id="release_date" name="release_date"
                       required="required">
                <label for="number_songs">
                  Number of songs on the album (this will determine the number of song entries below):
                </label>
                <input type="number"
                       id="number_songs" name="number_songs"
                       required="required"
                       min="1"
                       height="1">
                <label for="art_file">
                  Submit a jpeg or png of the album cover:
                </label>
                <input type="file"
                       id="art_file" name="art_file"
                       accept="image/jpeg, image/png">
                <label for="introduction">
                  Write a general introduction to the album - this text will be partly displayed on the link to this page:
                </label>
                <textarea id="introduction" name="introduction"
                          required="required"
                          rows="10"></textarea>
                <label for="title_discussion">
                  Discuss the album title - list some possible interpretations, considering the actual definitions of the words, and explain what it could imply for the album:
                </label>
                <textarea id="title_discussion" name="title_discussion"
                          required="required"
                          rows="10"></textarea>
                <label for="art_discussion">
                  Describe the album cover in detail, and discuss what it conveys to the listener upon first glance:
                </label>
                <textarea id="art_discussion" name="art_discussion"
                          required="required"
                          rows="10"></textarea>
              </fieldset>
              <fieldset id="song[1]_information">
                <legend>
                  Song 1 Information
                </legend>
                <label for="song[1]_title">
                  Song title:
                </label>
                <input type="text"
                       id="song[1]_title" name="song[1]_title"
                       required="required">
                <label for="song[1]_duration">
                  Duration:
                </label>
                <input type="text"
                       id="song[1]_duration" name="song[1]_duration"
                       required="required"
                       placeholder="e.g. 00:00">
                <label for="song[1]_link">
                  Provide a url for the song from Spotify or YouTube, if possible:
                </label>
                <input type="url"
                       id="song[1]_link" name="song[1]_link">
                <label for="song[1]_instruments/samples">
                  List any instruments and/or samples used in the song:
                </label>
                <input type="text"
                       id="song[1]_instruments/samples" name="song[1]_instruments/samples"
                       required="required">
                <label for="song[1]_samplelink">
                  Provide a url for the sample source, if possible:
                </label>
                <input type="url"
                       id="song[1]_samplelink" name="song[1]_samplelink">
                <label for="song[1]_sound">
                  Describe the sound of the song and how the samples and instruments are used or distorted to acheive this sound:
                </label>
                <textarea id="song[1]_sound" name="song[1]_sound"
                          required="required"
                          rows="10"></textarea>
                <label for="song[1]_significance">
                  Describe why this song is important to the album as a whole; if the album tells a story, then include an interpretation of what is happening in this song:
                </label>
                <textarea id="song[1]_significance" name="song[1]_significance"
                          required="required"
                          rows="10"></textarea>
                <label for="song[1]_inspiration">
                  Include anything that the composer has said about this specific song, or any other quotes that may be relevant to it:
                </label>
                <textarea id="song[1]_inspiration" name="song[1]_inspiration"
                          required="required"
                          rows="10"></textarea>
              </fieldset>
              <fieldset id="concluding_thoughts">
                <legend>
                  Concluding Thoughts and Additional Content
                </legend>
                <label for="conclusion">
                  Write a concluding section for the album analysis
                </label>
                <textarea id="conclusion" name="conclusion"
                          required="required"
                          rows="10"></textarea>
                <label for="additional_content">
                  Provide a url for any relevant content, including interviews, music videos, etc.
                </label>
                <input type="url"
                       id="additional_content" name="additional_content"
                       multiple>
              </fieldset>
            </form>
          </div>
</code>```

And here is the relevant CSS:

```<code>fieldset
{
  max-width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
legend
{
  color:hsl(104, 70%, 41%);
}
label
{
  font-size: 0.8rem;
}
textarea
{
  resize: none;
}
input, textarea
{
  margin: 2%;
  margin-left: 0;
  margin-right: 0;
}
#submit
{
  color: hsl(65, 70%, 50%);
  background-color: hsl(220, 70%, 15%);
}
@media (min-width: 1000px)
{
  fieldset
  {
    display: grid;
    grid-template-columns: 1fr 3fr;
    gap: 3%;
  }
  input, textarea
  {
    margin: 0;
  }
}
</code>```

Please note that this is for a school project, the project is only teaching front end, and this is the first website I have created.

Body:
I want to have three fieldsets that each contain several labels and an equal number of input or textarea elements. I want the fieldsets to expand to the necessary height to contain all of their contents. This works fine for a smaller and larger screen, but just after the breakpoint, these elements contained within the fieldsets overflow out into each other, as if the fieldsets are unable to expand.

Here is an image of the problem:

I have tried to change the height rules of the outer div (#submit), the form, and the fieldsets. I have tried setting the fieldset to overflow: auto, which technically works since the content can be seen with scroll bars, but that is not what I really want. I just want all of the content to be visible and to expand the fieldsets, form, and div container to accommodate all of that. Also bonus question: I want the input elements (not the textarea) to only be the height of one line while keeping the current layout; is this possible?

Here is the relevant html:

              Submit an analysis

            <form action="" method="post">
              <fieldset id="album_information">
                <legend>
                  Album Information
                </legend>

                  Album title:

                <input type="text"
                       id="album_title" name="album_title"
                       required="required">

                  Artist title:

                <input type="text"
                       id="artist_title" name="artist_title"
                       required="required"
                       list="artists">
                <datalist id="artists">
                  <option>death's dynamic shroud</option>
                  <option>Hallmark '87</option>
                  <option>telepath</option>
                  <option>猫 シ Corp.</option>
                </datalist>

                  Release date:

                <input type="date"
                       id="release_date" name="release_date"
                       required="required">

                  Number of songs on the album (this will determine the number of song entries below):

                <input type="number"
                       id="number_songs" name="number_songs"
                       required="required"
                       min="1"
                       height="1">

                  Submit a jpeg or png of the album cover:

                <input type="file"
                       id="art_file" name="art_file"
                       accept="image/jpeg, image/png">

                  Write a general introduction to the album - this text will be partly displayed on the link to this page:

                <textarea id="introduction" name="introduction"
                          required="required"
                          rows="10"></textarea>

                  Discuss the album title - list some possible interpretations, considering the actual definitions of the words, and explain what it could imply for the album:

                <textarea id="title_discussion" name="title_discussion"
                          required="required"
                          rows="10"></textarea>

                  Describe the album cover in detail, and discuss what it conveys to the listener upon first glance:

                <textarea id="art_discussion" name="art_discussion"
                          required="required"
                          rows="10"></textarea>
              </fieldset>
              <fieldset id="song[1]_information">
                <legend>
                  Song 1 Information
                </legend>

                  Song title:

                <input type="text"
                       id="song[1]_title" name="song[1]_title"
                       required="required">

                  Duration:

                <input type="text"
                       id="song[1]_duration" name="song[1]_duration"
                       required="required"
                       placeholder="e.g. 00:00">

                  Provide a url for the song from Spotify or YouTube, if possible:

                <input type="url"
                       id="song[1]_link" name="song[1]_link">

                  List any instruments and/or samples used in the song:

                <input type="text"
                       id="song[1]_instruments/samples" name="song[1]_instruments/samples"
                       required="required">

                  Provide a url for the sample source, if possible:

                <input type="url"
                       id="song[1]_samplelink" name="song[1]_samplelink">

                  Describe the sound of the song and how the samples and instruments are used or distorted to acheive this sound:

                <textarea id="song[1]_sound" name="song[1]_sound"
                          required="required"
                          rows="10"></textarea>

                  Describe why this song is important to the album as a whole; if the album tells a story, then include an interpretation of what is happening in this song:

                <textarea id="song[1]_significance" name="song[1]_significance"
                          required="required"
                          rows="10"></textarea>

                  Include anything that the composer has said about this specific song, or any other quotes that may be relevant to it:

                <textarea id="song[1]_inspiration" name="song[1]_inspiration"
                          required="required"
                          rows="10"></textarea>
              </fieldset>
              <fieldset id="concluding_thoughts">
                <legend>
                  Concluding Thoughts and Additional Content
                </legend>

                  Write a concluding section for the album analysis

                <textarea id="conclusion" name="conclusion"
                          required="required"
                          rows="10"></textarea>

                  Provide a url for any relevant content, including interviews, music videos, etc.

                <input type="url"
                       id="additional_content" name="additional_content"
                       multiple>
              </fieldset>
            </form>

And here is the relevant CSS:

fieldset
{
  max-width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
legend
{
  color:hsl(104, 70%, 41%);
}
label
{
  font-size: 0.8rem;
}
textarea
{
  resize: none;
}
input, textarea
{
  margin: 2%;
  margin-left: 0;
  margin-right: 0;
}
#submit
{
  color: hsl(65, 70%, 50%);
  background-color: hsl(220, 70%, 15%);
}
@media (min-width: 1000px)
{
  fieldset
  {
    display: grid;
    grid-template-columns: 1fr 3fr;
    gap: 3%;
  }
  input, textarea
  {
    margin: 0;
  }
}

Please note that this is for a school project, the project is only teaching front end, and this is the first website I have created.


问:
How to add owners to dynamic Microsoft 365 group with Powershell?
I can't seem to manage to add 'owners' to a dynamic 365 group with Powershell.

In the GUI it is possible but if fails with Powershell.

https://learn.microsoft.com/en-us/powershell/module/exchange/add-unifiedgrouplinks?view=exchange-ps

First i need to add the users as a member to the group, offcours not working because it is a dynamic group.

```<code>PS C:\WINDOWS\system32> Add-UnifiedGroupLinks -Identity "Klas_1A1F_22-23" -LinkType "Members" -Links "a****es.desa*****r@***.be"
Membership for this group is managed automatically by using a rule. Edit the membership rule to change the group membership.
    + CategoryInfo          : NotSpecified: (Klas_1A1F_22-23...5a-2170b2539977:ADObjectId) [Add-UnifiedGroupLinks], DynamicGroupMem...DeniedException
    + FullyQualifiedErrorId : [Server=PA4PR03MB6992,RequestId=cec5e218-c170-4d2d-8108-d529910bc7b5,TimeStamp=13/12/2022 20:28:38] [FailureCategory=Cmdlet-DynamicGroupMembershipChangeDeniedExc
   eption] D3C4100,Microsoft.Exchange.Management.RecipientTasks.AddUnifiedGroupLinks
    + PSComputerName        : outlook.office365.com
</code>```

Instant as a owner also fails, like the manual also reffers:

```<code>PS C:\WINDOWS\system32> Add-UnifiedGroupLinks -Identity "Klas_1A1F_22-23" -LinkType "Owners" -Links "a****es.desa*****r@***.be"
Only Members can be Owners of a group. Please add 'annelies.desaeger' first as members before adding them as owners.
    + CategoryInfo          : NotSpecified: (Klas_1A1F_22-23...5a-2170b2539977:ADObjectId) [Add-UnifiedGroupLinks], ADNotAMemberException
    + FullyQualifiedErrorId : [Server=PA4PR03MB6992,RequestId=1ee4f0e9-aa80-4903-9702-c9bca9ef625d,TimeStamp=13/12/2022 20:28:59] [FailureCategory=Cmdlet-ADNotAMemberException] 9B67D48,Micros
   oft.Exchange.Management.RecipientTasks.AddUnifiedGroupLinks
    + PSComputerName        : outlook.office365.com
</code>```

Anyone can help?

Thx!

Body:
I can't seem to manage to add 'owners' to a dynamic 365 group with Powershell.

In the GUI it is possible but if fails with Powershell.

https://learn.microsoft.com/en-us/powershell/module/exchange/add-unifiedgrouplinks?view=exchange-ps

First i need to add the users as a member to the group, offcours not working because it is a dynamic group.

PS C:\WINDOWS\system32> Add-UnifiedGroupLinks -Identity "Klas_1A1F_22-23" -LinkType "Members" -Links "a****es.desa*****r@***.be"
Membership for this group is managed automatically by using a rule. Edit the membership rule to change the group membership.
    + CategoryInfo          : NotSpecified: (Klas_1A1F_22-23...5a-2170b2539977:ADObjectId) [Add-UnifiedGroupLinks], DynamicGroupMem...DeniedException
    + FullyQualifiedErrorId : [Server=PA4PR03MB6992,RequestId=cec5e218-c170-4d2d-8108-d529910bc7b5,TimeStamp=13/12/2022 20:28:38] [FailureCategory=Cmdlet-DynamicGroupMembershipChangeDeniedExc
   eption] D3C4100,Microsoft.Exchange.Management.RecipientTasks.AddUnifiedGroupLinks
    + PSComputerName        : outlook.office365.com

Instant as a owner also fails, like the manual also reffers:

PS C:\WINDOWS\system32> Add-UnifiedGroupLinks -Identity "Klas_1A1F_22-23" -LinkType "Owners" -Links "a****es.desa*****r@***.be"
Only Members can be Owners of a group. Please add 'annelies.desaeger' first as members before adding them as owners.
    + CategoryInfo          : NotSpecified: (Klas_1A1F_22-23...5a-2170b2539977:ADObjectId) [Add-UnifiedGroupLinks], ADNotAMemberException
    + FullyQualifiedErrorId : [Server=PA4PR03MB6992,RequestId=1ee4f0e9-aa80-4903-9702-c9bca9ef625d,TimeStamp=13/12/2022 20:28:59] [FailureCategory=Cmdlet-ADNotAMemberException] 9B67D48,Micros
   oft.Exchange.Management.RecipientTasks.AddUnifiedGroupLinks
    + PSComputerName        : outlook.office365.com

Anyone can help?

Thx!


问:
Application crash without error message - Help appreciated
I am a little bit lost. My .Net application (Winforms) shows many user controls on a flowlayout panel. Sometimes when moving the screen around (controls have to be painted) or reloading the screen, the application exit without any messages. All I see are two entries in the eventviewer:

```<code>Anwendung: MainForm.exe
Frameworkversion: v4.0.30319
Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet.
Ausnahmeinformationen: System.ComponentModel.Win32Exception
   bei System.Windows.Forms.NativeWindow.CreateHandle(System.Windows.Forms.CreateParams)
   bei System.Windows.Forms.Control.CreateHandle()
   bei System.Windows.Forms.Control.get_Handle()
   bei System.Windows.Forms.Control.CreateGraphicsInternal()
   bei System.Windows.Forms.ThreadExceptionDialog..ctor(System.Exception)
   bei System.Windows.Forms.Application+ThreadContext.OnThreadException(System.Exception)
   bei System.Windows.Forms.Control.WndProcException(System.Exception)
   bei System.Windows.Forms.Control+ControlNativeWindow.OnThreadException(System.Exception)
   bei System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
   bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
   bei System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
   bei System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
   bei System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
   bei System.Windows.Forms.Application.Run(System.Windows.Forms.Form)
   bei MainForm.Program.Main()
</code>```
```<code>Name der fehlerhaften Anwendung: MainForm.exe, Version: 1.22.8345.35922, Zeitstempel: 0x63680394
Name des fehlerhaften Moduls: KERNELBASE.dll, Version: 10.0.22000.1219, Zeitstempel: 0x554c45b0
Ausnahmecode: 0xe0434352
Fehleroffset: 0x00140762
ID des fehlerhaften Prozesses: 0x2a5c
Startzeit der fehlerhaften Anwendung: 0x01d8fa95dda003f6
Pfad der fehlerhaften Anwendung: C:\Users\MG\source\repos\SM1.22.8345.35933\MainForm\bin\Debug\MainForm.exe
Pfad des fehlerhaften Moduls: C:\Windows\System32\KERNELBASE.dll
Berichtskennung: a8a7b9a0-a5d1-4eb8-8340-39c6c236ad1a
Vollständiger Name des fehlerhaften Pakets:
Anwendungs-ID, die relativ zum fehlerhaften Paket ist:
</code>```

I am not a debugging pro and I hope that I might get a good tipp how the avoid these crashes. Any ideas are highly appreciated!

SUPPLEMENT:
Should I do something like this in the usercontrol?

```<code>
private void button1_Click(object sender, EventArgs e)
{
    var threadParameters = new System.Threading.ThreadStart(delegate { WriteTextSafe("This text was set safely."); });
    var thread2 = new System.Threading.Thread(threadParameters);
    thread2.Start();
}

public void WriteTextSafe(string text)
{
    if (textBox1.InvokeRequired)
    {
        // Call this same method but append THREAD2 to the text
        Action safeWrite = delegate { WriteTextSafe($"{text} (THREAD2)"); };
        textBox1.Invoke(safeWrite);
    }
    else
        textBox1.Text = text;
}
</code>```

Body:
I am a little bit lost. My .Net application (Winforms) shows many user controls on a flowlayout panel. Sometimes when moving the screen around (controls have to be painted) or reloading the screen, the application exit without any messages. All I see are two entries in the eventviewer:

Anwendung: MainForm.exe
Frameworkversion: v4.0.30319
Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet.
Ausnahmeinformationen: System.ComponentModel.Win32Exception
   bei System.Windows.Forms.NativeWindow.CreateHandle(System.Windows.Forms.CreateParams)
   bei System.Windows.Forms.Control.CreateHandle()
   bei System.Windows.Forms.Control.get_Handle()
   bei System.Windows.Forms.Control.CreateGraphicsInternal()
   bei System.Windows.Forms.ThreadExceptionDialog..ctor(System.Exception)
   bei System.Windows.Forms.Application+ThreadContext.OnThreadException(System.Exception)
   bei System.Windows.Forms.Control.WndProcException(System.Exception)
   bei System.Windows.Forms.Control+ControlNativeWindow.OnThreadException(System.Exception)
   bei System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
   bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
   bei System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
   bei System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
   bei System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
   bei System.Windows.Forms.Application.Run(System.Windows.Forms.Form)
   bei MainForm.Program.Main()

Name der fehlerhaften Anwendung: MainForm.exe, Version: 1.22.8345.35922, Zeitstempel: 0x63680394
Name des fehlerhaften Moduls: KERNELBASE.dll, Version: 10.0.22000.1219, Zeitstempel: 0x554c45b0
Ausnahmecode: 0xe0434352
Fehleroffset: 0x00140762
ID des fehlerhaften Prozesses: 0x2a5c
Startzeit der fehlerhaften Anwendung: 0x01d8fa95dda003f6
Pfad der fehlerhaften Anwendung: C:\Users\MG\source\repos\SM1.22.8345.35933\MainForm\bin\Debug\MainForm.exe
Pfad des fehlerhaften Moduls: C:\Windows\System32\KERNELBASE.dll
Berichtskennung: a8a7b9a0-a5d1-4eb8-8340-39c6c236ad1a
Vollständiger Name des fehlerhaften Pakets:
Anwendungs-ID, die relativ zum fehlerhaften Paket ist:

I am not a debugging pro and I hope that I might get a good tipp how the avoid these crashes. Any ideas are highly appreciated!

SUPPLEMENT:
Should I do something like this in the usercontrol?

private void button1_Click(object sender, EventArgs e)
{
    var threadParameters = new System.Threading.ThreadStart(delegate { WriteTextSafe("This text was set safely."); });
    var thread2 = new System.Threading.Thread(threadParameters);
    thread2.Start();
}

public void WriteTextSafe(string text)
{
    if (textBox1.InvokeRequired)
    {
        // Call this same method but append THREAD2 to the text
        Action safeWrite = delegate { WriteTextSafe($"{text} (THREAD2)"); };
        textBox1.Invoke(safeWrite);
    }
    else
        textBox1.Text = text;
}


问:
react-scripts instaalation hangs in ideal tree
Iam creating a node js application with react frontend. When run npm run build for react frontend, it showed react-scripts not found. So tried to install it using npm install -g react-scripts. It goes on and finally hangs at

(#########⠂⠂⠂⠂⠂⠂⠂⠂⠂) ⠴ idealTree: timing idealTree Completed in 60877ms

please help


问:
Calling a function inside a "if" statement returns old value - explanations

Goal

I need to execute a function adder if a condition is met, and then use the return value of this function, still only if this condition is met.

What I tried

```<code>@echo off

:main
set _sum=5
if "T" == "T" (
    call :adder 25 10
    echo "25 + 10 = %_sum%"
)
goto eof

:adder
setlocal
set number1=%1
set number2=%2
endlocal & set /a _sum="%number1% + %number2%"
goto eof

:eof
</code>```

Issue

This prints:

```<code>"25 + 10 = 5"
</code>```

Additionally, when adding a echo "25 + 10 = %_sum%" after the if block, the output then becomes:

```<code>"25 + 10 = 5"
"25 + 10 = 35"
</code>```

This seems to indicate that the entire if block is evaluated when encountered, thus replacing the _sum variable by the value it has before the execution of the if block.

This is further verified by removing the @echo off, the relevant output here is:

```<code>if "T" == "T" (
call :adder 25 10
 echo "25 + 10 = 5"
)
</code>```

Full output:

```<code>> set _sum=5
> if "T" == "T" (
call :adder 25 10
 echo "25 + 10 = 5"
)
> setlocal
> set number1=25
> set number2=10
> endlocal   & set /a _sum="25 + 10"
> goto eof
"25 + 10 = 5"
> echo "25 + 10 = 35"
"25 + 10 = 35"
> goto eof
</code>```

Solution

The only solution I have for now is postponing the use of the return values to after the if block. In practice, it may force me to use a second if-else statement with the exact same conditions.

```<code>set _sum=5
if "T" == "T" (
    call :adder 25 10
)
if "T" == "T" (
    echo "25 + 10 = %_sum%"
)
</code>```

Is there another solution to this problem?

EDIT

There is indeed another solution to this problem, called "Delayed Expansion". More about this in the question this one is a duplicate of.

Body:
Goal

I need to execute a function adder if a condition is met, and then use the return value of this function, still only if this condition is met.

What I tried

@echo off

:main
set _sum=5
if "T" == "T" (
    call :adder 25 10
    echo "25 + 10 = %_sum%"
)
goto eof

:adder
setlocal
set number1=%1
set number2=%2
endlocal & set /a _sum="%number1% + %number2%"
goto eof

:eof

Issue

This prints:

"25 + 10 = 5"

Additionally, when adding a echo "25 + 10 = %_sum%" after the if block, the output then becomes:

"25 + 10 = 5"
"25 + 10 = 35"

This seems to indicate that the entire if block is evaluated when encountered, thus replacing the _sum variable by the value it has before the execution of the if block.

This is further verified by removing the @echo off, the relevant output here is:

if "T" == "T" (
call :adder 25 10
 echo "25 + 10 = 5"
)

Full output:

> set _sum=5
> if "T" == "T" (
call :adder 25 10
 echo "25 + 10 = 5"
)
> setlocal
> set number1=25
> set number2=10
> endlocal   & set /a _sum="25 + 10"
> goto eof
"25 + 10 = 5"
> echo "25 + 10 = 35"
"25 + 10 = 35"
> goto eof

Solution

The only solution I have for now is postponing the use of the return values to after the if block. In practice, it may force me to use a second if-else statement with the exact same conditions.

set _sum=5
if "T" == "T" (
    call :adder 25 10
)
if "T" == "T" (
    echo "25 + 10 = %_sum%"
)

Is there another solution to this problem?

EDIT

There is indeed another solution to this problem, called "Delayed Expansion". More about this in the question this one is a duplicate of.


问:
Fastapi token returns None in jwt authentication?
In fastapi jwt implementAation token returns null.
dependency functions

```<code>reuseable_oauth = OAuth2PasswordBearer(
    tokenUrl="/login",
    scheme_name="JWT",
    auto_error = False
)

async def get_current_user(token: str = Depends(reuseable_oauth)):
    try:
        print(token)
        payload = jwt.decode(
            token, JWT_SECRET_KEY, algorithms=[ALGORITHM]
        )
        token_data = payload['sub']

        if datetime.fromtimestamp(token_data.exp) < datetime.now():
            raise HTTPException(
                status_code = status.HTTP_401_UNAUTHORIZED,
                detail="Token expired",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except(jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user: Union[dict[str, Any], None] = db.get(token_data.sub, None)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Could not find user",
        )
     return user

class TokenSchema(BaseModel):
   accesstoken : str = Field(...)

</code>```

routing functions

```<code>@app.post('/login', summary="Create access and refresh tokens for user", response_model=TokenSchema)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = db.get(form_data.username, None)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect email or password"
        )

    hashed_pass = user['password']
    if not verify_password(form_data.password, hashed_pass):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect email or password"
        )

    return {
        "accesstoken": create_access_token(user['email'])
    }

from app.deps import get_current_user

@app.get('/me', summary='Get details of currently logged in user', response_model=UserOut)
async def get_me(user: User = Depends(get_current_user)):
    return user

</code>```

I first make a post to /login and then get request to /me. However, token in get_current_user funtion is null in the first place, which in turn gives further errors, which I also check in print(token) line.
What could be the reason and how to solve them?
I refer to jwt-authentication

Body:
In fastapi jwt implementAation token returns null.
dependency functions

reuseable_oauth = OAuth2PasswordBearer(
    tokenUrl="/login",
    scheme_name="JWT",
    auto_error = False
)

async def get_current_user(token: str = Depends(reuseable_oauth)):
    try:
        print(token)
        payload = jwt.decode(
            token, JWT_SECRET_KEY, algorithms=[ALGORITHM]
        )
        token_data = payload['sub']

        if datetime.fromtimestamp(token_data.exp) < datetime.now():
            raise HTTPException(
                status_code = status.HTTP_401_UNAUTHORIZED,
                detail="Token expired",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except(jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user: Union[dict[str, Any], None] = db.get(token_data.sub, None)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Could not find user",
        )
     return user

class TokenSchema(BaseModel):
   accesstoken : str = Field(...)

routing functions

@app.post('/login', summary="Create access and refresh tokens for user", response_model=TokenSchema)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = db.get(form_data.username, None)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect email or password"
        )

    hashed_pass = user['password']
    if not verify_password(form_data.password, hashed_pass):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect email or password"
        )

    return {
        "accesstoken": create_access_token(user['email'])
    }

from app.deps import get_current_user

@app.get('/me', summary='Get details of currently logged in user', response_model=UserOut)
async def get_me(user: User = Depends(get_current_user)):
    return user

I first make a post to /login and then get request to /me. However, token in get_current_user funtion is null in the first place, which in turn gives further errors, which I also check in print(token) line.
What could be the reason and how to solve them?
I refer to jwt-authentication


问:
Using Microsoft Authentication Library with External Providers (ASP.NET 6)
I have an Azure App Service developed in .NET 6. I wish to authenticate users against several providers (Azure AD, Google, etc). Upon following the (I think) accurate tutorial I was able to authenticate against Microsoft accounts using MSAL with the following code:

```<code>var builder = WebApplication.CreateBuilder(args);

// Managed identity credential
var credential = new DefaultAzureCredential();
// Add key vault for initial access
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration.GetValue<string>("Azure:VaultUri")), credential);
// Integrate key vault into Azure app config
builder.Configuration.AddAzureAppConfiguration(options =>
{
    // Load config string from vault
    var configConnection = builder.Configuration.GetValue<string>("config");
    // Connect to config
    options.Connect(configConnection);
    options.ConfigureKeyVault(kv => kv.SetCredential(credential));
});

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// CUSTOM DI
builder.Services.AddSingleton<IDatabaseRepo, CosmosDatabaseRepo>();

// Build
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
</code>```

The protected controller method is simply decorated with [Authorize].

That works great for Microsoft accounts. However, every attempt to integrate Google into this flow fails. I've done the following:

Follow various example utilizing the Microsoft.AspNetCore.Authentication.Google package. I added AddGoogle method with the client id and secret set. This results in an invalid token error.

The OAuth process works (using Postman) and provides both an access token and id token. But:

The access token fails with invalid_token

The open id token fails saying invalid_token and invalid signature.

If I remove AddMicrosoftIdentityWebApi and only use the AddGoogle method then I always receive a 500 Internal Server Error indicating an auth scheme was not defined. Doesn't matter where I define it- whether in AddAuthorization or decorated on the controller's Authorize attribute.

Attempted using manual JWT validation. This seems problematic because:

It also results in the 500 error whatever I try.

It's not supposed to be required if I understand the packages correctly.

ALSO:

The Google client id has been added to my App Service as an identity provider with the associated App (client) ID.

There's 38974 tutorials out there and none seem to point in the right direction/don't address this issue. Any and all guidance is appreciated.

Body:
I have an Azure App Service developed in .NET 6. I wish to authenticate users against several providers (Azure AD, Google, etc). Upon following the (I think) accurate tutorial I was able to authenticate against Microsoft accounts using MSAL with the following code:

var builder = WebApplication.CreateBuilder(args);

// Managed identity credential
var credential = new DefaultAzureCredential();
// Add key vault for initial access
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration.GetValue<string>("Azure:VaultUri")), credential);
// Integrate key vault into Azure app config
builder.Configuration.AddAzureAppConfiguration(options =>
{
    // Load config string from vault
    var configConnection = builder.Configuration.GetValue<string>("config");
    // Connect to config
    options.Connect(configConnection);
    options.ConfigureKeyVault(kv => kv.SetCredential(credential));
});

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// CUSTOM DI
builder.Services.AddSingleton<IDatabaseRepo, CosmosDatabaseRepo>();

// Build
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

The protected controller method is simply decorated with [Authorize].

That works great for Microsoft accounts. However, every attempt to integrate Google into this flow fails. I've done the following:

Follow various example utilizing the Microsoft.AspNetCore.Authentication.Google package. I added AddGoogle method with the client id and secret set. This results in an invalid token error.

The OAuth process works (using Postman) and provides both an access token and id token. But:

The access token fails with invalid_token

The open id token fails saying invalid_token and invalid signature.

If I remove AddMicrosoftIdentityWebApi and only use the AddGoogle method then I always receive a 500 Internal Server Error indicating an auth scheme was not defined. Doesn't matter where I define it- whether in AddAuthorization or decorated on the controller's Authorize attribute.

Attempted using manual JWT validation. This seems problematic because:

It also results in the 500 error whatever I try.

It's not supposed to be required if I understand the packages correctly.

ALSO:

The Google client id has been added to my App Service as an identity provider with the associated App (client) ID.

There's 38974 tutorials out there and none seem to point in the right direction/don't address this issue. Any and all guidance is appreciated.


问:
g++ can't locate header files while CMake compilation is successful
I've a project structure like this:

```<code>project root
│   CMakeLists.txt
│
└───common-libs
│   │   CMakeLists.txt
│   │   libFiles.cpp
│   │   libFiles.h
│   │   ...
│
└───src
│   │   CMakeLists.txt
│   │   main.h
│   │   main.cpp

</code>```

common-libs folder contains my own implementations of some functions. I can include them in main.h with #include <libFiles.h> without any problem. Cmake compiles it. Problem occured whenver I try to debug the main.cpp on Visual Studio Code. Normally I have a task.json file something like this:

```<code>{
  "command": "/usr/bin/g++",
  "args": [
        "-std=c++17",
        "-g",
        "-I",
        "${workspaceFolder}/common-lib/*.cpp",
        "${workspaceFolder}/common-lib/*.h",
        "-o",
        "main",
        "-lpthread"
        ...
        ]
}
</code>```

There was a older version of the project where where I included the libraries with their relative path like so: #include "../common-libs/libFiles.h" and with task.json above I could debug without a problem. At that time there was no CMake in the project. While adding CMake I wanted to decouple the common-lib.

Problem

As I said, this code compiles with CMake. Although I give include directories on arguments to g++, whenever I try to run this on debug on VS Code, compiler seems to not see the files. Saying no such file or directory.

My assumption is since I'm not using any path -relative or not- and calling #include <someFile.h> like this, does compiler looks at just default directories and tries to find that file in those directories (in this case just default headers)? I either need to change the way I include header files, or I need to show the compiler where it can find the files.

What can I do to solve this?

If needed:

CMakeLists.txt on common-lib is something like this:

```<code>add_library(common-lib STATIC libFiles.cpp ...) # in reality there are more files of course

target_link_libraries(common-lib pthread curl ... )

target_include_directories(common-lib PUBLIC ${CMAKE_CURRENT_LIST_DIR})
</code>```

and CMakeLists.txt on src:

```<code>add_executable(main main.h main.cpp)

target_link_libraries(main PRIVATE common-lib)
</code>```

Body:
I've a project structure like this:

project root
│   CMakeLists.txt
│
└───common-libs
│   │   CMakeLists.txt
│   │   libFiles.cpp
│   │   libFiles.h
│   │   ...
│
└───src
│   │   CMakeLists.txt
│   │   main.h
│   │   main.cpp

common-libs folder contains my own implementations of some functions. I can include them in main.h with #include <libFiles.h> without any problem. Cmake compiles it. Problem occured whenver I try to debug the main.cpp on Visual Studio Code. Normally I have a task.json file something like this:

{
  "command": "/usr/bin/g++",
  "args": [
        "-std=c++17",
        "-g",
        "-I",
        "${workspaceFolder}/common-lib/*.cpp",
        "${workspaceFolder}/common-lib/*.h",
        "-o",
        "main",
        "-lpthread"
        ...
        ]
}

There was a older version of the project where where I included the libraries with their relative path like so: #include "../common-libs/libFiles.h" and with task.json above I could debug without a problem. At that time there was no CMake in the project. While adding CMake I wanted to decouple the common-lib.

Problem

As I said, this code compiles with CMake. Although I give include directories on arguments to g++, whenever I try to run this on debug on VS Code, compiler seems to not see the files. Saying no such file or directory.

My assumption is since I'm not using any path -relative or not- and calling #include <someFile.h> like this, does compiler looks at just default directories and tries to find that file in those directories (in this case just default headers)? I either need to change the way I include header files, or I need to show the compiler where it can find the files.

What can I do to solve this?

If needed:

CMakeLists.txt on common-lib is something like this:

add_library(common-lib STATIC libFiles.cpp ...) # in reality there are more files of course

target_link_libraries(common-lib pthread curl ... )

target_include_directories(common-lib PUBLIC ${CMAKE_CURRENT_LIST_DIR})

and CMakeLists.txt on src:

add_executable(main main.h main.cpp)

target_link_libraries(main PRIVATE common-lib)


问:
YOLOv7 error : " Image size exceeds limit of pixels, could be decom pression bomb DOS attack."
I recetly got an error of to big images:
Image size (223533999 pixels) exceeds limit of 178956970 pixels, could be decom
pression bomb DOS attack.

Do i have an option to extend this limit?


问:
Use a fileSystemWatcher script to run a batchfile in an unspecified destination
The following code will watch for any new jpeg images in the “c:\a\b\” directory and subdirectories:

```<code>#monitors folders with new files
$watcher = New-Object System.IO.FileSystemWatcher

#perameter that allows subdirectories to be monitored as well
$watcher.IncludeSubdirectories = $true

#Path that will be monitored
$watcher.Path = 'C:\a\b'
#$watcher.Filter = "*.jpg"

#enables watcher to raise events
$watcher.EnableRaisingEvents = $true

$action = {
    # Get the path of the detected file
    $path = $event.SourceEventArgs.FullPath

    # Get the parent directory of the detected file
    $parentDir = (Get-Item $path).Directory.Parent

    # Construct the destination path for the copied file using the parent directory
    # and the name of the parent directory with a .png extension
    $destination = "$($parentDir.FullName)\$($parentDir.Name).png"

    # Copy the detected file to the destination path and rename it
    Copy-Item $path $destination
# Run the batch file
Start-Process -FilePath "compare.bat" -WorkingDirectory $parentDir.FullName
    }
Register-ObjectEvent $watcher 'Created' -Action $action

</code>```

The code also renames the file (.png extension so as not to retrigger… I know it’s not properly converted but it works for my purposes) then, copies it into a parent folder. For example:

```<code>Filewatcher monitors:
C:\a\b\ and subdirectories

An image is detected in:
C:\a\b\c\d\detected.jpg

Filewatcher then copies and renames into a parent directory:
Copies C:\a\b\c\d\detected.jpg into c:\a\b\
renames “detected.jpg” to “b.png”
</code>```

This works great already. The problem is that I’d now like to have the script run a batchfile in the destination directory:
C:\a\b\batch.bat

I can’t make the destination static because the new jpg image could be in any of the subdirectories:

```<code>C:\a\b\c\detected.jpg
C:\a\b\c\d\detected.jpg
C:\a\b\c\d\e\detected.jpg

</code>```

Each of these sub directories have the same batchfile that needs to be executed. For simplicity, all the batchfiles are named exactly the same.
I’ve tried SEVERAL different modifications even the following code suggested by chatGPT:

```<code># Create a new instance of the FileSystemWatcher class, specifying the path to monitor
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "c:\a\b"
$watcher.Filter = "*.jpg"

# Set the event handlers for the FileSystemWatcher events
$watcher.Created += {
  # This event is raised when a file matching the specified pattern is created
  # in the monitored directory or one of its subdirectories

  # Get the full path of the created file
  $filePath = $Event.SourceEventArgs.FullPath

  # Copy the file to the parent directory, giving it a .png extension
  $fileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath)
  $destination = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($filePath), "..\..", "$fileName.png")
  Copy-Item $filePath $destination
}

# Enable the FileSystemWatcher events
$watcher.EnableRaisingEvents = $true
</code>```

The error received with the chatGPT suggestion was:

```<code>this is the error: InvalidOperation: Line | 7 | $watcher.Created += { | ~~~~~~~~~~~~~~~~~~~~~ | The property 'Created' cannot be found on this object. Verify that the property exists and can be set.
</code>```

I’m just trying to get the script to properly identify exactly which folder the png image was copied into so I can trigger a known batchfile that’s already in there. I know it’s possible because the script already knows where to copy the renamed image to!

Any help would be great. Thanks!

Be the first to beat chatGPT! Lol jk… kinda

Body:
The following code will watch for any new jpeg images in the “c:\a\b\” directory and subdirectories:

#monitors folders with new files
$watcher = New-Object System.IO.FileSystemWatcher

#perameter that allows subdirectories to be monitored as well
$watcher.IncludeSubdirectories = $true

#Path that will be monitored
$watcher.Path = 'C:\a\b'
#$watcher.Filter = "*.jpg"

#enables watcher to raise events
$watcher.EnableRaisingEvents = $true

$action = {
    # Get the path of the detected file
    $path = $event.SourceEventArgs.FullPath

    # Get the parent directory of the detected file
    $parentDir = (Get-Item $path).Directory.Parent

    # Construct the destination path for the copied file using the parent directory
    # and the name of the parent directory with a .png extension
    $destination = "$($parentDir.FullName)\$($parentDir.Name).png"

    # Copy the detected file to the destination path and rename it
    Copy-Item $path $destination
# Run the batch file
Start-Process -FilePath "compare.bat" -WorkingDirectory $parentDir.FullName
    }
Register-ObjectEvent $watcher 'Created' -Action $action

The code also renames the file (.png extension so as not to retrigger… I know it’s not properly converted but it works for my purposes) then, copies it into a parent folder. For example:

Filewatcher monitors:
C:\a\b\ and subdirectories

An image is detected in:
C:\a\b\c\d\detected.jpg

Filewatcher then copies and renames into a parent directory:
Copies C:\a\b\c\d\detected.jpg into c:\a\b\
renames “detected.jpg” to “b.png”

This works great already. The problem is that I’d now like to have the script run a batchfile in the destination directory:
C:\a\b\batch.bat

I can’t make the destination static because the new jpg image could be in any of the subdirectories:

C:\a\b\c\detected.jpg
C:\a\b\c\d\detected.jpg
C:\a\b\c\d\e\detected.jpg

Each of these sub directories have the same batchfile that needs to be executed. For simplicity, all the batchfiles are named exactly the same.
I’ve tried SEVERAL different modifications even the following code suggested by chatGPT:

# Create a new instance of the FileSystemWatcher class, specifying the path to monitor
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "c:\a\b"
$watcher.Filter = "*.jpg"

# Set the event handlers for the FileSystemWatcher events
$watcher.Created += {
  # This event is raised when a file matching the specified pattern is created
  # in the monitored directory or one of its subdirectories

  # Get the full path of the created file
  $filePath = $Event.SourceEventArgs.FullPath

  # Copy the file to the parent directory, giving it a .png extension
  $fileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath)
  $destination = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($filePath), "..\..", "$fileName.png")
  Copy-Item $filePath $destination
}

# Enable the FileSystemWatcher events
$watcher.EnableRaisingEvents = $true

The error received with the chatGPT suggestion was:

this is the error: InvalidOperation: Line | 7 | $watcher.Created += { | ~~~~~~~~~~~~~~~~~~~~~ | The property 'Created' cannot be found on this object. Verify that the property exists and can be set.

I’m just trying to get the script to properly identify exactly which folder the png image was copied into so I can trigger a known batchfile that’s already in there. I know it’s possible because the script already knows where to copy the renamed image to!

Any help would be great. Thanks!

Be the first to beat chatGPT! Lol jk… kinda


问:
Loading failed for the module with source “http://127.0.0.1:5173/resources/js/Pages/Ads/Index.vue?t=1670962685226”. Using Inertia, VueJS and Laravel
I am currently developing a CRUD application using Laravel 9, InertiaJS and VueJS.

When I try to go to the route /ads I have the following error message in the console :

My index page is in /Pages/Ads/Index.vue

The code of my route (web.php) is :

```<code>Route::resource('ads', AdController::class);
</code>```

The code of my controller is :

```<code>class AdController extends Controller
{
    public function index(Request $request)
    {
        $ads = Ad::with(['model','user'])->get();
        return inertia('Ads/Index', compact('ads'));
    }
}

</code>```

The code of my Pages/Ads/Index.vue is :

```<code><template>
    <h1>Index ad</h1>
</template>

<script>
export default {
    name: 'Index ad',
    props: {
        ads: Object,
    },
}
</script>
</code>```

I don't understand why I have this error, because I have other routes working and rendering properly Vue pages.
I check the Laravel and Inertia documentation but I didn't found the issue.

Thanks in advance for your help :)

I tried to look the at the differences with my code that is working with other routes, I checked the Laravel and Inertia documentation, and look online same issues.

Body:
I am currently developing a CRUD application using Laravel 9, InertiaJS and VueJS.

When I try to go to the route /ads I have the following error message in the console :

My index page is in /Pages/Ads/Index.vue

The code of my route (web.php) is :

Route::resource('ads', AdController::class);

The code of my controller is :

class AdController extends Controller
{
    public function index(Request $request)
    {
        $ads = Ad::with(['model','user'])->get();
        return inertia('Ads/Index', compact('ads'));
    }
}

The code of my Pages/Ads/Index.vue is :

<template>

Index ad

</template>

I don't understand why I have this error, because I have other routes working and rendering properly Vue pages.
I check the Laravel and Inertia documentation but I didn't found the issue.

Thanks in advance for your help :)

I tried to look the at the differences with my code that is working with other routes, I checked the Laravel and Inertia documentation, and look online same issues.


问:
Python - Press a specific button on a Sound that plays through Windows/Game
is it possible to Press a Button on Keyboard or do Something else when a specific Sound is played via the "Standard" Audio device under Windows?

Like python is always listening to the Audio, and if the specific sound like a Alarm is ringing then Press Button X and/or Send Message Y.