问:
Flutter: Async Await Function Not Waiting
I am doing some image processing and building in my app using the Image package. In this case, I am building a LinearProgressIndicator widget that is then converted into an image file, that is then merged into a larger image later on. However, the functions to build and take the image of the progress indicator widget isn't being waited on and the following error is observed

```<code>FileSystemException: Cannot open file, path = '/Users//Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Library/Caches/bar.png' (OS Error: No such file or directory, errno = 2)
</code>```

However, the progress indicator file is being created (I can see the cache), and then if I rerunning the image processing it works just fine (because now the file is there). However, I need it work on the first time. Here is what I have for image processing

```<code>import 'package:image/image.dart' as ui;

Future<File> instagramChalShare(BuildContext context, double progress) async {
   //this is where it does not appear the progressBarPathFunct is being waited on
   final testFile = await progressBarPathFunct(context, progress);
    ui.Image tester = ui.decodeImage(testFile.readAsBytesSync());
    //image is then resized
    ui.Image progressResized = ui.Image(600, 90);
    ui.drawImage(progressResized, tester);

   //now progress bar is merged into larger image
   final mergedImage = ui.Image(width, height);
   ui.copyInto(mergedImage, progressResized, blend: true);

   List<int> imageFile = ui.encodePng(mergedImage);
   final imageFilePath = await File('${(await getTemporaryDirectory()).path}/temp.png').create();
    print('picture finished $imageFilePath');
    return imageFilePath.writeAsBytes(imageFile);
}
</code>```

Here is the function to build the LinearProgressIndictor, convert it to an image, and create a file where the image is held.

```<code>  Future<File> progressBarPathFunct(BuildContext context, double progress) async {
    final progressFile = File('${(await getTemporaryDirectory()).path}/bar.png');
    var indicator = LinearPercentIndicator(
      percent: progress > 1.0 ? 1.0 : progress,
      width: context.size.width,
      lineHeight: 13,
      ),
      barRadius: Radius.circular(20),
    );
    screenshotController.captureFromWidget(
      InheritedTheme.captureAll(context, Material(child: indicator)),
    ).then((capturedProgress) async {
      await progressFile.create(recursive: true);
      await progressFile.writeAsBytes(capturedProgress);
    });
    print('progress bar path from functions ${progressFile.path}');
    return progressFile;
  }
</code>```

This function is working, but it seems the top one creating the merged Image file is not waiting for this function to finish before attempting to complete.

Edit

I am following the example from the screenshot package to generate an image of a widget that is not on the screen.

Body:
I am doing some image processing and building in my app using the Image package. In this case, I am building a LinearProgressIndicator widget that is then converted into an image file, that is then merged into a larger image later on. However, the functions to build and take the image of the progress indicator widget isn't being waited on and the following error is observed

FileSystemException: Cannot open file, path = '/Users//Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Library/Caches/bar.png' (OS Error: No such file or directory, errno = 2)

However, the progress indicator file is being created (I can see the cache), and then if I rerunning the image processing it works just fine (because now the file is there). However, I need it work on the first time. Here is what I have for image processing

import 'package:image/image.dart' as ui;

Future<File> instagramChalShare(BuildContext context, double progress) async {
   //this is where it does not appear the progressBarPathFunct is being waited on
   final testFile = await progressBarPathFunct(context, progress);
    ui.Image tester = ui.decodeImage(testFile.readAsBytesSync());
    //image is then resized
    ui.Image progressResized = ui.Image(600, 90);
    ui.drawImage(progressResized, tester);

   //now progress bar is merged into larger image
   final mergedImage = ui.Image(width, height);
   ui.copyInto(mergedImage, progressResized, blend: true);

   List<int> imageFile = ui.encodePng(mergedImage);
   final imageFilePath = await File('${(await getTemporaryDirectory()).path}/temp.png').create();
    print('picture finished $imageFilePath');
    return imageFilePath.writeAsBytes(imageFile);
}

Here is the function to build the LinearProgressIndictor, convert it to an image, and create a file where the image is held.

  Future<File> progressBarPathFunct(BuildContext context, double progress) async {
    final progressFile = File('${(await getTemporaryDirectory()).path}/bar.png');
    var indicator = LinearPercentIndicator(
      percent: progress > 1.0 ? 1.0 : progress,
      width: context.size.width,
      lineHeight: 13,
      ),
      barRadius: Radius.circular(20),
    );
    screenshotController.captureFromWidget(
      InheritedTheme.captureAll(context, Material(child: indicator)),
    ).then((capturedProgress) async {
      await progressFile.create(recursive: true);
      await progressFile.writeAsBytes(capturedProgress);
    });
    print('progress bar path from functions ${progressFile.path}');
    return progressFile;
  }

This function is working, but it seems the top one creating the merged Image file is not waiting for this function to finish before attempting to complete.

Edit

I am following the example from the screenshot package to generate an image of a widget that is not on the screen.


来源: stackexchange

问:
Is there a Gimap project ported to derive support from Jakarta Mail?
There was a project "Gimap" - to build onto the javax.mail system to support some Google extensions to IMAP protocol.

This project can still be found here: https://javaee.github.io/javamail/#Download_JavaMail_Release (or https://github.com/javaee/javamail/tree/master/gimap )

The underlying project javax.mail was sent out from Oracle and into Jakarta, now found here: https://github.com/jakartaee/mail-api

but I don't think Gimap was taken along. Can someone describe what happened to that, and where's the best place to find something equivalent based on Jakarta or any other currently supported libraries?

ContentLicense: CC BY-SA 4.0


问:
VS Code has colored one of my CSS selectors differently
I'm working on a intro-level project where I have begun to use aspect-ratio as a way to apply a few rules to some images. What I can't figure out is why VS Code suggests, auto-completes, and links to MDN Reference just like every other valid CSS selector, but for whatever reason it colors the text white. I've seen this before and it just goes away by itself sometimes or I move onto to a different project and forget about it.

Screenshot of the 'aspect-ratio' selector being white as opposed to the light blue of all of the other selectors.

I've re-written it a couple of times, moved the comments around and re-written the CSS selection entirely and it won't go away.


问:
React JS scroll optimization
I use onscroll event in my React component like this:

```<code>const ExpensiveComponent = () => {

};

export const Optimize2 = () => {
  const [scrollTop, setScrollTop] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollTop(window.scrollY);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      window.addEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div>
      <CenteredLayout>
        <ExpensiveComponent />
      </CenteredLayout>
    </div>
  );
};

</code>```

And this is works fine, but I want optimizette that.  So my question is how can I optimise this code?

Title: React JS scroll optimization

Body:
I use onscroll event in my React component like this:

const ExpensiveComponent = () => {

};

export const Optimize2 = () => {
  const [scrollTop, setScrollTop] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollTop(window.scrollY);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      window.addEventListener('scroll', handleScroll);
    };
  }, []);

  return (

      <CenteredLayout>
        <ExpensiveComponent />
      </CenteredLayout>

  );
};

And this is works fine, but I want optimizette that.  So my question is how can I optimise this code?


问:
Why is my MSAL Redirect not going back to my extension?
I've tried to use localhost instead of the <extension_id>chromiumapp.org but it just ignores it and try to go to the <extension_id>chromiumapp.org anyways. It does take my credentials, it is just not redirecting properly. Any ideas?

