问:
Is there any way to extend the speech to text time using "SpeechRecognition - Web APIs"?
I'm creating an extension for Chrome that should use "speech to text". It should recognize a numbers that the user says. This works all correctly, although it has some limits...

Even if I have set recognition.continuous = true;, it turns off the google extension after 5 minutes. Is there any solution (ideally free) that would extend this time?

Is there any solution that will reduce the the time from last speech recognition to actually write it down?

Is there any solution that will extend the "silent" time (It's around 3-4 seconds by default)? The result in console says "content.js:60 no-speech"

Content.js

```<code>window.speechToText = function () {
  // Check if the browser supports the SpeechRecognition API
  if ("webkitSpeechRecognition" in window) {
    var recognition = new webkitSpeechRecognition();
    recognition.continuous = true;
    recognition.interimResults = true;

    recognition.start();

    var transcript = "";

    recognition.onresult = function (event) {
      transcript = "";
      // Get the transcription of the speech
      for (var i = event.resultIndex; i < event.results.length; i++) {
        if (event.results[i].isFinal) {
          transcript += event.results[i][0].transcript;
        }
      }

      // Filter the transcription to keep only the digits
      transcript = transcript.replace(/[^0-9]/g, "");

      // Log the filtered transcription to the console
      console.log(transcript);
      console.log("\n");

      document.querySelector(".input_area").innerHTML = transcript;

      document.querySelector(".input_area").dispatchEvent(
        new KeyboardEvent("keydown", {
          code: "Enter",
          key: "Enter",
          charCode: 13,
          keyCode: 13,
          view: window,
          bubbles: true,
        })
      );
    };

    recognition.onerror = function (event) {
      // Handle the error
      switch (event.error) {
        case "network":
          console.error("There was a network error");
          break;
        case "not-allowed":
          console.error("The user has denied permission to use the microphone");
          break;
        case "service-not-allowed":
          console.error(
            "The user has denied permission to use the speech recognition service"
          );
          break;
        default:
          console.error(event.error);
      }
    };
  } else {
    console.error("Speech recognition is not supported in this browser");
  }
};

</code>```

pupup.js

```<code>document.addEventListener('DOMContentLoaded', function() {
  var speechSwitch = document.getElementById('speech-switch');

  speechSwitch.addEventListener('change', function() {
    if (speechSwitch.checked) {
      // Start speech recognition
      chrome.tabs.executeScript({
        code: 'window.speechToText()'
      });
    } else {
      // Stop speech recognition
      chrome.tabs.executeScript({
        code: 'window.speechToText.stop()'
      });
    }
  });
});

</code>```

background.js

```<code>chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript({
      code: 'window.speechToText()'
    });
  });
</code>```

After the 5 minutes of recognition going I've got an error relative to network and I tried to fix it this way (cheating that if it stop it will automatically start again), although that's not correct I suppose.

```<code>  // Handle network error by turning off and on the speech recognition
  recognition.onerror = function(event) {
      if (event.error === 'network') {
        speechSwitch.checked = false;
        setTimeout(function() {
          speechSwitch.checked = true;
        }, 1000);
      }
  };
</code>```

Body:
I'm creating an extension for Chrome that should use "speech to text". It should recognize a numbers that the user says. This works all correctly, although it has some limits...

Even if I have set recognition.continuous = true;, it turns off the google extension after 5 minutes. Is there any solution (ideally free) that would extend this time?

Is there any solution that will reduce the the time from last speech recognition to actually write it down?

Is there any solution that will extend the "silent" time (It's around 3-4 seconds by default)? The result in console says "content.js:60 no-speech"

Content.js

window.speechToText = function () {
  // Check if the browser supports the SpeechRecognition API
  if ("webkitSpeechRecognition" in window) {
    var recognition = new webkitSpeechRecognition();
    recognition.continuous = true;
    recognition.interimResults = true;

    recognition.start();

    var transcript = "";

    recognition.onresult = function (event) {
      transcript = "";
      // Get the transcription of the speech
      for (var i = event.resultIndex; i < event.results.length; i++) {
        if (event.results[i].isFinal) {
          transcript += event.results[i][0].transcript;
        }
      }

      // Filter the transcription to keep only the digits
      transcript = transcript.replace(/[^0-9]/g, "");

      // Log the filtered transcription to the console
      console.log(transcript);
      console.log("\n");

      document.querySelector(".input_area").innerHTML = transcript;

      document.querySelector(".input_area").dispatchEvent(
        new KeyboardEvent("keydown", {
          code: "Enter",
          key: "Enter",
          charCode: 13,
          keyCode: 13,
          view: window,
          bubbles: true,
        })
      );
    };

    recognition.onerror = function (event) {
      // Handle the error
      switch (event.error) {
        case "network":
          console.error("There was a network error");
          break;
        case "not-allowed":
          console.error("The user has denied permission to use the microphone");
          break;
        case "service-not-allowed":
          console.error(
            "The user has denied permission to use the speech recognition service"
          );
          break;
        default:
          console.error(event.error);
      }
    };
  } else {
    console.error("Speech recognition is not supported in this browser");
  }
};

pupup.js

document.addEventListener('DOMContentLoaded', function() {
  var speechSwitch = document.getElementById('speech-switch');

  speechSwitch.addEventListener('change', function() {
    if (speechSwitch.checked) {
      // Start speech recognition
      chrome.tabs.executeScript({
        code: 'window.speechToText()'
      });
    } else {
      // Stop speech recognition
      chrome.tabs.executeScript({
        code: 'window.speechToText.stop()'
      });
    }
  });
});

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript({
      code: 'window.speechToText()'
    });
  });

After the 5 minutes of recognition going I've got an error relative to network and I tried to fix it this way (cheating that if it stop it will automatically start again), although that's not correct I suppose.

  // Handle network error by turning off and on the speech recognition
  recognition.onerror = function(event) {
      if (event.error === 'network') {
        speechSwitch.checked = false;
        setTimeout(function() {
          speechSwitch.checked = true;
        }, 1000);
      }
  };


来源: stackexchange

问:
Allow user to download audio derived from text to speech
I am using Web Speech API to convert text to speech in JavaScript. I need help on how I can allow users download the audio from the converted text.

This is my code

```<code>const textarea = document.querySelector("textarea"),
voiceList = document.querySelector("select"),
speechBtn = document.querySelector("button");

let synth = speechSynthesis,
isSpeaking = true;

voices();

function voices(){
    for(let voice of synth.getVoices()){
        let selected = voice.name === "Google US English" ? "selected" : "";
        let option = `<option value="${voice.name}" ${selected}>${voice.name} (${voice.lang})</option>`;
        voiceList.insertAdjacentHTML("beforeend", option);
    }
}

synth.addEventListener("voiceschanged", voices);

function textToSpeech(text){
    let utterance = new SpeechSynthesisUtterance(text);
    for(let voice of synth.getVoices()){
        if(voice.name === voiceList.value){
            utterance.voice = voice;
        }
    }
    synth.speak(utterance);
}

speechBtn.addEventListener("click", e =>{
    e.preventDefault();
    if(textarea.value !== ""){
        if(!synth.speaking){
            textToSpeech(textarea.value);
        }
        if(textarea.value.length > 80){
            setInterval(()=>{
                if(!synth.speaking && !isSpeaking){
                    isSpeaking = true;
                    speechBtn.innerText = "Convert To Speech";
                }else{
                }
            }, 500);
            if(isSpeaking){
                synth.resume();
                isSpeaking = false;
                speechBtn.innerText = "Pause Speech";
            }else{
                synth.pause();
                isSpeaking = true;
                speechBtn.innerText = "Resume Speech";
            }
        }else{
            speechBtn.innerText = "Convert To Speech";
        }
    }
});
</code>```

Is it possible for me to allow users download the audio derived from my text to speech converter.

ContentLicense: CC BY-SA 4.0

Body:
I am using Web Speech API to convert text to speech in JavaScript. I need help on how I can allow users download the audio from the converted text.

This is my code

const textarea = document.querySelector("textarea"),
voiceList = document.querySelector("select"),
speechBtn = document.querySelector("button");

let synth = speechSynthesis,
isSpeaking = true;

voices();

function voices(){
    for(let voice of synth.getVoices()){
        let selected = voice.name === "Google US English" ? "selected" : "";
        let option = `<option value="${voice.name}" ${selected}>${voice.name} (${voice.lang})</option>`;
        voiceList.insertAdjacentHTML("beforeend", option);
    }
}

