问:
WPF Interaction.Triggers not working with AutoCompleteBox
I am trying to use the AutoCompleteBox from the NuGet package DotNetProjects.WpfToolkit.Input. The Github repository for the WpfToolkit is https://github.com/dotnetprojects/WpfToolkit

Everything in the AutoCompleteBox works very well, with one exception.

When you start typing in the control, it fires a "Populating" event.  I can handle this event fine with an event handler in the code behind.
However, if I try to use Interaction.Triggers to redirect the event to a command in my view-model class, the function is not called.

I have stripped the code down to a bare minimum.

NuGet packages

CommunityToolkit.Mvvm

DotNetProjects.WpfToolkit.Input

Microsoft.Xaml.Behaviors.Wpf

Xaml code

```<code><Window x:Class="AutoCompleteTestMvvm.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:input="clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="300">
  <Grid>
    <input:AutoCompleteBox Width="200" Height="24" Populating="AutoCompleteBox_Populating">
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="Populating">
          <i:InvokeCommandAction Command="{Binding PopulateComand}"/>
        </i:EventTrigger>
      </i:Interaction.Triggers>
    </input:AutoCompleteBox>
  </Grid>
</Window>
</code>```

Code behind

```<code>using System.Windows;
using System.Windows.Controls;

namespace AutoCompleteTestMvvm
{
  public partial class MainWindow : Window
  {
    private ViewModel _vm ;

    public MainWindow()
    {
      InitializeComponent ();
      _vm = DataContext as ViewModel;
    }

    private void AutoCompleteBox_Populating( object sender, PopulatingEventArgs e )
    {
      // This event handler gets called
      MessageBox.Show ( "Populating event in code behind" ) ;
    }
  }
}
</code>```

View Model

```<code>using CommunityToolkit.Mvvm.ComponentModel;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;

namespace AutoCompleteTestMvvm
{
  internal class ViewModel : ObservableObject
  {
    public ICommand PopulateCommand { get; private set; }

    public ViewModel()
    {
      PopulateCommand = new RelayCommand ( Populate );
    }

    public void Populate()
    {
      // This method does not get called
      System.Windows.MessageBox.Show ( "Populating command in view model" );
    }
  }
}
</code>```

In this example, the Populating event is handled in two ways:

via the event handler AutoCompleteBox_Populating in the code behind

via the EventTrigger which should invoke the command Populate in the view model

The event handler in the code behind is invoked correctly, so I an certain that the event is being generated.

The command in the code behind is not invoked.

What am I getting wrong?

Body:
I am trying to use the AutoCompleteBox from the NuGet package DotNetProjects.WpfToolkit.Input. The Github repository for the WpfToolkit is https://github.com/dotnetprojects/WpfToolkit

Everything in the AutoCompleteBox works very well, with one exception.

When you start typing in the control, it fires a "Populating" event.  I can handle this event fine with an event handler in the code behind.
However, if I try to use Interaction.Triggers to redirect the event to a command in my view-model class, the function is not called.

I have stripped the code down to a bare minimum.

NuGet packages

CommunityToolkit.Mvvm

DotNetProjects.WpfToolkit.Input

Microsoft.Xaml.Behaviors.Wpf

Xaml code

<Window x:Class="AutoCompleteTestMvvm.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:input="clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="300">
  <Grid>
    <input:AutoCompleteBox Width="200" Height="24" Populating="AutoCompleteBox_Populating">

    </input:AutoCompleteBox>
  </Grid>
</Window>

Code behind

using System.Windows;
using System.Windows.Controls;

namespace AutoCompleteTestMvvm
{
  public partial class MainWindow : Window
  {
    private ViewModel _vm ;

    public MainWindow()
    {
      InitializeComponent ();
      _vm = DataContext as ViewModel;
    }

    private void AutoCompleteBox_Populating( object sender, PopulatingEventArgs e )
    {
      // This event handler gets called
      MessageBox.Show ( "Populating event in code behind" ) ;
    }
  }
}

View Model

using CommunityToolkit.Mvvm.ComponentModel;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;

namespace AutoCompleteTestMvvm
{
  internal class ViewModel : ObservableObject
  {
    public ICommand PopulateCommand { get; private set; }

    public ViewModel()
    {
      PopulateCommand = new RelayCommand ( Populate );
    }

    public void Populate()
    {
      // This method does not get called
      System.Windows.MessageBox.Show ( "Populating command in view model" );
    }
  }
}

In this example, the Populating event is handled in two ways:

via the event handler AutoCompleteBox_Populating in the code behind

via the EventTrigger which should invoke the command Populate in the view model

The event handler in the code behind is invoked correctly, so I an certain that the event is being generated.

The command in the code behind is not invoked.

What am I getting wrong?


来源: stackexchange

问:
yt-dl command to download audio files - in a python script
I want to convert this command into a python call:

```<code>yt-dlp --continue --no-overwrites --extract-audio --audio-format mp3 -o "ST_%(upload_date)s_%(title).50s.%(ext)s" https://www.youtube.com/channel/UCYt3jqP4rRP2rr5Ye8fs0LQ/videos --playlist-reverse --restrict-filenames   --add-metadata --postprocessor-args "-metadata albumartist=rAmAnuja-dayA" --download-archive ./ytdl-archive.txt
</code>```

The python call will look something like:

```<code>  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    error_code = ydl.download([url])
</code>```

What should my options dict look like? Here is a start (not sure if it is right):

```<code>ydl_opts_base = {
  'format': 'm4a/bestaudio/best',
  # ℹ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
  'postprocessors': [{  # Extract audio using ffmpeg
    'key': 'FFmpegExtractAudio',
    'preferredcodec': 'm4a',
  }],
  'verbose': True, # Useful for checking if we have the latest version.
  'playlistreverse': True,
  'restrictfilenames': True,
  "nooverwrites": True,
  "continuedl": True,
  "outtmpl": {"default": "ST_%(upload_date)s_%(title).50s.mp3"}
}
ydl_opts = copy(ydl_opts_base)
ydl_opts.update(options_dict)
ydl_opts["paths"] = {"home": dest_dir}
ydl_opts["download_archive"] = os.path.join(dest_dir, "ytdl-archive.txt")

ydl_opts['postprocessor_args'] = {"metadata": {"albumartist": "rAmAnuja-dayA"}}

</code>```

(This works with the latest version of yt-dl - downloads an mp3.)

ContentLicense: CC BY-SA 4.0

Body:
I want to convert this command into a python call:

yt-dlp --continue --no-overwrites --extract-audio --audio-format mp3 -o "ST_%(upload_date)s_%(title).50s.%(ext)s" https://www.youtube.com/channel/UCYt3jqP4rRP2rr5Ye8fs0LQ/videos --playlist-reverse --restrict-filenames   --add-metadata --postprocessor-args "-metadata albumartist=rAmAnuja-dayA" --download-archive ./ytdl-archive.txt

The python call will look something like:

  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    error_code = ydl.download([url])

What should my options dict look like? Here is a start (not sure if it is right):

ydl_opts_base = {
  'format': 'm4a/bestaudio/best',
  # ℹ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
  'postprocessors': [{  # Extract audio using ffmpeg
    'key': 'FFmpegExtractAudio',
    'preferredcodec': 'm4a',
  }],
  'verbose': True, # Useful for checking if we have the latest version.
  'playlistreverse': True,
  'restrictfilenames': True,
  "nooverwrites": True,
  "continuedl": True,
  "outtmpl": {"default": "ST_%(upload_date)s_%(title).50s.mp3"}
}
ydl_opts = copy(ydl_opts_base)
ydl_opts.update(options_dict)
ydl_opts["paths"] = {"home": dest_dir}
ydl_opts["download_archive"] = os.path.join(dest_dir, "ytdl-archive.txt")

ydl_opts['postprocessor_args'] = {"metadata": {"albumartist": "rAmAnuja-dayA"}}

(This works with the latest version of yt-dl - downloads an mp3.)


问:
Massive load time of over 15 secs of React App on Mobile browser
I have deployed an app on React but the load time on mobile browsers is over 17 secs? and on web is about 6 seconds. Not sure where to look at is it an issue with setup, compresion or the theme used in building the platform. https://app.latom.in/co/getlocal

Any thoughts?

Thanks


问:
How do I track a UPI transaction by transaction id

Get payment status from transaction id

Can I track / find payment status by transaction id on upi apps like google pay, phonepe etc..

I am asking, can any one (Public) view the transaction status by transaction id

Thanks.

I am asking, can any one (Public) view the transaction status by transaction id


问:
How to set an alias in powershell that has parameters?
I want to set an alias in powershell to compile my c++ file using the command

g++ -std=c++17 -O2 any_file_name.cpp -o any_file_name -Wall

I want to map this command to "co" so that when I type any co any_file_name it should compile. Is there a way of doing this ?


问:
I am trying to analyze accelerometer data using the GGIR package but getting error attached below
I am trying to analyze accelerometer data using the GGIR package. The file is available in location datadir.

The error is :

No files to analyze. Check that there are accelerometer files in the directory specified with argument data-dir

The code is :

```<code>GGIR(datadir="C:/Users/admin/Downloads/given", outputdir="C:/Users/admin/Downloads/out",f0=1,f1=1)
</code>```

Body:
I am trying to analyze accelerometer data using the GGIR package. The file is available in location datadir.

The error is :

No files to analyze. Check that there are accelerometer files in the directory specified with argument data-dir

The code is :

GGIR(datadir="C:/Users/admin/Downloads/given", outputdir="C:/Users/admin/Downloads/out",f0=1,f1=1)


问:
ERROR in ../node_modules/@tensorflow-models/pose-detection/dist/pose-detection.esm.js
While running my project, I got the below 3 errors

