问:
How to check current fragment is visible or shown to user in Activity
```<code>     class SecondFragment : Fragment() {
            override fun onCreateView(
                inflater: LayoutInflater, container: ViewGroup?,
                savedInstanceState: Bundle?
            ): View? {
                // Inflate the layout for this fragment
                return inflater.inflate(R.layout.fragment_second, container, false)
            }

         fun showOffer(){
            if (isAdded ) {
                activity?.let {

                   tv_offer.postulated(    if (tv_offer.isShown)
{
                            tv.text( = display(activity,"offers is"+offer)
                        }20000)

                    }
                }
            }

        }
    }
</code>```

This my fragment code but sometimes my code crash and shows below crash when i switching to other fragment or view because of

```<code>java.lang.IllegalStateException: Fragment h\{678aa89} (0b01c202-7ded-41a6-9f04-c2b36aec3ec4) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(SourceFile:952)
</code>```

So I am looking solution that when our current fragment is visible to user then only i want to execute that line can any one please help me in this .how to check current fragment is visible to user .

Body:
     class SecondFragment : Fragment() {
            override fun onCreateView(
                inflater: LayoutInflater, container: ViewGroup?,
                savedInstanceState: Bundle?
            ): View? {
                // Inflate the layout for this fragment
                return inflater.inflate(R.layout.fragment_second, container, false)
            }

         fun showOffer(){
            if (isAdded ) {
                activity?.let {

                   tv_offer.postulated(    if (tv_offer.isShown)
{
                            tv.text( = display(activity,"offers is"+offer)
                        }20000)

                    }
                }
            }

        }
    }

This my fragment code but sometimes my code crash and shows below crash when i switching to other fragment or view because of

java.lang.IllegalStateException: Fragment h\{678aa89} (0b01c202-7ded-41a6-9f04-c2b36aec3ec4) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(SourceFile:952)

So I am looking solution that when our current fragment is visible to user then only i want to execute that line can any one please help me in this .how to check current fragment is visible to user .


来源: stackexchange

问:
Alternative of VpnService in iOS (Swift)
We have an android app that has a custom VPN built into it. We have used VpnService class to implement this feature. This is the code in Android used to build a virtual interface.
We create the tunnel first and then create multiple udp sessions in multiple threads.

```<code>try {
   if (vpnInterface == null) {
       Builder builder = new Builder();
       builder.setMtu(1024);
       builder.addAddress("10.10.10.9", 32);
       builder.addRoute("10.10.10.0", 24);
       vpnInterface = builder
              .setSession(getString(R.string.app_name))
              .setConfigureIntent(pendingIntent)
              .setBlocking(true)
              .establish();

       FileDescriptor vpnFileDescriptor = vpnInterface.getFileDescriptor();
       writePacket(vpnFileDescriptor);
       readPacket(vpnFileDescriptor);
     }

    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

We want to do the exact same thing is ios as well. I'm a swift newbie and I tried to work with Network extensions and use the NEPacketTunnelNetworkSettings to replicate this feature but I could not make it work. How would I create a layer 3 virtual network interface in iOS? This is what I have so far.

```<code>import NetworkExtension

class PacketTunnelProvider: NEPacketTunnelProvider {

    override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {

        let serverAddress = "10.10.10.10"
        let clientAddress = "10.10.10.9"
        let mtu = 1024 as NSNumber?
        let netMask = "255.255.255.255"

        let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: serverAddress)
        settings.ipv4Settings = NEIPv4Settings(addresses: [clientAddress], subnetMasks: [netMask])
        settings.ipv4Settings?.includedRoutes = [NEIPv4Route.default()]
        settings.ipv4Settings?.excludedRoutes = []
        settings.mtu = mtu

        setTunnelNetworkSettings(settings){ error in
            if let e = error {
                print("ERROR:",e)
                NSLog("Settings error %@", e.localizedDescription)
            } else {
                NSLog("Settings %@", "Settings have been created successfully and tunnel has started")
            }
        }

    }

    override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
        // Add code here to start the process of stopping the tunnel.
        completionHandler()
    }

    override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
        // Add code here to handle the message.
        if let handler = completionHandler {
            handler(messageData)
        }
    }

    override func sleep(completionHandler: @escaping () -> Void) {
        // Add code here to get ready to sleep.
        completionHandler()
    }

    override func wake() {
        // Add code here to wake up.
    }
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
We have an android app that has a custom VPN built into it. We have used VpnService class to implement this feature. This is the code in Android used to build a virtual interface.
We create the tunnel first and then create multiple udp sessions in multiple threads.

try {
   if (vpnInterface == null) {
       Builder builder = new Builder();
       builder.setMtu(1024);
       builder.addAddress("10.10.10.9", 32);
       builder.addRoute("10.10.10.0", 24);
       vpnInterface = builder
              .setSession(getString(R.string.app_name))
              .setConfigureIntent(pendingIntent)
              .setBlocking(true)
              .establish();

       FileDescriptor vpnFileDescriptor = vpnInterface.getFileDescriptor();
       writePacket(vpnFileDescriptor);
       readPacket(vpnFileDescriptor);
     }

    } catch (Exception e) {
        e.printStackTrace();
    }

We want to do the exact same thing is ios as well. I'm a swift newbie and I tried to work with Network extensions and use the NEPacketTunnelNetworkSettings to replicate this feature but I could not make it work. How would I create a layer 3 virtual network interface in iOS? This is what I have so far.

import NetworkExtension

class PacketTunnelProvider: NEPacketTunnelProvider {

    override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {

        let serverAddress = "10.10.10.10"
        let clientAddress = "10.10.10.9"
        let mtu = 1024 as NSNumber?
        let netMask = "255.255.255.255"

        let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: serverAddress)
        settings.ipv4Settings = NEIPv4Settings(addresses: [clientAddress], subnetMasks: [netMask])
        settings.ipv4Settings?.includedRoutes = [NEIPv4Route.default()]
        settings.ipv4Settings?.excludedRoutes = []
        settings.mtu = mtu

        setTunnelNetworkSettings(settings){ error in
            if let e = error {
                print("ERROR:",e)
                NSLog("Settings error %@", e.localizedDescription)
            } else {
                NSLog("Settings %@", "Settings have been created successfully and tunnel has started")
            }
        }

    }

    override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
        // Add code here to start the process of stopping the tunnel.
        completionHandler()
    }

    override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
        // Add code here to handle the message.
        if let handler = completionHandler {
            handler(messageData)
        }
    }

    override func sleep(completionHandler: @escaping () -> Void) {
        // Add code here to get ready to sleep.
        completionHandler()
    }

    override func wake() {
        // Add code here to wake up.
    }
}


问:
RxJS marble test fail with operator delay()
I have the following test, it works...

```<code>import { TestScheduler } from 'rxjs/internal/testing/TestScheduler';

describe('RxJx', () => {

  const testScheduler = new TestScheduler((actual, expected) => {

    console.log('works here?');

    console.log(actual);
    console.log(expected);

    expect(actual).toEqual(expected);
  });

  it('rxjs delay should work', () => {

    testScheduler.run((helpers) => {
      const {cold, expectObservable} = helpers;
      const sequence1 = cold('-a--b--c---|', {a: 2, b: 2, c: 10});
      // const sequence = '- 1ms a--b--c---|';
      const sequence = '-a--b--c---|';

      expectObservable(
        // sequence1.pipe(delay(1))
        sequence1
      ).toBe(sequence, {a: 2, b: 2, c: 10});

    });

  });

});
</code>```

result screenshot...

but as soon as I add a delay operator, the code stops working.

```<code>import { TestScheduler } from 'rxjs/internal/testing/TestScheduler';
import { delay } from 'rxjs';

describe('RxJx', () => {

  const testScheduler = new TestScheduler((actual, expected) => {

    console.log('works here?');

    console.log(actual);
    console.log(expected);

    expect(actual).toEqual(expected);
  });

  it('rxjs delay should work', () => {

    testScheduler.run((helpers) => {
      const {cold, expectObservable} = helpers;
      const sequence1 = cold('-a--b--c---|', {a: 2, b: 2, c: 10});
      const sequence = ' 1s -a--b--c---|';
      // const sequence = '-a--b--c---|';

      expectObservable(
        sequence1.pipe(delay(1000))
        // sequence1
      ).toBe(sequence, {a: 2, b: 2, c: 10});

    });

  });

});
</code>```

TestScheduler gets confusing result.

result screenshot

Please help me figure out what am I doing wrong?

If I do so, the tests pass...

```<code>const sequence1 = cold('-a--b--c', {a: 2, b: 2, c: 10});
const sequence = ' 1s -a--b--c';
</code>```

result screenshot...

Angular 15, build in test with RxJs

Body:
I have the following test, it works...

import { TestScheduler } from 'rxjs/internal/testing/TestScheduler';

describe('RxJx', () => {

  const testScheduler = new TestScheduler((actual, expected) => {

    console.log('works here?');

    console.log(actual);
    console.log(expected);

    expect(actual).toEqual(expected);
  });

  it('rxjs delay should work', () => {

    testScheduler.run((helpers) => {
      const {cold, expectObservable} = helpers;
      const sequence1 = cold('-a--b--c---|', {a: 2, b: 2, c: 10});
      // const sequence = '- 1ms a--b--c---|';
      const sequence = '-a--b--c---|';

      expectObservable(
        // sequence1.pipe(delay(1))
        sequence1
      ).toBe(sequence, {a: 2, b: 2, c: 10});

    });

  });

});

result screenshot...

but as soon as I add a delay operator, the code stops working.

import { TestScheduler } from 'rxjs/internal/testing/TestScheduler';
import { delay } from 'rxjs';

describe('RxJx', () => {

  const testScheduler = new TestScheduler((actual, expected) => {

    console.log('works here?');

    console.log(actual);
    console.log(expected);

    expect(actual).toEqual(expected);
  });

  it('rxjs delay should work', () => {

    testScheduler.run((helpers) => {
      const {cold, expectObservable} = helpers;
      const sequence1 = cold('-a--b--c---|', {a: 2, b: 2, c: 10});
      const sequence = ' 1s -a--b--c---|';
      // const sequence = '-a--b--c---|';

      expectObservable(
        sequence1.pipe(delay(1000))
        // sequence1
      ).toBe(sequence, {a: 2, b: 2, c: 10});

    });

  });

});