synth.addEventListener("voiceschanged", voices);

function textToSpeech(text){
    let utterance = new SpeechSynthesisUtterance(text);
    for(let voice of synth.getVoices()){
        if(voice.name === voiceList.value){
            utterance.voice = voice;
        }
    }
    synth.speak(utterance);
}

speechBtn.addEventListener("click", e =>{
    e.preventDefault();
    if(textarea.value !== ""){
        if(!synth.speaking){
            textToSpeech(textarea.value);
        }
        if(textarea.value.length > 80){
            setInterval(()=>{
                if(!synth.speaking && !isSpeaking){
                    isSpeaking = true;
                    speechBtn.innerText = "Convert To Speech";
                }else{
                }
            }, 500);
            if(isSpeaking){
                synth.resume();
                isSpeaking = false;
                speechBtn.innerText = "Pause Speech";
            }else{
                synth.pause();
                isSpeaking = true;
                speechBtn.innerText = "Resume Speech";
            }
        }else{
            speechBtn.innerText = "Convert To Speech";
        }
    }
});

Is it possible for me to allow users download the audio derived from my text to speech converter.


问:
Why MongoDB mismatching my search criteria?

Problem:

Once i hit GET /api/v1/products?categoryName=test 200 3005 - 12.698 ms it retrives the correct result:

{
    "statue": "SUCCESS",
    "results": 1,
    "count": 1,
    "data": [
        {
            "prodBasicInfo": {
                "style": "",
                "kind": "Pet Cages, Carriers & Houses, Pet Parrot Carrier Bag",
                "model": "DM21BC-971",
                ...etc
}
```
<p>However, When i hit <code>GET /api/v1/products?categoryNammmmmmmmmmmmme=test 200 59534 - 89.657 ms </code> it retrives <strong>all items</strong> !! IDK Why but it simply does. And Whatever i type instade of <code>categoryNammmmmmmmmmmmme</code> it returns back all items <strong><code>136</code></strong> :</p>
<pre class="lang-json prettyprint-override"><code>{
    "statue": "SUCCESS",
    "results": 20,
    "count": 136,
    "data": [
        {
            "prodBasicInfo": {
                "style": "",
                "kind": "Pet Cages, Carriers & Houses, Pet Parrot Carrier Bag",
                "model": "DM21BC-971",
                ...etc
}
</code>```

My code Implemintation:

export default class APIFeaturesBuilder {
    readonly reqQuery;
    public modelQuery;
    public collectionCountAfterFiltering;

    constructor(
        modelQuery: any,
        reqQuery?: any,
        collectionCountAfterFiltering?: any
    ) {
        this.modelQuery = modelQuery;
        this.reqQuery = reqQuery;
        this.collectionCountAfterFiltering = collectionCountAfterFiltering;
    }

    public filtering(): any {
        const shallowQr = { ...this.reqQuery };
        const excludedQrFields = ["sort", "page", "limit", "fields"];

        /*
            clean some fields from a copy of 'reqQuery'
            those fields gonna be handled another way.
        */
        for (const key in shallowQr) {
            if (excludedQrFields.includes(key)) delete shallowQr[key];
        }

        /*
            re-shaping the rest of the reqQuery = shallowQr
            to make it looks like mongo's query.
        */

        let reqQueryString = shallowQr ? JSON.stringify(shallowQr) : "";

        reqQueryString = reqQueryString.replace(
            /\b('lte|lt|gte|gt')\b/g,
            (match) => `$${match}`
        );

        const reqQueryProcessed = reqQueryString
            ? JSON.parse(reqQueryString)
            : {};

        console.log(reqQueryProcessed); // { categoryNammmmmmmmmmmmme: 'test' }

        this.modelQuery = this.modelQuery.find(reqQueryProcessed);
        this.collectionCountAfterFiltering =
            this.modelQuery.find(reqQueryProcessed);

        return this;
    }

    // AND OTHER METHODS HERE....
    // ...
}
```
<h4>And this how i use the method:</h4>
<pre class="lang-js prettyprint-override"><code>// >>> read all
export const getAllProducts = async (
    req: Request,
    res: Response
): Promise<void> => {
    try {
        const apiPipsResult = new APIFeaturesBuilder(Product.find(), req.query)
            .filtering()
            .sorting()
            .selectingFields()
            .paginating();
        const prods = await apiPipsResult.modelQuery;

        res.json({
            statue: `SUCCESS`,
            results: prods.length,
            data: prods,
        });
    } catch (err) {
        res.status(400).json({
            message: `Could not find any products.`,
            error: err,
        });
    }
};
</code>```

Body:
Problem:

Once i hit GET /api/v1/products?categoryName=test 200 3005 - 12.698 ms it retrives the correct result:

{
    "statue": "SUCCESS",
    "results": 1,
    "count": 1,
    "data": [
        {
            "prodBasicInfo": {
                "style": "",
                "kind": "Pet Cages, Carriers & Houses, Pet Parrot Carrier Bag",
                "model": "DM21BC-971",
                ...etc
}

However, When i hit GET /api/v1/products?categoryNammmmmmmmmmmmme=test 200 59534 - 89.657 ms  it retrives all items !! IDK Why but it simply does. And Whatever i type instade of categoryNammmmmmmmmmmmme it returns back all items 136 :

{
    "statue": "SUCCESS",
    "results": 20,
    "count": 136,
    "data": [
        {
            "prodBasicInfo": {
                "style": "",
                "kind": "Pet Cages, Carriers & Houses, Pet Parrot Carrier Bag",
                "model": "DM21BC-971",
                ...etc
}

My code Implemintation:

export default class APIFeaturesBuilder {
    readonly reqQuery;
    public modelQuery;
    public collectionCountAfterFiltering;

    constructor(
        modelQuery: any,
        reqQuery?: any,
        collectionCountAfterFiltering?: any
    ) {
        this.modelQuery = modelQuery;
        this.reqQuery = reqQuery;
        this.collectionCountAfterFiltering = collectionCountAfterFiltering;
    }

    public filtering(): any {
        const shallowQr = { ...this.reqQuery };
        const excludedQrFields = ["sort", "page", "limit", "fields"];

        /*
            clean some fields from a copy of 'reqQuery'
            those fields gonna be handled another way.
        */
        for (const key in shallowQr) {
            if (excludedQrFields.includes(key)) delete shallowQr[key];
        }

        /*
            re-shaping the rest of the reqQuery = shallowQr
            to make it looks like mongo's query.
        */

        let reqQueryString = shallowQr ? JSON.stringify(shallowQr) : "";

        reqQueryString = reqQueryString.replace(
            /\b('lte|lt|gte|gt')\b/g,
            (match) => `$${match}`
        );

        const reqQueryProcessed = reqQueryString
            ? JSON.parse(reqQueryString)
            : {};

        console.log(reqQueryProcessed); // { categoryNammmmmmmmmmmmme: 'test' }

        this.modelQuery = this.modelQuery.find(reqQueryProcessed);
        this.collectionCountAfterFiltering =
            this.modelQuery.find(reqQueryProcessed);

        return this;
    }

    // AND OTHER METHODS HERE....
    // ...
}

And this how i use the method:

// >>> read all
export const getAllProducts = async (
    req: Request,
    res: Response
): Promise<void> => {
    try {
        const apiPipsResult = new APIFeaturesBuilder(Product.find(), req.query)
            .filtering()
            .sorting()
            .selectingFields()
            .paginating();
        const prods = await apiPipsResult.modelQuery;

        res.json({
            statue: `SUCCESS`,
            results: prods.length,
            data: prods,
        });
    } catch (err) {
        res.status(400).json({
            message: `Could not find any products.`,
            error: err,
        });
    }
};


问:
ItemsControl DİsplayMemberPath property does not work
In the following code, the variable named attributes is defined as a collection of SchemaAttribute objects, in which each object has a "Name" property and bunch of other properties. I create an ItemsControl object and bind the attributes to it. I also have an Expander object and the data is stored in the expander object.

Expander expander = new Expander();

var attributes = _dataProvider.GetSchemaAttributes();

ItemsControl itemsControl = new ItemsControl();

itemsControl.ItemsSource = attributes;
itemsControl.DisplayMemberPath = "Name";

expander.Content = itemsControl;
```

Using DisplayMemberPath makes expander's content empty. How can I display the Name property properly?

Body:
In the following code, the variable named attributes is defined as a collection of SchemaAttribute objects, in which each object has a "Name" property and bunch of other properties. I create an ItemsControl object and bind the attributes to it. I also have an Expander object and the data is stored in the expander object.

Expander expander = new Expander();

var attributes = _dataProvider.GetSchemaAttributes();

ItemsControl itemsControl = new ItemsControl();

itemsControl.ItemsSource = attributes;
itemsControl.DisplayMemberPath = "Name";

expander.Content = itemsControl;

Using DisplayMemberPath makes expander's content empty. How can I display the Name property properly?


问:
Change the background color of a selected item in a tabbar
I'm developing an app on IOS 15.5 (Xcode 13.4.1) and I want to make a tab bar with this look:

But, I can't make that purple box in the selected item like in the image, and it looks like this:

How can I get that purple box?

This is the code I'm using for this:

```<code>import SwiftUI

var tabcolor = Color(red: 120/255, green: 57/255, blue: 62/255)

struct VistaMain: View {
    @EnvironmentObject var vm: ViewModel
    @State var seleccion : Int = 0

    var colorSeleccion: Color = Color(red: 73 / 255, green: 82 / 255, blue: 189 / 255)

    init(){
        UITabBar.appearance().barTintColor  = UIColor(red: 56/255, green: 57/255, blue: 62/255, alpha: 0)
        UITabBar.appearance().backgroundColor  = UIColor(red: 56/255, green: 57/255, blue: 62/255, alpha: 1)
    }

    var body: some View {
        //InicioView()
        Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
            .ignoresSafeArea()
            .overlay(
        TabView(selection: $seleccion){
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")//.background( frame(width: 30, height: 30))
                }
                .tag(0)
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")
                }
                .tag(1)
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")
                }
                .tag(2)

            VistaPerfilUsuario(usuarioCurrent: vm.usuariosArray[0], foto: UIImage(data: vm.usuariosArray[0].foto!)!).environmentObject(ViewModel())
                .tabItem{
                    Label("Perfil", systemImage: "person.circle.fill")
                }
                .tag(4)
        }
        )
    }
}
</code>```

Is it possible on that iOS version?

Body:
I'm developing an app on IOS 15.5 (Xcode 13.4.1) and I want to make a tab bar with this look:

But, I can't make that purple box in the selected item like in the image, and it looks like this:

How can I get that purple box?

This is the code I'm using for this:

import SwiftUI

var tabcolor = Color(red: 120/255, green: 57/255, blue: 62/255)

struct VistaMain: View {
    @EnvironmentObject var vm: ViewModel
    @State var seleccion : Int = 0

    var colorSeleccion: Color = Color(red: 73 / 255, green: 82 / 255, blue: 189 / 255)

    init(){
        UITabBar.appearance().barTintColor  = UIColor(red: 56/255, green: 57/255, blue: 62/255, alpha: 0)
        UITabBar.appearance().backgroundColor  = UIColor(red: 56/255, green: 57/255, blue: 62/255, alpha: 1)
    }

    var body: some View {
        //InicioView()
        Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
            .ignoresSafeArea()
            .overlay(
        TabView(selection: $seleccion){
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")//.background( frame(width: 30, height: 30))
                }
                .tag(0)
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")
                }
                .tag(1)
            NuevoExperimentoView()
                .tabItem{
                    Label("Nuevo exp", systemImage: "list.bullet.rectangle.portrait")
                }
                .tag(2)

            VistaPerfilUsuario(usuarioCurrent: vm.usuariosArray[0], foto: UIImage(data: vm.usuariosArray[0].foto!)!).environmentObject(ViewModel())
                .tabItem{
                    Label("Perfil", systemImage: "person.circle.fill")
                }
                .tag(4)
        }
        )
    }
}

Is it possible on that iOS version?


问:
Column not updating having array - Laravel Eloquent
I have an column where array gets saved into database and I have made casts into model

Model

protected $fillable = [
    'name',
    'location',
    'country_id',
    'website',
    'phone',
    'images',
];

protected $casts = [
    'images' => 'array',
];
```
<p>Now I have a functionality where I have to remove an element from an array and save it again back to table but I don't know the column does not updates.</p>
<pre class="lang-php prettyprint-override"><code>public function removeImage($id, Request $request)
{
    $image = $request->image;
    $project = Project::findOrFail($id);
    $images = $project->images;
    if (($key = array_search($image, $images)) !== false) {
        unset($images[$key]);
        $imagesArray = array_values(array_filter($images));
        $project->images = $imagesArray;
        $project->save();
        $file = public_path('uploads/'.$image);
        File::delete($file);
    }
}
</code>```

The Column is saving like this:

```<code>["projects\/\/9e14acf681eb26b860bab49bb5da3579.jpg","projects\/\/8f5fbb1bc517eba0f9a229b505a48e1d.jpg","projects\/\/7a1a3dc5c614fb4d9c3dfae0e0200c99.jpg"]
</code>```

I don't know but the updated array is not updating into column.
Any help can be appreciated.

Body:
I have an column where array gets saved into database and I have made casts into model

Model

protected $fillable = [
    'name',
    'location',
    'country_id',
    'website',
    'phone',
    'images',
];

protected $casts = [
    'images' => 'array',
];

Now I have a functionality where I have to remove an element from an array and save it again back to table but I don't know the column does not updates.

public function removeImage($id, Request $request)
{
    $image = $request->image;
    $project = Project::findOrFail($id);
    $images = $project->images;
    if (($key = array_search($image, $images)) !== false) {
        unset($images[$key]);
        $imagesArray = array_values(array_filter($images));
        $project->images = $imagesArray;
        $project->save();
        $file = public_path('uploads/'.$image);
        File::delete($file);
    }
}

The Column is saving like this:

["projects\/\/9e14acf681eb26b860bab49bb5da3579.jpg","projects\/\/8f5fbb1bc517eba0f9a229b505a48e1d.jpg","projects\/\/7a1a3dc5c614fb4d9c3dfae0e0200c99.jpg"]

I don't know but the updated array is not updating into column.
Any help can be appreciated.


问:
Mail getting redirected to a mailbox and can't see why
I am fairly new to the exchange server and I want to have an email for certain users redirected to their Gmail address so I tried something like this:

Set-Mailbox xxx@xyz.com -ForwardingSmtpAddress xxx@gmail.com -DeliverToMailboxAndForward $True

but that wasn't working (no mail made it to Gmail), so in their Outlook settings, I created an inbox rule that applies to all messages and 'redirects' the message to their gmail account. Two issues with that:

Some messages never make it to Gmail and not sure why and have no idea how to even troubleshoot that.

All their mail is getting additionally redirected to my mailbox so I am now getting their messages as well as mine. I have checked everything I can think of on all the mailboxes involved and I don't see how that can be happening.

Does anyone have any ideas?


问:
SwiftUI get scrolling progress with Geometry Reader
im getting problem to make updates on my view by changing scroll progress.

As example let's take case when user start scrolling view, and after value >= 50, subview makes offset by Y to 10.
Animation works, but im getting message on my console:

[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.

```<code>struct TestViw: View {
    @State var animate: Bool = false
    var body: some View {
        VStack(spacing: 0) {
            Rectangle().fill(Color.red)
                .offset(y: animate ? 10 : 0)
            ScrollView{
                VStack{
                    ForEach(0...100, id: \.self) {
                        Text(String($0))
                    }
                }
                .readProgress(onChange: { progress in
                    withAnimation{ animate = progress >= 50 ? true : false }
                })
            }.coordinateSpace(name: "scrollProgress")
        }
    }
}
</code>```

Extension:

```<code>extension View {

 func readProgress(onChange: @escaping (CGFloat) -> Void) -> some View {
        background(
            GeometryReader { geo in
                let value = -geo.frame(in: .named("scrollProgress")).minY

                Color.clear
                    .preference(
                        key: ScrollProportion.self,
                        value: value
                    )
                    .onPreferenceChange(ScrollProportion.self, perform: onChange)
            }
        )
    }
}
</code>```

Body:
im getting problem to make updates on my view by changing scroll progress.

As example let's take case when user start scrolling view, and after value >= 50, subview makes offset by Y to 10.
Animation works, but im getting message on my console:

[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.

struct TestViw: View {
    @State var animate: Bool = false
    var body: some View {
        VStack(spacing: 0) {
            Rectangle().fill(Color.red)
                .offset(y: animate ? 10 : 0)
            ScrollView{
                VStack{
                    ForEach(0...100, id: \.self) {
                        Text(String($0))
                    }
                }
                .readProgress(onChange: { progress in
                    withAnimation{ animate = progress >= 50 ? true : false }
                })
            }.coordinateSpace(name: "scrollProgress")
        }
    }
}

Extension:

extension View {

 func readProgress(onChange: @escaping (CGFloat) -> Void) -> some View {
        background(
            GeometryReader { geo in
                let value = -geo.frame(in: .named("scrollProgress")).minY

                Color.clear
                    .preference(
                        key: ScrollProportion.self,
                        value: value
                    )
                    .onPreferenceChange(ScrollProportion.self, perform: onChange)
            }
        )
    }
}


问:
HEGY.test from pdR produces dimnames error
I was going on about my business with time series and wanted to check for seasonal unit roots. I imported pdR (version = 1.8) and typed

```<code>hegy.out <- HEGY.test(wts=inf_Q, itsd=c(1,0,c(1:3)), regvar=0, selectlags=list(mode="aic", Pmax=12))
</code>```

The inf_Q dataset is also from pdR and this sample code is the example given in HEGY.test documentation.

After i run this suddenly i get this error.

Error in dimnames(regvarcoefs) <- list(regvarnames, colnames) :
length of 'dimnames' [1] not equal to array extent

It got me searching for an answer for why this happens. And i couldn't find it. Probably version related but of which package?

Body:
I was going on about my business with time series and wanted to check for seasonal unit roots. I imported pdR (version = 1.8) and typed

hegy.out <- HEGY.test(wts=inf_Q, itsd=c(1,0,c(1:3)), regvar=0, selectlags=list(mode="aic", Pmax=12))

The inf_Q dataset is also from pdR and this sample code is the example given in HEGY.test documentation.

After i run this suddenly i get this error.

Error in dimnames(regvarcoefs) <- list(regvarnames, colnames) :
length of 'dimnames' [1] not equal to array extent

It got me searching for an answer for why this happens. And i couldn't find it. Probably version related but of which package?


问:
Safes Competiton - How can i improve my safe?
I'm doing a safes competition in assembly and I wrote this safe:
Edit: This is My safe now:

```<code>MySafe:

  mov bx, 0Fh
  mov cx, 10h
  xor [bx], 3F3Fh
  add bx, 2
  and [bx+di], di
  and [bx+si], bh
  mov dx,8
  mov ax, [bx]             ;ax = key , bx = adress
  mov cx, 9
  mov bx,550
  mov word [1234h],2
  mov si, dx                ;si = 8
  mul word [1234h]          ;dx:ax = 2k
  mov [1234h],cx            ;[1234h] = 9
  mov dx, ax                ;dx = 2k & 0xffff
  dec bx                    ;bx = 550 - 1 = 549
  mov cx,si                 ;cx = 8 = si
  mov ax,si                 ;ax = 8

myLoop: ;the loop goes 8 times
  sub bx,ax                 ;bx = 549 - 8
  dec cx
jnz myLoop
  dec bx                    ;bx = 485 - 1 = 484
  mov ax, dx                ;ax = 2k & 0xffff
  add ax,bx                 ;ax = 484 + (2k & 0xffff)
  mul word [1234h]          ;ax = 9 * (484 + (2k & 0xffff))
  cmp ax,4644
  jnz MySafe
</code>```

now, The address of the key is in bx, but I want it will be more hard to find what address of the key for this safe.
The goal is to stop the infinite loop.
Anyone have an idea?

Body:
I'm doing a safes competition in assembly and I wrote this safe:
Edit: This is My safe now:

MySafe:

  mov bx, 0Fh
  mov cx, 10h
  xor [bx], 3F3Fh
  add bx, 2
  and [bx+di], di
  and [bx+si], bh
  mov dx,8
  mov ax, [bx]             ;ax = key , bx = adress
  mov cx, 9
  mov bx,550
  mov word [1234h],2
  mov si, dx                ;si = 8
  mul word [1234h]          ;dx:ax = 2k
  mov [1234h],cx            ;[1234h] = 9
  mov dx, ax                ;dx = 2k & 0xffff
  dec bx                    ;bx = 550 - 1 = 549
  mov cx,si                 ;cx = 8 = si
  mov ax,si                 ;ax = 8

myLoop: ;the loop goes 8 times
  sub bx,ax                 ;bx = 549 - 8
  dec cx
jnz myLoop
  dec bx                    ;bx = 485 - 1 = 484
  mov ax, dx                ;ax = 2k & 0xffff
  add ax,bx                 ;ax = 484 + (2k & 0xffff)
  mul word [1234h]          ;ax = 9 * (484 + (2k & 0xffff))
  cmp ax,4644
  jnz MySafe

now, The address of the key is in bx, but I want it will be more hard to find what address of the key for this safe.
The goal is to stop the infinite loop.
Anyone have an idea?


问:
RuntimeError: This version of jaxlib was built using AVX instructions, which your CPU and/or operating system do not support
I want to use pysyft, when I import syft moudule I get the following error:

RuntimeError: This version of jaxlib was built using AVX instructions, which your CPU and/or operating system do not support. You may be able work around this issue by building jaxlib from source.

system: Mac OS

I follow the tutorial:https://openmined.github.io/PySyft/install_tutorials/overview.html


问:
Android Compose Google Test Crash
I've been having this issues since the first version of the application. As far as I can see, Google using a tool to run the tests on the Compose applications. There is a few crashes are happening that I see on Firebase Crashlytics when the application is "In Review" stage. Here are the crashes:

Fatal Exception: androidx.compose.runtime.ComposeRuntimeError: Compose Runtime internal error. Unexpected or incorrect use of the Compose internal runtime API (Cannot reposition while in an empty region). Please report to Google or use https://goo.gle/compose-feedback

```<code>   at androidx.compose.runtime.ComposerKt.composeRuntimeError(Composer.kt:4383)
   at androidx.compose.runtime.SlotReader.reposition(SlotTable.kt:3448)
   at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2348)
   at androidx.compose.runtime.ComposerImpl.skipToGroupEnd(Composer.kt:2666)
   at androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:164)
   at androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:141)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
   at androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:133)
   at androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:128)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
   at androidx.compose.animation.CrossfadeKt.Crossfade(Crossfade.kt:142)
   at androidx.compose.animation.CrossfadeKt$Crossfade$7.invoke(:17)
   at androidx.compose.animation.CrossfadeKt$Crossfade$7.invoke(:8)
   at androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:145)
   at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2375)
   at androidx.compose.runtime.ComposerImpl.skipCurrentGroup(Composer.kt:2643)
   at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3260)
   at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3238)
   at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:341)
   at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(:1)
   at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:3238)
   at androidx.compose.runtime.ComposerImpl.recompose$runtime_release(Composer.kt:3203)
   at androidx.compose.runtime.CompositionImpl.recompose(Composition.kt:771)
   at androidx.compose.runtime.Recomposer.performRecompose(Recomposer.kt:1031)
   at androidx.compose.runtime.Recomposer.access$performRecompose(Recomposer.kt:125)
   at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:534)
   at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:503)
   at androidx.compose.ui.platform.AndroidUiFrameClock$withFrameNanos$2$callback$1.doFrame(AndroidUiFrameClock.android.kt:34)
   at androidx.compose.ui.platform.AndroidUiDispatcher.performFrameDispatch(AndroidUiDispatcher.android.kt:109)
   at androidx.compose.ui.platform.AndroidUiDispatcher.access$performFrameDispatch(AndroidUiDispatcher.android.kt:41)
   at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.doFrame(AndroidUiDispatcher.android.kt:69)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1035)
   at android.view.Choreographer.doCallbacks(Choreographer.java:845)
   at android.view.Choreographer.doFrame(Choreographer.java:775)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
   at android.os.Handler.handleCallback(Handler.java:938)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loopOnce(Looper.java:201)
   at android.os.Looper.loop(Looper.java:288)
   at android.app.ActivityThread.main(ActivityThread.java:7839)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