```<code>ERROR in ../node_modules/@tensorflow-models/pose-detection/dist/pose-detection.esm.js 18:0-452
Module not found: Error: Can't resolve '@tensorflow/tfjs-core' in 'C:\Users\hp\Desktop\node_modules\@tensorflow-models\poose-detection\dist'

ERROR in ../node_modules/@tensorflow-models/pose-detection/dist/pose-detection.esm.js 19:0-65
Module not found: Error: Can't resolve '@tensorflow/tfjs-converter' in 'C:\Users\hp\Desktop\node_modules\@tensorflow-modeels\pose-detection\dist'

ERROR in ./src/pages/Yoga/Yoga.js 108:56-88
export 'Supporteds' (imported as 'poseDetection') was not found in '@tensorflow-models/pose-detection' (possible exports:: SupportedModels, TrackerType, calculators, createDetector, movenet, util)
</code>```

Can anyone please help to solve these errors?

Body:
While running my project, I got the below 3 errors

ERROR in ../node_modules/@tensorflow-models/pose-detection/dist/pose-detection.esm.js 18:0-452
Module not found: Error: Can't resolve '@tensorflow/tfjs-core' in 'C:\Users\hp\Desktop\node_modules\@tensorflow-models\poose-detection\dist'

ERROR in ../node_modules/@tensorflow-models/pose-detection/dist/pose-detection.esm.js 19:0-65
Module not found: Error: Can't resolve '@tensorflow/tfjs-converter' in 'C:\Users\hp\Desktop\node_modules\@tensorflow-modeels\pose-detection\dist'

ERROR in ./src/pages/Yoga/Yoga.js 108:56-88
export 'Supporteds' (imported as 'poseDetection') was not found in '@tensorflow-models/pose-detection' (possible exports:: SupportedModels, TrackerType, calculators, createDetector, movenet, util)

Can anyone please help to solve these errors?