This is my authConfig.js
`

```<code>export const msalConfig = {
    auth: {
        clientId: "<clientId>",
        authority: "<tenant id and url>", // This is a URL (e.g. https://login.microsoftonline.com/{your tenant ID})
        knownAuthorities: ['foo.b2clogin.com'],
        redirectUri: "https://foobar.chromiumapp.org", // THIS KEEPS TRYING TO LOAD AS A PAGE AND CANT REACH IT
        navigateToLoginRequestUrl: true
    },
    cache: {
        cacheLocation: "sessionStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
};

// Add scopes here for ID token to be used at Microsoft identity platform endpoints.
export const loginRequest = {
    scopes: ["<tenant>.onmicrosoft.com/<tenant>.all"]
};

// Add the endpoints here for Microsoft Graph API services you'd like to use.
export const graphConfig = {
    graphMeEndpoint: "https://graph.microsoft.com"
};
</code>```

`

What would it be a proper redirect uri?

thank you!!

Body:
I've tried to use localhost instead of the <extension_id>chromiumapp.org but it just ignores it and try to go to the <extension_id>chromiumapp.org anyways. It does take my credentials, it is just not redirecting properly. Any ideas?

This is my authConfig.js
`

export const msalConfig = {
    auth: {
        clientId: "<clientId>",
        authority: "<tenant id and url>", // This is a URL (e.g. https://login.microsoftonline.com/{your tenant ID})
        knownAuthorities: ['foo.b2clogin.com'],
        redirectUri: "https://foobar.chromiumapp.org", // THIS KEEPS TRYING TO LOAD AS A PAGE AND CANT REACH IT
        navigateToLoginRequestUrl: true
    },
    cache: {
        cacheLocation: "sessionStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
};

// Add scopes here for ID token to be used at Microsoft identity platform endpoints.
export const loginRequest = {
    scopes: ["<tenant>.onmicrosoft.com/<tenant>.all"]
};

// Add the endpoints here for Microsoft Graph API services you'd like to use.
export const graphConfig = {
    graphMeEndpoint: "https://graph.microsoft.com"
};

`

What would it be a proper redirect uri?

thank you!!


问:
How do I use generics to link function argument types together?
I have an interesting Generics problem, where I'd like the second of two functional arguments to be derived from the first argument.
The associated code sandbox here: https://codesandbox.io/s/infallible-silence-3d47nd?file=/src/index.ts)

I understand that it is relatively straightforward to use a generic that will constrain a second function argument based on the type of the first argument. See below:

```<code>const funct = <T>(first: T, second: {message: T})
</code>```

However, I'm trying to expand on this for the following use case (See the screenshot for a complete problem statement):

I have a function (express middleware) that I'd like to strongly type based on the config (will be explained later):

```<code>type ConfigType = {
    request?: {
        query?: ZodObject
    }
}

type HandlerType = (req: Request, res: Response) => void

const registerRoute = (config: ConfigType, handler: HandlerType) => void.
</code>```

As is known, the above Request type can accept generics to strictly type its req.query, req.body properties, etc...

I'd like to essentially pass in the query ZodObject (found in argument 1) into the Request generic (in argument 2)

```<code>(req: Request<z.infer<ZodObject>>, res: Response) => void
</code>```

In order to do this, I need to solve two smaller issues:

How can I "access" the deeply nested ZodObject in the function signature (located at config?.request?.query), where each level is optional.
if each level is only Optional?

I feel like the answer is to use ternary conditions of the form: T['request'] extends undefined ? <Object IS NOT defined, so return never>: <Object IS defined, so I can continue drilling>.
As an example, I'm thinking the following. T['request'] extends undefined ? never : T['request']['query'].
Even if the above works, is there a cleaner way of doing this "prop drilling"?
It makes me think of a deeply nested Pick<> that typescript offers as a utility method.

Once I can logically conclude (using ternary) that my zod object is defined, how can I pass in the inferred type as a generic?

I'd like to pass in the above ZodObject in as: (req: Request<z.infer<ZodObject>>, res: Response) => void
Is this the proper way of doing so?

I've tried the following as a best attempt at solving my issue.

```<code>const registerRoute = <T extends ConfigType>(
  config: T,
  handler: (
    req: Request<
      T['request'] extends undefined ? never :
      T['request']['query'] extends undefined ? never: z.infer<typeof T['request']['query']>
    >
  )
) => {

}
</code>```

Body:
I have an interesting Generics problem, where I'd like the second of two functional arguments to be derived from the first argument.
The associated code sandbox here: https://codesandbox.io/s/infallible-silence-3d47nd?file=/src/index.ts)

I understand that it is relatively straightforward to use a generic that will constrain a second function argument based on the type of the first argument. See below:

const funct = <T>(first: T, second: {message: T})

However, I'm trying to expand on this for the following use case (See the screenshot for a complete problem statement):

I have a function (express middleware) that I'd like to strongly type based on the config (will be explained later):

type ConfigType = {
    request?: {
        query?: ZodObject
    }
}

type HandlerType = (req: Request, res: Response) => void

const registerRoute = (config: ConfigType, handler: HandlerType) => void.

As is known, the above Request type can accept generics to strictly type its req.query, req.body properties, etc...

I'd like to essentially pass in the query ZodObject (found in argument 1) into the Request generic (in argument 2)

(req: Request<z.infer<ZodObject>>, res: Response) => void

In order to do this, I need to solve two smaller issues:

How can I "access" the deeply nested ZodObject in the function signature (located at config?.request?.query), where each level is optional.
if each level is only Optional?

I feel like the answer is to use ternary conditions of the form: T['request'] extends undefined ? <Object IS NOT defined, so return never>: <Object IS defined, so I can continue drilling>.
As an example, I'm thinking the following. T['request'] extends undefined ? never : T['request']['query'].
Even if the above works, is there a cleaner way of doing this "prop drilling"?
It makes me think of a deeply nested Pick<> that typescript offers as a utility method.

Once I can logically conclude (using ternary) that my zod object is defined, how can I pass in the inferred type as a generic?

I'd like to pass in the above ZodObject in as: (req: Request<z.infer<ZodObject>>, res: Response) => void
Is this the proper way of doing so?

I've tried the following as a best attempt at solving my issue.

const registerRoute = <T extends ConfigType>(
  config: T,
  handler: (
    req: Request<
      T['request'] extends undefined ? never :
      T['request']['query'] extends undefined ? never: z.infer<typeof T['request']['query']>
    >
  )
) => {

}


问:
npm not installing packages and not creating package-lock.json

I created a new Laravel project with laravel new x

changed into that folder with cd x

tried installing the npm packages with npm install

This didn't work like expected.

I just got an Error: Cannot destructure property 'name' of '.for' as it is undefined.

Then I was like yeah lets just add a name to the package so I did

Ran npm install again

After that it installed something and prompted: Installed 1 Package

Instead of installing the specified devDependencies, creating a package-lock and a node_modules folder, it installed a package with the name that i just specified, globally. I knew that because of npm ls -g. So now i dont have any packages installed locally in my folder but a dependency globally that does nothing.

Output of npm ls and npm ls -g:

```<code>C:\Users\johnw\AppData\Roaming\npm
└── theNameIJustSpecified@
</code>```

My package.json looks like this (and was auto-generated by the laravel installer):

{
    "name": "myName",
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "devDependencies": {
        "axios": "^1.1.2",
        "laravel-vite-plugin": "^0.7.2",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "vite": "^4.0.0"
    }
}
```
<ul>
<li>npm -v: 9.2.0</li>
<li>node -v: v19.3.0</li>
<li>os: windows 11</li>
</ul>
<p>Normally  this just worked out of the box with the Laravel installer. I just typed <code>npm install</code> and it worked.</p>
<p>I tried reinstalling Node and npm, even used Nvm for Windows without any change.
I tried restarting my pc without any change.
I tried creating the <code>package.json</code> via <code>npm init</code>, didn't change anything other than the output of <code>npm ls -g</code> (added 1.0.0 to the end):</p>
```C:\Users\johnw\AppData\Roaming\npm
└── theNameIJustSpecified@1.0.0
```

Edit: Tried downgrading to npm 8, also didn't work.
Downgrading to 7 works again, but I get warning because of too old version.

I checked other projects (old Laravel projects) and they have the same problem now. I used to work in them for months using npm packages for asset bundling. Now they give me the same error.

Body:
I created a new Laravel project with laravel new x

changed into that folder with cd x

tried installing the npm packages with npm install

This didn't work like expected.

I just got an Error: Cannot destructure property 'name' of '.for' as it is undefined.

Then I was like yeah lets just add a name to the package so I did

Ran npm install again

After that it installed something and prompted: Installed 1 Package

Instead of installing the specified devDependencies, creating a package-lock and a node_modules folder, it installed a package with the name that i just specified, globally. I knew that because of npm ls -g. So now i dont have any packages installed locally in my folder but a dependency globally that does nothing.

Output of npm ls and npm ls -g:

C:\Users\johnw\AppData\Roaming\npm
└── theNameIJustSpecified@

My package.json looks like this (and was auto-generated by the laravel installer):

{
    "name": "myName",
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "devDependencies": {
        "axios": "^1.1.2",
        "laravel-vite-plugin": "^0.7.2",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "vite": "^4.0.0"
    }
}

npm -v: 9.2.0

node -v: v19.3.0

os: windows 11

Normally  this just worked out of the box with the Laravel installer. I just typed npm install and it worked.

I tried reinstalling Node and npm, even used Nvm for Windows without any change.
I tried restarting my pc without any change.
I tried creating the package.json via npm init, didn't change anything other than the output of npm ls -g (added 1.0.0 to the end):

C:\Users\johnw\AppData\Roaming\npm
└── theNameIJustSpecified@1.0.0

Edit: Tried downgrading to npm 8, also didn't work.
Downgrading to 7 works again, but I get warning because of too old version.

I checked other projects (old Laravel projects) and they have the same problem now. I used to work in them for months using npm packages for asset bundling. Now they give me the same error.


问:
CURLOPT_REQUEST_TARGET with pycurl
I would like to use pycurl with the option that matches --request-target on the command line tool.

When trying this with the following code:

```<code>import pycurl
c = pycurl.Curl()
c.setopt(c.URL, "http://192.168.2.230")
c.setopt(c.REQUEST_TARGET, "*")
c.perform()
print(c.getinfo(c.HTTP_CODE))
</code>```

I get the following error:

AttributeError: trying to obtain a non-existing attribute: REQUEST_TARGET

A similar thing happens when I change c.setopt(c.REQUEST_TARGET, "*") to c.setopt(c.CURLOPT_REQUEST_TARGET, "*")

AttributeError: trying to obtain a non-existing attribute: CURLOPT_REQUEST_TARGET

Is there a way to use CURLOPT_REQUEST_TARGET with pycurl?

--------------- update -------------------

User barmar below gave me a hint to look at setopt_string for setting custom options. This looks promising.
I tried this:

```<code>import pycurl
c = pycurl.Curl()
c.setopt(c.URL, "http://192.168.2.230")
c.setopt_string(266, "*")
c.perform()
print(c.getinfo(c.HTTP_CODE))
</code>```

This however results in the following error:

TypeError: strings are not supported for this option

--------------- update 2 -------------------

Ended up making a pull request to add the feature

Title: CURLOPT_REQUEST_TARGET with pycurl

Body:
I would like to use pycurl with the option that matches --request-target on the command line tool.

When trying this with the following code:

import pycurl
c = pycurl.Curl()
c.setopt(c.URL, "http://192.168.2.230")
c.setopt(c.REQUEST_TARGET, "*")
c.perform()
print(c.getinfo(c.HTTP_CODE))

I get the following error:

AttributeError: trying to obtain a non-existing attribute: REQUEST_TARGET

A similar thing happens when I change c.setopt(c.REQUEST_TARGET, "*") to c.setopt(c.CURLOPT_REQUEST_TARGET, "*")

AttributeError: trying to obtain a non-existing attribute: CURLOPT_REQUEST_TARGET

Is there a way to use CURLOPT_REQUEST_TARGET with pycurl?

--------------- update -------------------

User barmar below gave me a hint to look at setopt_string for setting custom options. This looks promising.
I tried this:

import pycurl
c = pycurl.Curl()
c.setopt(c.URL, "http://192.168.2.230")
c.setopt_string(266, "*")
c.perform()
print(c.getinfo(c.HTTP_CODE))

This however results in the following error:

TypeError: strings are not supported for this option

--------------- update 2 -------------------

Ended up making a pull request to add the feature


问:
ffmpeg convert rtmp audio/video stream to icecast2 audio/video stream
I've been using this command to convert my public rtmp audio/video stream to a local mp3 audio icecast2 stream, but I have been unable to do the same for both video and audio.

[Audio Only] (This works fine)

ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -vn -codec:a libmp3lame -b:a 128k -f mp3 -content_type audio/mpeg icecast://source:password@192.168.1.xxx:80/live

I've tried to re-write in order to support video, but I keep hitting dead ends

[Audio & Video Attempt] (this does not work)

ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -codec:v -f mpeg4 -b:v -f mpeg4 -content_type video/mpeg4 icecast://source:password@192.168.1.xxx:80/live

When I run this command, it gives me the error below asking for a suitable format.

```<code>$ ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -codec:v -f mpeg4 -b:v -f mpeg4 -content_type video/mpeg4 icecast://source:password@192.168.1.xxx:80/live
[h264 @ 0x5598ffbb8980] co located POCs unavailable
[h264 @ 0x5598ffbb8980] mmco: unref short failure
Input #0, flv, from 'rtmp://162.142.xx.xxx:xxx/stream':
  Metadata:
    |RtmpSampleAccess: true
    Server          : NGINX RTMP (github.com/sergey-dryabzhinsky/nginx-rtmp-module)
    displayWidth    : 1280
    displayHeight   : 720
    fps             : 48
    videokeyframe_frequency: 0
    profile         :
    level           :
  Duration: 00:00:00.00, start: 28117.779000, bitrate: N/A
  Stream #0:0: Audio: aac (LC), 48000 Hz, stereo, fltp, 327 kb/s
  Stream #0:1: Video: h264 (High), yuv420p(tv, bt709, progressive), 1280x720 [SAR 1:1 DAR 16:9], 2560 kb/s, 48 fps, 48 tbr, 1k tbn
[NULL @ 0x5598ffb8bec0] Unable to find a suitable output format for 'mpeg4'
mpeg4: Invalid argument
</code>```

I am positive that icecast2 can support video streams, however on the few occasions that I was able to actively stream successfully to it, it only showed an empty video embed.

I've re-written the command for AV multiple times while referencing ffmpeg documentation, however my above attempt seems to be the closest (concept-wise) that I have gotten.

What flags/formatting might I be missing which are causing the stream not to work?

Body:
I've been using this command to convert my public rtmp audio/video stream to a local mp3 audio icecast2 stream, but I have been unable to do the same for both video and audio.

[Audio Only] (This works fine)

ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -vn -codec:a libmp3lame -b:a 128k -f mp3 -content_type audio/mpeg icecast://source:password@192.168.1.xxx:80/live

I've tried to re-write in order to support video, but I keep hitting dead ends

[Audio & Video Attempt] (this does not work)

ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -codec:v -f mpeg4 -b:v -f mpeg4 -content_type video/mpeg4 icecast://source:password@192.168.1.xxx:80/live

When I run this command, it gives me the error below asking for a suitable format.

$ ffmpeg -re -i rtmp://162.142.xx.xxx:xxx/stream -codec:v -f mpeg4 -b:v -f mpeg4 -content_type video/mpeg4 icecast://source:password@192.168.1.xxx:80/live
[h264 @ 0x5598ffbb8980] co located POCs unavailable
[h264 @ 0x5598ffbb8980] mmco: unref short failure
Input #0, flv, from 'rtmp://162.142.xx.xxx:xxx/stream':
  Metadata:
    |RtmpSampleAccess: true
    Server          : NGINX RTMP (github.com/sergey-dryabzhinsky/nginx-rtmp-module)
    displayWidth    : 1280
    displayHeight   : 720
    fps             : 48
    videokeyframe_frequency: 0
    profile         :
    level           :
  Duration: 00:00:00.00, start: 28117.779000, bitrate: N/A
  Stream #0:0: Audio: aac (LC), 48000 Hz, stereo, fltp, 327 kb/s
  Stream #0:1: Video: h264 (High), yuv420p(tv, bt709, progressive), 1280x720 [SAR 1:1 DAR 16:9], 2560 kb/s, 48 fps, 48 tbr, 1k tbn
[NULL @ 0x5598ffb8bec0] Unable to find a suitable output format for 'mpeg4'
mpeg4: Invalid argument

I am positive that icecast2 can support video streams, however on the few occasions that I was able to actively stream successfully to it, it only showed an empty video embed.

I've re-written the command for AV multiple times while referencing ffmpeg documentation, however my above attempt seems to be the closest (concept-wise) that I have gotten.

What flags/formatting might I be missing which are causing the stream not to work?


问:
Optimize Past stock calculation using cumulative sum in python and pandas without iterating through dataframe (Performance warning)
I'm calculating the cumulative sum of one specific Clothes store stock over time (grouped by Family, Groups, Year and months). To be able to re-establish the stock levels of the past based on three values: Number of purchased items , Number of sold items and the current stock i have today.

I have already solved the calculation problem by: Merging the stock table with the movement table and calculating the mov_itens['novo_estoque'] with the formula bellow:

```<code>mov_itens['novo_estoque'] = mov_itens['vendas'] - mov_itens['compras'] + mov_itens['estoque']

</code>```

Then i have transformed it on a multi-index dataframe. Where indexes are respecticelly: codfamily, codgroup, year and month. By doing:

```<code>gruposemindice = mov_itens.groupby(['codfamilia','codgrupo','ano','mes']).sum()

</code>```

And calculated the CUMSUM() on the 'estoque' column. Where i could not use it after a map or something like that, because i wasn't able to return (to my new dataframe) the other columns that shouldn't receive the cumulative sum.

```<code> gruposemindice_ord = gruposemindice.sort_index(ascending=False)

</code>```
```<code>for i in gruposemindice_ord.index:
    if(f == i[0]):#codfamilia
        if(g == i[1]):#codgrupo
                gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
                #calcular giro de estoque nessa linha
                print(gruposemindice_ord.loc[i[:-2]])

        else:
            g = i[1]
    else:
        f = i[0]
</code>```

The problem is that I'm doing it iteratively and the dataframe is sorted DESCENDING by index, which makes the query last like order(n) for each index that I access. In fact, it should be Order (1) [direct access], to be fast enough and do not cause a bottleneck and these errors that are appearing....

```<code>gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:10: **PerformanceWarning: indexing past lexsort depth may impact performance.**
  print(gruposemindice_ord.loc[i[:-2]])
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:9: PerformanceWarning: indexing past lexsort depth may impact performance.
  gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:9: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
</code>```

According to python,I can correct it just ASCENDING sorting the dataframe before doing the manipulation, but I need a DESCENDING sorting, because stock info is only available for the current month, which is the last month of the table, and then I calculate the previous months starting for it.... If I sort the other way the calculation will not work.

Some Observations

The dataframe Multi-indexes are the numbers of the Families, Groups and Brands of the store, so I can't re-index and loose these numbers,

Also i cannot do this by account on an ascending order, as my first stock is on the last month

I am already checking if the sort and transaction are correct (As pointed on another stack answer).

```<code>gruposemindice_ord = gruposemindice.sort_index(ascending=False)
gruposemindice_ord.index.is_lexsorted()
</code>```

Hope someone can help me!
Best Regards, Diego Mello

Body:
I'm calculating the cumulative sum of one specific Clothes store stock over time (grouped by Family, Groups, Year and months). To be able to re-establish the stock levels of the past based on three values: Number of purchased items , Number of sold items and the current stock i have today.

I have already solved the calculation problem by: Merging the stock table with the movement table and calculating the mov_itens['novo_estoque'] with the formula bellow:

mov_itens['novo_estoque'] = mov_itens['vendas'] - mov_itens['compras'] + mov_itens['estoque']

Then i have transformed it on a multi-index dataframe. Where indexes are respecticelly: codfamily, codgroup, year and month. By doing:

gruposemindice = mov_itens.groupby(['codfamilia','codgrupo','ano','mes']).sum()

And calculated the CUMSUM() on the 'estoque' column. Where i could not use it after a map or something like that, because i wasn't able to return (to my new dataframe) the other columns that shouldn't receive the cumulative sum.

 gruposemindice_ord = gruposemindice.sort_index(ascending=False)

for i in gruposemindice_ord.index:
    if(f == i[0]):#codfamilia
        if(g == i[1]):#codgrupo
                gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
                #calcular giro de estoque nessa linha
                print(gruposemindice_ord.loc[i[:-2]])

        else:
            g = i[1]
    else:
        f = i[0]

The problem is that I'm doing it iteratively and the dataframe is sorted DESCENDING by index, which makes the query last like order(n) for each index that I access. In fact, it should be Order (1) [direct access], to be fast enough and do not cause a bottleneck and these errors that are appearing....

gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:10: **PerformanceWarning: indexing past lexsort depth may impact performance.**
  print(gruposemindice_ord.loc[i[:-2]])
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:9: PerformanceWarning: indexing past lexsort depth may impact performance.
  gruposemindice_ord.loc[i[:-2]]['estoque'] = (gruposemindice_ord.loc[i[:-2]]['novo_estoque']).cumsum()
C:\Users\Diego\AppData\Local\Temp/ipykernel_20264/1416332248.py:9: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

According to python,I can correct it just ASCENDING sorting the dataframe before doing the manipulation, but I need a DESCENDING sorting, because stock info is only available for the current month, which is the last month of the table, and then I calculate the previous months starting for it.... If I sort the other way the calculation will not work.

Some Observations

The dataframe Multi-indexes are the numbers of the Families, Groups and Brands of the store, so I can't re-index and loose these numbers,

Also i cannot do this by account on an ascending order, as my first stock is on the last month

I am already checking if the sort and transaction are correct (As pointed on another stack answer).

gruposemindice_ord = gruposemindice.sort_index(ascending=False)
gruposemindice_ord.index.is_lexsorted()

Hope someone can help me!
Best Regards, Diego Mello


问:
Where can I find more documentation on VSCode's LSP configurations and settings?
I have been tinkering with the VSCode's Language Server Protocol for a while now. I really would like to learn more. However I couldn't find much resources.
Right now I am trying to find the documentation for this part of code

```<code>transport: TransportKind.ipc
</code>```

from here.
What if I need to find other forms of communication like stdio or something else or what other transport options are there and possible examples.
Where can I find these

Body:
I have been tinkering with the VSCode's Language Server Protocol for a while now. I really would like to learn more. However I couldn't find much resources.
Right now I am trying to find the documentation for this part of code

transport: TransportKind.ipc

from here.
What if I need to find other forms of communication like stdio or something else or what other transport options are there and possible examples.
Where can I find these


问:
Uncaught TypeError: Cannot set properties of null (setting 'innerText') in JavaScript
I'm not sure what the problem is, I'm following a YT tutorial and even the exact same code.

this shows in problem

script.js:37

Uncaught TypeError: Cannot set properties of null (setting 'innerText')     at showQuestion (script.js:37:31)     at setnextQuestion (script.js:33) at HTMLButtonElement.startGame (script.js:26:5) showQuestion @ script.js:37 setnextQuestion @ script.js:33 startGame @ script.js:26

This is my script code:

```<code>const startButton = document.getElementById('start-btn')
const nextButton  = document.getElementById('next-btn')

const questionContainElement = document.getElementById('question-container')
const questionElement        = document.getElementById('question')
const answerButtonsElement   = document.getElementById('answer-buttons')

let shuffledQuestionIndex;
let quizScore = 0;

startButton.addEventListener('click', startGame)

nextButton.addEventListener('click ',() =>{
     currectQuestionIndex++
     setnextQuestion()
})

function startGame(){
    startButton.classList.add('hide')
    shuffledQuestionIndex=question.sort(() =>Math.random() -0.5)
    currectQuestionIndex=0;
    questionContainElement.classList.remove('hide')
    setnextQuestion()
    quizScore=0
}

function setnextQuestion(){
    resetState();
    showQuestion(shuffledQuestionIndex[currectQuestionIndex])
}

function showQuestion(question) {
    questionElement.innerText = question.question;
    question.answers.forEach((answer) =>{
    const button =document.createElement('button')
    button.innerText=answer.text;
    button.classList.add('btn')
    if(answer.correct)
    {
      button.dataset.correctanswer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
    })
 }
</code>```

Thankful for any kind of help

Body:
I'm not sure what the problem is, I'm following a YT tutorial and even the exact same code.

this shows in problem

script.js:37

Uncaught TypeError: Cannot set properties of null (setting 'innerText')     at showQuestion (script.js:37:31)     at setnextQuestion (script.js:33) at HTMLButtonElement.startGame (script.js:26:5) showQuestion @ script.js:37 setnextQuestion @ script.js:33 startGame @ script.js:26

This is my script code:

const startButton = document.getElementById('start-btn')
const nextButton  = document.getElementById('next-btn')

const questionContainElement = document.getElementById('question-container')
const questionElement        = document.getElementById('question')
const answerButtonsElement   = document.getElementById('answer-buttons')

let shuffledQuestionIndex;
let quizScore = 0;

startButton.addEventListener('click', startGame)

nextButton.addEventListener('click ',() =>{
     currectQuestionIndex++
     setnextQuestion()
})

function startGame(){
    startButton.classList.add('hide')
    shuffledQuestionIndex=question.sort(() =>Math.random() -0.5)
    currectQuestionIndex=0;
    questionContainElement.classList.remove('hide')
    setnextQuestion()
    quizScore=0
}

function setnextQuestion(){
    resetState();
    showQuestion(shuffledQuestionIndex[currectQuestionIndex])
}

function showQuestion(question) {
    questionElement.innerText = question.question;
    question.answers.forEach((answer) =>{
    const button =document.createElement('button')
    button.innerText=answer.text;
    button.classList.add('btn')
    if(answer.correct)
    {
      button.dataset.correctanswer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
    })
 }

Thankful for any kind of help


问:
Unable to play sound and rpi_rf at same time
I'm unable to play a sound in the background and send a 433 Mhz wireless RF signal (rpi-rf module) at the same time. The whole script works, but no RF signal is sent. No output/error either. Whenever I cut out the audio of the script, it suddenly works fine.

My code:

```<code>import time
import pygame

pygame.mixer.init() #This is already enough to prevent the RF signal from working
#pygame.mixer.music.load("/home/pi/file.mp3")
#pygame.mixer.music.play(999)

print("startwait")
time.sleep(10)

from rpi_rf import RFDevice
rfdevice = RFDevice(17)
rfdevice.enable_tx()
rfdevice.tx_code(4612, None, None)
time.sleep(1)
rfdevice.tx_code(4610, None, None)
rfdevice.cleanup()
</code>```

When commenting out pygame.mixer.init() it works perfectly fine.
Tried using vlc instead of pygame, exactly the same problem.
Using Raspberry Pi 1 Model B+, Python 3.7 and Raspbian 10.

How do I fix this?

Body:
I'm unable to play a sound in the background and send a 433 Mhz wireless RF signal (rpi-rf module) at the same time. The whole script works, but no RF signal is sent. No output/error either. Whenever I cut out the audio of the script, it suddenly works fine.

My code:

import time
import pygame

pygame.mixer.init() #This is already enough to prevent the RF signal from working
#pygame.mixer.music.load("/home/pi/file.mp3")
#pygame.mixer.music.play(999)

print("startwait")
time.sleep(10)

from rpi_rf import RFDevice
rfdevice = RFDevice(17)
rfdevice.enable_tx()
rfdevice.tx_code(4612, None, None)
time.sleep(1)
rfdevice.tx_code(4610, None, None)
rfdevice.cleanup()

When commenting out pygame.mixer.init() it works perfectly fine.
Tried using vlc instead of pygame, exactly the same problem.
Using Raspberry Pi 1 Model B+, Python 3.7 and Raspbian 10.

How do I fix this?


问:
Got this error POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAIAPVIvYAy4K20V5KgrEj4VESZ55ch6II 400
I am trying to upload signup data like image in firestore. I have setup firestore and storage in firebase although it gives this error.
"POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAIAPVIvYAy4K20V5KgrEj4VESZ55ch6II 400"

what to do ? Can anyone please help?

My signup page:

```<code>import React, { useState } from "react";
import { Link } from "react-router-dom";
import { Container, Row, Col, Form, FormGroup } from "reactstrap";
import Helmet from "../components/Helmet/Helmet";
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { setDoc, doc } from "firebase/firestore";

import { auth } from "../firebase.config";
import { storage } from "../firebase.config";
import { db } from "../firebase.config";

import { toast } from "react-toastify";
import "../styles/login.css";

const Signup = () => {
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [file, setFile] = useState(null);
  const [loading, setLoading] = useState(false);

  const signupUser = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const userCredential = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      );

      const user = userCredential.user;

      const storageRef = ref(storage, `images/${Date.now() + username}`);
      const uploadTask = uploadBytesResumable(storageRef, file);

      uploadTask.on(
        (error) => {
          toast.error(error.message);
        },
        () => {
          getDownloadURL(updateProfile.snapshot.ref).then(
            async (downloadURL) => {
              await updateProfile(user, {
                displayName: username,
                photoURL: downloadURL,
              });
              await setDoc(doc(db, "users", user.uid), {
                uid: user.uid,
                displayName: username,
                email,
                photoURL: downloadURL,
              });
            }
          );
        }
      );
    } catch (error) {
      toast.error("something went wrong");
    }
  };
  return (
    <Helmet title="Signup">
      <section>
        <Container>
          <Row>
            <Col lg="6" className="m-auto text-center">
              <h3 className="fw-bold mb-2">Signup</h3>

              <Form className="auth__form" onSubmit={signupUser}>
                <FormGroup className="form__group">
                  <input
                    type="text"
                    placeholder="username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="email"
                    placeholder="Enter your email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="file"
                    onChange={(e) => setFile(e.target.files[0])}
                  />
                </FormGroup>

                <button type="submit" className="buy__btn auth__btn">
                  Create an account
                </button>
                <p>
                  Already have an account? <Link to="/login">Login</Link>
                </p>
              </Form>
            </Col>
          </Row>
        </Container>
      </section>
    </Helmet>
  );
};