</code>```

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference

```<code>   at androidx.test.tools.crawler.platform.RemotePlatform.handleOverlayServiceRequest(RemotePlatform.java:6)
   at androidx.test.tools.crawler.platform.RemotePlatform.messageLoop(RemotePlatform.java:48)
   at androidx.test.tools.crawler.platform.RemotePlatform.lambda$startCrawlAndWaitUntilFinished$0$androidx-test-tools-crawler-platform-RemotePlatform(RemotePlatform.java:1)
   at androidx.test.tools.crawler.platform.RemotePlatform$$ExternalSyntheticLambda1.run(:6)
   at java.lang.Thread.run(Thread.java:920)
</code>```

Since I know this is only happening in Google's review process it's okay but still disturbs me to see this. Anyone has faced with this issue and have a proper solution for this?

P.S: I use compose dependencies with BOM file (version: 2022.12.00)

Title: Android Compose Google Test Crash

Body:
I've been having this issues since the first version of the application. As far as I can see, Google using a tool to run the tests on the Compose applications. There is a few crashes are happening that I see on Firebase Crashlytics when the application is "In Review" stage. Here are the crashes:

Fatal Exception: androidx.compose.runtime.ComposeRuntimeError: Compose Runtime internal error. Unexpected or incorrect use of the Compose internal runtime API (Cannot reposition while in an empty region). Please report to Google or use https://goo.gle/compose-feedback

   at androidx.compose.runtime.ComposerKt.composeRuntimeError(Composer.kt:4383)
   at androidx.compose.runtime.SlotReader.reposition(SlotTable.kt:3448)
   at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2348)
   at androidx.compose.runtime.ComposerImpl.skipToGroupEnd(Composer.kt:2666)
   at androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:164)
   at androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:141)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
   at androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:133)
   at androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:128)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
   at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
   at androidx.compose.animation.CrossfadeKt.Crossfade(Crossfade.kt:142)
   at androidx.compose.animation.CrossfadeKt$Crossfade$7.invoke(:17)
   at androidx.compose.animation.CrossfadeKt$Crossfade$7.invoke(:8)
   at androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:145)
   at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2375)
   at androidx.compose.runtime.ComposerImpl.skipCurrentGroup(Composer.kt:2643)
   at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3260)
   at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3238)
   at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:341)
   at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(:1)
   at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:3238)
   at androidx.compose.runtime.ComposerImpl.recompose$runtime_release(Composer.kt:3203)
   at androidx.compose.runtime.CompositionImpl.recompose(Composition.kt:771)
   at androidx.compose.runtime.Recomposer.performRecompose(Recomposer.kt:1031)
   at androidx.compose.runtime.Recomposer.access$performRecompose(Recomposer.kt:125)
   at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:534)
   at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:503)
   at androidx.compose.ui.platform.AndroidUiFrameClock$withFrameNanos$2$callback$1.doFrame(AndroidUiFrameClock.android.kt:34)
   at androidx.compose.ui.platform.AndroidUiDispatcher.performFrameDispatch(AndroidUiDispatcher.android.kt:109)
   at androidx.compose.ui.platform.AndroidUiDispatcher.access$performFrameDispatch(AndroidUiDispatcher.android.kt:41)
   at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.doFrame(AndroidUiDispatcher.android.kt:69)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1035)
   at android.view.Choreographer.doCallbacks(Choreographer.java:845)
   at android.view.Choreographer.doFrame(Choreographer.java:775)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
   at android.os.Handler.handleCallback(Handler.java:938)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loopOnce(Looper.java:201)
   at android.os.Looper.loop(Looper.java:288)
   at android.app.ActivityThread.main(ActivityThread.java:7839)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference

   at androidx.test.tools.crawler.platform.RemotePlatform.handleOverlayServiceRequest(RemotePlatform.java:6)
   at androidx.test.tools.crawler.platform.RemotePlatform.messageLoop(RemotePlatform.java:48)
   at androidx.test.tools.crawler.platform.RemotePlatform.lambda$startCrawlAndWaitUntilFinished$0$androidx-test-tools-crawler-platform-RemotePlatform(RemotePlatform.java:1)
   at androidx.test.tools.crawler.platform.RemotePlatform$$ExternalSyntheticLambda1.run(:6)
   at java.lang.Thread.run(Thread.java:920)

Since I know this is only happening in Google's review process it's okay but still disturbs me to see this. Anyone has faced with this issue and have a proper solution for this?

P.S: I use compose dependencies with BOM file (version: 2022.12.00)


问:
Firebase hosting connecting custom domain
Have been getting this issue in the picture for days with my site not found

but I can go to it using chessonline-4b2d0.firebaseapp.com

do i just need to wait for google ?

this is a custom domain but we haven't finished setting it up ?

but nothing else on the matter is there anyway i can triple check what is happening?


问:
Where can I find the security options in SQL Server Management Studio?
I'm trying to change server authentication mode, but all the info that I'm finding about it points at a menu that does not appear for me.

Steps tried:

In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.

Yes, no problem at all.

On the Security page, under Server authentication, select the new server authentication mode, and then click OK.

There is no Security page visible to me. There's a bunch of different pages, but Security is not one of them. So where do I go?


问:
Squid proxy service on docker with multiple ip on this same interface
I using squid on docker, and have problem with connect to other site by selected ip.
I always connected by default host ip, not additional failover ip.

My setup:

a) server
-dedicated server on ovh.org
-1 dedicated ip from server, and 6 additional by ovh service 'failover ip'
-each failover ip added to main interface, and I have on main eno1 interface has 7 ip.
-i added all failover-ip by this guide on ovh.org

b) problem
-I added to squid.conf my failover ip, but when I connect to this ip remote and using squid, I always using host ip, not additionaly. What is wrong?
-my gist setup docker-compose, and squid.conf
https://gist.github.com/mxcdh/22baa3d7fa2d9dcb2279520b81d71afa

p.s
When I logged to host, not on squid on docker, and put in terminal:

```<code>ip-failover-1-results
</code>```

It's working, but on squid no.

Body:
I using squid on docker, and have problem with connect to other site by selected ip.
I always connected by default host ip, not additional failover ip.

My setup:

a) server
-dedicated server on ovh.org
-1 dedicated ip from server, and 6 additional by ovh service 'failover ip'
-each failover ip added to main interface, and I have on main eno1 interface has 7 ip.
-i added all failover-ip by this guide on ovh.org

b) problem
-I added to squid.conf my failover ip, but when I connect to this ip remote and using squid, I always using host ip, not additionaly. What is wrong?
-my gist setup docker-compose, and squid.conf
https://gist.github.com/mxcdh/22baa3d7fa2d9dcb2279520b81d71afa

p.s
When I logged to host, not on squid on docker, and put in terminal:

ip-failover-1-results

It's working, but on squid no.


问:
Mapbox countries change style of one single country javascript
I'm using Mapbox country boundaries source to display country shapes over the map.

I need to style each country with a different color. I'm only able to do it when creating a separate layer for each country, but that takes really long to render.

```<code>countriesLayer.setFilter('countries-simplification-data', ['in', 'ADM0_A3_IS'].concat(['US']));
</code>```

Is there a way to style each country/polygon separately using just one single layer?

This is how I create the layer:

```<code>   map.addSource("countries-no-simplification", {
      type: "vector",

      url: "mapbox://mapbox.country-boundaries-v1"
    });

    let countriesLayer = map.addLayer({
      id: "countries-simplification-data",
      type: "fill",
      source: "countries-no-simplification",
      "source-layer": "country_boundaries",

      paint: {
        "fill-color": "#ff69b4",
        "fill-opacity": 0.3
      }
    });