问:
Python equivalent for Matlab function 'net' (custom shallow neural network)?
I am learning python and having to convert my matlab code into python, in matlab i used the function 'net(numInputs, numLayers)' (https://www.mathworks.com/help/deeplearning/ref/network.html;jsessionid=0e697784e952dce49d61aa6400d3) to create a network and am looking to find an equivalent function to produce the same network in python.

Ive seen plenty of post about creating a custom shallow neural network from scratch as well as using keras to build one but they seem too advanced for my understanding as im still fairly new to python, was hoping there is a simpler way as with matlab.


问:
Heroku app won't restart after error 14 (Memory quota exceeded)
We have a Django app deployed on Heroku with the following Procfile:

```<code>release: python manage.py migrate
web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug
celery: celery -A RDHQ worker -l info
</code>```

Yesterday the app was down and accessing the site returned ERR_CONNECTION_TIMED_OUT.

When I looked at the logs, I saw that the celery process was showing an R14 (Memory usage exceeded) error:

```<code>2022-12-24T07:14:46.771299+00:00 heroku[celery.1]: Process running mem=526M(102.7%)
2022-12-24T07:14:46.772983+00:00 heroku[celery.1]: Error R14 (Memory quota exceeded)
</code>```

I restarted the dynos a couple of times, but the celery dyno immediately throws the same error after restart.

I then removed the celery process entirely from my Procfile:

```<code>release: python manage.py migrate
web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug
</code>```

After I pushed the new Procfile to Heroku, the app is still down!

I tried manually scaling down the web dyno and then scaling it up again - nothing.

This is what the logs show:

```<code>2022-12-24T07:57:26.757537+00:00 app[web.1]: [2022-12-24 07:57:26 +0000] [12] [DEBUG] Closing connection.
2022-12-24T07:57:53.000000+00:00 app[heroku-postgres]: source=HEROKU_POSTGRESQL_SILVER addon=postgresql-reticulated-80597 sample#current_transaction=796789 sample#db_size=359318383bytes sample#tables=173 sample#active-connections=12 sample#waiting-connections=0 sample#index-cache-hit-rate=0.99972 sample#table-cache-hit-rate=0.99943 sample#load-avg-1m=0.01 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0.076923 sample#tmp-disk-used=543600640 sample#tmp-disk-available=72435191808 sample#memory-total=8038324kB sample#memory-free=3006824kB sample#memory-cached=4357424kB sample#memory-postgres=25916kB sample#wal-percentage-used=0.06576949341778418
2022-12-24T07:59:26.615551+00:00 app[web.1]: [2022-12-24 07:59:26 +0000] [12] [DEBUG] GET /us/first-aid-cover/california/
2022-12-24T07:59:28.421560+00:00 app[web.1]: 10.1.23.217 - - [24/Dec/2022:07:59:28 +0000] "GET /us/first-aid-cover/california/?order_by=title HTTP/1.1" 200 4380 "-" "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)"
2022-12-24T07:59:28.420775+00:00 heroku[router]: at=info method=GET path= "/us/first-aid-cover/california/?order_by=title" host=www.racedirectorshq.com request_id=c0d1bc3f-90ad-4b5d-ac2b-edaf4d777e26 fwd="54.36.149.50" dyno=web.1 connect=0ms service=1806ms status=200 bytes=4991 protocol=https
2022-12-24T07:59:34.952805+00:00 app[web.1]: [2022-12-24 07:59:34 +0000] [12] [DEBUG] Closing connection.
</code>```

I'm totally at a loss as to how to fix this and our app has been down for almost a day now. Please help.

EDIT: It was a DNS issue in the end. Fixed.

Body:
We have a Django app deployed on Heroku with the following Procfile:

release: python manage.py migrate
web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug
celery: celery -A RDHQ worker -l info

Yesterday the app was down and accessing the site returned ERR_CONNECTION_TIMED_OUT.

When I looked at the logs, I saw that the celery process was showing an R14 (Memory usage exceeded) error:

2022-12-24T07:14:46.771299+00:00 heroku[celery.1]: Process running mem=526M(102.7%)
2022-12-24T07:14:46.772983+00:00 heroku[celery.1]: Error R14 (Memory quota exceeded)

I restarted the dynos a couple of times, but the celery dyno immediately throws the same error after restart.

I then removed the celery process entirely from my Procfile:

release: python manage.py migrate
web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug

After I pushed the new Procfile to Heroku, the app is still down!

I tried manually scaling down the web dyno and then scaling it up again - nothing.

This is what the logs show:

2022-12-24T07:57:26.757537+00:00 app[web.1]: [2022-12-24 07:57:26 +0000] [12] [DEBUG] Closing connection.
2022-12-24T07:57:53.000000+00:00 app[heroku-postgres]: source=HEROKU_POSTGRESQL_SILVER addon=postgresql-reticulated-80597 sample#current_transaction=796789 sample#db_size=359318383bytes sample#tables=173 sample#active-connections=12 sample#waiting-connections=0 sample#index-cache-hit-rate=0.99972 sample#table-cache-hit-rate=0.99943 sample#load-avg-1m=0.01 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0.076923 sample#tmp-disk-used=543600640 sample#tmp-disk-available=72435191808 sample#memory-total=8038324kB sample#memory-free=3006824kB sample#memory-cached=4357424kB sample#memory-postgres=25916kB sample#wal-percentage-used=0.06576949341778418
2022-12-24T07:59:26.615551+00:00 app[web.1]: [2022-12-24 07:59:26 +0000] [12] [DEBUG] GET /us/first-aid-cover/california/
2022-12-24T07:59:28.421560+00:00 app[web.1]: 10.1.23.217 - - [24/Dec/2022:07:59:28 +0000] "GET /us/first-aid-cover/california/?order_by=title HTTP/1.1" 200 4380 "-" "Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)"
2022-12-24T07:59:28.420775+00:00 heroku[router]: at=info method=GET path= "/us/first-aid-cover/california/?order_by=title" host=www.racedirectorshq.com request_id=c0d1bc3f-90ad-4b5d-ac2b-edaf4d777e26 fwd="54.36.149.50" dyno=web.1 connect=0ms service=1806ms status=200 bytes=4991 protocol=https
2022-12-24T07:59:34.952805+00:00 app[web.1]: [2022-12-24 07:59:34 +0000] [12] [DEBUG] Closing connection.

I'm totally at a loss as to how to fix this and our app has been down for almost a day now. Please help.

EDIT: It was a DNS issue in the end. Fixed.


问:
Buttons popup on a TMemo on MouseEnter and disappears on MouseLeave
```<code>procedure TfrmMain.memInfoMouseEnter(Sender: TObject);
begin
  if AktivArt then
  begin
    btnAddMemo.BringToFront;
    btnEditMemo.BringToFront;
  end;
end;

procedure TfrmMain.memInfoMouseLeave(Sender: TObject);
begin
  btnAddMemo.SendToBack;
  btnEditMemo.SendToBack;
end;
</code>```

This works very well, but the problem is that when the mouse enter the buttons the they start to blink. Anyone who have a suggestion to solve this, or another way to get popup-buttons in a TMemo?

Body:
procedure TfrmMain.memInfoMouseEnter(Sender: TObject);
begin
  if AktivArt then
  begin
    btnAddMemo.BringToFront;
    btnEditMemo.BringToFront;
  end;
end;

procedure TfrmMain.memInfoMouseLeave(Sender: TObject);
begin
  btnAddMemo.SendToBack;
  btnEditMemo.SendToBack;
end;

This works very well, but the problem is that when the mouse enter the buttons the they start to blink. Anyone who have a suggestion to solve this, or another way to get popup-buttons in a TMemo?


问:
why does it say "keeps stopping" when I run the emulator?
[[[[enter image description here](https://i.stack.imgur.com/THp2K.png)](https://i.stack.imgur.com/ubf5E.png)](https://i.stack.imgur.com/6xAta.png)](https://i.stack.imgur.com/dyrx9.png)
When İ "run", there is a problem in the first picture in the "emulator". How can I solve this problem?

I took a course on udemy. I wrote the same code that the teacher wrote. But there is such a problem in my code.


问:
BullMQ throwing "Missing lock for job <jobId> failed" after using moveToDelayed
I'm following this pattern in the docs https://docs.bullmq.io/patterns/process-step-jobs

But it seems like the example code throws a Missing lock for job <jobId> failed error. Following is a minimal reproducible version

import { Worker, Queue } from "bullmq";

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

enum Step {
  Initial,
  Second,
  Finish,
}

type JobData = {
  step: Step;
};

const worker = new Worker<JobData>("reproduce-error", async (job, token) => {
  let step = job.data.step;
  while (step !== Step.Finish) {
    switch (step) {
      case Step.Initial: {
        await sleep(3 * 1000);
        await job.moveToDelayed(Date.now() + 1000, token);
        await job.update({
          step: Step.Second,
        });
        await job.updateProgress(1);
        step = Step.Second;
        break;
      }
      case Step.Second: {
        await sleep(3 * 1000);
        await job.update({
          step: Step.Finish,
        });
        await job.updateProgress(2);
        step = Step.Finish;
        return Step.Finish;
      }
      default: {
        throw new Error("invalid step");
      }
    }
  }
});

worker.on("error", (failedReason) => console.log(failedReason));

worker.on("progress", (job, progress) =>
  console.log("progress", job.data, progress)
);

const queue = new Queue<JobData>("reproduce-error");
queue.add("Reproduce error", { step: Step.Initial });
```
<p>Here's a stack trace of the error</p>
```    at Scripts.finishedErrors (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/scripts.ts:356:16)
    at Job.moveToFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/job.ts:618:26)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handleFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:642:11)
    at async Worker.retryIfFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:788:16)
    at async Worker.run (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:385:34)
```

Here's what I've thought so far:

I suspect moveToDelayed moves the job to the delayed set but it keeps running the current execution. That's why it tries to move the same job to the delayed set twice and thus fails. But, changing the break to return in the Initial block should change that, but even that doesn't help and gives the same error. So there might be something more fundamental that's going wrong here.

Any help would be appreciated. Thanks in advance!

Body:
I'm following this pattern in the docs https://docs.bullmq.io/patterns/process-step-jobs

But it seems like the example code throws a Missing lock for job <jobId> failed error. Following is a minimal reproducible version

import { Worker, Queue } from "bullmq";

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

enum Step {
  Initial,
  Second,
  Finish,
}

type JobData = {
  step: Step;
};

const worker = new Worker<JobData>("reproduce-error", async (job, token) => {
  let step = job.data.step;
  while (step !== Step.Finish) {
    switch (step) {
      case Step.Initial: {
        await sleep(3 * 1000);
        await job.moveToDelayed(Date.now() + 1000, token);
        await job.update({
          step: Step.Second,
        });
        await job.updateProgress(1);
        step = Step.Second;
        break;
      }
      case Step.Second: {
        await sleep(3 * 1000);
        await job.update({
          step: Step.Finish,
        });
        await job.updateProgress(2);
        step = Step.Finish;
        return Step.Finish;
      }
      default: {
        throw new Error("invalid step");
      }
    }
  }
});

worker.on("error", (failedReason) => console.log(failedReason));

worker.on("progress", (job, progress) =>
  console.log("progress", job.data, progress)
);

const queue = new Queue<JobData>("reproduce-error");
queue.add("Reproduce error", { step: Step.Initial });

Here's a stack trace of the error

    at Scripts.finishedErrors (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/scripts.ts:356:16)
    at Job.moveToFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/job.ts:618:26)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handleFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:642:11)
    at async Worker.retryIfFailed (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:788:16)
    at async Worker.run (/Users/sumit/Coding/indiemaker/twips/reproduce-bullmq-error/node_modules/bullmq/src/classes/worker.ts:385:34)

Here's what I've thought so far:

I suspect moveToDelayed moves the job to the delayed set but it keeps running the current execution. That's why it tries to move the same job to the delayed set twice and thus fails. But, changing the break to return in the Initial block should change that, but even that doesn't help and gives the same error. So there might be something more fundamental that's going wrong here.

Any help would be appreciated. Thanks in advance!


问:
I found lots of solution,but they are not ok for my project
I want to connect to postgressql Database from my springboot application. But I am getting error in maven for hibernate.org

I have downloaded hibernate dependencies in my local. This is my first spring boot project. I think it is not about database connection. All of the problems are in pom.xml file and maven dependencies. Also I am using intellij IDEA.

this is my pom.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.0.0</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>FirstSpringBootProject</groupId>
   <artifactId>RentACar</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>RentACar</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
      <dependency>
         <groupId>javax.persistence</groupId>
         <artifactId>javax.persistence-api</artifactId>
         <version>2.2</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springdoc</groupId>
         <artifactId>springdoc-openapi-ui</artifactId>
         <version>1.6.6</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>4.3.6.Final</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-jpa</artifactId>
         <version>2.7.5</version>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>
</code>```

Body:
I want to connect to postgressql Database from my springboot application. But I am getting error in maven for hibernate.org

I have downloaded hibernate dependencies in my local. This is my first spring boot project. I think it is not about database connection. All of the problems are in pom.xml file and maven dependencies. Also I am using intellij IDEA.

this is my pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.0.0</version>
      <relativePath/>
   </parent>
   <groupId>FirstSpringBootProject</groupId>
   <artifactId>RentACar</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>RentACar</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>

      <dependency>
         <groupId>javax.persistence</groupId>
         <artifactId>javax.persistence-api</artifactId>
         <version>2.2</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springdoc</groupId>
         <artifactId>springdoc-openapi-ui</artifactId>
         <version>1.6.6</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>4.3.6.Final</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-jpa</artifactId>
         <version>2.7.5</version>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>


问:
React Query with firebase returns undefined
I am very new to state management libraries and the one that I chose was React Query. I have followed multiple tutorials about it with mock data, but when I try to use my firebase imported data, it returns undefined. I am attaching all of my code with instances of React Query in it. This app is in next js 12.

file where I want to fetch and render data

```<code>const fetchDbData = async () => {
    const {currentUser} = UseAuth();
    function getLoc() {
        if (currentUser) {
            return 'users/' + currentUser.uid + '/userInvestments'
        } else {
            return 'users/TestDocumentForDatabase/userInvestments'
        };
    }
    const loc = getLoc();
    const q = query(collection(db, loc));
    const snapshot = await getDocs(q);
    console.log(snapshot)
    const {data, status, error} = useQuery(
        ['firebaseData'],
        () => snapshot.forEach(doc => doc.data()),
        {
            refetchOnWindowFocus: false
        },
        {
            retry: false
        },
    )
    return {data, status, error}
}

export default function usePortfolio() {
    const {data, status, error} = fetchDbData
    .....
</code>```

_app.js

```<code>
export const queryClient = new QueryClient({
  defaultOptions: {
      queries: {
          refetchOnWindowFocus: false,
          useInfiniteQury: false,
      },
  }
})
export default function App({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider >
        <RootLayout>
          <Component {...pageProps} />
        </RootLayout>
      </AuthProvider>

    </QueryClientProvider>
)}

</code>```

Body:
I am very new to state management libraries and the one that I chose was React Query. I have followed multiple tutorials about it with mock data, but when I try to use my firebase imported data, it returns undefined. I am attaching all of my code with instances of React Query in it. This app is in next js 12.

file where I want to fetch and render data

const fetchDbData = async () => {
    const {currentUser} = UseAuth();
    function getLoc() {
        if (currentUser) {
            return 'users/' + currentUser.uid + '/userInvestments'
        } else {
            return 'users/TestDocumentForDatabase/userInvestments'
        };
    }
    const loc = getLoc();
    const q = query(collection(db, loc));
    const snapshot = await getDocs(q);
    console.log(snapshot)
    const {data, status, error} = useQuery(
        ['firebaseData'],
        () => snapshot.forEach(doc => doc.data()),
        {
            refetchOnWindowFocus: false
        },
        {
            retry: false
        },
    )
    return {data, status, error}
}

export default function usePortfolio() {
    const {data, status, error} = fetchDbData
    .....

_app.js

export const queryClient = new QueryClient({
  defaultOptions: {
      queries: {
          refetchOnWindowFocus: false,
          useInfiniteQury: false,
      },
  }
})
export default function App({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider >
        <RootLayout>
          <Component {...pageProps} />
        </RootLayout>
      </AuthProvider>

    </QueryClientProvider>
)}


问:
Update AppBar Title with only re-rending the AppBar
Objective

My goal is to have an AppBar at the top of the page that has a title in it. Then in the "Main" area of my screen I will have a route that renders a different component depending on the url. These are the components that need to update the page title that is being rendered in the AppBar. I only want the AppBar to re-render and nothing else, because it's the only thing that will have actual data change in.

Originally I was using useState() and just prop drilling the [pageTitle, setPageTitle] down to the components. From what I've read, you should avoid prop drilling if possible.

So I've tried leveraging useContext() but everything in the tree still re-renders.

Caveats

I would like to keep the layout of the HTML like I currently have it if possible. I'm not sure if that affects anything.

How I Tested For Re-rendering

I have console.log() statements per component. I got rid of strict mode in order to make sure the components are rendering only once. I tested this prior to leveraging useContext and the statements only print out once.

Now when I click on a navigation link you will notice it prints out a console.log() for all of the components that <PageTitleContext.Provider> is wrapping.

I only want the <AppBar> to re-render and nothing else, because this is the only component that is displaying the pageTitle.

Sandbox Code

https://codesandbox.io/s/appbar-page-title-update-m5y9el?file=/src/pages/Dashboard.jsx


问:
Cannot show null object in jsonobject
I have called a rest api from exsternal system using restTemplate. everything is work fine but when I get null in some of values (in example the footer value is null) it is always give jsonexception error

result api

```<code>{
    "status": "success",
    "data": {
        "id": "22",
        "organization_id": "33",
        "name": "name_isf",
        "language": "id",
        "header": {
            "format": "IMAGE",
            "example": "#<Hashie::Mash header_handle=#<Hashie::Array [\"result_pic"]>>"
        },
        "body": "contenty for body",
        "footer": null,
        "buttons": [],
        "status": "APPROVED",
        "category": "PERSONAL_FINANCE_UPDATE"
    }
}
</code>```

every call api exsternal i always catch with jsonobject like below

```<code>JSONObject res2 = qontakService.getDetailTemplate();
</code>```

then i will give that to the controller

```<code>JSONObject gabunganResult = new JSONObject();
gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get()));
gabunganResult.put("templateQontak", res2);
</code>```

and the result error is

```<code>com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: java.util.HashMap["details"]->net.sf.json.JSONObject["templateQontak"]->net.sf.json.JSONObject["data"]->net.sf.json.JSONObject["footer"]->net.sf.json.JSONNull["empty"])
</code>```

how do I solve this problem ? thank you

Title: Cannot show null object in jsonobject

Body:
I have called a rest api from exsternal system using restTemplate. everything is work fine but when I get null in some of values (in example the footer value is null) it is always give jsonexception error

result api

{
    "status": "success",
    "data": {
        "id": "22",
        "organization_id": "33",
        "name": "name_isf",
        "language": "id",
        "header": {
            "format": "IMAGE",
            "example": "#<Hashie::Mash header_handle=#<Hashie::Array [\"result_pic"]>>"
        },
        "body": "contenty for body",
        "footer": null,
        "buttons": [],
        "status": "APPROVED",
        "category": "PERSONAL_FINANCE_UPDATE"
    }
}

every call api exsternal i always catch with jsonobject like below

JSONObject res2 = qontakService.getDetailTemplate();

then i will give that to the controller

JSONObject gabunganResult = new JSONObject();
gabunganResult.put("template", objectMapper.writeValueAsString(getDetail.get()));
gabunganResult.put("templateQontak", res2);

and the result error is

com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: java.util.HashMap["details"]->net.sf.json.JSONObject["templateQontak"]->net.sf.json.JSONObject["data"]->net.sf.json.JSONObject["footer"]->net.sf.json.JSONNull["empty"])

how do I solve this problem ? thank you


问:
how to target specific section when i use javaScript Parallax
I'm trying to get a cool parallax effect using vanilla java script, but whenever I scroll down, all the sections with the parallax start at the same time. What I really need is for them to start when I reach the exact section, not when I scroll down. Please help, I'm a noob when it comes to javascript. I took this code from codepen from Gary Simon Design course, but I couldn't do it right, so I need help. thats what i've done so far .

window.addEventListener('scroll', function(e) {

const target = document.querySelectorAll('.scroll, .scroll2');

var index = 0, length = target.length;
for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.rate;

    if(target[index].dataset.direction === 'vertical') {
        target[index].style.transform = 'translate3d(0px,'+pos+'px, 0px)';
    } else {
        var posX = window.pageYOffset * target[index].dataset.ratex;
        var posY = window.pageYOffset * target[index].dataset.ratey;

        target[index].style.transform = 'translate3d('+posX+'px, '+posY+'px, 0px)';
    }
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>     body {
    margin: 0;
    height: 100vh;
    font-size: 5em;
    font-family: 'Montserrat';
    font-weight: bold;
}

section {
    height: 100%;
    overflow: hidden;
}

section .sec {
    height: 100%;
    overflow: hidden;
}
.sec ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: repeat(3, auto);
    justify-content: center;
    align-items: middle;
    place-items: center;
    min-height: 120vh;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: repeat(3, auto);
    justify-content: center;
    align-items: middle;
    place-items: center;
    height: 50vh;
}

.bg-0{
    background-image: url(./images/section.jpg);
    background-color: blue;
    background-attachment: fixed;
    background-position: center;
    height: 50vh;
}</code>```

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Elena</title>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" integrity="sha512-tS3S5qG0BlhnQROyJXvNjeEM4UpMXHrQfTGmbQ1gKmelCxlSEBUaxhRBj/EFTzpbP4RVSrpEikbmdJobCvhE3g==" crossorigin="anonymous" referrerpolicy="no-referrer">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css" integrity="sha512-OTcub78R3msOCtY3Tc6FzeDJ8N9qvQn1Ph49ou13xgA9VsH9+LRxoFU6EqLhW4+PKRfU+/HReXmSZXHEkpYoOA==" crossorigin="anonymous" referrerpolicy="no-referrer">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

par

al

lax

par

al

lax

rovident nisi similique eos. Nam, rerum assumenda incidunt quo illum sunt impedit! Maxime, culpa fugiat? Dolores architecto, nisi nostrum officiis aut distinctio quam fugit at, saepe, cumque quae debitis? Eligendi praesentium, iusto eaque asperiores neque laudantium qui. Provident cumque aut libero mollitia debitis sed illum, in quos repellat, illo soluta. Numquam dolores tempore ea reprehenderit deleniti, possimus unde sed vel distinctio corrupti, ex commodi labore. Voluptas eum deleniti natus modi illo repellat harum enim esse at sunt. Impedit quasi iste consectetur earum explicabo ut quod odit. Iste, deleniti repellendus! Ipsam, possimus? Quaerat eaque suscipit facere labore obcaecati beatae, sequi dolor enim quae similique. Aliquam minima expedita, aliquid veniam recusandae sequi possimus itaque, dignissimos exercitationem ipsam voluptate! Voluptatum optio dolore, ipsum atque repellat odit nulla repellendus suscipit, aperiam cum, fugit ducimus. Veniam labore dignissimos deserunt aliquid iure accusamus optio ducimus expedita sunt earum doloremque voluptatibus aperiam dolore, unde odit excepturi delectus? Porro corrupti totam quod recusandae, ipsa dolores fugit rem natus ratione et aspernatur deserunt facere. Ad delectus fugit, iure accusantium saepe minus velit dicta cumque fugiat illum! Unde recusandae exercitationem nemo temporibus? Labore totam necessitatibus natus sunt at ipsum! Nam.

```

Body:
I'm trying to get a cool parallax effect using vanilla java script, but whenever I scroll down, all the sections with the parallax start at the same time. What I really need is for them to start when I reach the exact section, not when I scroll down. Please help, I'm a noob when it comes to javascript. I took this code from codepen from Gary Simon Design course, but I couldn't do it right, so I need help. thats what i've done so far .

window.addEventListener('scroll', function(e) {

const target = document.querySelectorAll('.scroll, .scroll2');

var index = 0, length = target.length;
for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.rate;

    if(target[index].dataset.direction === 'vertical') {
        target[index].style.transform = 'translate3d(0px,'+pos+'px, 0px)';
    } else {
        var posX = window.pageYOffset * target[index].dataset.ratex;
        var posY = window.pageYOffset * target[index].dataset.ratey;

        target[index].style.transform = 'translate3d('+posX+'px, '+posY+'px, 0px)';
    }
}

});

     body {
    margin: 0;
    height: 100vh;
    font-size: 5em;
    font-family: 'Montserrat';
    font-weight: bold;
}

section {
    height: 100%;
    overflow: hidden;
}

section .sec {
    height: 100%;
    overflow: hidden;
}
.sec ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: repeat(3, auto);
    justify-content: center;
    align-items: middle;
    place-items: center;
    min-height: 120vh;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: grid;
    grid-template-columns: repeat(3, auto);
    justify-content: center;
    align-items: middle;
    place-items: center;
    height: 50vh;
}