TestScheduler gets confusing result.

result screenshot

Please help me figure out what am I doing wrong?

If I do so, the tests pass...

const sequence1 = cold('-a--b--c', {a: 2, b: 2, c: 10});
const sequence = ' 1s -a--b--c';

result screenshot...

Angular 15, build in test with RxJs


问:
how to send django formset data with ajax?
first I want get data from form and then send this data to server with ajax...

```<code><script>
    document.querySelector('form').addEventListener('submit', (e) => {
        const data = Object.formEntries(new FormData(e.target).entries());
        console.log(data);
        SubmitButtonClicked();
    });
</script>

<script>
    function SubmitButtonClicked(){
        $.ajax({
            dataType:"json",
            type:"POST",
            url:"{% url 'meraj_public:new_rrr' %}",
            data: {
                csrfmiddlewaretoken: "{{ csrf_token }}",
                data: data,
            },

            success: function(response){
                let success = response.success;
                if (succes === false){
                    alert('error');
                }else{
                    alert('success')
                }
            }
        })
    }
</script>
</code>```

but here, data not diplay on console and there was an error:
Uncaught ReferenceError SubmitButtonClicked is not defined

my first question is:
How to get all form data?

and then:
How to send data to the view and check validation of data in order that show error or save data?

Body:
first I want get data from form and then send this data to server with ajax...

but here, data not diplay on console and there was an error:
Uncaught ReferenceError SubmitButtonClicked is not defined

my first question is:
How to get all form data?

and then:
How to send data to the view and check validation of data in order that show error or save data?


问:
Identify if processor config is higher that i3 with system_info2
How could I identify if the CPU configuration is higher than i3 on flutter?

I have already used system_info2 to retrieve the information but for the comparison it is a bit difficult for me.

Here is my code:

```<code>bool isCPUHigherThanI3() {
    final cores = SysInfo.cores;
    bool isCPUCoreI = cores.first.name.contains('i');
    if (isCPUCoreI) {
      var coreNameList = cores.first.name.split(' ');
      var coreI = coreNameList.elementAt(2);
      if (int.parse(coreI.split('').elementAt(1)) >= 3) {
        return true;
      }
    } else {
      if (Platform.isMacOS) {
        return true;
      }
    }
    return false;
  }
</code>```

Body:
How could I identify if the CPU configuration is higher than i3 on flutter?

I have already used system_info2 to retrieve the information but for the comparison it is a bit difficult for me.

Here is my code:

bool isCPUHigherThanI3() {
    final cores = SysInfo.cores;
    bool isCPUCoreI = cores.first.name.contains('i');
    if (isCPUCoreI) {
      var coreNameList = cores.first.name.split(' ');
      var coreI = coreNameList.elementAt(2);
      if (int.parse(coreI.split('').elementAt(1)) >= 3) {
        return true;
      }
    } else {
      if (Platform.isMacOS) {
        return true;
      }
    }
    return false;
  }


问:
Kubernetes - Block direct IP access to service
I have an nginx app set up as load balancer in my k8s infrastructure and I want to block access to it by server ip.

I have assigned to it a public IP address that I used to set up all the DNS entries that I needed, but the service is still accessible by plain IP address.

Is there a k8s way of blocking access that is not behind a domain name?


问:
Importing cell value from different Google Sheets worksheet and extracting number after searching for string (ADVANCED)
I have a sheet where I need to add a number from another worksheet, but it isn't always in the same cell.

Let me explain: I need to add a formula to access a different Sheets file, search for the words "MONTHLY BUDGET: $2000" ("2000" will change as I will have various different sheets) and add to the cell just the number 2000.

I got most of this done by using the formula =VALUE(REGEXREPLACE(VLOOKUP("MONTHLY BUDGET: $*",J2:J100,1,FALSE),"[^[:digit:]]", "")) but this only works if I have the MONTHLY BUDGET information on the same sheet. How can I do this lookup in a different file?

I managed to import the other file information using =IMPORTRANGE(*FILEURL*, "SheetName!A2:A100") but this imports all the rows, since the MONTHLY BUDGTE will sometimes be in row 10, and other times, it may be in row 90. What I don't want to do is have to import 100 rows into my file for each client, just to look for the budget. Any way to do this without importing the entire information?

PS: I cannot edit the file I am importing from.

All I need to do is lookup a speficic text (MONTHLY BUDGET) in another file and import only the cell that contains this text. Can this be done?


问:
Amplify UPDATE_FAILED API key not found
I created an application in amplify aws at first I use apiKey for appsync but then I switched to userPool and when I want to push my changes to amplify I got the error apKey not found from cloudFormation stack

i'm searching now how to delete unused api Key

Title: Amplify UPDATE_FAILED API key not found


问:
Key Error: [ ] not in index ... in pandas
Code:

```<code>mysteries = pd.read_csv("/kaggle/input/oldumu/deneme111.cvs")

cols = ["Time","Fp1","AF3","AF7","Fz","F1","F3","F5","F7","FC1","FC3","FC5","FT7","Cz","C1","C3","C5","T7","CP1","CP3","CP5","TP7","TP9","Pz","P1","P3","P5","P7","PO3","PO7","Oz","O1","Fpz","Fp2","AF4","AF8","F2","F4","F6","F8","FC2","FC4","FC6","FT8","C2","C4","C6","T8","CPz","CP2","CP4","CP6","TP8","TP10","P2","P4","P6","P8","POz","PO4","PO8","O2"]
fig = plt.figure(figsize=(15,14))
ax = fig.add_subplot(2, 3, 1)
ax.imshow(recurrence_plot(pd.read_csv("/kaggle/input/oldumu/deneme111.cvs")[cols].values,steps=1000))
ax.set_xlabel('Walking')
</code>```

Error:

```<code>KeyError: "['Time' 'Fp1' 'AF3' 'AF7' 'Fz' 'F1' 'F3' 'F5' 'F7' 'FC1' 'FC3' 'FC5' 'FT7'\n 'Cz' 'C1' 'C3' 'C5' 'T7' 'CP1' 'CP3' 'CP5' 'TP7' 'TP9' 'Pz' 'P1' 'P3' 'P5'\n 'P7' 'PO3' 'PO7' 'Oz' 'O1' 'Fpz' 'Fp2' 'AF4' 'AF8' 'F2' 'F4' 'F6' 'F8'\n 'FC2' 'FC4' 'FC6' 'FT8' 'C2' 'C4' 'C6' 'T8' 'CPz' 'CP2' 'CP4' 'CP6' 'TP8'\n 'TP10' 'P2' 'P4' 'P6' 'P8' 'POz' 'PO4' 'PO8' 'O2'] not in index"
</code>```

I have a 62x150000 matrix with EEG data. I want to plot the recurrence plot of the data. I found this code on Kaggle and wanted to use it with my own data. It gives me this "key error" when I write the column names of my data .... the long thing like "time,Fp1...".

I have no idea what I'm doing wrong or what should I change. I'm incredibly new to Python.

If anyone can help me I'd appreciate it a lot. I'm gonna link the kaggle too so maybe you can see what I'm missing.

https://www.kaggle.com/code/lkeyter/recuplots-and-cnns-for-time-series-classification

Body:
Code:

mysteries = pd.read_csv("/kaggle/input/oldumu/deneme111.cvs")

cols = ["Time","Fp1","AF3","AF7","Fz","F1","F3","F5","F7","FC1","FC3","FC5","FT7","Cz","C1","C3","C5","T7","CP1","CP3","CP5","TP7","TP9","Pz","P1","P3","P5","P7","PO3","PO7","Oz","O1","Fpz","Fp2","AF4","AF8","F2","F4","F6","F8","FC2","FC4","FC6","FT8","C2","C4","C6","T8","CPz","CP2","CP4","CP6","TP8","TP10","P2","P4","P6","P8","POz","PO4","PO8","O2"]
fig = plt.figure(figsize=(15,14))
ax = fig.add_subplot(2, 3, 1)
ax.imshow(recurrence_plot(pd.read_csv("/kaggle/input/oldumu/deneme111.cvs")[cols].values,steps=1000))
ax.set_xlabel('Walking')

Error:

KeyError: "['Time' 'Fp1' 'AF3' 'AF7' 'Fz' 'F1' 'F3' 'F5' 'F7' 'FC1' 'FC3' 'FC5' 'FT7'\n 'Cz' 'C1' 'C3' 'C5' 'T7' 'CP1' 'CP3' 'CP5' 'TP7' 'TP9' 'Pz' 'P1' 'P3' 'P5'\n 'P7' 'PO3' 'PO7' 'Oz' 'O1' 'Fpz' 'Fp2' 'AF4' 'AF8' 'F2' 'F4' 'F6' 'F8'\n 'FC2' 'FC4' 'FC6' 'FT8' 'C2' 'C4' 'C6' 'T8' 'CPz' 'CP2' 'CP4' 'CP6' 'TP8'\n 'TP10' 'P2' 'P4' 'P6' 'P8' 'POz' 'PO4' 'PO8' 'O2'] not in index"

I have a 62x150000 matrix with EEG data. I want to plot the recurrence plot of the data. I found this code on Kaggle and wanted to use it with my own data. It gives me this "key error" when I write the column names of my data .... the long thing like "time,Fp1...".

I have no idea what I'm doing wrong or what should I change. I'm incredibly new to Python.

If anyone can help me I'd appreciate it a lot. I'm gonna link the kaggle too so maybe you can see what I'm missing.

https://www.kaggle.com/code/lkeyter/recuplots-and-cnns-for-time-series-classification


问:
How do I deal with this 'maximum recursion depth' error in Selenium Python?
I used the Microsoft Power Automate Desktop (PAD) to create a robot that automates a website. In PAD, I created a main flow and some sub-flows labelled Call_1 to Call_5 as shown in the first screenshot below. The main flow executes some codes that opens up the browser and then after jumps into Call_1 and executes the codes in Call_1. At the end of Call_1, a condition is supposed to be met. If the condition is met, the execution jumps to the beginning of Call_1 and Call_1 is then repeated, but if the condition is not met, the flow jumps to Call_2. If the condition is met at the end of Call_2, the flow jumps back to Call_1, if not it jumps forward to Call_3. If condition is met in Call_3 flow jumps back to Call_1, if not it jumps forward to Call_4 and so on until it get to Call_5. If condition is met at Call_5 flow jumps back to Call_1, if not met the flow stops.
first screenshot