export default Signup;

</code>```

I think I have configured firebase correctly.

Body:
I am trying to upload signup data like image in firestore. I have setup firestore and storage in firebase although it gives this error.
"POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyAIAPVIvYAy4K20V5KgrEj4VESZ55ch6II 400"

what to do ? Can anyone please help?

My signup page:

import React, { useState } from "react";
import { Link } from "react-router-dom";
import { Container, Row, Col, Form, FormGroup } from "reactstrap";
import Helmet from "../components/Helmet/Helmet";
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { setDoc, doc } from "firebase/firestore";

import { auth } from "../firebase.config";
import { storage } from "../firebase.config";
import { db } from "../firebase.config";

import { toast } from "react-toastify";
import "../styles/login.css";

const Signup = () => {
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [file, setFile] = useState(null);
  const [loading, setLoading] = useState(false);

  const signupUser = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const userCredential = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      );

      const user = userCredential.user;

      const storageRef = ref(storage, `images/${Date.now() + username}`);
      const uploadTask = uploadBytesResumable(storageRef, file);

      uploadTask.on(
        (error) => {
          toast.error(error.message);
        },
        () => {
          getDownloadURL(updateProfile.snapshot.ref).then(
            async (downloadURL) => {
              await updateProfile(user, {
                displayName: username,
                photoURL: downloadURL,
              });
              await setDoc(doc(db, "users", user.uid), {
                uid: user.uid,
                displayName: username,
                email,
                photoURL: downloadURL,
              });
            }
          );
        }
      );
    } catch (error) {
      toast.error("something went wrong");
    }
  };
  return (
    <Helmet title="Signup">

        <Container>
          <Row>
            <Col lg="6" className="m-auto text-center">

Signup

              <Form className="auth__form" onSubmit={signupUser}>
                <FormGroup className="form__group">
                  <input
                    type="text"
                    placeholder="username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="email"
                    placeholder="Enter your email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </FormGroup>

                <FormGroup className="form__group">
                  <input
                    type="file"
                    onChange={(e) => setFile(e.target.files[0])}
                  />
                </FormGroup>

                <button type="submit" className="buy__btn auth__btn">
                  Create an account
                </button>

                  Already have an account? <Link to="/login">Login</Link>

              </Form>
            </Col>
          </Row>
        </Container>

    </Helmet>
  );
};

export default Signup;

I think I have configured firebase correctly.


问:
Context.CLIPBOARD_SERVICE type mismatch error
I am newbie for Kotlin. I tried to add an option near to "cut","copy".. options. And it will paste any random number on any app. But when i try this :

```<code>var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// Context.CLIPBOARD_SERVICE type mismatch error and no value passed for parameter 'p1' error
</code>```

Here is my codes:

```<code>import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat.getSystemService
import java.util.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        }
    }

    class CustomActionModeCallback : ActionMode.Callback {

        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            val inflater: MenuInflater = mode!!.menuInflater
            inflater.inflate(R.menu.menu_custom_action_mode, menu)
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            when (item!!.itemId) {
                R.id.menu_item_custom -> {

                    var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    var randomNumber = "123123"
                    var clip = ClipData.newPlainText("Random Number", randomNumber)
                    clipboard.setPrimaryClip(clip)
                    mode!!.finish()
                    return true
                }
            }
            return false
        }