.bg-0{
    background-image: url(./images/section.jpg);
    background-color: blue;
    background-attachment: fixed;
    background-position: center;
    height: 50vh;
}

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Elena</title>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" integrity="sha512-tS3S5qG0BlhnQROyJXvNjeEM4UpMXHrQfTGmbQ1gKmelCxlSEBUaxhRBj/EFTzpbP4RVSrpEikbmdJobCvhE3g==" crossorigin="anonymous" referrerpolicy="no-referrer">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css" integrity="sha512-OTcub78R3msOCtY3Tc6FzeDJ8N9qvQn1Ph49ou13xgA9VsH9+LRxoFU6EqLhW4+PKRfU+/HReXmSZXHEkpYoOA==" crossorigin="anonymous" referrerpolicy="no-referrer">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

par

al

lax

par

al

lax

rovident nisi similique eos. Nam, rerum assumenda incidunt quo illum sunt impedit! Maxime, culpa fugiat? Dolores architecto, nisi nostrum officiis aut distinctio quam fugit at, saepe, cumque quae debitis? Eligendi praesentium, iusto eaque asperiores neque laudantium qui. Provident cumque aut libero mollitia debitis sed illum, in quos repellat, illo soluta. Numquam dolores tempore ea reprehenderit deleniti, possimus unde sed vel distinctio corrupti, ex commodi labore. Voluptas eum deleniti natus modi illo repellat harum enim esse at sunt. Impedit quasi iste consectetur earum explicabo ut quod odit. Iste, deleniti repellendus! Ipsam, possimus? Quaerat eaque suscipit facere labore obcaecati beatae, sequi dolor enim quae similique. Aliquam minima expedita, aliquid veniam recusandae sequi possimus itaque, dignissimos exercitationem ipsam voluptate! Voluptatum optio dolore, ipsum atque repellat odit nulla repellendus suscipit, aperiam cum, fugit ducimus. Veniam labore dignissimos deserunt aliquid iure accusamus optio ducimus expedita sunt earum doloremque voluptatibus aperiam dolore, unde odit excepturi delectus? Porro corrupti totam quod recusandae, ipsa dolores fugit rem natus ratione et aspernatur deserunt facere. Ad delectus fugit, iure accusantium saepe minus velit dicta cumque fugiat illum! Unde recusandae exercitationem nemo temporibus? Labore totam necessitatibus natus sunt at ipsum! Nam.