</code>```

Body:
I'm using Mapbox country boundaries source to display country shapes over the map.

I need to style each country with a different color. I'm only able to do it when creating a separate layer for each country, but that takes really long to render.

countriesLayer.setFilter('countries-simplification-data', ['in', 'ADM0_A3_IS'].concat(['US']));

Is there a way to style each country/polygon separately using just one single layer?

This is how I create the layer:

   map.addSource("countries-no-simplification", {
      type: "vector",

      url: "mapbox://mapbox.country-boundaries-v1"
    });

    let countriesLayer = map.addLayer({
      id: "countries-simplification-data",
      type: "fill",
      source: "countries-no-simplification",
      "source-layer": "country_boundaries",

      paint: {
        "fill-color": "#ff69b4",
        "fill-opacity": 0.3
      }
    });


问:
Error: Invalid src prop - next.config.js problem with image component
I hope you can help me with this issue

im my next.config.js, I have:
`

```<code>module.exports = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.googleapis.com',
        pathname: '/[some folder]/**',
      }
    ]
  }
}
</code>```

Yet I get this error:
Error: Invalid src prop (https://storage.googleapis.com/[some folder]/newtest2/DSC_1690.JPG) on next/image, hostname "storage.googleapis.com" is not configured under images in your next.config.js
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

, when I use:

```<code> <Image
src="https://storage.googleapis.com/[some folder]/newtest2/DSC_1690.JPG"
alt="Picture of the author"
width={250}
height={250}
  />
</code>```

the file exists.

I´m runnning in dev mode local

I´ve tried alomst anything and combinations on the config file, nothing works. When I use a local file there´s no problem

Body:
I hope you can help me with this issue

im my next.config.js, I have:
`

module.exports = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.googleapis.com',
        pathname: '/[some folder]/**',
      }
    ]
  }
}

Yet I get this error:
Error: Invalid src prop (https://storage.googleapis.com/[some folder]/newtest2/DSC_1690.JPG) on next/image, hostname "storage.googleapis.com" is not configured under images in your next.config.js
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

, when I use:

 <Image
src="https://storage.googleapis.com/[some folder]/newtest2/DSC_1690.JPG"
alt="Picture of the author"
width={250}
height={250}
  />

the file exists.

I´m runnning in dev mode local

I´ve tried alomst anything and combinations on the config file, nothing works. When I use a local file there´s no problem


问:
Apple Script: how to get notified/alerted when a certain action hasn't been performed for a specific amount of time?
I have a script that says to run a certain app every 60 minutes. Is it possible to be notified/alerted if the said app hasn't run in 61 minutes?</p>
```<code>repeat
tell application "RunThisAppHourly" to launch
end tell
delay 3600
end repeat
</code>```

Body:
I have a script that says to run a certain app every 60 minutes. Is it possible to be notified/alerted if the said app hasn't run in 61 minutes?

repeat
tell application "RunThisAppHourly" to launch
end tell
delay 3600
end repeat


问:
SpringBoot + Spring Security OAuth2 2.0 Resource Server JWT at Startup Expectation is not calling Authorisation Server
Summary :

Testing out Spring Security OAuth2 Resource Server JWT with SpringBoot 2.7.7 which uses Spring Security 5.7.6 to query Authorisation Server at startup.

According to :
https://docs.spring.io/spring-security/reference/5.7/servlet/oauth2/resource-server/jwt.html#_startup_expectations

Startup Expectations

When this property and these dependencies are used, Resource Server
will automatically configure itself to validate JWT-encoded Bearer
Tokens.

It achieves this through a deterministic startup process:

Query the Provider Configuration or Authorization Server Metadata endpoint for the jwks_url property

Query the jwks_url endpoint for supported algorithms

Configure the validation strategy to query jwks_url for valid public keys of the algorithms found

Configure the validation strategy to validate each JWTs iss claim against idp.example.com.

A consequence of this process is that the authorization server must be
up and receiving requests in order for Resource Server to successfully
start up.

If the authorization server is down when Resource Server queries it
(given appropriate timeouts), then startup will fail.

I have the property defined in application.properties AND the dependencies in pom.xml as above.

However, my very small example to try this out does not work ( e.g. The Resource Server does not appear to be querying the Authorisation Server at all at startup, and therefore the Resource Server starts-up successfully.

I was expecting my very small app to fail at startup as per documentation, but it did not ! Went as far as shutting down the Authorisation Server, and the SpringBoot Resources Server app still starts up.

Here's what I did :

1) pom.xml

```<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>2.7.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.example</groupId>
    <artifactId>oauth2-resource-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>oauth2-resource-server</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2021.0.5</spring-cloud.version>
        <bootstrap.version>5.2.3</bootstrap.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!--dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency-->
        <!--dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>${bootstrap.version}</version>
        </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.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

2. application.properties

```<code>server.port=8081
spring.thymeleaf.cache=false

spring.security.oauth2.resourceserver.jwt.issuer-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/connect/jwk_uri
</code>```

3. Configuration class:

```<code>package org.example.oauth2resourceserver;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    String jwkSetUri;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .antMatchers(HttpMethod.GET, "/**").hasAuthority("SCOPE_message:read")
                        .antMatchers(HttpMethod.POST, "/**").hasAuthority("SCOPE_message:write")
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
    }
}
</code>```

4. Controller

```<code>package org.example.oauth2resourceserver;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ExampleMVCController {

    @GetMapping("/")
    public String main(Model model) {
        return "welcome";
    }

    @GetMapping("/welcome")
    public String welcome(Model model) {
        return "welcome";
    }
}
</code>```

5. Application

```<code>package org.example.oauth2resourceserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Oauth2ResourceServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(Oauth2ResourceServerApplication.class, args);
    }

}
</code>```

With the Authorisation Server down, output on the console when I run the Resource Server is:

```<code>2022-12-28 03:32:38.148  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : Starting Oauth2ResourceServerApplication using Java 11.0.15 on xxxxx-Inspiron-15-7510 with PID 1377958 (/home/xxxxx/projects/oauth2-resource-server/target/classes started by jsalvo in /home/xxxxx/projects/oauth2-resource-server)
2022-12-28 03:32:38.150  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : No active profile set, falling back to 1 default profile: "default"
2022-12-28 03:32:38.561  INFO 1377958 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=12f14043-de4d-3b01-a8aa-ef038a41274e
2022-12-28 03:32:38.733  INFO 1377958 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2022-12-28 03:32:38.739  INFO 1377958 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-12-28 03:32:38.739  INFO 1377958 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.70]
2022-12-28 03:32:38.819  INFO 1377958 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-12-28 03:32:38.820  INFO 1377958 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 634 ms
2022-12-28 03:32:38.931  INFO 1377958 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@748ac6f3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@68f6e55d, org.springframework.security.web.context.SecurityContextPersistenceFilter@2bfaba70, org.springframework.security.web.header.HeaderWriterFilter@5584d9c6, org.springframework.security.web.csrf.CsrfFilter@3bf54172, org.springframework.security.web.authentication.logout.LogoutFilter@58af5076, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter@650c405c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@9301672, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2577a95d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6fff46bf, org.springframework.security.web.session.SessionManagementFilter@17e9bc9e, org.springframework.security.web.access.ExceptionTranslationFilter@4da39ca9, org.springframework.security.web.access.intercept.AuthorizationFilter@2954f6ab]
2022-12-28 03:32:39.140  INFO 1377958 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2022-12-28 03:32:39.152  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : Started Oauth2ResourceServerApplication in 1.27 seconds (JVM running for 1.512)
</code>```

What am I missing ?

What code in Spring Security OAuth2 Resource Server does the call to the Authorisation Server at startup ?

UPDATE 2022-12-28

As suggested by the comments, I have completely removed my OAuth2ResourceServerSecurityConfiguration above. Still no luck.

On looking at the source code for OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration :

It appears that you must only specify one of the following properties, but not both:

```<code>spring.security.oauth2.resourceserver.jwt.issuer-uri
spring.security.oauth2.resourceserver.jwt.jwk-set-uri
</code>```

The method at :

JwtDecoderConfiguration.jwtDecoderByIssuerUri() method has an @IssuerUriCondition annotation that dictates a condition where you must only have the spring.security.oauth2.resourceserver.jwt.issuer-uri property defined.

So I commented out the other property ( commented out spring.security.oauth2.resourceserver.jwt.jwk-set-uri from application.properties), but when I debug into that method via IntelliJ, it steps at line 139 below but it does not step / stop at line 141 within the lambda, which is where the code that actually calls the authorisation server, even if I try to Step-In ( F7 ) from line 139:

In short, I am still at a loss. Anyone have any ideas ?

Body:
Summary :

Testing out Spring Security OAuth2 Resource Server JWT with SpringBoot 2.7.7 which uses Spring Security 5.7.6 to query Authorisation Server at startup.

According to :
https://docs.spring.io/spring-security/reference/5.7/servlet/oauth2/resource-server/jwt.html#_startup_expectations

Startup Expectations

When this property and these dependencies are used, Resource Server
will automatically configure itself to validate JWT-encoded Bearer
Tokens.

It achieves this through a deterministic startup process:

Query the Provider Configuration or Authorization Server Metadata endpoint for the jwks_url property

Query the jwks_url endpoint for supported algorithms

Configure the validation strategy to query jwks_url for valid public keys of the algorithms found

Configure the validation strategy to validate each JWTs iss claim against idp.example.com.

A consequence of this process is that the authorization server must be
up and receiving requests in order for Resource Server to successfully
start up.

If the authorization server is down when Resource Server queries it
(given appropriate timeouts), then startup will fail.

I have the property defined in application.properties AND the dependencies in pom.xml as above.

However, my very small example to try this out does not work ( e.g. The Resource Server does not appear to be querying the Authorisation Server at all at startup, and therefore the Resource Server starts-up successfully.

I was expecting my very small app to fail at startup as per documentation, but it did not ! Went as far as shutting down the Authorisation Server, and the SpringBoot Resources Server app still starts up.

Here's what I did :

1) pom.xml

<?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>2.7.7</version>
        <relativePath/>
    </parent>
    <groupId>org.example</groupId>
    <artifactId>oauth2-resource-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>oauth2-resource-server</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2021.0.5</spring-cloud.version>
        <bootstrap.version>5.2.3</bootstrap.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>${bootstrap.version}</version>
        </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.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

2. application.properties

server.port=8081
spring.thymeleaf.cache=false

spring.security.oauth2.resourceserver.jwt.issuer-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/connect/jwk_uri

3. Configuration class:

package org.example.oauth2resourceserver;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    String jwkSetUri;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .antMatchers(HttpMethod.GET, "/**").hasAuthority("SCOPE_message:read")
                        .antMatchers(HttpMethod.POST, "/**").hasAuthority("SCOPE_message:write")
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
    }
}