</code>```

What i tried : Copy Clipboard

What happened :
Context.CLIPBOARD_SERVICE type mismatch error and no value passed for parameter 'p1' error

Body:
I am newbie for Kotlin. I tried to add an option near to "cut","copy".. options. And it will paste any random number on any app. But when i try this :

var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// Context.CLIPBOARD_SERVICE type mismatch error and no value passed for parameter 'p1' error

Here is my codes:

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat.getSystemService
import java.util.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        }
    }

    class CustomActionModeCallback : ActionMode.Callback {

        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            val inflater: MenuInflater = mode!!.menuInflater
            inflater.inflate(R.menu.menu_custom_action_mode, menu)
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            when (item!!.itemId) {
                R.id.menu_item_custom -> {

                    var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    var randomNumber = "123123"
                    var clip = ClipData.newPlainText("Random Number", randomNumber)
                    clipboard.setPrimaryClip(clip)
                    mode!!.finish()
                    return true
                }
            }
            return false
        }

What i tried : Copy Clipboard

What happened :
Context.CLIPBOARD_SERVICE type mismatch error and no value passed for parameter 'p1' error


问:
Creating self-referential structs
I am facing a need to create a self-referential structure Foo, and to date I've managed to come up with the following:

```<code>use std::pin::Pin;