问:
Optimizing oracle database connection acquisition time on Spring boot
I have an Spring boot application that runs several services and uses oracle database. The database is maintained properly, indexes also added up, and when executing SQL statements directly on SQL Developer, it's getting executed in milliseconds.

In the spring boot, I use this to execute the statement:

```<code>Session session = sessionFactory.getCurrentSession();
session.createQuery("from Table where id = :id and status = 0").setParameter("id", id);
</code>```

Here is the config properties for the database:

```<code>spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
hibernate.hbm2ddl.auto=none
</code>```

Here is the way of datasource initialization in the datasource config:

```<code>    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(url, name, pw);
        dataSource.setDriverClassName(...);
        return dataSource;
    }
</code>```

Recently, it takes so much time to acquire the database connection, it can go up to 10 seconds jut for acquiring connection. I don't think there is any problem in the query. As from the database side, it's also ok. The resources of server which running this service and the database server are also fine, as well as the network. The servers also have auto-scale feature to create new instance when the memory getting low. I just can't figure out what should I do to improve the acquisition time. Could you please help?

Body:
I have an Spring boot application that runs several services and uses oracle database. The database is maintained properly, indexes also added up, and when executing SQL statements directly on SQL Developer, it's getting executed in milliseconds.

In the spring boot, I use this to execute the statement:

Session session = sessionFactory.getCurrentSession();
session.createQuery("from Table where id = :id and status = 0").setParameter("id", id);

Here is the config properties for the database:

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
hibernate.hbm2ddl.auto=none

Here is the way of datasource initialization in the datasource config:

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(url, name, pw);
        dataSource.setDriverClassName(...);
        return dataSource;
    }

Recently, it takes so much time to acquire the database connection, it can go up to 10 seconds jut for acquiring connection. I don't think there is any problem in the query. As from the database side, it's also ok. The resources of server which running this service and the database server are also fine, as well as the network. The servers also have auto-scale feature to create new instance when the memory getting low. I just can't figure out what should I do to improve the acquisition time. Could you please help?


问:
How Do I Convert input arg tf.string to string in tf.function
```<code>@tf.function(input_signature=[
tf.TensorSpec(shape=[], dtype=tf.string, name="key"),
tf.TensorSpec(shape=[], dtype=tf.string, name="value")
])
def infer(self, key, value):
    tf.print(key)
    xxx
</code>```

I want to implement universal input, something like this

```<code>key: age#gender
value: 0#1
=>
age_tensor = tf.constant(value=0, name="age")
gender_tensor = tf.constant(value=1,name="gender")
</code>```

so I want to convert tf.string to string.

use tf.print function can normally print the input args，Do I have any way to simulate the function of tf.print and assign the printed value to a variable to implement tf.string to string?

or

Is there any other way I can do this?

Body:
@tf.function(input_signature=[
tf.TensorSpec(shape=[], dtype=tf.string, name="key"),
tf.TensorSpec(shape=[], dtype=tf.string, name="value")
])
def infer(self, key, value):
    tf.print(key)
    xxx

I want to implement universal input, something like this

key: age#gender
value: 0#1
=>
age_tensor = tf.constant(value=0, name="age")
gender_tensor = tf.constant(value=1,name="gender")

so I want to convert tf.string to string.

use tf.print function can normally print the input args，Do I have any way to simulate the function of tf.print and assign the printed value to a variable to implement tf.string to string?

or

Is there any other way I can do this?


问:
firebase:error(auth/missing-missing-email)
```<code>const LoginScreen = (props) => {
  const [email,setEmail]=useState(null);
  const [password,setPassword]=useState(null);
  const login=()=>{

signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {

    alert("user login successfully");
    props.replace("HomeScreen");
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    alert(errorMessage);
  });

</code>```

this is my code of login screen

on clicking login button this error occurs . the email id and password is correct and exist