Please note that the flow is supposed to run in a loop indefinitely until it either gets stopped at Call_5(with condition not met) or it is manually stopped.

Everything works fine in Power Automate Desktop (PAD) but I am trying to achieve this as well using selenium python. I have set up different python files, written the necessary codes and named them accordingly as main, Call_1, Call_2 and so on, as seen in the second screenshot below. The problem I am having now is that I can't seem to find a way to make the execution of the codes follow the same steps as I have explained above using PAD without hitting an error. I am not able to simply jump back and forth between the python files like I am able to do on the sub-flows in PAD.
second screenshot

I have tried using the import method, I set it to import Call_2 into Call_1 once the condition is not met in Call_1, and to import Call_1 into call Call_2 when the condition is met in Call_2 and when not met, import Call_3 and so on. This kind of works for a while but then runs into a "maximum recursion depth exceeded" error after running for some time.
third screenshot

I want to know if there is a way to deal with this problem on selenium python. I am using PyCharm as an editor.


问:
How to map custom language patterns in VSCode syntax highlighter extension to specific colors in theme?
I like the Dracula VSCode theme. However, I have a new programming language as well, which I have written a basic VSCode syntax highlighter for.

```<code>{
  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
  "name": "Link",
  "patterns": [
    {
      "include": "#nestedtermsexternal"
    },
    {
      "include": "#nestedterms"
    },
    {
      "include": "#terms"
    },
    {
      "include": "#punctuations"
    },
    {
      "include": "#strings"
    },
    {
      "include": "#numbers"
    },
    {
      "include": "#codes"
    },
    {
      "include": "#comments"
    }
  ],
  "repository": {
    "comments": {
      "patterns": [
        {
          "name": "comment.line.number-sign.link",
          "match": "\\# .+"
        }
      ]
    },
    "codes": {
      "patterns": [
        {
          "name": "constant.character.escape.language.link",
          "match": "\\#\\w+"
        }
      ]
    },
    "nestedtermsexternal": {
      "patterns": [
        {
          "name": "entity.language.link",
          "begin": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*) ",
          "beginCaptures": {
            "1": {
              "name": "string.quoted.double.link"
            }
          },
          "end": "[,\n]",
          "patterns": [
            {
              "include": "#terms"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#codes"
            },
            {
              "include": "#comments"
            }
          ]
        }
      ]
    },
    "nestedterms": {
      "patterns": [
        {
          "name": "term.language.link",
          "begin": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(\\()",
          "beginCaptures": {
            "1": {
              "name": "string.quoted.double.link"
            },
            "2": {
              "name": "string.quoted.double.link"
            }
          },
          "end": "\\)",
          "endCaptures": {
            "0": {
              "name": "string.quoted.double.link"
            }
          },
          "patterns": [
            {
              "include": "#comments"
            },
            {
              "include": "#terms"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#codes"
            }
          ]
        }
      ]
    },
    "terms": {
      "patterns": [
        {
          "name": "term.language.link",
          "match": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*)"
        }
      ]
    },
    "numbers": {
      "patterns": [
        {
          "name": "constant.numeric.integer.link",
          "match": "\\d+"
        },
        {
          "name": "constant.numeric.decimal.link",
          "match": "\\d+\\.\\d+"
        }
      ]
    },
    "punctuations": {
      "patterns": [
        {
          "name": "punctuation.separator.parameter.link",
          "match": ","
        }
      ]
    },
    "strings": {
      "name": "template.link",
      "begin": "\\<",
      "beginCaptures": {
        "0": {
          "name": "entity.name.type.link"
        }
      },
      "end": "\\>",
      "endCaptures": {
        "0": {
          "name": "entity.name.type.link"
        }
      },
      "patterns": [
        {
          "include": "#codes"
        },
        {
          "name": "entity.name.type.link",
          "match": "\\\\."
        },
        {
          "name": "punctuation.term.link",
          "begin": "\\{",
          "beginCaptures": {
            "0": {
              "name": "entity.name.type.link"
            }
          },
          "end": "\\}",
          "endCaptures": {
            "0": {
              "name": "entity.name.type.link"
            }
          },
          "patterns": [
            {
              "include": "#nestedterms"
            },
            {
              "include": "#terms"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#punctuations"
            },
            {
              "include": "#codes"
            }
          ]
        },
        {
          "name": "entity.name.type.link",
          "match": "[^\\\\{>]+"
        }
      ]
    }
  },
  "scopeName": "source.link"
}
</code>```

I understand that VSCode takes the things like entity.name.* and maps them to specific colors in each theme automatically. But in the Dracula case, it is mapping the syntax elements to Dracula colors in the wrong configuration (from my design eye perspective). I don't want yellow in this context, and red in this context, I want it to be reversed. But at the same time, semantically I still want the same entity.name.* to be used there.

Is there any way I can tell VSCode, on a theme-by-theme basis, which colors to use in which semantic position?

Body:
I like the Dracula VSCode theme. However, I have a new programming language as well, which I have written a basic VSCode syntax highlighter for.

{
  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
  "name": "Link",
  "patterns": [
    {
      "include": "#nestedtermsexternal"
    },
    {
      "include": "#nestedterms"
    },
    {
      "include": "#terms"
    },
    {
      "include": "#punctuations"
    },
    {
      "include": "#strings"
    },
    {
      "include": "#numbers"
    },
    {
      "include": "#codes"
    },
    {
      "include": "#comments"
    }
  ],
  "repository": {
    "comments": {
      "patterns": [
        {
          "name": "comment.line.number-sign.link",
          "match": "\\# .+"
        }
      ]
    },
    "codes": {
      "patterns": [
        {
          "name": "constant.character.escape.language.link",
          "match": "\\#\\w+"
        }
      ]
    },
    "nestedtermsexternal": {
      "patterns": [
        {
          "name": "entity.language.link",
          "begin": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*) ",
          "beginCaptures": {
            "1": {
              "name": "string.quoted.double.link"
            }
          },
          "end": "[,\n]",
          "patterns": [
            {
              "include": "#terms"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#codes"
            },
            {
              "include": "#comments"
            }
          ]
        }
      ]
    },
    "nestedterms": {
      "patterns": [
        {
          "name": "term.language.link",
          "begin": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(\\()",
          "beginCaptures": {
            "1": {
              "name": "string.quoted.double.link"
            },
            "2": {
              "name": "string.quoted.double.link"
            }
          },
          "end": "\\)",
          "endCaptures": {
            "0": {
              "name": "string.quoted.double.link"
            }
          },
          "patterns": [
            {
              "include": "#comments"
            },
            {
              "include": "#terms"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#codes"
            }
          ]
        }
      ]
    },
    "terms": {
      "patterns": [
        {
          "name": "term.language.link",
          "match": "([a-z][a-z0-9]*(?:-[a-z0-9]+)*)"
        }
      ]
    },
    "numbers": {
      "patterns": [
        {
          "name": "constant.numeric.integer.link",
          "match": "\\d+"
        },
        {
          "name": "constant.numeric.decimal.link",
          "match": "\\d+\\.\\d+"
        }
      ]
    },
    "punctuations": {
      "patterns": [
        {
          "name": "punctuation.separator.parameter.link",
          "match": ","
        }
      ]
    },
    "strings": {
      "name": "template.link",
      "begin": "\\<",
      "beginCaptures": {
        "0": {
          "name": "entity.name.type.link"
        }
      },
      "end": "\\>",
      "endCaptures": {
        "0": {
          "name": "entity.name.type.link"
        }
      },
      "patterns": [
        {
          "include": "#codes"
        },
        {
          "name": "entity.name.type.link",
          "match": "\\\\."
        },
        {
          "name": "punctuation.term.link",
          "begin": "\\{",
          "beginCaptures": {
            "0": {
              "name": "entity.name.type.link"
            }
          },
          "end": "\\}",
          "endCaptures": {
            "0": {
              "name": "entity.name.type.link"
            }
          },
          "patterns": [
            {
              "include": "#nestedterms"
            },
            {
              "include": "#terms"
            },
            {
              "include": "#numbers"
            },
            {
              "include": "#strings"
            },
            {
              "include": "#punctuations"
            },
            {
              "include": "#codes"
            }
          ]
        },
        {
          "name": "entity.name.type.link",
          "match": "[^\\\\{>]+"
        }
      ]
    }
  },
  "scopeName": "source.link"
}

I understand that VSCode takes the things like entity.name.* and maps them to specific colors in each theme automatically. But in the Dracula case, it is mapping the syntax elements to Dracula colors in the wrong configuration (from my design eye perspective). I don't want yellow in this context, and red in this context, I want it to be reversed. But at the same time, semantically I still want the same entity.name.* to be used there.

Is there any way I can tell VSCode, on a theme-by-theme basis, which colors to use in which semantic position?


问:
Access Security Context inside a Project Reactor Operator
I am currently in the process of creating a service which processes requests with the Project Reactor library.

To communicate with external services, each requests to the main service contains a JSON Web Token, which it needs to add to any request made to external services.

To facilitate this, there exists a service-client library, which retrieves the token from
the SecurityContext on each request, and adds it to the request.

What I am now struggling with is how to transfer the security context from the point of entry (the endpoint of the main service) to the point of exit (the service-client request), as the security context does not get transferred automatically between operators.

I have already included the Context Propagation library into the service, as proposed here, but it does not seem to capture the security context.

I also found a blog post, which mentions the following:

[..] the Spring Security authentication context is retrieved from the Project Reactor’s context since the latter is already filled with it by the Spring WebFlux Security module.

This sounds like what I am looking for, but I have not been able to replicate this so far, although I include both spring-boot-starter-webflux and spring-boot-starter-security into the project.

As a short sketch, this is what I am attempting to do:

public void handleRequest(Request request) {
    SecurityContextHolder.getContext().setAuthentication(new BearerTokenAuthenticationToken(request.authorization()));
    Mono.just(request)
      .onNext(request -> {
        return Mono.deferContextual(contextView -> {
            contextView.stream().forEach(objectObjectEntry -> log.info("Key: {}, Value: {}", objectObjectEntry.getKey(), objectObjectEntry.getValue()));  //here I would like to see the authorization set above
            Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // Seeing the authentication object set above here is the goal, so that I can access it in the library.
            return acknowledger.acknowledge();
          })
      })
      .contextCapture()
      .subscribe()
}
```

Does someone know how to solve this?

Body:
I am currently in the process of creating a service which processes requests with the Project Reactor library.

To communicate with external services, each requests to the main service contains a JSON Web Token, which it needs to add to any request made to external services.

To facilitate this, there exists a service-client library, which retrieves the token from
the SecurityContext on each request, and adds it to the request.

What I am now struggling with is how to transfer the security context from the point of entry (the endpoint of the main service) to the point of exit (the service-client request), as the security context does not get transferred automatically between operators.

I have already included the Context Propagation library into the service, as proposed here, but it does not seem to capture the security context.

I also found a blog post, which mentions the following:

[..] the Spring Security authentication context is retrieved from the Project Reactor’s context since the latter is already filled with it by the Spring WebFlux Security module.

This sounds like what I am looking for, but I have not been able to replicate this so far, although I include both spring-boot-starter-webflux and spring-boot-starter-security into the project.

As a short sketch, this is what I am attempting to do:

public void handleRequest(Request request) {
    SecurityContextHolder.getContext().setAuthentication(new BearerTokenAuthenticationToken(request.authorization()));
    Mono.just(request)
      .onNext(request -> {
        return Mono.deferContextual(contextView -> {
            contextView.stream().forEach(objectObjectEntry -> log.info("Key: {}, Value: {}", objectObjectEntry.getKey(), objectObjectEntry.getValue()));  //here I would like to see the authorization set above
            Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // Seeing the authentication object set above here is the goal, so that I can access it in the library.
            return acknowledger.acknowledge();
          })
      })
      .contextCapture()
      .subscribe()
}

Does someone know how to solve this?


问:
In web page, how to get the input-file-name saved on disk after user modify it in dialog-box
I build a text that I want to save on my disk.
I suggest a file-name, but user can modify it.
How to get the final file-name ?
Where can I access to this value in my following-code ?
Which element contains the final file-name ?

Best regards.

```<code>/*
    */
function saveTextOnLocalFile( textToWrite , strFileName, dotAndExt) {

    //  create a new Blob (html5 magic) that conatins the data from your form feild
    let textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});

    // Specify the name of the file to be saved
    if (strFileName == null) {
        strFileName = "export-" + new Date().yyyymmddhhmmss() + dotAndExt;
        }

    // create a link for our script to 'click'
    let downloadLink = document.createElement("a");
    downloadLink.download = strFileName;
    // provide text for the link. This will be hidden
    downloadLink.innerHTML = "My Hidden Link";

    downloadLink.href = window.URL.createObjectURL( textFileAsBlob);
    // when link is clicked call a function to remove it from the DOM in case user wants to save a second file.
    downloadLink.onclick = destroyClickedElement;
    // make sure the link is hidden.
    downloadLink.style.display = "none";
    // add the link to the DOM
    document.body.appendChild(downloadLink);
    // click the new link
    downloadLink.click();
    }

/**/
function destroyClickedElement(event) {
    let downloadLink = event.target;
    let fileName = downloadLink.download;
    // remove the link from the DOM
    document.body.removeChild( event.target);
    }
</code>```

Body:
I build a text that I want to save on my disk.
I suggest a file-name, but user can modify it.
How to get the final file-name ?
Where can I access to this value in my following-code ?
Which element contains the final file-name ?

Best regards.

/*
    */
function saveTextOnLocalFile( textToWrite , strFileName, dotAndExt) {

    //  create a new Blob (html5 magic) that conatins the data from your form feild
    let textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});

    // Specify the name of the file to be saved
    if (strFileName == null) {
        strFileName = "export-" + new Date().yyyymmddhhmmss() + dotAndExt;
        }

    // create a link for our script to 'click'
    let downloadLink = document.createElement("a");
    downloadLink.download = strFileName;
    // provide text for the link. This will be hidden
    downloadLink.innerHTML = "My Hidden Link";

    downloadLink.href = window.URL.createObjectURL( textFileAsBlob);
    // when link is clicked call a function to remove it from the DOM in case user wants to save a second file.
    downloadLink.onclick = destroyClickedElement;
    // make sure the link is hidden.
    downloadLink.style.display = "none";
    // add the link to the DOM
    document.body.appendChild(downloadLink);
    // click the new link
    downloadLink.click();
    }

/**/
function destroyClickedElement(event) {
    let downloadLink = event.target;
    let fileName = downloadLink.download;
    // remove the link from the DOM
    document.body.removeChild( event.target);
    }


问:
Migrate yarn.lock dependencies to bun.lockb file
I want to read yarn.lock file and generate bun.lockb from that with the same dependencies to be used in bun install, without this bun is creating the deps based on package.json and is big projects (specially typescript projects) it brings lost of type conflicts.


问:
Infer shaping does not work for transpose
The infer shape does not seem to work very well for transposes. It doesn't propagate  to the end of the network. According to https://github.com/onnx/onnx/blob/main/docs/ShapeInference.md, this might be because of the dynamic shapes but I don't see what transposes might have to do with dynamic shapes.

Python code generating the network:

```<code>import numpy
import onnx
from onnx.helper import (
make_model, make_node, set_model_props, make_tensor,
make_graph, make_tensor_value_info)

# inputs

# 'X' is the name, TensorProto.FLOAT the type, [None, None] the shape
A = make_tensor_value_info('A', onnx.TensorProto.FLOAT, [32, 128])
B = make_tensor_value_info('B', onnx.TensorProto.FLOAT, [64, 128])
C = make_tensor_value_info('C', onnx.TensorProto.FLOAT, [32, 128])
tB = make_tensor_value_info('tB', onnx.TensorProto.FLOAT, [128, 64])
AtB = make_tensor_value_info('AtB', onnx.TensorProto.FLOAT, [32, 64])
AtBt = make_tensor_value_info('AtBt', onnx.TensorProto.FLOAT, [64, 32])

# outputs, the shape is left undefined

Y = make_tensor_value_info('Y', onnx.TensorProto.FLOAT, [64, 128])

# nodes
node_transpose1 = make_node('Transpose', ['B'], ['tB'], perm=[1, 0])
node_transpose2 = make_node('Transpose', ['AtB'], ['AtBt'], perm=[1, 0])
node1 = make_node('MatMul', ['A', 'tB'], ['AtB'])
node2 = make_node('MatMul', ['AtBt', 'C'], ['Y'])

# from nodes to graph
# the graph is built from the list of nodes, the list of inputs,
# the list of outputs and a name.

graph = make_graph([node_transpose1, node_transpose2, node1, node2],  # nodes
               'lr',  # a name
               [A, B, C],  # inputs
               [Y])  # outputs

# onnx graph
# there is no metata in this case.

onnx_model = make_model(graph)

onnx.save(onnx_model, "model2.onnx")
</code>```

Afterwards, I do shape inferring with

```<code>import onnx
from onnx import shape_inference
model = onnx.load("model2.onnx")
inferred_model = shape_inference.infer_shapes(model)
onnx.save(inferred_model, "model2.onnx")
</code>```

and then, the problem of no propagation can be seen on the figure with the second transpose that has input but no output dimension . Output is again correct because that could be set in the Python. Does anyone see the problem? Thanks!

Body:
The infer shape does not seem to work very well for transposes. It doesn't propagate  to the end of the network. According to https://github.com/onnx/onnx/blob/main/docs/ShapeInference.md, this might be because of the dynamic shapes but I don't see what transposes might have to do with dynamic shapes.

Python code generating the network:

import numpy
import onnx
from onnx.helper import (
make_model, make_node, set_model_props, make_tensor,
make_graph, make_tensor_value_info)

# inputs

# 'X' is the name, TensorProto.FLOAT the type, [None, None] the shape
A = make_tensor_value_info('A', onnx.TensorProto.FLOAT, [32, 128])
B = make_tensor_value_info('B', onnx.TensorProto.FLOAT, [64, 128])
C = make_tensor_value_info('C', onnx.TensorProto.FLOAT, [32, 128])
tB = make_tensor_value_info('tB', onnx.TensorProto.FLOAT, [128, 64])
AtB = make_tensor_value_info('AtB', onnx.TensorProto.FLOAT, [32, 64])
AtBt = make_tensor_value_info('AtBt', onnx.TensorProto.FLOAT, [64, 32])

# outputs, the shape is left undefined

Y = make_tensor_value_info('Y', onnx.TensorProto.FLOAT, [64, 128])

# nodes
node_transpose1 = make_node('Transpose', ['B'], ['tB'], perm=[1, 0])
node_transpose2 = make_node('Transpose', ['AtB'], ['AtBt'], perm=[1, 0])
node1 = make_node('MatMul', ['A', 'tB'], ['AtB'])
node2 = make_node('MatMul', ['AtBt', 'C'], ['Y'])

# from nodes to graph
# the graph is built from the list of nodes, the list of inputs,
# the list of outputs and a name.

graph = make_graph([node_transpose1, node_transpose2, node1, node2],  # nodes
               'lr',  # a name
               [A, B, C],  # inputs
               [Y])  # outputs

# onnx graph
# there is no metata in this case.

onnx_model = make_model(graph)

onnx.save(onnx_model, "model2.onnx")

Afterwards, I do shape inferring with

import onnx
from onnx import shape_inference
model = onnx.load("model2.onnx")
inferred_model = shape_inference.infer_shapes(model)
onnx.save(inferred_model, "model2.onnx")

and then, the problem of no propagation can be seen on the figure with the second transpose that has input but no output dimension . Output is again correct because that could be set in the Python. Does anyone see the problem? Thanks!


问:
How to create/enable sticky sessions in Spring Boot
As I'm working on a vaadin project, I need sticky sessions for session replication. Otherwise, it won't work. I'm using JDBC to store the session. But since it's not sticky yet, the website keeps refreshing when starting the app. I know it has something to do with the load balancer. But since I'm a total beginner I have no idea how to access it and set custom configurations.

This is my properties file

```<code>server.port=${PORT:8080}
logging.level.org.atmosphere = warn
spring.mustache.check-template-location = false
spring.session.jdbc.initialize-schema= embedded
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.h2.Driver
spring.session.jdbc.table-name=SPRING_SESSION
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.session.store-type=jdbc
spring.datasource.url=jdbc:h2:~/sessions
spring.datasource.username=xx
spring.datasource.password=xx
vaadin.launch-browser=true
</code>```

And here are my dependencies

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>
</code>```