4. Controller

package org.example.oauth2resourceserver;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ExampleMVCController {

    @GetMapping("/")
    public String main(Model model) {
        return "welcome";
    }

    @GetMapping("/welcome")
    public String welcome(Model model) {
        return "welcome";
    }
}

5. Application

package org.example.oauth2resourceserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Oauth2ResourceServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(Oauth2ResourceServerApplication.class, args);
    }

}

With the Authorisation Server down, output on the console when I run the Resource Server is:

2022-12-28 03:32:38.148  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : Starting Oauth2ResourceServerApplication using Java 11.0.15 on xxxxx-Inspiron-15-7510 with PID 1377958 (/home/xxxxx/projects/oauth2-resource-server/target/classes started by jsalvo in /home/xxxxx/projects/oauth2-resource-server)
2022-12-28 03:32:38.150  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : No active profile set, falling back to 1 default profile: "default"
2022-12-28 03:32:38.561  INFO 1377958 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=12f14043-de4d-3b01-a8aa-ef038a41274e
2022-12-28 03:32:38.733  INFO 1377958 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2022-12-28 03:32:38.739  INFO 1377958 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-12-28 03:32:38.739  INFO 1377958 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.70]
2022-12-28 03:32:38.819  INFO 1377958 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-12-28 03:32:38.820  INFO 1377958 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 634 ms
2022-12-28 03:32:38.931  INFO 1377958 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@748ac6f3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@68f6e55d, org.springframework.security.web.context.SecurityContextPersistenceFilter@2bfaba70, org.springframework.security.web.header.HeaderWriterFilter@5584d9c6, org.springframework.security.web.csrf.CsrfFilter@3bf54172, org.springframework.security.web.authentication.logout.LogoutFilter@58af5076, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter@650c405c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@9301672, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2577a95d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6fff46bf, org.springframework.security.web.session.SessionManagementFilter@17e9bc9e, org.springframework.security.web.access.ExceptionTranslationFilter@4da39ca9, org.springframework.security.web.access.intercept.AuthorizationFilter@2954f6ab]
2022-12-28 03:32:39.140  INFO 1377958 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2022-12-28 03:32:39.152  INFO 1377958 --- [           main] o.e.o.Oauth2ResourceServerApplication    : Started Oauth2ResourceServerApplication in 1.27 seconds (JVM running for 1.512)