Body:
const LoginScreen = (props) => {
  const [email,setEmail]=useState(null);
  const [password,setPassword]=useState(null);
  const login=()=>{

signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {

    alert("user login successfully");
    props.replace("HomeScreen");
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    alert(errorMessage);
  });

this is my code of login screen

on clicking login button this error occurs . the email id and password is correct and exist


问:
Scan network for http endpoints in node,js
I'm making a commandline chat tool similar to IRC, and i've been wanting to include a feature where you are able to scan your local network for rooms. On the server end, I've set up a http endpoint on port 9009 to respond with a peice of JSON data containing the room nickname, whether it is encrypted, and the port to use. However, I have had some difficulty scanning the network from the clientside.

I thought about running a for loop or something to loop through the IP adresses, but different networks can have different IP formats. I also considered nmap, but that would be an extra dependancy to set up, and you still need to provide a router IP.


问:
skimage.morphology does not contain Mediall_axis (python/ image process)
Dears,

my scikit, skimage does not contain medial_axis
Hence I get this below error while running

(python/ image process)

"medial_axis" is not defined

i tried uninstall and install skimage-image using pip install
but it did not work out

[update]

I had a file named "skimage.py" that was the reason it did not work anyway


问:
Scrapy crawling data using product API
I scrape the target site with scrapy. However, there are cache problems on the site and most of the time I can get updated data with a delay of 4-5 minutes. I know some people scrape this site using API. However, I searched the site and couldn't find the API link. I looked for all XHR-type content in the Network section, but could not find it.
How can I scrape the relevant site with API.

My code I am currently using:

```<code>def parse(self, response):
        for li in response.css('li'):
            item=MediamarktItem()
            script_text = li.css('script::text').extract_first()
            if script_text:
                data = json.loads(re.search(r'var product\d+ = (.*);', script_text).group(1))
                name = data['name']
                price = data['price']
                product_id = data['id']

                item['rowid'] = hash(str(datetime.datetime.now()) + product_id)
                item['date'] = str(datetime.datetime.now())
                item['listing_id'] = product_id
                item['product_name'] = name
                item['price'] = price
                item['product_id'] = product_id
                item['url'] = "https://www.mediamarkt.com.tr/tr/product/" + "-" + product_id + '.html'
                item['merchantName'] = "Mediamarkt"
                yield item
</code>```

When I examined the site a little, I saw that it made a request like the one below. But I couldn't figure out how to pull data from url. Thank you in advance for your help.

```<code>  https://www.mediamarkt.com.tr/tr/product/productlistajax.json
</code>```

Title: Scrapy crawling data using product API

Body:
I scrape the target site with scrapy. However, there are cache problems on the site and most of the time I can get updated data with a delay of 4-5 minutes. I know some people scrape this site using API. However, I searched the site and couldn't find the API link. I looked for all XHR-type content in the Network section, but could not find it.
How can I scrape the relevant site with API.

My code I am currently using:

def parse(self, response):
        for li in response.css('li'):
            item=MediamarktItem()
            script_text = li.css('script::text').extract_first()
            if script_text:
                data = json.loads(re.search(r'var product\d+ = (.*);', script_text).group(1))
                name = data['name']
                price = data['price']
                product_id = data['id']

                item['rowid'] = hash(str(datetime.datetime.now()) + product_id)
                item['date'] = str(datetime.datetime.now())
                item['listing_id'] = product_id
                item['product_name'] = name
                item['price'] = price
                item['product_id'] = product_id
                item['url'] = "https://www.mediamarkt.com.tr/tr/product/" + "-" + product_id + '.html'
                item['merchantName'] = "Mediamarkt"
                yield item

When I examined the site a little, I saw that it made a request like the one below. But I couldn't figure out how to pull data from url. Thank you in advance for your help.

  https://www.mediamarkt.com.tr/tr/product/productlistajax.json


问:
NBeats does not work for long-term daily time series data. How can I process my data to correct this?
I am following the code as per this notebook: https://www.kaggle.com/code/stpeteishii/google-stock-prediction-darts/notebook

It's a really simple implementation of the NBeats model, and it takes into account 400 days of the Google stockprice. However, when I increase the database to take into account all 4000 days, the N-Beats forecast is completely thrown of and gives a completely incorrect forecast with a mape of over 100.

I understand that one possibility is due to the seasonal nature of the stockprice. I tried the Dicky Fueller test (not using the Darts library) and it is indeed seasonal data. However, when I try to inspect seasonality with the Darts library as follows:

```<code>from darts.utils.statistics import plot_acf, check_seasonality

plot_acf(train, m=365, alpha=0.05)
I get a max lag error.
</code>```

Can someone please help me as to how to forecast stock market data of a 10 year daily timeseries using the darts library? Also, I'd be extremely grateful if someone could give me some additional tips when it comes to forecasting stock data with darts since there's not much info/tutorials available online.

I've gone through the entire docs and I've got a good hang of working with darts using the darts open-source databases, however none of the examples seem to work with stock market data.

Any help would be greatly appreciated.
Thanks!

Body:
I am following the code as per this notebook: https://www.kaggle.com/code/stpeteishii/google-stock-prediction-darts/notebook

It's a really simple implementation of the NBeats model, and it takes into account 400 days of the Google stockprice. However, when I increase the database to take into account all 4000 days, the N-Beats forecast is completely thrown of and gives a completely incorrect forecast with a mape of over 100.

I understand that one possibility is due to the seasonal nature of the stockprice. I tried the Dicky Fueller test (not using the Darts library) and it is indeed seasonal data. However, when I try to inspect seasonality with the Darts library as follows:

from darts.utils.statistics import plot_acf, check_seasonality

plot_acf(train, m=365, alpha=0.05)
I get a max lag error.

Can someone please help me as to how to forecast stock market data of a 10 year daily timeseries using the darts library? Also, I'd be extremely grateful if someone could give me some additional tips when it comes to forecasting stock data with darts since there's not much info/tutorials available online.

I've gone through the entire docs and I've got a good hang of working with darts using the darts open-source databases, however none of the examples seem to work with stock market data.

Any help would be greatly appreciated.
Thanks!


问:
Where to get example data used in PostgreSQL documentation?
I would like to follow through and experiment with the examples in the PostgreSQL documentation but find it difficult to compare impacts of commands without actual working data.

Is there sample data or a default database that correlates with all the examples in the PostgreSQL documentation ?

Problem:

Getting table or column "does not exist" errors when executing SQL in documentation (https://www.postgresql.org/docs/10/tutorial-window.html):

```<code>SELECT depname, empno, salary, enroll_date
FROM
  (SELECT depname, empno, salary, enroll_date,
          rank() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
     FROM empsalary
  ) AS ss
WHERE pos < 3;
</code>```

Error:

```<code>SQL Error [42703]: ERROR: column "enroll_date" does not exist
</code>```

Attempted workarounds:

Stack Builder does not list sample data installation options

The sources do not contain required sample data (eg. "src\tutorial" directory et al in https://ftp.postgresql.org/pub/source/v10.23/postgresql-10.23.tar.gz)

Any 3rd-party sample data found appear incomplete or non-official (eg. "advanced-psql-examples.sql" from https://gist.github.com/marko-asplund/5561404 missing "enroll_date" column)

Versions:

PostgreSQL 10.23 (https://web3.pioneersoftware.co.uk/files/pgsql/10/postgresql-10.23-1-windows.exe)

Stack Builder 4.2.1

Body:
I would like to follow through and experiment with the examples in the PostgreSQL documentation but find it difficult to compare impacts of commands without actual working data.

Is there sample data or a default database that correlates with all the examples in the PostgreSQL documentation ?

Problem:

Getting table or column "does not exist" errors when executing SQL in documentation (https://www.postgresql.org/docs/10/tutorial-window.html):

SELECT depname, empno, salary, enroll_date
FROM
  (SELECT depname, empno, salary, enroll_date,
          rank() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
     FROM empsalary
  ) AS ss
WHERE pos < 3;

Error:

SQL Error [42703]: ERROR: column "enroll_date" does not exist

Attempted workarounds:

Stack Builder does not list sample data installation options

The sources do not contain required sample data (eg. "src\tutorial" directory et al in https://ftp.postgresql.org/pub/source/v10.23/postgresql-10.23.tar.gz)

Any 3rd-party sample data found appear incomplete or non-official (eg. "advanced-psql-examples.sql" from https://gist.github.com/marko-asplund/5561404 missing "enroll_date" column)

Versions:

PostgreSQL 10.23 (https://web3.pioneersoftware.co.uk/files/pgsql/10/postgresql-10.23-1-windows.exe)

Stack Builder 4.2.1


问:
npm conflict in peer dependencies
This error comes every time I try to install any dependencies. I don't want to use --force or --legacy-peer-deps. Any other solution to this?

Title: npm conflict in peer dependencies


问:
How can I solve the "Tainted canvas" error caused by html2canvas?
I am creating a web application, and I want it to have a feature that allows the user to download screenshots of the page.
I tried to use a library called html2canvas, and I had written the code as it said on the tutorial, but it returned an error:
Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Here's the code that I have written to use html2canvas :

```
<pre class="lang-js prettyprint-override"><code>html2canvas(document.querySelector("#Display")).then(canvas => {
   const downloadLink = document.createElement("a");
   downloadLink.href = canvas.toDataURL("image/png");
   downloadLink.click()
});
</code>```

And this is the library's source code : https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js

Could anyone solve this problem?

Body:
I am creating a web application, and I want it to have a feature that allows the user to download screenshots of the page.
I tried to use a library called html2canvas, and I had written the code as it said on the tutorial, but it returned an error:
Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Here's the code that I have written to use html2canvas :

html2canvas(document.querySelector("#Display")).then(canvas => {
   const downloadLink = document.createElement("a");
   downloadLink.href = canvas.toDataURL("image/png");
   downloadLink.click()
});

And this is the library's source code : https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js

Could anyone solve this problem?


问:
CLRS red black tree deletion
```<code>01 void RedBlackTree::deleteNode(Node *z)
02 {
03     Node *y = z;
04     Color yOriginalColor = y->color;
05     Node *x;
06     if (z->left == sentinel)
07     {
08         x = z->right;
09         transplant(z, z->right);
10     }
11     else if (z->right == sentinel)
12     {
13         x = z->left;
14         transplant(z, z->left);
15     }
16     else
17     {
18         y = minimum(z->right);
19         yOriginalColor = y->color;
20         x = y->right;
21         if (y->parent == z)
22         {
23             x->parent = y;  // WHY??
24         }
25         else
26         {
27             transplant(y, y->right);
28             y->right = z->right;
29             y->right->parent = y;
30         }
31         transplant(z, y);
32         y->left = z->left;
33         y->left->parent = y;
34         y->color = z->color;
35     }
36
37     delete z;
38
39     if (yOriginalColor == Color::BLACK)
40     {
41         deleteFixUp(x);
42     }
43 }
</code>```

In line 20, we assign y->right to x. In line 23, we assign y to x->parent.
Isn't the assignment in line 23 redundant since the parent of x is y already?

In the book it says

When y's original parent is z, however, we do not want x.p to point to y's original parent, since we are removing that node from the tree. Because node y will move up to take z's position in the tree, setting x.p to y in line 13 causes x.p to point to the original position of y's parent, even if x = T.nil.

I don't understand the explanation from the book, why would x.p points to z. When we move node y from its original position to z's position, shouldn't y's child x remain unaffected, still attached to y?

I come across 2 posts asking similar queations as I do, however, I'm still confused after reading through the answers.

red black tree pseudocode redundancy

issue with the red black delete algorithm mentioned in introduction to algorithm

After these 2 questions, I get one more question. I don't understand the assignment of y to x.p in line 23 has anything to do with x being the sentinel node (e.g. T.nil) or not.

Title: CLRS red black tree deletion

Body:
01 void RedBlackTree::deleteNode(Node *z)
02 {
03     Node *y = z;
04     Color yOriginalColor = y->color;
05     Node *x;
06     if (z->left == sentinel)
07     {
08         x = z->right;
09         transplant(z, z->right);
10     }
11     else if (z->right == sentinel)
12     {
13         x = z->left;
14         transplant(z, z->left);
15     }
16     else
17     {
18         y = minimum(z->right);
19         yOriginalColor = y->color;
20         x = y->right;
21         if (y->parent == z)
22         {
23             x->parent = y;  // WHY??
24         }
25         else
26         {
27             transplant(y, y->right);
28             y->right = z->right;
29             y->right->parent = y;
30         }
31         transplant(z, y);
32         y->left = z->left;
33         y->left->parent = y;
34         y->color = z->color;
35     }
36
37     delete z;
38
39     if (yOriginalColor == Color::BLACK)
40     {
41         deleteFixUp(x);
42     }
43 }

In line 20, we assign y->right to x. In line 23, we assign y to x->parent.
Isn't the assignment in line 23 redundant since the parent of x is y already?

In the book it says

When y's original parent is z, however, we do not want x.p to point to y's original parent, since we are removing that node from the tree. Because node y will move up to take z's position in the tree, setting x.p to y in line 13 causes x.p to point to the original position of y's parent, even if x = T.nil.

I don't understand the explanation from the book, why would x.p points to z. When we move node y from its original position to z's position, shouldn't y's child x remain unaffected, still attached to y?

I come across 2 posts asking similar queations as I do, however, I'm still confused after reading through the answers.

red black tree pseudocode redundancy

issue with the red black delete algorithm mentioned in introduction to algorithm

After these 2 questions, I get one more question. I don't understand the assignment of y to x.p in line 23 has anything to do with x being the sentinel node (e.g. T.nil) or not.


问:
support buy , resistance sell signal
i m new to pine script and i have found an indicator version 5 that can draw lines of support and resistance, i m trying to add a buy and a sell signal when the line of support or resistance first created but it gives me a signal in every candle and i want it only in first candle, this is the code. and thank you

```<code>group_bbp    = 'Support/Resistance'
bars                    = input.int(25, title = "Pivot", group = 'Support/Resistance')
tipe                    = input.string("Body", title = "Type", options = ["Wick", "Body"])
show_c                = input.bool(true, title = "Show Support/Resistance", group = "Timeframes")
pivot_high_c            = fixnan(ta.pivothigh(tipe == "Wick" ? high : close, bars, bars)[1])
pivot_low_c            = fixnan(ta.pivotlow(tipe == "Wick" ? low : close, bars, bars)[1])

resistance_high_c      = plot(show_c ? pivot_high_c : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1, linewidth=1, title="Resistance", style=plot.style_line)
resistance_low_c      = plot(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1, linewidth=1, title="Support", style=plot.style_line)
</code>```
```<code>plotshape(show_c ?pivot_high_c  : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1,  title="Resistance", style=shape.triangledown, size=size.small)
plotshape(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1,    title="Support",  style=shape.triangleup, size=size.small)
</code>```

this is what i try

plotshape(show_c ?pivot_high_c  : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1,  title="Resistance", style=shape.triangledown, size=size.small)
plotshape(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1,    title="Support",  style=shape.triangleup, size=size.small)

Title: support buy , resistance sell signal

Body:
i m new to pine script and i have found an indicator version 5 that can draw lines of support and resistance, i m trying to add a buy and a sell signal when the line of support or resistance first created but it gives me a signal in every candle and i want it only in first candle, this is the code. and thank you

group_bbp    = 'Support/Resistance'
bars                    = input.int(25, title = "Pivot", group = 'Support/Resistance')
tipe                    = input.string("Body", title = "Type", options = ["Wick", "Body"])
show_c                = input.bool(true, title = "Show Support/Resistance", group = "Timeframes")
pivot_high_c            = fixnan(ta.pivothigh(tipe == "Wick" ? high : close, bars, bars)[1])
pivot_low_c            = fixnan(ta.pivotlow(tipe == "Wick" ? low : close, bars, bars)[1])

resistance_high_c      = plot(show_c ? pivot_high_c : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1, linewidth=1, title="Resistance", style=plot.style_line)
resistance_low_c      = plot(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1, linewidth=1, title="Support", style=plot.style_line)

plotshape(show_c ?pivot_high_c  : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1,  title="Resistance", style=shape.triangledown, size=size.small)
plotshape(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1,    title="Support",  style=shape.triangleup, size=size.small)

this is what i try

plotshape(show_c ?pivot_high_c  : na, color=ta.change(pivot_high_c) ? na : #ff0040, offset = -bars - 1,  title="Resistance", style=shape.triangledown, size=size.small)
plotshape(show_c ? pivot_low_c : na, color=ta.change(pivot_low_c) ? na : #6aff00, offset = -bars - 1,    title="Support",  style=shape.triangleup, size=size.small)


问:
before, beforeEach, after, and afterEach of mocha equivalent in pytest
I'm new to python and using pytest along with requests to start API testing.

I want to run some scripts before each test module and other snippets before each test case in a module for testcases data setup.

I've checked pytest fixtures and scope but I don't think this is what I'm looking for as I can't control the data passed to fixtures. What other possible solutions for that?


问:
formatting individual link with linkifyjs
I cant understand how I can format few links in individual way... for example github.com with rel:follow (not working). How I can building something like a IF: if(url==mywebiste.com){rel: follow} in const options?? is it possible? https://linkify.js.org/docs/options.html#format

```<code>const beforeEl = document.getElementById('linkify-demo-before')
const afterEl = document.getElementById('linkify-demo-after')

const options = {
  title: "External Link",
  rel: 'nofollow noreferrer noopener',
  target: '_blank',

  formatHref: {
    hashtag: (val) => `https://www.twitter.com/hashtag/${val.substr(1)}`,
    mention: (val) => `https://github.com/${val.substr(1)}`,
  }
}

linkifyHtml("github.com", {
  rel: 'follow',
 });

afterEl.innerHTML = linkifyStr(beforeEl.value, options)
beforeEl.addEventListener('input', () => {
  afterEl.innerHTML = linkifyStr(beforeEl.value, options)

})
</code>```

Body:
I cant understand how I can format few links in individual way... for example github.com with rel:follow (not working). How I can building something like a IF: if(url==mywebiste.com){rel: follow} in const options?? is it possible? https://linkify.js.org/docs/options.html#format

const beforeEl = document.getElementById('linkify-demo-before')
const afterEl = document.getElementById('linkify-demo-after')

const options = {
  title: "External Link",
  rel: 'nofollow noreferrer noopener',
  target: '_blank',

  formatHref: {
    hashtag: (val) => `https://www.twitter.com/hashtag/${val.substr(1)}`,
    mention: (val) => `https://github.com/${val.substr(1)}`,
  }
}

linkifyHtml("github.com", {
  rel: 'follow',
 });

afterEl.innerHTML = linkifyStr(beforeEl.value, options)
beforeEl.addEventListener('input', () => {
  afterEl.innerHTML = linkifyStr(beforeEl.value, options)

})


问:
Web API gets SQL network connection error after a few hours of running
I have a Blazor app that connects to an API. Both of them are on the same server (IIS).
Everything works fine, but after one or two days, when users try to log in, API returns this error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
---> System.ComponentModel.Win32Exception (53): The network path was not found.

I tried to reset all the SQL server services (SQL Browser, SQLSERVERAGENT,... ), but it didn't work.
I also tried to restart my website and web API in IIS, but it didn't work.
The only thing that worked is restarting the server!
What's the problem? Why do we get this error after a few hours?


问:
PHPSTORM_META how to specify return type
https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html#navigate-to-a-metadata-directive

There is a custom DI (legacy) that works like this:

/** @var SomeClass $settings */
$settings = DI()->GetSettings(SomeClass::NAME);

$settings instanceof SomeClass = true
SomeClass::NAME - constant, exists in every class
```
<p>How to specify in <code>.phpstorm.meta.php</code> that something that ends in <code>::NAME</code> should be returned as a value?</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace PHPSTORM_META
{
    override(DI()->GetSettings(0'::NAME'), type(0));
}
</code>```

Body:
https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html#navigate-to-a-metadata-directive

There is a custom DI (legacy) that works like this:

/** @var SomeClass $settings */
$settings = DI()->GetSettings(SomeClass::NAME);

$settings instanceof SomeClass = true
SomeClass::NAME - constant, exists in every class

How to specify in .phpstorm.meta.php that something that ends in ::NAME should be returned as a value?

<?php

namespace PHPSTORM_META
{
    override(DI()->GetSettings(0'::NAME'), type(0));
}


问:
Get non unique values from two arrays
I have two arrays,

```<code>var existingArray = [10,20,30,40];
var newArray =[10,20,30,40,50,60,70];
</code>```

I want to extract non unique elements by using filter from above two arrays and output should be

```<code>var updatedArray =[50,60,70];
</code>```

I am using javascript es6

Title: Get non unique values from two arrays

Body:
I have two arrays,

var existingArray = [10,20,30,40];
var newArray =[10,20,30,40,50,60,70];

I want to extract non unique elements by using filter from above two arrays and output should be

var updatedArray =[50,60,70];

I am using javascript es6


问:
NExtJS getStaticProps() call every time
I have created nodejs server for nextjs app

```<code>onst app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
    createServer(async (req, res) => {
        try {
            const parsedUrl = parse(req.url, true)
            const { pathname, query } = parsedUrl
            await handle(req, res, parsedUrl)
        } catch (err) {
            console.error('Error occurred handling', req.url, err)
            res.statusCode = 500
            res.end('internal server error')
        }
    }).listen(port, (err) => {
        if (err) throw err
        console.log(`> Ready on http://${hostname}:${port}`)
    })
});
</code>```

And create build for next app and run start:server
package.json

```<code>"build": "next build",
"start:server": "SET NODE_ENV=production && node server.js"
</code>```

Problem :
I have page with getStaticProps but when I reload page I have different content / Why ? I have create build and call getStaticProps

```<code>export async function getStaticProps() {
  const userRequest =
    await fetch('https://catfact.ninja/fact');
  const userData = await userRequest.json();
  return {
    props: {
      data: userData
    }
  };
}

export default function Home({ data }) {
  return (
    <div>
        <h1>
          Welcome
        </h1>
       random  info {data.fact}
    </div>
  )
}
</code>```

Title: NExtJS getStaticProps() call every time

Body:
I have created nodejs server for nextjs app

onst app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
    createServer(async (req, res) => {
        try {
            const parsedUrl = parse(req.url, true)
            const { pathname, query } = parsedUrl
            await handle(req, res, parsedUrl)
        } catch (err) {
            console.error('Error occurred handling', req.url, err)
            res.statusCode = 500
            res.end('internal server error')
        }
    }).listen(port, (err) => {
        if (err) throw err
        console.log(`> Ready on http://${hostname}:${port}`)
    })
});