Body:
As I'm working on a vaadin project, I need sticky sessions for session replication. Otherwise, it won't work. I'm using JDBC to store the session. But since it's not sticky yet, the website keeps refreshing when starting the app. I know it has something to do with the load balancer. But since I'm a total beginner I have no idea how to access it and set custom configurations.

This is my properties file

server.port=${PORT:8080}
logging.level.org.atmosphere = warn
spring.mustache.check-template-location = false
spring.session.jdbc.initialize-schema= embedded
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.h2.Driver
spring.session.jdbc.table-name=SPRING_SESSION
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.session.store-type=jdbc
spring.datasource.url=jdbc:h2:~/sessions
spring.datasource.username=xx
spring.datasource.password=xx
vaadin.launch-browser=true

And here are my dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>


问:
Blazor DotNet.invokeMethodAsync doesn't call C# function (no errors)
I've a JS rendered HTML button:

```<code>'<button onclick="fnDisplayCustomer(54)">Click me!</button>'
</code>```

Which successfully calls the function:

```<code>fnDisplayCustomer = function (customerId) {
    DotNet.invokeMethodAsync('displayCustomer', customerId)
        .then(result => {
            console.log(result)
        });
}
</code>```

The JS function should then call the C# function:

```<code>[JSInvokable]
public int displayCustomer(int customerId)
{
    return customerId;
}
</code>```

The JS is in its own file called at the bottom of the page's razor file.

Debugging through the JS in browser, the DotNet.invokeMethodAsync is hit, but the C# method isn't. No errors are thrown, but a break point insidethe C# method is never hit, and the console.log line in the invokeMethodAsync function doesn't fire.

I read that methods called by invokeMethodAsync need to be static (this appears to be incorrect) but I still tried:

```<code>[JSInvokable]
public static int displayCustomer(int customerId)
{
    return customerId;
}
</code>```

The assembly name can be specified in the invokeMethodAsync, but as I'm calling the script from the page I'm unsure if this is needed. Also I'm not entirely sure of its function as the assembly name isn't the the name of the page class which contains my method I want to call. I could have method in all of my classes called "displayCustomer" all doing different things, I fail to see how specifying the assembly name and a method name gets it to the specific method of that name I want.

I initially call the JS from C# using

Microsoft.JSInterop;

Calling JS from the C# is working fine.

I'm unsure how to diagnose my issue as I'm not getting any JS or C# errors/warnings.

Body:
I've a JS rendered HTML button:

'<button onclick="fnDisplayCustomer(54)">Click me!</button>'

Which successfully calls the function:

fnDisplayCustomer = function (customerId) {
    DotNet.invokeMethodAsync('displayCustomer', customerId)
        .then(result => {
            console.log(result)
        });
}

The JS function should then call the C# function:

[JSInvokable]
public int displayCustomer(int customerId)
{
    return customerId;
}

The JS is in its own file called at the bottom of the page's razor file.

Debugging through the JS in browser, the DotNet.invokeMethodAsync is hit, but the C# method isn't. No errors are thrown, but a break point insidethe C# method is never hit, and the console.log line in the invokeMethodAsync function doesn't fire.

I read that methods called by invokeMethodAsync need to be static (this appears to be incorrect) but I still tried:

[JSInvokable]
public static int displayCustomer(int customerId)
{
    return customerId;
}

The assembly name can be specified in the invokeMethodAsync, but as I'm calling the script from the page I'm unsure if this is needed. Also I'm not entirely sure of its function as the assembly name isn't the the name of the page class which contains my method I want to call. I could have method in all of my classes called "displayCustomer" all doing different things, I fail to see how specifying the assembly name and a method name gets it to the specific method of that name I want.

I initially call the JS from C# using

Microsoft.JSInterop;

Calling JS from the C# is working fine.

I'm unsure how to diagnose my issue as I'm not getting any JS or C# errors/warnings.


问:
.Net 6.0 Minimal API with UTF-16LE encoding
I am trying to build a small Web API in .Net (Minimal Web API wit .Net 6.0) but I need the response to be of type application/json and UTF-16LE encoding. Is there a possibility to do so?

I build the Api using the minimal template and it works fine but the encoding is by default UTF-8. I searcht for awnsers in the documentation from microsoft and here on stackoverflow but did not really find something which awnserd my question.


问:
SQL Server Select Query and Join to Multiple Databases in One Server
I have a scenario like this and I want to know if there is a way to solve this only using SQL queries:

I have n databases, with name tenant_1, tenant_2, tenant_3, ... , tenant_n and a database named main.
In main database, there's a table named tenants with following structure

tenant_name
tenant_db

Tenant 1
tenant_1

Tenant 2
tenant_2

Tenant n
tenant_n

In each tenant database, there's a table named settings with following structure

key
value

DATE
2022-12-15

...
...

Can I join the the tenants table to each settings table from each database? So the end result will be

tenant_name
tenant_db
date

Tenant 1
tenant_1
2022-12-15

Tenant 2
tenant_2
2022-12-15

Tenant n
tenant_n
2022-12-15

Is it possible to do this in SQL Server? Thanks in advance for your help


问:
Flink job getting stuck while reading from hive table in streaming mode using sql hints
I am trying to read data from hive tables using flink table api connector.
It is working file when I am trying to read data from hive tables in batch mode.

```<code>val sqlresult = tableEnv.sqlQuery(s"select * from $tableName")
</code>```

However, when I am trying to read data from hive tables in streaming mode using sql hints, then the flink job is getting stuck.

Documentation - (https://nightlies.apache.org/flink/flink-docs-release-1.16/docs/connectors/table/hive/hive_read_write/)

```<code>val sqlresult = tableEnv.sqlQuery(s"select * from $tableName /*+ OPTIONS('streaming-source.enable'='true', 'streaming-source.monitor-interval'='1 min', 'streaming-source.partition.include'='all') */")
</code>```

The flink is getting submitted but getting stuck and thus not able read streaming data from hive table.

Batch query is working fine.

```<code>val sqlresult = tableEnv.sqlQuery(s"select * from $tableName")
</code>```

Body:
I am trying to read data from hive tables using flink table api connector.
It is working file when I am trying to read data from hive tables in batch mode.

val sqlresult = tableEnv.sqlQuery(s"select * from $tableName")

However, when I am trying to read data from hive tables in streaming mode using sql hints, then the flink job is getting stuck.

Documentation - (https://nightlies.apache.org/flink/flink-docs-release-1.16/docs/connectors/table/hive/hive_read_write/)

val sqlresult = tableEnv.sqlQuery(s"select * from $tableName /*+ OPTIONS('streaming-source.enable'='true', 'streaming-source.monitor-interval'='1 min', 'streaming-source.partition.include'='all') */")

The flink is getting submitted but getting stuck and thus not able read streaming data from hive table.

Batch query is working fine.

val sqlresult = tableEnv.sqlQuery(s"select * from $tableName")


问:
Illuminate\Auth\RequestGuard::attempt does not exist on Laravel/Lument 6.x
i'm working on a project developed by another team and i'm trying to make it work on a new server.
After all the installation and configuration i'm getting this error Method Illuminate\Auth\RequestGuard::attempt does not exist. using

```<code>Auth::attempt($credentials)
</code>```

in my AuthController.php

app/config/auth.php

```<code><?php
    return [
        'defaults' => [
            'guard' => 'api',
            'passwords' => 'users',
        ],

        'guards' => [
            'api' => [
                'driver' => 'jwt',
                'provider' => 'users',
            ],
        ],

        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => \App\User::class
            ]
        ]
    ];
</code>```

I already searched around the web and found many solutions but nothing seems to work.

Thanks

Body:
i'm working on a project developed by another team and i'm trying to make it work on a new server.
After all the installation and configuration i'm getting this error Method Illuminate\Auth\RequestGuard::attempt does not exist. using

Auth::attempt($credentials)

in my AuthController.php

app/config/auth.php

<?php
    return [
        'defaults' => [
            'guard' => 'api',
            'passwords' => 'users',
        ],

        'guards' => [
            'api' => [
                'driver' => 'jwt',
                'provider' => 'users',
            ],
        ],

        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => \App\User::class
            ]
        ]
    ];

I already searched around the web and found many solutions but nothing seems to work.

Thanks


问:
Kubernetes pod throttling
Let me try to explain our situation. At night we scale all deployments to 0 replicas (and store the original value in an annotation) to reduce costs.
In the morning the replicas are restored to their original values. This is where the problem starts as they overburden the node where the CPU plateaus to 100%.
The warmup probes start to fail and, if they make it, the liveness probes will start restaring the pods. Too many pods are trying to get up at the same time...
After about 2 hours the system finally stabilizes. If we startup the pods manually, say 5 per minute, the system comes up in less then 10 minutes (!).
In other domains this is called the thundering herd problem or stampede problem and we haven't found a fix yet for Kubernetes.

I understand that a project like Trimaran takes into account the CPU utilization but its goal is to be more efficient and not throttle pod creation per se right. Will we be abusing Trimaran for our use case or is it a good fit you think?

If not it is time for me to learn Go and the Scheduling Framework as it can't be too hard to install a throttle for pod creation on a node where x pods can be created in a sliding window of x minutes. Am I on the right track? Thank you.

This is the script that before the blackout stores the number of replicas in the annotations so that in the morning it can be restored to the original value:

```<code># annotate first
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl annotate --overwrite deploy "}{@.metadata.name}{" previous-size="}{@.spec.replicas}{" \n"}{end}' | sh

# scale to 0
kubectl scale --replicas=0 $(kubectl get deploy -o name)

# scaleback
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl scale deploy "}{@.metadata.name}{" --replicas="}{.metadata.annotations.previous-size}{"\n"}{end}' | sh
</code>```

Update 1
I investigated the resource request and limits but they state what in total can be run on a node. Not how it can throttle the number of pod creations per time window on the node.

Title: Kubernetes pod throttling

Body:
Let me try to explain our situation. At night we scale all deployments to 0 replicas (and store the original value in an annotation) to reduce costs.
In the morning the replicas are restored to their original values. This is where the problem starts as they overburden the node where the CPU plateaus to 100%.
The warmup probes start to fail and, if they make it, the liveness probes will start restaring the pods. Too many pods are trying to get up at the same time...
After about 2 hours the system finally stabilizes. If we startup the pods manually, say 5 per minute, the system comes up in less then 10 minutes (!).
In other domains this is called the thundering herd problem or stampede problem and we haven't found a fix yet for Kubernetes.