What am I missing ?

What code in Spring Security OAuth2 Resource Server does the call to the Authorisation Server at startup ?

UPDATE 2022-12-28

As suggested by the comments, I have completely removed my OAuth2ResourceServerSecurityConfiguration above. Still no luck.

On looking at the source code for OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration :

It appears that you must only specify one of the following properties, but not both:

spring.security.oauth2.resourceserver.jwt.issuer-uri
spring.security.oauth2.resourceserver.jwt.jwk-set-uri

The method at :

JwtDecoderConfiguration.jwtDecoderByIssuerUri() method has an @IssuerUriCondition annotation that dictates a condition where you must only have the spring.security.oauth2.resourceserver.jwt.issuer-uri property defined.

So I commented out the other property ( commented out spring.security.oauth2.resourceserver.jwt.jwk-set-uri from application.properties), but when I debug into that method via IntelliJ, it steps at line 139 below but it does not step / stop at line 141 within the lambda, which is where the code that actually calls the authorisation server, even if I try to Step-In ( F7 ) from line 139:

In short, I am still at a loss. Anyone have any ideas ?


问:
how to preview core data in a PreviewProvider
This is in my View

```<code>struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let persistenceController = PersistenceController.shared
    ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.previewDevice("iphone 14 pro")
    }
}
</code>```

This is in my persistence file

```<code>import CoreData

class PersistenceController: ObservableObject {
     static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            let TodoItem = Todo(context: viewContext)
            TodoItem.name = "clean"
            TodoItem.priority = "High"

        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "coreDataToDo")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}
</code>```

I cant figure out how to load the data that is stored in core data and not that data that I randomly generated in PersistenceController in the for loop. What I am getting in the preview is mostly what is in the forloop

Body:
This is in my View

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let persistenceController = PersistenceController.shared
    ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.previewDevice("iphone 14 pro")
    }
}

This is in my persistence file

import CoreData

class PersistenceController: ObservableObject {
     static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            let TodoItem = Todo(context: viewContext)
            TodoItem.name = "clean"
            TodoItem.priority = "High"

        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "coreDataToDo")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

I cant figure out how to load the data that is stored in core data and not that data that I randomly generated in PersistenceController in the for loop. What I am getting in the preview is mostly what is in the forloop


问:
Filter Table by date vba
I am having trouble filtering a table by date. All the other filters work in the code and the variable(MonthNumber) carries the date into this sub. Moving the ordering of the filters makes no differance.

```<code>Sub FilterRawDataTbl(HomeCode, MonthNumber, CompanyName)
Sheets("Raw Data").Activate
On Error Resume Next
rawData.AutoFilter.ShowAllData
On Error GoTo 0

rawData.Range.AutoFilter Field:=1, _
    Criteria1:=HomeCode

rawData.Range.AutoFilter Field:=4, _
    Criteria1:="=*" & CompanyName & "*", Operator:=xlAnd

rawData.Range.AutoFilter Field:=2, _
    Criteria1:="<=" & MonthNumber, Operator:=xlAnd
End Sub
</code>```

I would like it to filter Before or equal to the date that is carried in the variable.

Title: Filter Table by date vba

Body:
I am having trouble filtering a table by date. All the other filters work in the code and the variable(MonthNumber) carries the date into this sub. Moving the ordering of the filters makes no differance.

Sub FilterRawDataTbl(HomeCode, MonthNumber, CompanyName)
Sheets("Raw Data").Activate
On Error Resume Next
rawData.AutoFilter.ShowAllData
On Error GoTo 0

rawData.Range.AutoFilter Field:=1, _
    Criteria1:=HomeCode

rawData.Range.AutoFilter Field:=4, _
    Criteria1:="=*" & CompanyName & "*", Operator:=xlAnd

rawData.Range.AutoFilter Field:=2, _
    Criteria1:="<=" & MonthNumber, Operator:=xlAnd
End Sub

I would like it to filter Before or equal to the date that is carried in the variable.


问:
How can I speed up transcription availability for Zoom calls?
I'm building a Zoom integration with the Zoom API.

After a call, I would like to access the call transcript within 5 minutes. However, Zoom API only provides this later. I often experience 15-60 minutes delays.

How could I get the call transcript faster at a reasonable cost?

Options I have considered:

Don't build for Zoom

But my target users are here

Send bots to meetings

But it's costly and having a bot in a meeting can be a bad experience

Get people to use Zoom in their browser and capture captions from there

But requires a significant user behavior change

Build Mac and Windows apps that use Zoom local recordings and captions

But increases build complexity significantly

Wait until Zoom speeds up the availability of their transcript after a call