And create build for next app and run start:server
package.json

"build": "next build",
"start:server": "SET NODE_ENV=production && node server.js"

Problem :
I have page with getStaticProps but when I reload page I have different content / Why ? I have create build and call getStaticProps

export async function getStaticProps() {
  const userRequest =
    await fetch('https://catfact.ninja/fact');
  const userData = await userRequest.json();
  return {
    props: {
      data: userData
    }
  };
}

export default function Home({ data }) {
  return (

          Welcome

       random  info {data.fact}

  )
}


问:
Why is CloudFront not forwarding query strings when using route parameters?
An HTTP API with two routes:

/route1

/route2/{param}

Using a CloudFront cache policy with myquery query string included:

when calling /route1?myquery=foo - the query string is available in the lambda payload,

when calling /route2/something?myquery=foo - the query string is missing from the payload.

When calling the API directly, without CloudFront, the query string is always in the payload.

Why is that?


问:
Script copy Last Modified object in Windows10
I wanna the script that Copy the last object that modified (based on "Data modified" in Windows Explorer)

For Example:

D:\Source\A1.txt        Data modified: 12/24/2022
D:\Source\A2.txt        Data modified: 12/23/2022

After use that script, Copy only A1.txt in destination path (like F:\destination)


问:
Launch my App Activity on Home key pressed
I am developing a Launcher app for Android TV and want to override the functionality of Home button. I want to bring my Application's Activity to top when Home button is pressed so that it acts as default launcher. I tried this Android Studio TV remote buttons but did not work. It is definitely possible because there are button mapper apps on the PlayStore. I have this in my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_TV_LISTINGS" />

    <uses-feature
        android:name="android.hardware.touchscreen"
        android:required="false" />
    <uses-feature
        android:name="android.software.leanback"
        android:required="true" />

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

    <queries>
        <intent>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.action.LAUNCHER" />
        </intent>
    </queries>

    <application
        android:name=".AppName"
        android:allowBackup="true"
        android:banner="@mipmap/ic_launcher_round"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppTheme">
        <activity
            android:name=".AppActivity"
            android:excludeFromRecents="true"
            android:exported="true"
            android:launchMode="singleTask"
            android:stateNotNeeded="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LAUNCHER_APP" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.MONKEY" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".broadcast_receivers.PackageChangeReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_CHANGED" />
                <action android:name="android.intent.action.PACKAGE_FULLY_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