I understand that a project like Trimaran takes into account the CPU utilization but its goal is to be more efficient and not throttle pod creation per se right. Will we be abusing Trimaran for our use case or is it a good fit you think?

If not it is time for me to learn Go and the Scheduling Framework as it can't be too hard to install a throttle for pod creation on a node where x pods can be created in a sliding window of x minutes. Am I on the right track? Thank you.

This is the script that before the blackout stores the number of replicas in the annotations so that in the morning it can be restored to the original value:

# annotate first
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl annotate --overwrite deploy "}{@.metadata.name}{" previous-size="}{@.spec.replicas}{" \n"}{end}' | sh

# scale to 0
kubectl scale --replicas=0 $(kubectl get deploy -o name)

# scaleback
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl scale deploy "}{@.metadata.name}{" --replicas="}{.metadata.annotations.previous-size}{"\n"}{end}' | sh

Update 1
I investigated the resource request and limits but they state what in total can be run on a node. Not how it can throttle the number of pod creations per time window on the node.


问:
scala nested XML parsing with CDATA
I have an xml structure to be parsed as follows :

```<code><?xml version="1.0" encoding="utf-8"?>
<System>
  <header>
    <identification serialNumber="100"/>
  </header>
  <actionPointList>
    <actionPoint>
        <property><![CDATA[<Event type="Event1" name="EventName1" time="2018-03-27 04:31:02Z">
                <UseCase>Receive</UseCase>
                <LocalIP>103.8.0.31</LocalIP>
                <LocalHost>103.8.0.31</LocalHost>
                </Event>]]>
        </property>
        <property><![CDATA[<Event type="Event2" name="EventName2" time="2018-03-27 05:31:02Z">
                <UseCase>Send</UseCase>
                <RemoteIP>10.22.0.54</RemoteIP>
                <RemoteHost>10.22.0.54</RemoteHost>
                <StartDateTime>2018-03-27 06:31:01.21</StartDateTime>
                <StopDateTime>2018-03-27 06:31:02.14</StopDateTime>
                <TransferredObjects>1</TransferredObjects>
                <TransferredBytes>354200</TransferredBytes>
                <EncryptionUsed>false</EncryptionUsed>
                </Event>]]>
        </property>
    </actionPoint>
  </actionPointList>
</System>
</code>```

I want to get an array of Events which are in the CDATA.
Is there a simple way to get a list without getting text of each node and then accumulating?
The below code works, but is a bit long:

```<code>val propertyNodes = myXml \\ "actionPoint" \ "property"
for (propertyNode <- propertyNodes) {
val eventText= propertyNode.text
//Extract from eventText
}
</code>```

Is there a simpler way compared to this?

Title: scala nested XML parsing with CDATA

Body:
I have an xml structure to be parsed as follows :

<?xml version="1.0" encoding="utf-8"?>
<System>

    <identification serialNumber="100"/>

  <actionPointList>
    <actionPoint>
        <property><![CDATA[<Event type="Event1" name="EventName1" time="2018-03-27 04:31:02Z">
                <UseCase>Receive</UseCase>
                <LocalIP>103.8.0.31</LocalIP>
                <LocalHost>103.8.0.31</LocalHost>
                </Event>]]>
        </property>
        <property><![CDATA[<Event type="Event2" name="EventName2" time="2018-03-27 05:31:02Z">
                <UseCase>Send</UseCase>
                <RemoteIP>10.22.0.54</RemoteIP>
                <RemoteHost>10.22.0.54</RemoteHost>
                <StartDateTime>2018-03-27 06:31:01.21</StartDateTime>
                <StopDateTime>2018-03-27 06:31:02.14</StopDateTime>
                <TransferredObjects>1</TransferredObjects>
                <TransferredBytes>354200</TransferredBytes>
                <EncryptionUsed>false</EncryptionUsed>
                </Event>]]>
        </property>
    </actionPoint>
  </actionPointList>
</System>

I want to get an array of Events which are in the CDATA.
Is there a simple way to get a list without getting text of each node and then accumulating?
The below code works, but is a bit long:

val propertyNodes = myXml \\ "actionPoint" \ "property"
for (propertyNode <- propertyNodes) {
val eventText= propertyNode.text
//Extract from eventText
}

Is there a simpler way compared to this?


问:
sign the message token using digital certificate private key (pxf file) in C#
Requirement: I am developing a service that calls an API which has a parameter named token. Token message  needs to be signed using digital certificate .pfx file. The digital signature algorithm will be SHA256withRSA, then convert the signed token to base64 encoding and at last pass the signature string to the token field of request message.

Issue : In my console/service application code, it throws an error at line 7: Unable to cast object of type System.Security.Cryptography.RSACng to type System.Security.Cryptography.RSACryptoServiceProvider

```<code>public string HBLTxnToken()
   {
        string contentToEncode = "HBL -531,0701,1,01900099870014,1,NPR,HBL-531,2101,1,0830122854100011,1,HBL@999";
        X509Certificate2 certificate = new X509Certificate2(@"C://Users//nabinpr//Desktop//Code//Test File//HBL.pfx", "123"); //first parameter is path of certificate and second is password.
        if (certificate.HasPrivateKey)
        {
            RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)certificate.PrivateKey; // Error : System.InvalidCastException: 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'

           byte[] utf8Data = Encoding.UTF8.GetBytes(contentToEncode);
            byte[] signature = privateKey.SignData(utf8Data, "sha256");
            return Convert.ToBase64String(signature);
        }
        else
        {
            return "0";
        }
    }
</code>```

I have been stuck in this from two days, I am getting different token value, valid token is given below. If the token generated from my code matched with below value then we can assume its correct. seek experts help.

Resulting token value should be : LmvlZkZW1K/DPtBZ0d9UIVwByXVPWoApOZsnJFfLw+pD+5Fknt+t9aNkaNUjcNlYdctyTwr+EZ/ZI7IXPr/UQQVinZHiLowHqn9TykRWlDRSQLdoOrYxEMVApk7EzbT49s77FW2WX1IJV7L/Xmti5PZxjkedfDcHBVATyxjH/IE=

Body:
Requirement: I am developing a service that calls an API which has a parameter named token. Token message  needs to be signed using digital certificate .pfx file. The digital signature algorithm will be SHA256withRSA, then convert the signed token to base64 encoding and at last pass the signature string to the token field of request message.

Issue : In my console/service application code, it throws an error at line 7: Unable to cast object of type System.Security.Cryptography.RSACng to type System.Security.Cryptography.RSACryptoServiceProvider

public string HBLTxnToken()
   {
        string contentToEncode = "HBL -531,0701,1,01900099870014,1,NPR,HBL-531,2101,1,0830122854100011,1,HBL@999";
        X509Certificate2 certificate = new X509Certificate2(@"C://Users//nabinpr//Desktop//Code//Test File//HBL.pfx", "123"); //first parameter is path of certificate and second is password.
        if (certificate.HasPrivateKey)
        {
            RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)certificate.PrivateKey; // Error : System.InvalidCastException: 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'

           byte[] utf8Data = Encoding.UTF8.GetBytes(contentToEncode);
            byte[] signature = privateKey.SignData(utf8Data, "sha256");
            return Convert.ToBase64String(signature);
        }
        else
        {
            return "0";
        }
    }

I have been stuck in this from two days, I am getting different token value, valid token is given below. If the token generated from my code matched with below value then we can assume its correct. seek experts help.

Resulting token value should be : LmvlZkZW1K/DPtBZ0d9UIVwByXVPWoApOZsnJFfLw+pD+5Fknt+t9aNkaNUjcNlYdctyTwr+EZ/ZI7IXPr/UQQVinZHiLowHqn9TykRWlDRSQLdoOrYxEMVApk7EzbT49s77FW2WX1IJV7L/Xmti5PZxjkedfDcHBVATyxjH/IE=


问:
Laravel jQuery Problem that is Uncaught TypeError: Cannot read properties of undefined (reading 'value')
```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'value')
    at $.<computed>.<computed>.menufocus (jquery-ui.js:5911:50)
    at HTMLUListElement.handlerProxy (jquery-ui.js:626:7)
    at HTMLUListElement.dispatch (jquery-3.6.0.js:5430:27)
    at elemData.handle (jquery-3.6.0.js:5234:28)
    at Object.trigger (jquery-3.6.0.js:8719:12)
    at HTMLUListElement.<anonymous> (jquery-3.6.0.js:8797:17)
    at Function.each (jquery-3.6.0.js:385:19)
    at jQuery.fn.init.each (jquery-3.6.0.js:207:17)
    at jQuery.fn.init.trigger (jquery-3.6.0.js:8796:15)
    at $.<computed>.<computed>._trigger (jquery-ui.js:715:16)
</code>```

'My Code in blade view is below:'

```<code><script>

$( "#searchName" ).autocomplete({
    source: "{{ route('item.autoSrchItem') }}",
    minLength: 2,
    autoFocus: true,
    Select: function(e, ui){
    console.log(ui.item);
  }
});
</script>
</code>```

My Code in Controller is as:

```<code>public function autoSrchItem(Request $request)
{
   $search = $request->term;
   $result = Item::where('title', 'LIKE', '%'. $search. '%')->get();
   $data = [];
       foreach ($result as $key => $value) {
    $data [] = ['id'=>$value->id, 'title'=>$value->title];
   }
      return response()->json($data);
 }
</code>```

`

'Image of my browser:'

Any one help me please.
I do not understand what the problem is. I am new in Laravel. When i give source a manual data. it works perfectly but when even I give source to my data table it shows the above mansion error.

Body:
Uncaught TypeError: Cannot read properties of undefined (reading 'value')
    at $.<computed>.<computed>.menufocus (jquery-ui.js:5911:50)
    at HTMLUListElement.handlerProxy (jquery-ui.js:626:7)
    at HTMLUListElement.dispatch (jquery-3.6.0.js:5430:27)
    at elemData.handle (jquery-3.6.0.js:5234:28)
    at Object.trigger (jquery-3.6.0.js:8719:12)
    at HTMLUListElement.<anonymous> (jquery-3.6.0.js:8797:17)
    at Function.each (jquery-3.6.0.js:385:19)
    at jQuery.fn.init.each (jquery-3.6.0.js:207:17)
    at jQuery.fn.init.trigger (jquery-3.6.0.js:8796:15)
    at $.<computed>.<computed>._trigger (jquery-ui.js:715:16)

'My Code in blade view is below:'

My Code in Controller is as:

public function autoSrchItem(Request $request)
{
   $search = $request->term;
   $result = Item::where('title', 'LIKE', '%'. $search. '%')->get();
   $data = [];
       foreach ($result as $key => $value) {
    $data [] = ['id'=>$value->id, 'title'=>$value->title];
   }
      return response()->json($data);
 }

`