struct Foo<'a> {
    x: u32,
    xp: Option<&'a u32>,
}

impl From<u32> for Pin<Box<Foo<'_>>> {
    fn from(x: u32) -> Self {
        let mut res = Box::pin(Foo { x, xp: None });
        let x = &res.x;
        let xp = &mut res.xp;
        *xp = Some(x);
        res
    }
}
</code>```

That looks like a book example of splitting a borrow, but I am probably missing a point here, because the compiler complains with a message that does not make it transparent what exactly is wrong:

```<code>error[E0502]: cannot borrow `res` as mutable because it is also borrowed as immutable
  --> src/lib.rs:12:23
   |
9  |     fn from(x: u32) -> Self {
   |                        ---- return type is Pin<Box<Foo<'1>>>
10 |         let mut res = Box::pin(Foo { x, xp: None });
11 |         let x = &res.x;
   |                  --- immutable borrow occurs here
12 |         let xp = &mut res.xp;
   |                       ^^^ mutable borrow occurs here
13 |         *xp = Some(x);
14 |         res
   |         --- returning this value requires that `res` is borrowed for `'1`
</code>```

I am aware of this question, but why does the compiler thinks that a move of the referred to data occurs here?

Is it possible to express the same idea, probably using unsafe code?

Title: Creating self-referential structs

Body:
I am facing a need to create a self-referential structure Foo, and to date I've managed to come up with the following:

use std::pin::Pin;

struct Foo<'a> {
    x: u32,
    xp: Option<&'a u32>,
}

impl From<u32> for Pin<Box<Foo<'_>>> {
    fn from(x: u32) -> Self {
        let mut res = Box::pin(Foo { x, xp: None });
        let x = &res.x;
        let xp = &mut res.xp;
        *xp = Some(x);
        res
    }
}

That looks like a book example of splitting a borrow, but I am probably missing a point here, because the compiler complains with a message that does not make it transparent what exactly is wrong:

error[E0502]: cannot borrow `res` as mutable because it is also borrowed as immutable
  --> src/lib.rs:12:23
   |
9  |     fn from(x: u32) -> Self {
   |                        ---- return type is Pin<Box<Foo<'1>>>
10 |         let mut res = Box::pin(Foo { x, xp: None });
11 |         let x = &res.x;
   |                  --- immutable borrow occurs here
12 |         let xp = &mut res.xp;
   |                       ^^^ mutable borrow occurs here
13 |         *xp = Some(x);
14 |         res
   |         --- returning this value requires that `res` is borrowed for `'1`

I am aware of this question, but why does the compiler thinks that a move of the referred to data occurs here?

Is it possible to express the same idea, probably using unsafe code?


问:
Cannot move a text object (variable) outside a function
I am trying to first convert pdf credit card statements to text then use regex to extract dates, amounts, and vendor from the individual lines.  I can extract all the lines of text as they appear on the statement but when I call the variable with the text file, it only returns the last line.

I set the directory and read-in the pdf credit card statement as "dfpdf"
I run this code ....

```<code>with plumb.open(dfpdf) as pdf:
    pages = pdf.pages
    for page in pdf.pages:
        text = page.extract_text()
        global line
        for line in text.split('\n'):
            print(line)
</code>```

this returns all the lines in the statement which is what I want.  But if I later call or try to print "line" all I get is the last line of the statement.  In addition to what is probably a really simple answer, I would also love a suggestion for a really good tutorial or class on using python to convert pdfs then using regex to create pd data frames.  Thanks to all of you out there who know what you're doing and take the time to help amatuers like me.  Mark

Body:
I am trying to first convert pdf credit card statements to text then use regex to extract dates, amounts, and vendor from the individual lines.  I can extract all the lines of text as they appear on the statement but when I call the variable with the text file, it only returns the last line.

I set the directory and read-in the pdf credit card statement as "dfpdf"
I run this code ....

with plumb.open(dfpdf) as pdf:
    pages = pdf.pages
    for page in pdf.pages:
        text = page.extract_text()
        global line
        for line in text.split('\n'):
            print(line)

this returns all the lines in the statement which is what I want.  But if I later call or try to print "line" all I get is the last line of the statement.  In addition to what is probably a really simple answer, I would also love a suggestion for a really good tutorial or class on using python to convert pdfs then using regex to create pd data frames.  Thanks to all of you out there who know what you're doing and take the time to help amatuers like me.  Mark


问:
how to compute a coordinate that forms a square around a GPS point given the max perimeter of square?
So the goal is that, when given a (lat, lng) point, which should form the center of square, and the max perimeter of the square in (in miles, km, etc.), output out:

```<code>[ (min_lat, min_lng), (max_lat, max_lng) ]
</code>```

Body:
So the goal is that, when given a (lat, lng) point, which should form the center of square, and the max perimeter of the square in (in miles, km, etc.), output out:

[ (min_lat, min_lng), (max_lat, max_lng) ]


问:
Automate SNAPSHOT isolation level for a particular SQL user
I need to have some users that are systematiically in the TRANSACTION ISOLATION LEVEL SNAPSHOT when they logs to the database.

I tried to use a LOGON trigger to set the user session to that isolation level when the ORIGINAL_LOGIN() was the user I wanted to promote... But this does not works...

I tried to see if it was possible to configure this in the ODBC connection strings.... but I found nothing

This is my actual code to test...

First part the source database :

```<code>CREATE DATABASE DB_SOURCE;
GO

ALTER DATABASE DB_SOURCE
   SET ALLOW_SNAPSHOT_ISOLATION ON;
GO

USE DB_SOURCE;
GO

CREATE TABLE T (C INT);
GO

INSERT INTO T VALUES (1), (2), (3);
GO`enter code here`
</code>```

Second part, the login and the user :

```<code>USE master;
GO

CREATE LOGIN CNX_USER_TEST
   WITH PASSWORD = 'foo',
        DEFAULT_DATABASE = DB_SOURCE;
GO

USE DB_SOURCE;
GO

CREATE USER USR_USER_TEST
   FROM LOGIN CNX_USER_TEST;
GO

GRANT SELECT TO USR_USER_TEST;
GO
</code>```

Third part, the logon trigger :

```<code>USE master;
GO

CREATE TRIGGER E_LOGON
ON ALL SERVER WITH EXECUTE AS N'sa'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()= N'CNX_USER_TEST'
BEGIN
   COMMIT;
   SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
END;
END;
</code>```

Fourth, the test...

In SSMS window 1 :

```<code>BEGIN TRAN ;

UPDATE T SET C = C + 1;
</code>```

In SSMS in another window connected with CNX_USER_TEST :

```<code>SELECT * FROM T;
</code>```

Blocked !

Body:
I need to have some users that are systematiically in the TRANSACTION ISOLATION LEVEL SNAPSHOT when they logs to the database.

I tried to use a LOGON trigger to set the user session to that isolation level when the ORIGINAL_LOGIN() was the user I wanted to promote... But this does not works...

I tried to see if it was possible to configure this in the ODBC connection strings.... but I found nothing

This is my actual code to test...

First part the source database :

CREATE DATABASE DB_SOURCE;
GO

ALTER DATABASE DB_SOURCE
   SET ALLOW_SNAPSHOT_ISOLATION ON;
GO

USE DB_SOURCE;
GO

CREATE TABLE T (C INT);
GO

INSERT INTO T VALUES (1), (2), (3);
GO`enter code here`

Second part, the login and the user :

USE master;
GO

CREATE LOGIN CNX_USER_TEST
   WITH PASSWORD = 'foo',
        DEFAULT_DATABASE = DB_SOURCE;
GO

USE DB_SOURCE;
GO

CREATE USER USR_USER_TEST
   FROM LOGIN CNX_USER_TEST;
GO

GRANT SELECT TO USR_USER_TEST;
GO

Third part, the logon trigger :

USE master;
GO

CREATE TRIGGER E_LOGON
ON ALL SERVER WITH EXECUTE AS N'sa'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()= N'CNX_USER_TEST'
BEGIN
   COMMIT;
   SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
END;
END;

Fourth, the test...

In SSMS window 1 :

BEGIN TRAN ;

UPDATE T SET C = C + 1;

In SSMS in another window connected with CNX_USER_TEST :

SELECT * FROM T;

Blocked !


问:
How to read values from nested dataset in TFDMongoQuery
I'm reading data from a MongoDB. Here is the data:

```<code>[{
  "_id": "100",
  "v": [
    {
      "length": 1,
      "path": "1.txt"
    },
    {
      "length": 2,
      "path": "2.txt"
    },
    {
      "length": 3,
      "path": "3.txt"
    },
    {
      "length": 4,
      "path": "4.txt"
    }
  ]
}]
</code>```

It is easy to read _id but not 1.txt, 2.txt and 3.txt. Here is my code:

```<code>    // fdMongQuery = TFDMongoQuery
        // dataset = TDataset

        fdMongQuery.Close;
        fdMongQuery.FieldDefs.Clear;
        fdMongQuery.Connection := fdCon;
        fdMongQuery.DatabaseName := 'DATABASE';
        fdMongQuery.CollectionName := 'COLLECTION';

        fdMongQuery.QMatch := '{_id:"100"}';
        fdMongQuery.QSort := '';
        fdMongQuery.Open;

        // read of id
    memoLogs.Lines.Add(fdMongQuery.FieldByName('_id').AsString);

    // read of detail
    dataset := TDataSetField(fdMongQuery.FieldByName('v')).NestedDataSet;
    while not dataset.Eof do
    begin
      memoLogs.Lines.Add(dataset.Fields[0].AsString);
      // output is:
//         (1, 1.txt)
//         (2, 2.txt)
//         (3, 3.txt)

      dataset.Next;
    end;
</code>```

I am expecting dataset.Fields[0].AsString should ouput 1 while dataset.Fields[1].AsString should output 1.txt but sadly no. So how can I read the path values?

Body:
I'm reading data from a MongoDB. Here is the data:

[{
  "_id": "100",
  "v": [
    {
      "length": 1,
      "path": "1.txt"
    },
    {
      "length": 2,
      "path": "2.txt"
    },
    {
      "length": 3,
      "path": "3.txt"
    },
    {
      "length": 4,
      "path": "4.txt"
    }
  ]
}]

It is easy to read _id but not 1.txt, 2.txt and 3.txt. Here is my code:

    // fdMongQuery = TFDMongoQuery
        // dataset = TDataset

        fdMongQuery.Close;
        fdMongQuery.FieldDefs.Clear;
        fdMongQuery.Connection := fdCon;
        fdMongQuery.DatabaseName := 'DATABASE';
        fdMongQuery.CollectionName := 'COLLECTION';

        fdMongQuery.QMatch := '{_id:"100"}';
        fdMongQuery.QSort := '';
        fdMongQuery.Open;

        // read of id
    memoLogs.Lines.Add(fdMongQuery.FieldByName('_id').AsString);

    // read of detail
    dataset := TDataSetField(fdMongQuery.FieldByName('v')).NestedDataSet;
    while not dataset.Eof do
    begin
      memoLogs.Lines.Add(dataset.Fields[0].AsString);
      // output is:
//         (1, 1.txt)
//         (2, 2.txt)
//         (3, 3.txt)

      dataset.Next;
    end;

I am expecting dataset.Fields[0].AsString should ouput 1 while dataset.Fields[1].AsString should output 1.txt but sadly no. So how can I read the path values?


问:
Secret-Agent, not working as intended with Bree.js
I'm using Secret-Agent, to test out some web scraping. When I manually run the node script, the script works as intended. [see screenshot].

When I run the same script with pm2 it crashes on 'await' commands.
pm2 start bree.js --watch

```<code>import { Browser, logger } from './../tools.js';

(async () => {
    logger('Browser 1');

    await Browser.goto('https://sample.com');

    logger('Browser 2');

    const title = await Browser.getElement('p');
    logger('Browser 3', title);

    await Browser.close();
})();
</code>```

Inside my Tools.js I'm using the code:

```<code>import agent from 'secret-agent';
class Scrape {
    constructor(friendlyName=null, config = {}) {
        // Set some init data
    }
    async goto(url) {
        logger(`goto >> ${url}`);
        this.url = url;

        try {
            const res = await agent.goto(url);
            const code = await res.response.statusCode;
            logger('statusCode', code);
            if (code === 200) {
                logger('goto >> statusCode === 200', res.response);
                return res
            } else {
                logger('goto >> ERROR statusCode, ', code);
            }

        } catch (e) {
            logger('goto >> ERROR > ', e);
            return false;
        }
    }
}
export let Browser = new Scrape();
</code>```

I keep getting this error, 116:25 is, const res = await agent.goto(url):

```<code>2022-12-29T21:06:42.576Z :: goto >> ERROR >  TypeError: Cannot read properties of null (reading 'goto')
    at Tab.goto (/secretagent/node_modules/client/lib/Tab.ts:160:36)
    at Scrape.goto (file:///secretagent/tools.js:116:25)
    at file:///secretagent/jobs/test.js:6:5
</code>```

Body:
I'm using Secret-Agent, to test out some web scraping. When I manually run the node script, the script works as intended. [see screenshot].

When I run the same script with pm2 it crashes on 'await' commands.
pm2 start bree.js --watch

import { Browser, logger } from './../tools.js';

(async () => {
    logger('Browser 1');

    await Browser.goto('https://sample.com');

    logger('Browser 2');

    const title = await Browser.getElement('p');
    logger('Browser 3', title);

    await Browser.close();
})();

Inside my Tools.js I'm using the code:

import agent from 'secret-agent';
class Scrape {
    constructor(friendlyName=null, config = {}) {
        // Set some init data
    }
    async goto(url) {
        logger(`goto >> ${url}`);
        this.url = url;

        try {
            const res = await agent.goto(url);
            const code = await res.response.statusCode;
            logger('statusCode', code);
            if (code === 200) {
                logger('goto >> statusCode === 200', res.response);
                return res
            } else {
                logger('goto >> ERROR statusCode, ', code);
            }

        } catch (e) {
            logger('goto >> ERROR > ', e);
            return false;
        }
    }
}
export let Browser = new Scrape();

I keep getting this error, 116:25 is, const res = await agent.goto(url):

2022-12-29T21:06:42.576Z :: goto >> ERROR >  TypeError: Cannot read properties of null (reading 'goto')
    at Tab.goto (/secretagent/node_modules/client/lib/Tab.ts:160:36)
    at Scrape.goto (file:///secretagent/tools.js:116:25)
    at file:///secretagent/jobs/test.js:6:5


问:
How can I use multiple classes in Model - MVC Java?
I am creating an app in Java and I am using the MVC architecture. I have the Model, View and Controller classes, and I have also another classes that help me with data. For example, I have the
next classes: Product, Store, Manager. How can I use the data in the Model class, I tried to copy paste my Classes and my code from main file, but all I have are errors.

In the second image I have the problems, the Model class. I really do not know what to do to make it work.


问:
Should I use firebase hosting redirects, rewrites or something else for my Angular internationalized versions of the application?
I am using Firebase to host my Angular app and recently I started migrating from ngx-translate to the angular way of i18n which is translation on build time. This creates a problem with the app because of the dynamic routing, e.g. localhost:4001/:clientId that should now be localhost:4001/{en,el}/:clientId.

The problem is that with some basic configuration, some patterns don't redirect correctly, for example if I ask for localhost:4001/en or localhost:4001/en/, it works. If I ask for localhost:4001/randomClientId, it rewrites it correctly as localhost:4001/en/randomClientId. But, if the clientId starts with en, then something weird happens, it rewrites it like so: localhost:4001/enXYZ => localhost:4001/en/XYZ instead of the expected (in my mind) localhost:4001/en/enXYZ.

Has anyone gone through something similar? Should I be using rewrites, redirects or something else entirely?

I have compiled 2 versions of my Angular app that sit in the following directory:

```<code>+ dist/
| + main-web/
| | + en/
| | | [ app files in English ]
| | + el/
| | | [ app files in Greek ]
</code>```

I don't have a main index.html like the Firebase examples, I just have the 2 translated versions.

My firebase.json config is like so:

```<code>{
  "hosting": {
    "public": "dist/main-web",
    "appAssociation": "AUTO",
    "rewrites": [
      {
        "source": "/links/**",
        "dynamicLinks": true
      },
      {
        "source": "/en/**",
        "destination": "/en/index.html"
      },
      {
        "source": "/en",
        "destination": "/en/index.html"
      },
      {
        "source": "/el/**",
        "destination": "/el/index.html"
      },
      {
        "source": "/el",
        "destination": "/el/index.html"
      },
      {
        "source": "**",
        "destination": "/en/index.html"
      }
    ],
    "i18n": { "root": "/" }
  }
}

</code>```

Last thing I've noticed is that with disabled JS, nothing happens. So firebase hosting emulator doesn't do much I assume? The hosting part in firebase.json writes a JS router? I've enabled angular router tracing to see if it had to do anything with that, but no.

Almost everything works with this, apart from the clientId starting with en. I haven't used glob patterns before so if you could also help me minimize the last 5 rewrites that would be awesome!

Body:
I am using Firebase to host my Angular app and recently I started migrating from ngx-translate to the angular way of i18n which is translation on build time. This creates a problem with the app because of the dynamic routing, e.g. localhost:4001/:clientId that should now be localhost:4001/{en,el}/:clientId.

The problem is that with some basic configuration, some patterns don't redirect correctly, for example if I ask for localhost:4001/en or localhost:4001/en/, it works. If I ask for localhost:4001/randomClientId, it rewrites it correctly as localhost:4001/en/randomClientId. But, if the clientId starts with en, then something weird happens, it rewrites it like so: localhost:4001/enXYZ => localhost:4001/en/XYZ instead of the expected (in my mind) localhost:4001/en/enXYZ.

Has anyone gone through something similar? Should I be using rewrites, redirects or something else entirely?

I have compiled 2 versions of my Angular app that sit in the following directory:

+ dist/
| + main-web/
| | + en/
| | | [ app files in English ]
| | + el/
| | | [ app files in Greek ]

I don't have a main index.html like the Firebase examples, I just have the 2 translated versions.

My firebase.json config is like so:

{
  "hosting": {
    "public": "dist/main-web",
    "appAssociation": "AUTO",
    "rewrites": [
      {
        "source": "/links/**",
        "dynamicLinks": true
      },
      {
        "source": "/en/**",
        "destination": "/en/index.html"
      },
      {
        "source": "/en",
        "destination": "/en/index.html"
      },
      {
        "source": "/el/**",
        "destination": "/el/index.html"
      },
      {
        "source": "/el",
        "destination": "/el/index.html"
      },
      {
        "source": "**",
        "destination": "/en/index.html"
      }
    ],
    "i18n": { "root": "/" }
  }
}

Last thing I've noticed is that with disabled JS, nothing happens. So firebase hosting emulator doesn't do much I assume? The hosting part in firebase.json writes a JS router? I've enabled angular router tracing to see if it had to do anything with that, but no.

Almost everything works with this, apart from the clientId starting with en. I haven't used glob patterns before so if you could also help me minimize the last 5 rewrites that would be awesome!


问:
jinja2: Exclude or reject items from template on include
Thanks in advance to anyone looking at this. I'm new to jinja and am trying to test something with the following 3 simple files:

pipe.j2:

```<code>{% include 'resources.yml' %}
</code>```

resources.yml:

resources:
- name: resource1
  type: aThing

- name: resource2
  type: anotherThing
```
<p>test.sh</p>
<pre class="lang-bash prettyprint-override"><code>j2 pipe.j2 > pipeline.yml
</code>```

The test.sh script runs fine, but i'm trying to exclude either of the resources in the resources.yml file. I've tried the following in the j2 file getting different errors:

example1:

```<code>{% include 'resources.yml' | reject('equalto','resource1') %}
TypeError: generator is not subscriptable
</code>```

example2:

```<code>{% include 'resources.yml' %}
{% set r_list = 'resources' %}
{% for rsc in r_list | rejectattr('name', 'equalto', 'resource1') %}
{% endfor %}

UndefinedError: 'str.object' has no attribute 'name'
</code>```

I checked online and haven't found any examples of what I'm trying to accomplish and am not sure if it's possible or if I'm doing it completely wrong. I'm trying to get a file that only contains non-rejected items as a final result.

Hoping to get in pipeline.yml file:

resources:
- name: resource2
  type: anotherThing
```

Body:
Thanks in advance to anyone looking at this. I'm new to jinja and am trying to test something with the following 3 simple files:

pipe.j2:

{% include 'resources.yml' %}

resources.yml:

resources:
- name: resource1
  type: aThing

- name: resource2
  type: anotherThing

test.sh

j2 pipe.j2 > pipeline.yml

The test.sh script runs fine, but i'm trying to exclude either of the resources in the resources.yml file. I've tried the following in the j2 file getting different errors:

example1:

{% include 'resources.yml' | reject('equalto','resource1') %}
TypeError: generator is not subscriptable

example2:

{% include 'resources.yml' %}
{% set r_list = 'resources' %}
{% for rsc in r_list | rejectattr('name', 'equalto', 'resource1') %}
{% endfor %}

UndefinedError: 'str.object' has no attribute 'name'

I checked online and haven't found any examples of what I'm trying to accomplish and am not sure if it's possible or if I'm doing it completely wrong. I'm trying to get a file that only contains non-rejected items as a final result.

Hoping to get in pipeline.yml file:

resources:
- name: resource2
  type: anotherThing


问:
Computing % return using groupby returns NaN
I have a dataframe that looks like this

```<code>       city    Year  Asset_Type  TotalTransac  NbBiens     psqm_city
0    Agadir  2010.0      Appart          3225     3156   6276.923077
1    Agadir  2010.0  Maison_Dar            37       37   8571.428571
2    Agadir  2010.0       Villa           107      103   6279.469027
3    Agadir  2011.0      Appart          2931     2816   6516.853933
4    Agadir  2011.0  Maison_Dar            33       32   9000.000000
..      ...     ...         ...           ...      ...           ...
171  Tanger  2019.0  Maison_Dar           268      263  12158.385093
172  Tanger  2020.0      Appart          5223     5180   5760.869565
173  Tanger  2020.0  Maison_Dar           193      192  13500.000000
</code>```

I am trying to compute the % return by Asset_Type using the following function:

```<code>Index_byCity["Returns"] = Index_byCity.groupby(['city','Year','Asset_Type'])['psqm_city'].apply(lambda x: (x - x.shift(1))-1 )
</code>```

But i get an unexpected output

```<code>0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
       ..
171   NaN
172   NaN
173   NaN
174   NaN
175   NaN
Name: Returns, Length: 176, dtype: float64
</code>```

I don't understand why iam getting this output since dtype shows psqm_city as a float.

```<code>city             object
Year            float64
Asset_Type       object
TotalTransac      int64
NbBiens           int64
psqm_city       float64
dtype: object
</code>```

Can someone help please

Body:
I have a dataframe that looks like this

       city    Year  Asset_Type  TotalTransac  NbBiens     psqm_city
0    Agadir  2010.0      Appart          3225     3156   6276.923077
1    Agadir  2010.0  Maison_Dar            37       37   8571.428571
2    Agadir  2010.0       Villa           107      103   6279.469027
3    Agadir  2011.0      Appart          2931     2816   6516.853933
4    Agadir  2011.0  Maison_Dar            33       32   9000.000000
..      ...     ...         ...           ...      ...           ...
171  Tanger  2019.0  Maison_Dar           268      263  12158.385093
172  Tanger  2020.0      Appart          5223     5180   5760.869565
173  Tanger  2020.0  Maison_Dar           193      192  13500.000000

I am trying to compute the % return by Asset_Type using the following function:

Index_byCity["Returns"] = Index_byCity.groupby(['city','Year','Asset_Type'])['psqm_city'].apply(lambda x: (x - x.shift(1))-1 )

But i get an unexpected output

0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
       ..
171   NaN
172   NaN
173   NaN
174   NaN
175   NaN
Name: Returns, Length: 176, dtype: float64

I don't understand why iam getting this output since dtype shows psqm_city as a float.

city             object
Year            float64
Asset_Type       object
TotalTransac      int64
NbBiens           int64
psqm_city       float64
dtype: object

Can someone help please


问:
Error: Invalid constructor input for SearchGoogleAdsRequest
I am trying to execute an Airflow Dag using the GoogleAdsToGcsOperator, and I am getting this error:

Failed to execute job 1874 for task run_operator (Invalid constructor input for SearchGoogleAdsRequest: customer_id: "xxxxxxx"
query: "SELECT campaign.id, ad_group.id, ad_group.name FROM ad_group"
page_size: 10000
; 13968)
I am using this image version "composer-2.1.2-airflow-2.3.4"

Do someone knows how to solve this error?


问:
Svelte with rxjs Observable in object property
I'm trying to use an rxjs Observable in Svelte rendering.  I understand I can do that :

```<code><span>{$myObservable}</span>
</code>```

but what if myObservable is inside an object:

```<code><span>{$myObject.myObservable}</span>
</code>```

the "$" now gives me the error :

(Stores must be declared at the top level of the component (this may
change in a future version of Svelte)

Anyone has a workaround for that?

Example here :
https://stackblitz.com/edit/testsveltebindrxjs?file=src%2FApp.svelte&terminal=dev

Body:
I'm trying to use an rxjs Observable in Svelte rendering.  I understand I can do that :

{$myObservable}

but what if myObservable is inside an object:

{$myObject.myObservable}

the "$" now gives me the error :

(Stores must be declared at the top level of the component (this may
change in a future version of Svelte)

Anyone has a workaround for that?

Example here :
https://stackblitz.com/edit/testsveltebindrxjs?file=src%2FApp.svelte&terminal=dev


问:
Downloading file in firebase storage blocked by CORs
I currently handle the uploading of files/images to cloud storage on the back end using busboy and store the url on the user's document.  On the front end, I would like users to be able to download their files. I am currently passing in the url/filename and making an XMLHttpRequest().  It works locally, but in production the request is being blocked by cors.  Is there a way to ensure the request goes through in production and no longer is blocked by cors?  The function below is currently handling the download request.</p>
```<code>  const handleDownload = (url, filename) => {
    const xhr = new XMLHttpRequest()
    xhr.responseType = 'blob'
    xhr.onload = function () {
      var a = document.createElement('a')
      a.href = window.URL.createObjectURL(xhr.response)
      a.download = filename
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
    }
    xhr.open('GET', url)
    xhr.send()
  }
</code>```

Body:
I currently handle the uploading of files/images to cloud storage on the back end using busboy and store the url on the user's document.  On the front end, I would like users to be able to download their files. I am currently passing in the url/filename and making an XMLHttpRequest().  It works locally, but in production the request is being blocked by cors.  Is there a way to ensure the request goes through in production and no longer is blocked by cors?  The function below is currently handling the download request.

  const handleDownload = (url, filename) => {
    const xhr = new XMLHttpRequest()
    xhr.responseType = 'blob'
    xhr.onload = function () {
      var a = document.createElement('a')
      a.href = window.URL.createObjectURL(xhr.response)
      a.download = filename
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
    }
    xhr.open('GET', url)
    xhr.send()
  }


问:
Embedded video is not appearing in extent spark report
I have an issue viewing attached videos to cucumber extent report. I can see the attached videos shown in cucumber report.

```<code>File video = new File("file_example_MP4_640_3MG.mp4");
byte[] videoAttachment = Files.toByteArray(video);
scenario.attach(videoAttachment, "video/mp4", "video");
</code>```

But in extent spark report which is generated does not have the videos embedded. Only screenshots are displayed in that report. Has anyone tried this before?

```<code><dependency>
<groupId>tech.grasshopper</groupId>
<artifactId>extentreports-cucumber7-adapter</artifactId>
<version>1.9.2</version>
</dependency>
</code>```

Body:
I have an issue viewing attached videos to cucumber extent report. I can see the attached videos shown in cucumber report.

File video = new File("file_example_MP4_640_3MG.mp4");
byte[] videoAttachment = Files.toByteArray(video);
scenario.attach(videoAttachment, "video/mp4", "video");

But in extent spark report which is generated does not have the videos embedded. Only screenshots are displayed in that report. Has anyone tried this before?

<dependency>
<groupId>tech.grasshopper</groupId>
<artifactId>extentreports-cucumber7-adapter</artifactId>
<version>1.9.2</version>
</dependency>


问:
AWS ECS Fargate request not reaching task container
So I setup a aws ecs cluster to run a docker image of Valhalla service almost as-is.

Issue : target group seems to be not able to check for cluster health, like if the health request was reaching the cluster, but container is not "forwarding" the request to Valhalla.

Description :

I created a repository on AWS ECR, and pushed a docker image of gisops/valhalla with only the valhalla.json file changed.
Here is the valhalla configuration I used.
Note that I changed the default listening port from 8002 to 80.

I created a ECS Fargate cluster, and a service that uses this task definition to launch a container that runs Valhalla.

The service receives traffic from an application load balancer via port 80.
The target group is checking /status path on port 80.

All set, the task is then creating, and task logs shows that Valhalla is initializing perfectly and running.

However the target group is not able to check for health status : the request seems to timeout.
If the request was reaching valhalla, the task logs would have at least show it (because valhalla logs every incoming request by default), but it doesn't.

Therefore fargate kills the task (Task failed ELB health checks in (target-group {my-target-group-uri})) (showing that the health request was reaching the cluster service indeed)

I don't think the issue is with the valhalla configuration, because I can run the same docker image locally, and it works perfectly, using :

```<code>docker run -dt -p 3000:80 -v /local/path/to/valhalla-files:/custom_files/ --name valhalla gisops/valhalla:latest
</code>```

And then checking localhost:3000/status

Anyone has an idea of what could be the issue ?

Already spent a lot of time on this, and I'm out of ideas. Thanks for your help !

Body:
So I setup a aws ecs cluster to run a docker image of Valhalla service almost as-is.

Issue : target group seems to be not able to check for cluster health, like if the health request was reaching the cluster, but container is not "forwarding" the request to Valhalla.

Description :

I created a repository on AWS ECR, and pushed a docker image of gisops/valhalla with only the valhalla.json file changed.
Here is the valhalla configuration I used.
Note that I changed the default listening port from 8002 to 80.

I created a ECS Fargate cluster, and a service that uses this task definition to launch a container that runs Valhalla.

The service receives traffic from an application load balancer via port 80.
The target group is checking /status path on port 80.

All set, the task is then creating, and task logs shows that Valhalla is initializing perfectly and running.

However the target group is not able to check for health status : the request seems to timeout.
If the request was reaching valhalla, the task logs would have at least show it (because valhalla logs every incoming request by default), but it doesn't.

Therefore fargate kills the task (Task failed ELB health checks in (target-group {my-target-group-uri})) (showing that the health request was reaching the cluster service indeed)

I don't think the issue is with the valhalla configuration, because I can run the same docker image locally, and it works perfectly, using :

docker run -dt -p 3000:80 -v /local/path/to/valhalla-files:/custom_files/ --name valhalla gisops/valhalla:latest

And then checking localhost:3000/status

Anyone has an idea of what could be the issue ?

Already spent a lot of time on this, and I'm out of ideas. Thanks for your help !


问:
How to host a Blazor ServerSide app on a VPS
I'm experimenting with the Blazor Server App and want to host it on my own VPS. I followed about every official documentation there is, but I can't get it to work.

VPS info:

Runs on Hostinger -> Ubuntu 18.04 64bit with Webmin

Installed all required dotnet versions on VPS:

When creating a test index.html and place it inside var\www\html\ it can be accessed through a browser and the content is shown

Blazor Server App info:

Start a new project > Blazor Server App > Publish > Local folder

Copy files from bin\release\netcoreapp3.1\publish* into VPS\var\www\html\

The files can be seen when browsing, but nothing executes

What am I missing here? How can what I want to do be done?

I was expecting the application to run, just like it did when executing it in Visual Studio.

I followed this tutorial based on a similar question
https://www.jeremymorgan.com/blog/linux/blazor-in-linux/, but I'm not using CentOS so it did not help much.