any leads are appreciated. Thanks.

Body:
I am developing a Launcher app for Android TV and want to override the functionality of Home button. I want to bring my Application's Activity to top when Home button is pressed so that it acts as default launcher. I tried this Android Studio TV remote buttons but did not work. It is definitely possible because there are button mapper apps on the PlayStore. I have this in my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_TV_LISTINGS" />

    <uses-feature
        android:name="android.hardware.touchscreen"
        android:required="false" />
    <uses-feature
        android:name="android.software.leanback"
        android:required="true" />

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

    <queries>
        <intent>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.action.LAUNCHER" />
        </intent>
    </queries>

    <application
        android:name=".AppName"
        android:allowBackup="true"
        android:banner="@mipmap/ic_launcher_round"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppTheme">
        <activity
            android:name=".AppActivity"
            android:excludeFromRecents="true"
            android:exported="true"
            android:launchMode="singleTask"
            android:stateNotNeeded="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LAUNCHER_APP" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.MONKEY" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".broadcast_receivers.PackageChangeReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_CHANGED" />
                <action android:name="android.intent.action.PACKAGE_FULLY_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

any leads are appreciated. Thanks.


问:
Message (user) attribute 'tracestate' must contain a non-empty value of type 'String'
Getting Message (user) attribute 'tracestate' must contain a non-empty value of type 'String' while trying to push the data in AWS SQS.

Using below body and function to push the data

Function used

```<code>import aws, { SQS } from 'aws-sdk';
import { ServiceConfigurationOptions } from 'aws-sdk/lib/service';

export default abstract class AbstractSQSPublisherService {
  protected sqs: SQS;
  private options: Parameters<typeof aws.config.update>[0];

  constructor(protected queueUrl: string, options: ServiceConfigurationOptions) {
    this.options = options;
    this.sqs = new SQS({ ...options, apiVersion: '2012-11-05' });
  }

  protected async publishToSqs(body: Record<string, unknown>) {
    await this.sqs
      .sendMessage({
        QueueUrl: this.queueUrl,
        MessageBody: JSON.stringify(body),
      })
      .promise();
  }
}

</code>```

Unable to find out why this issue is happening? For normal body like {notificationId: 2345} works well but sometimes it throws error shown above.

Body:
Getting Message (user) attribute 'tracestate' must contain a non-empty value of type 'String' while trying to push the data in AWS SQS.

Using below body and function to push the data

Function used

import aws, { SQS } from 'aws-sdk';
import { ServiceConfigurationOptions } from 'aws-sdk/lib/service';

export default abstract class AbstractSQSPublisherService {
  protected sqs: SQS;
  private options: Parameters<typeof aws.config.update>[0];

  constructor(protected queueUrl: string, options: ServiceConfigurationOptions) {
    this.options = options;
    this.sqs = new SQS({ ...options, apiVersion: '2012-11-05' });
  }

  protected async publishToSqs(body: Record<string, unknown>) {
    await this.sqs
      .sendMessage({
        QueueUrl: this.queueUrl,
        MessageBody: JSON.stringify(body),
      })
      .promise();
  }
}

Unable to find out why this issue is happening? For normal body like {notificationId: 2345} works well but sometimes it throws error shown above.


问:
Video loading issue on unity
I am using unity for a application, in that application i want to play a video from Amazon S3 . but the video was loading all at a time instead of straming like YouTube. Some one who is expert in this please help me.
Thanks in advance

I want video play in stream manner instead of loading all at once

Title: Video loading issue on unity


问:
TradingView Pine Editor - How to not join changing values in one line?
Here is my current pine script plotting opens and closes:

```<code>plot(swt ? weekOpen : na, title="Weekly Open", style=line, linewidth=2, color=green,transp=0)
plot(swt ? weekClose  : na, title="Weekly Close", style=line, linewidth=2, color=red,transp=0)
plot(spw ? monthClose : na, title="Monthly Close", style=circles, linewidth=3, color=black, transp=0)
</code>```

This is what it looks like:

I want the style to be a line and behave like the circles, except not being circles because they are not very accurate. I don't want the changing values to join up, how do I do this?

This is what my script looks like on MT4 (different code):

Body:
Here is my current pine script plotting opens and closes:

plot(swt ? weekOpen : na, title="Weekly Open", style=line, linewidth=2, color=green,transp=0)
plot(swt ? weekClose  : na, title="Weekly Close", style=line, linewidth=2, color=red,transp=0)
plot(spw ? monthClose : na, title="Monthly Close", style=circles, linewidth=3, color=black, transp=0)

This is what it looks like:

I want the style to be a line and behave like the circles, except not being circles because they are not very accurate. I don't want the changing values to join up, how do I do this?

This is what my script looks like on MT4 (different code):


问:
I am using Graphcms with reactjs, I am getting different data on fetching the data on react and on api playground of cms
enter image description here

In first picture I am running query on api playground of hygraph cms and in data it is showing data correctly, and like url of author is defined
In second picture I am fetching data from hygraph using apollo client on react using useQuery hook and showing data on console but it is showing the author url as null.
In third picture, the code for the react is given

why it's happening if I am using the same query ?


问:
migration of Hazelcast from 3 series to 5 series issue in AbstractEntryProcessor while extending it
alternate of below code

```<code>import com.hazelcast.map.AbstractEntryProcessor;

public class <ClassName> extends AbstractEntryProcessor<a,b>{

// body of the class

}

</code>```

error --> Cannot resolve symbol 'AbstractEntryProcessor'

please don't give the link of documentation and i know AbstractEntryProcessor is removed
SomeOne please help me in this

Body:
alternate of below code

import com.hazelcast.map.AbstractEntryProcessor;

public class <ClassName> extends AbstractEntryProcessor{

// body of the class

}

error --> Cannot resolve symbol 'AbstractEntryProcessor'

please don't give the link of documentation and i know AbstractEntryProcessor is removed
SomeOne please help me in this


问:
Java CLI binaries seem to behave differently on Linux and Windows
Java CLI binaries seem to behave differently on Linux and Windows.
It runs fine on Windows, but gives an error on Linux.

```<code># reproduce on linux or windows
git clone https://github.com/jmnote/demo.git
cd demo
javac -d bin -cp "lib/*" src/*
java -cp "bin;lib/*" App
</code>```
```<code>root@linux01:~:/demo# find | grep '.ja'
./src/App.java
./lib/gson-2.10.jar

root@linux01:~:/demo# cat src/App.java
import com.google.gson.Gson;

public class App {
    public static void main(String[] args) {
        Gson gson = new Gson();
        System.out.println("hello");
        System.out.println(gson);
    }
}
</code>```
```<code>PS C:\Users\user01> git clone https://github.com/jmnote/demo.git
Cloning into 'demo'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 10 (delta 1), reused 6 (delta 0), pack-reused 0
Receiving objects: 100% (10/10), 249.38 KiB | 22.67 MiB/s, done.
Resolving deltas: 100% (1/1), done.

PS C:\Users\user01> cd demo
PS C:\Users\user01\demo> javac -d bin -cp "lib/*" src/*
PS C:\Users\user01\demo> java -cp "bin;lib/*" App
hello
{serializeNulls:false,factories:[Factory...
</code>```
```<code>root@linux01:~# git clone https://github.com/jmnote/demo.git
Cloning into 'demo'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 10 (delta 1), reused 6 (delta 0), pack-reused 0
Unpacking objects: 100% (10/10), done.

root@linux01:~# cd demo
root@linux01:~/demo# javac -d bin -cp "lib/*" src/*
root@linux01:~/demo# java -cp "bin;lib/*" App
Error: Could not find or load main class App
Caused by: java.lang.ClassNotFoundException: App
</code>```

Why are the results different?
Is there any way to run it without errors on Linux?

Body:
Java CLI binaries seem to behave differently on Linux and Windows.
It runs fine on Windows, but gives an error on Linux.

# reproduce on linux or windows
git clone https://github.com/jmnote/demo.git
cd demo
javac -d bin -cp "lib/*" src/*
java -cp "bin;lib/*" App

root@linux01:~:/demo# find | grep '.ja'
./src/App.java
./lib/gson-2.10.jar

root@linux01:~:/demo# cat src/App.java
import com.google.gson.Gson;

public class App {
    public static void main(String[] args) {
        Gson gson = new Gson();
        System.out.println("hello");
        System.out.println(gson);
    }
}

PS C:\Users\user01> git clone https://github.com/jmnote/demo.git
Cloning into 'demo'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 10 (delta 1), reused 6 (delta 0), pack-reused 0
Receiving objects: 100% (10/10), 249.38 KiB | 22.67 MiB/s, done.
Resolving deltas: 100% (1/1), done.

PS C:\Users\user01> cd demo
PS C:\Users\user01\demo> javac -d bin -cp "lib/*" src/*
PS C:\Users\user01\demo> java -cp "bin;lib/*" App
hello
{serializeNulls:false,factories:[Factory...

root@linux01:~# git clone https://github.com/jmnote/demo.git
Cloning into 'demo'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 10 (delta 1), reused 6 (delta 0), pack-reused 0
Unpacking objects: 100% (10/10), done.

root@linux01:~# cd demo
root@linux01:~/demo# javac -d bin -cp "lib/*" src/*
root@linux01:~/demo# java -cp "bin;lib/*" App
Error: Could not find or load main class App
Caused by: java.lang.ClassNotFoundException: App

Why are the results different?
Is there any way to run it without errors on Linux?