'Image of my browser:'

Any one help me please.
I do not understand what the problem is. I am new in Laravel. When i give source a manual data. it works perfectly but when even I give source to my data table it shows the above mansion error.


问:
alternatives route not exists on the same route
My problem is the strange behavior of HERE Api.

alternatives = 5 in API query

I send a request for a route Warsaw - Berlin for a truck and receive one route with no alternative routes.
If I add an endpoint to the route, e.g. Madrid, then an one alternative route appears on the Warsaw - Berlin route, but if I remove Madrid and download the route again, it has no alternative routes.

edit.
It happens that on the Warsaw - Berlin route I receive one alternative route, and after adding an end point, e.g. Madrid on the Warsaw - Berlin route, I receive two alternative routes.

I am asking for help again


问:
show/hide checkout fields based on shipping method
when choosing certain shipping methods will hide or show some fields,
and had tried 2 ways to control checkout fields, but both results were not my expectations.

The first way use JS,  It's working in the front end, but shows "Billing Street address is a required field." during the checkout process.

```<code>jQuery(document).ready(function ($) {
  // Choosen shipping method selectors slug
  const shipMethod = 'input[name^="shipping_method"]',
    shipMethodChecked = shipMethod + ':checked';

  // Function that shows or hide imput select fields
  const arr = [
    '#billing_company_field',
    '#billing_address_1_field',
    '#billing_address_2_field',
    '#billing_state_field',
    '#billing_city_field',
    '#billing_postcode_field',
    '#shipping_company_field',
    '#shipping_address_1_field',
    '#shipping_address_2_field',
    '#shipping_state_field',
    '#shipping_city_field',
    '#shipping_postcode_field',
    '.woocommerce-shipping-fields'
  ];

  function showHide(actionToDo = 'show', selector = '') {
    for (let i = 0; i < selector.length; i++) {
      if (arr[i] === undefined) return;

      if (actionToDo === 'show') {
        $(selector[i]).show(200, function () {
          $(this).addClass('validate-required');
        });
      }

      if (actionToDo === 'hide') {
        $(selector[i]).hide(200, function () {
          $(this).removeClass('validate-required');
        });
      }
    }
  }

  // Initialising: Hide if choosen shipping method is "Home delivery"
  if ($(shipMethodChecked).val() === '_ecpay_logistics_tws') {
    showHide('hide', arr);
  }

  // Live event (When shipping method is changed)
  $(document.body).on('update_checkout', function () {
    if ($(shipMethodChecked).val() === '_ecpay_logistics_tws') {
      showHide('hide', arr);
    }
    if ($(shipMethodChecked).val() !== '_ecpay_logistics_tws') {
      showHide('show', arr);
    }
  });
});

</code>```

The second way is in Plugin PHP,  It's also working when the first load page, and not dynamically show/hide by the chosen shipping....

```<code>add_filter( 'woocommerce_checkout_fields' , 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields($fields) {
    $shipping_method = 'WC_ECPAY_LOGISTICS_ID'; // Set the desired shipping method to hide the checkout field(s).
    global $woocommerce;

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

    if ($chosen_shipping == $shipping_method) {
        unset($fields['billing']['billing_address_1']); // Add/change filed name to be hide
        unset($fields['billing']['billing_address_2']);
        }
    return $fields;
}
</code>```

any good ideas?

Body:
when choosing certain shipping methods will hide or show some fields,
and had tried 2 ways to control checkout fields, but both results were not my expectations.

The first way use JS,  It's working in the front end, but shows "Billing Street address is a required field." during the checkout process.

jQuery(document).ready(function ($) {
  // Choosen shipping method selectors slug
  const shipMethod = 'input[name^="shipping_method"]',
    shipMethodChecked = shipMethod + ':checked';

  // Function that shows or hide imput select fields
  const arr = [
    '#billing_company_field',
    '#billing_address_1_field',
    '#billing_address_2_field',
    '#billing_state_field',
    '#billing_city_field',
    '#billing_postcode_field',
    '#shipping_company_field',
    '#shipping_address_1_field',
    '#shipping_address_2_field',
    '#shipping_state_field',
    '#shipping_city_field',
    '#shipping_postcode_field',
    '.woocommerce-shipping-fields'
  ];

  function showHide(actionToDo = 'show', selector = '') {
    for (let i = 0; i < selector.length; i++) {
      if (arr[i] === undefined) return;

      if (actionToDo === 'show') {
        $(selector[i]).show(200, function () {
          $(this).addClass('validate-required');
        });
      }

      if (actionToDo === 'hide') {
        $(selector[i]).hide(200, function () {
          $(this).removeClass('validate-required');
        });
      }
    }
  }

  // Initialising: Hide if choosen shipping method is "Home delivery"
  if ($(shipMethodChecked).val() === '_ecpay_logistics_tws') {
    showHide('hide', arr);
  }

  // Live event (When shipping method is changed)
  $(document.body).on('update_checkout', function () {
    if ($(shipMethodChecked).val() === '_ecpay_logistics_tws') {
      showHide('hide', arr);
    }
    if ($(shipMethodChecked).val() !== '_ecpay_logistics_tws') {
      showHide('show', arr);
    }
  });
});

The second way is in Plugin PHP,  It's also working when the first load page, and not dynamically show/hide by the chosen shipping....

add_filter( 'woocommerce_checkout_fields' , 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields($fields) {
    $shipping_method = 'WC_ECPAY_LOGISTICS_ID'; // Set the desired shipping method to hide the checkout field(s).
    global $woocommerce;

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

    if ($chosen_shipping == $shipping_method) {
        unset($fields['billing']['billing_address_1']); // Add/change filed name to be hide
        unset($fields['billing']['billing_address_2']);
        }
    return $fields;
}

any good ideas?


问:
Avoid circular references when mapping hieararchy of objects using decorator
I setup a minimal project at https://github.com/milanjour/mapstruct-hierarchy

I have a CategoryDto which has a field called subcategories which is a List<CategoryDto>

I want to use CategorySubcategoriesDecorator to map the persisted CategoryEntity.subCategoryIds to such CategoryDto.subcategories.

So I have created

```<code>@Mapper(uses = {
    CategorySubcategoriesDecorator.class,
})
public interface CategoryConverter {

  @Mappings({
      @Mapping(source = ".", target = "subCategories")
  })
  CategoryDto convertEntityToDto(CategoryEntity catalogEntity, @Context Integer levels);

}
</code>```

(spring as default component model is passed through compiler args)

but Spring is telling me I have circular references. How can I avoid them?

I have this ouput:

```<code>┌─────┐
|  categoryConverterImpl (field private org.example.CategorySubcategoriesDecorator org.example.CategoryConverterImpl.categorySubcategoriesDecorator)
↑     ↓
|  categorySubcategoriesDecorator defined in file [/Users/dem/Documents/projects/poc/mapstruct-hierarchy/build/classes/java/main/org/example/CategorySubcategoriesDecorator.class]
↑     ↓
|  categoryService defined in file [/Users/dem/Documents/projects/poc/mapstruct-hierarchy/build/classes/java/main/org/example/CategoryService.class]
└─────┘
</code>```

Body:
I setup a minimal project at https://github.com/milanjour/mapstruct-hierarchy

I have a CategoryDto which has a field called subcategories which is a List<CategoryDto>

I want to use CategorySubcategoriesDecorator to map the persisted CategoryEntity.subCategoryIds to such CategoryDto.subcategories.

So I have created

@Mapper(uses = {
    CategorySubcategoriesDecorator.class,
})
public interface CategoryConverter {

  @Mappings({
      @Mapping(source = ".", target = "subCategories")
  })
  CategoryDto convertEntityToDto(CategoryEntity catalogEntity, @Context Integer levels);

}

(spring as default component model is passed through compiler args)

but Spring is telling me I have circular references. How can I avoid them?

I have this ouput:

┌─────┐
|  categoryConverterImpl (field private org.example.CategorySubcategoriesDecorator org.example.CategoryConverterImpl.categorySubcategoriesDecorator)
↑     ↓
|  categorySubcategoriesDecorator defined in file [/Users/dem/Documents/projects/poc/mapstruct-hierarchy/build/classes/java/main/org/example/CategorySubcategoriesDecorator.class]
↑     ↓
|  categoryService defined in file [/Users/dem/Documents/projects/poc/mapstruct-hierarchy/build/classes/java/main/org/example/CategoryService.class]
└─────┘


问:
Angular – Iframe fullscreen on button click on iPhone – Safari and the other browsers
I am struggling a bit with the iPhone issue. Clicking the fullscreen icon calls the fullscreen on Android but unfortunately, nothing happens for iPhone.

My purpose is to:

open fullscreen mode on iPhone to not see any URL bar and phone icons like battery etc.

if it is somehow not possible – minimize the URL bar to see the only string, not the whole input.

Does anyone know how to handle that?

My current method, working for Android devices:

```<code>  fullscreen() {
if (document.fullscreenElement) {
  document.exitFullscreen();
} else {
  document.documentElement.requestFullscreen();
}
</code>```

}

Body:
I am struggling a bit with the iPhone issue. Clicking the fullscreen icon calls the fullscreen on Android but unfortunately, nothing happens for iPhone.

My purpose is to:

open fullscreen mode on iPhone to not see any URL bar and phone icons like battery etc.

if it is somehow not possible – minimize the URL bar to see the only string, not the whole input.

Does anyone know how to handle that?

My current method, working for Android devices:

  fullscreen() {
if (document.fullscreenElement) {
  document.exitFullscreen();
} else {
  document.documentElement.requestFullscreen();
}

}


问:
How can I set value of variable max_active_tis_per_dag at run time for a task in Airflow 2.3.x?
I am currently trying to make the parallel execution of Apache Airflow 2.3.x dynamic task.