But they might do this only after several years

Educate users that waiting for 15-60 minutes is OK

But they will likely not agree

Use a 3rd party transcription service

But this gets expensive


问:
Can't initialize array of not copyable structs
I have an array of not copyable structs [notCopyableStruct; 10], which I want to later initialize in a for loop like this:

let mut arr: [notCopyableStruct; 10];
for i in 0..10 {
    arr[i] = /* sth. */;
}
```
<p>But Rust won't let me modify an uninitialized array.</p>
<p>I tried using Options since they are made exactly for that, but that doesn't work either since <code>None</code> is an <code>Option<notCopyableStruct></code> type and it can only be copied if <code>notCopyableStruct</code> itself can be copied</p>
<pre class="lang-rs prettyprint-override"><code>let mut arr: [Option<notCopyableStruct>; 10] = [None; 10];
for i in 0..10 {
    arr[i] = Some(/* sth. */);
}
</code>```

I don't want to use a vector since it's completely unnecessary.

Body:
I have an array of not copyable structs [notCopyableStruct; 10], which I want to later initialize in a for loop like this:

let mut arr: [notCopyableStruct; 10];
for i in 0..10 {
    arr[i] = /* sth. */;
}

But Rust won't let me modify an uninitialized array.

I tried using Options since they are made exactly for that, but that doesn't work either since None is an Option<notCopyableStruct> type and it can only be copied if notCopyableStruct itself can be copied

let mut arr: [Option<notCopyableStruct>; 10] = [None; 10];
for i in 0..10 {
    arr[i] = Some(/* sth. */);
}

I don't want to use a vector since it's completely unnecessary.


问:
How do you use returnKeyLabel?
I used returnKeyLabel instead of returnKeyType, but it doesn't work at all.

I tried it on Android, and used a fixed value such as 'go'.

Could it be a problem with the device?

tell me your opinions.

Title: How do you use returnKeyLabel?


问:
how to send binaryMessage in Spring WebSocketHandler?
I am using WebFlux.

No matter what the data client sends, the WebSocket Broker just need to send it back. The logic I want is easy.

I tried to use WebSocketSession.binaryMessage(). However I don't know how to make it work.

I searched on Google and GitHub, but I failed to find the answer. Here's my incorrect code:

```<code>public class ReactiveWebSocketHandler implements WebSocketHandler {
  @Override
  public Mono<Void> handle(WebSocketSession serverSession) {
    return serverSession.send(
        serverSession.receive());
  }
}
</code>```

When running the code above, I got Error:

```<code>io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
 at io.netty.util.internal.ReferenceCountUpdater.toLiveRealRefCnt(ReferenceCountUpdater.java:83)
 Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException
</code>```

Could you tell me how to write the code to implement the logic?

Body:
I am using WebFlux.

No matter what the data client sends, the WebSocket Broker just need to send it back. The logic I want is easy.

I tried to use WebSocketSession.binaryMessage(). However I don't know how to make it work.

I searched on Google and GitHub, but I failed to find the answer. Here's my incorrect code:

public class ReactiveWebSocketHandler implements WebSocketHandler {
  @Override
  public Mono<Void> handle(WebSocketSession serverSession) {
    return serverSession.send(
        serverSession.receive());
  }
}

When running the code above, I got Error:

io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
 at io.netty.util.internal.ReferenceCountUpdater.toLiveRealRefCnt(ReferenceCountUpdater.java:83)
 Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException

Could you tell me how to write the code to implement the logic?


问:
How to use ckeditor5 with Laravel
I install ckeditor5 using npm after install them i put this code in app.js

import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document';
import PageBreak from '@ckeditor/ckeditor5-page-break/src/pagebreak';

DecoupledEditor.builtinPlugins.push(PageBreak);
```
<p>I include the <code>app.js</code> in my <code>blade</code> file and put this code in blade:</p>
<pre class="lang-html prettyprint-override"><code><div class="document-editor__editable"></div>

<script>
    DecoupledEditor
        .create(document.querySelector('.document-editor__editable'), {
            plugins: [PageBreak],
            toolbar: ['pageBreak']
        })
        .then(editor => {
            console.error(editor);
        }).catch(err => {
            console.error(err);
        });
</script>

</code>```

I got this error in console while running npm run dev

image

Title: How to use ckeditor5 with Laravel

Body:
I install ckeditor5 using npm after install them i put this code in app.js

import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document';
import PageBreak from '@ckeditor/ckeditor5-page-break/src/pagebreak';

DecoupledEditor.builtinPlugins.push(PageBreak);

I include the app.js in my blade file and put this code in blade:

I got this error in console while running npm run dev

image


问:
I want to optimize the placements of plants in my raised garden with pyhton
The plants have follwing attributs:

name (obviously)

planting date (e.g. 21.01)

harvest date

good neighbors (e.g. [cucumber, oninion])

bad neighbors

min. distance to next crop (e.g. 20cm)

And I have a raised garden with a defined size ( x * y ), so I can't just plant all the crops I want.

Now I want to write a python code, that can show me the optimal arrangement of my plants for a whole year.

-> I give the programm a list of possible crops
-> The programm shows me the top 5 seeding calender arrangements

On paper I started with the follwing way (but no idea, how i could do that in code)

Sort the crops by the dates: (4 different possible cases for two crops)

I planting date 1 before planting date 2
harvest date 1 before harvest date 2

II planting date 1 after planting date 2
harvest date 1 before harvest date 2

III planting date 1 before planting date 2
harvest date 1 after harvest date 2

IV planting date 1 after planting date 2
harvest date 1 after harvest date 2

For the overlapping dates:
compare every possible arrangement of crops (only good neighbors together, smallest possible distance between them, most crops on the given size)

Does anybody have an idea on how to do this stuff in python?
And are there better ways / algorithms for this sort of optimization?


问:
how to convert ip2location CSV database to BIN data file
I'm building a nodeJs app and I need to get the ISP of each client, I did find a free database of ip to ASN but it's in CSV format.
I'm using the official ip2location NPM package (ip2location-nodejs) to retrieve ip data from a BIN database, but the problem this package accept only BIN databases.
So how can I convert CSV database to BIN data file ?

If the conversion from the CSV to BIN is not possible, what's the best way to query the CSV database to find an ip data


问:
Problem committing a project from RStudio to Github
I'm trying to push my files to my GitHub, but I'm getting the following error:

```<code>error: cannot run rpostback-askpass: No such file or directory
fatal: could not read Username for 'https://github.com': Device not configured
</code>```

Details:

I'm using MAC

My git version: git version 2.32.1 (Apple Git-133)

I'm linking my project to GitHub with HTTP protocole

I ran git config --global user.name and user.mail in the terminal in Rstudio

I tried to use the solution of running git push -u origin main and when I type in my credentials, it gives me the error: "authentication failed". I never changed my password to GitHub, I checked it today to enter the website, it works.

I tried using ssh protocol instead but it seems to be giving me even more errors even though I created my ssh key and added it successfully to my GitHub. Specifically when I click on create new project and add the ssh link Rstudio says:

```<code>Cloning into 'data-science-hw'...
ssh_askpass: exec(rpostback-askpass): No such file or directory Host key verification failed.
fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
</code>```

I went through all the possible suggestions I could find on the internet but none of them worked. I also tried linking a token generated by git, but it work either.

I would be very happy if anybody has any idea what else I could try..

Body:
I'm trying to push my files to my GitHub, but I'm getting the following error:

error: cannot run rpostback-askpass: No such file or directory
fatal: could not read Username for 'https://github.com': Device not configured

Details:

I'm using MAC

My git version: git version 2.32.1 (Apple Git-133)

I'm linking my project to GitHub with HTTP protocole

I ran git config --global user.name and user.mail in the terminal in Rstudio

I tried to use the solution of running git push -u origin main and when I type in my credentials, it gives me the error: "authentication failed". I never changed my password to GitHub, I checked it today to enter the website, it works.

I tried using ssh protocol instead but it seems to be giving me even more errors even though I created my ssh key and added it successfully to my GitHub. Specifically when I click on create new project and add the ssh link Rstudio says:

Cloning into 'data-science-hw'...
ssh_askpass: exec(rpostback-askpass): No such file or directory Host key verification failed.
fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.

I went through all the possible suggestions I could find on the internet but none of them worked. I also tried linking a token generated by git, but it work either.

I would be very happy if anybody has any idea what else I could try..