When executing below DAG, let say 100 dynamic "sanitize_payment" task is created in "sanitize_payment_group". I have set value of "max_active_tis_per_dag" 16 for now, but i want to change the value depending upon some condition. For example, if "batch_id" is 1, max_active_tis_per_dag=10 and if "batch_id" is 2 then max_active_tis_per_dag=15.

```<code>@dag(
    dag_id="data_transfer_dag",
    schedule_interval=None,
    tags=["Data transfer"],
    default_args={
        "owner": "Open",
        "start_date": pendulum.today("UTC").add(days=-1),
        "depends_on_past": False,
        "email_on_failure": False,
        "email_on_retry": False,
        "email": "",
        "retries": 1,
        "retry_delay": timedelta(seconds=10),
    },
    description="Data transfer dag"
)
def data_transfer():

    @task()
    def fetch_batch_user_to_process(**kwargs):
        batch_id = kwargs['dag_run'].conf.get('batch_id')
        prepared_data = [{"batch_id": batch_id}]
        return prepared_data

    @task_group(group_id="sanitize_payment_group")
    def sanitize_payment_group(users_data):
        @task(max_active_tis_per_dag=16)
        def sanitize_payment(data):
            """Some operation"""
            correct_api_version_data = data  # Dummy operation
            return correct_api_version_data

        task_result = sanitize_payment.expand(data=users_data)
        return task_result

    @task_group(group_id="process_payment_group")
    def process_payment_group(users_data):
        @task(max_active_tis_per_dag=1)
        def process_payment(payment_data):
            """Some operation"""
            data = payment_data  # Dummy operation
            return data

        task_result = process_payment.expand(payment_data=users_data)
        return task_result

    @task_group(group_id="create_contact_group")
    def create_contact_group(user_data):
        @task(max_active_tis_per_dag=16)
        def create_contact(user_info):
            """Some Operation"""
            if_contact_present = user_info  # Dummy operation
            return if_contact_present

        task_result = create_contact.expand(user_info=user_data)
        return task_result

    @task()
    def end_processing():
        logging.info("ending the dag.")

    end = end_processing()
    batch_to_process = fetch_batch_user_to_process()

    process_payment_group(sanitize_payment_group(create_contact_group(batch_to_process))) >> end

DAG = data_transfer()
</code>```

Body:
I am currently trying to make the parallel execution of Apache Airflow 2.3.x dynamic task.

When executing below DAG, let say 100 dynamic "sanitize_payment" task is created in "sanitize_payment_group". I have set value of "max_active_tis_per_dag" 16 for now, but i want to change the value depending upon some condition. For example, if "batch_id" is 1, max_active_tis_per_dag=10 and if "batch_id" is 2 then max_active_tis_per_dag=15.

@dag(
    dag_id="data_transfer_dag",
    schedule_interval=None,
    tags=["Data transfer"],
    default_args={
        "owner": "Open",
        "start_date": pendulum.today("UTC").add(days=-1),
        "depends_on_past": False,
        "email_on_failure": False,
        "email_on_retry": False,
        "email": "",
        "retries": 1,
        "retry_delay": timedelta(seconds=10),
    },
    description="Data transfer dag"
)
def data_transfer():

    @task()
    def fetch_batch_user_to_process(**kwargs):
        batch_id = kwargs['dag_run'].conf.get('batch_id')
        prepared_data = [{"batch_id": batch_id}]
        return prepared_data

    @task_group(group_id="sanitize_payment_group")
    def sanitize_payment_group(users_data):
        @task(max_active_tis_per_dag=16)
        def sanitize_payment(data):
            """Some operation"""
            correct_api_version_data = data  # Dummy operation
            return correct_api_version_data

        task_result = sanitize_payment.expand(data=users_data)
        return task_result

    @task_group(group_id="process_payment_group")
    def process_payment_group(users_data):
        @task(max_active_tis_per_dag=1)
        def process_payment(payment_data):
            """Some operation"""
            data = payment_data  # Dummy operation
            return data

        task_result = process_payment.expand(payment_data=users_data)
        return task_result

    @task_group(group_id="create_contact_group")
    def create_contact_group(user_data):
        @task(max_active_tis_per_dag=16)
        def create_contact(user_info):
            """Some Operation"""
            if_contact_present = user_info  # Dummy operation
            return if_contact_present

        task_result = create_contact.expand(user_info=user_data)
        return task_result

    @task()
    def end_processing():
        logging.info("ending the dag.")

    end = end_processing()
    batch_to_process = fetch_batch_user_to_process()

    process_payment_group(sanitize_payment_group(create_contact_group(batch_to_process))) >> end

DAG = data_transfer()


问:
unable to load external reCAPTCHA dependencies when using auth to authenticate my mobile
When I started to auth mobile number the first step is verified by CAPTCHA

Then the webpage that verifying by CAPTCHA is loading but it stops suddenly and then I have the error below in the logs

[firebase_auth/web-internal-error] unable to load external reCAPTCHA dependencies!

It is working on a device and one not.

I am runing on IOS device

Here it is my flutter doctor result

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 2.10.5, on macOS 13.0 22A380 darwin-arm, locale en-EG)
    • Flutter version 2.10.5 at /Users/Home/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5464c5bac7 (8 months ago), 2022-04-18 09:55:37 -0700
    • Engine revision 57d3bac3dd
    • Dart version 2.16.2
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/Home/Library/Android/sdk
    • Platform android-33, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] IntelliJ IDEA Ultimate Edition (version 2021.2.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 60.1.4
    • Dart plugin version 212.5284.31

[✓] VS Code (version 1.74.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554                        • android-arm64  • Android 12 (API 31) (emulator)
    • iPhone 14 (mobile)          • E4D5DE76-9812-4DE2-9069-DA890CC69502 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-1 (simulator)
    • Chrome (web)                • chrome                               • web-javascript • Google Chrome 108.0.5359.98

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

Also you could find my AppDelegate that I am using on IOS

```<code>import UIKit
import Flutter
import FirebaseCore
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

     override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
                let firebaseAuth = Auth.auth()
                firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)
      }
      override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
                let firebaseAuth = Auth.auth()
                if (firebaseAuth.canHandleNotification(userInfo)){
                    print(userInfo)
                    return
                }
     }

}
</code>```

Body:
When I started to auth mobile number the first step is verified by CAPTCHA

Then the webpage that verifying by CAPTCHA is loading but it stops suddenly and then I have the error below in the logs

[firebase_auth/web-internal-error] unable to load external reCAPTCHA dependencies!

It is working on a device and one not.

I am runing on IOS device

Here it is my flutter doctor result

flutter doctor -v
[✓] Flutter (Channel stable, 2.10.5, on macOS 13.0 22A380 darwin-arm, locale en-EG)
    • Flutter version 2.10.5 at /Users/Home/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5464c5bac7 (8 months ago), 2022-04-18 09:55:37 -0700
    • Engine revision 57d3bac3dd
    • Dart version 2.16.2
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/Home/Library/Android/sdk
    • Platform android-33, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] IntelliJ IDEA Ultimate Edition (version 2021.2.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 60.1.4
    • Dart plugin version 212.5284.31

[✓] VS Code (version 1.74.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554                        • android-arm64  • Android 12 (API 31) (emulator)
    • iPhone 14 (mobile)          • E4D5DE76-9812-4DE2-9069-DA890CC69502 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-1 (simulator)
    • Chrome (web)                • chrome                               • web-javascript • Google Chrome 108.0.5359.98

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Also you could find my AppDelegate that I am using on IOS

import UIKit
import Flutter
import FirebaseCore
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

     override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
                let firebaseAuth = Auth.auth()
                firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)
      }
      override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
                let firebaseAuth = Auth.auth()
                if (firebaseAuth.canHandleNotification(userInfo)){
                    print(userInfo)
                    return
                }
     }

}


问:
How useState works in react
There are many examples of a simplified implementation of useState to explain how it works. The bottom line is to store an array of calls to useState and when changing the value, reset the call counter and get the state from there during rendering, increasing the counter. But such an implementation breaks easily if we use conditional rendering. That is, we sequentially called useState for 2 components, but if, for example, 2 more new components appeared between the first two, then at the output we get that the state will move from component 4 to the second. But if you use useState from react, then it somehow understands where which component is located and processes it correctly.

Shown schematically below. That is, the order of the components changes during conditional rendering, and therefore the state from component2 (left) will go to new1 (on the right), but it should go there from component2 (red arrow).

The question is, is it possible to somehow modify the simplified implementation so that it works correctly?

Here is a simplified implementation: https://codesandbox.io/s/wizardly-rgb-rqixxt?file=/src/index.js
Here is the implementation from react: https://codesandbox.io/s/dazzling-breeze-c5nz9e?file=/src/index.js

Title: How useState works in react


问:
Invalid image from a base64 string
I receive an image in base64 from my nodejs express server like so:

```<code>  fs.writeFileSync("image.png", tensor);
  const readStream = fs.createReadStream('image.png');
  readStream.pipe(res);
</code>```

This is what I see in the console on the client.

Then I try to download it like this:

```<code>function downloadBase64File(contentType, base64Data, fileName) {
  const linkSource = `data:${contentType};base64,${base64Data}`;
  const downloadLink = document.createElement("a");
  downloadLink.href = linkSource;
  downloadLink.download = fileName;
  downloadLink.click();
}

downloadBase64File("image/png", response.data, "image.png");
</code>```

However, the downloaded image is corrupt, even though the size seems to be ok ~7.3MB:

What can be wrong here? How to send a base64 image to the client and download it?

Thank you

Title: Invalid image from a base64 string

Body:
I receive an image in base64 from my nodejs express server like so:

  fs.writeFileSync("image.png", tensor);
  const readStream = fs.createReadStream('image.png');
  readStream.pipe(res);

This is what I see in the console on the client.

Then I try to download it like this:

function downloadBase64File(contentType, base64Data, fileName) {
  const linkSource = `data:${contentType};base64,${base64Data}`;
  const downloadLink = document.createElement("a");
  downloadLink.href = linkSource;
  downloadLink.download = fileName;
  downloadLink.click();
}

downloadBase64File("image/png", response.data, "image.png");

However, the downloaded image is corrupt, even though the size seems to be ok ~7.3MB:

What can be wrong here? How to send a base64 image to the client and download it?

Thank you