问:
options.filter() is not a function in MUI autocomplete
I am trying to create an autocomplete function in MERN stack and am using MUI autocomplete. I keep getting this error when I type anything in the box

** useAutocomplete.js:201 Uncaught TypeError: options.filter is not a function**

My code is below, the backend is functioning perfectly and returns an the data to the frontend successfully.

``

```<code>    import React, { useState, useEffect } from 'react';
    import TextField from '@mui/material/TextField';
    import Stack from '@mui/material/Stack';
    import Autocomplete from '@mui/material/Autocomplete';
    import SearchService from '../../services/search.services';
    import Select from 'react-select';

    export default function Search() {
     const [options, setOptions] = useState([]);
     const [value, setValue] = useState(null);
    useEffect(() => {
     SearchService.get()
      .then((response) => {
        console.log(response.data.data)
        setOptions(response.data.data);
      });
      console.log(options)
    }, []);

   const handleInputChange = async (value, event) => {
    // Update options list based on input value
    console.log(value)
    const updatedOptions = await SearchService.get(value);
    setOptions(updatedOptions);
    console.log(options)
    }

   return (
    <Stack spacing={2} sx={{ width: 300 }}>
         <Autocomplete
      filterOptions={(x) => x}
      options={!options ? [{label: 'Loading...', id: 0}] : options}
      value={value}
      onInputChange={(event, newValue) => {
        handleInputChange(newValue)
      }}

      renderInput={params => (
        <TextField
          {...params}
          label="Select an option"
          variant="outlined"
        />
      )}
    />
    </Stack>
      );
     }

</code>```

``

Any help would be greatly appreciated!

I tried using other stackoverflow questions that were similar, I tried using the documentation and nothing works. I tried different iterations of the same things but nothing will fix this.

Body:
I am trying to create an autocomplete function in MERN stack and am using MUI autocomplete. I keep getting this error when I type anything in the box

** useAutocomplete.js:201 Uncaught TypeError: options.filter is not a function**

My code is below, the backend is functioning perfectly and returns an the data to the frontend successfully.

``

    import React, { useState, useEffect } from 'react';
    import TextField from '@mui/material/TextField';
    import Stack from '@mui/material/Stack';
    import Autocomplete from '@mui/material/Autocomplete';
    import SearchService from '../../services/search.services';
    import Select from 'react-select';

    export default function Search() {
     const [options, setOptions] = useState([]);
     const [value, setValue] = useState(null);
    useEffect(() => {
     SearchService.get()
      .then((response) => {
        console.log(response.data.data)
        setOptions(response.data.data);
      });
      console.log(options)
    }, []);

   const handleInputChange = async (value, event) => {
    // Update options list based on input value
    console.log(value)
    const updatedOptions = await SearchService.get(value);
    setOptions(updatedOptions);
    console.log(options)
    }

   return (
    <Stack spacing={2} sx={{ width: 300 }}>
         <Autocomplete
      filterOptions={(x) => x}
      options={!options ? [{label: 'Loading...', id: 0}] : options}
      value={value}
      onInputChange={(event, newValue) => {
        handleInputChange(newValue)
      }}

      renderInput={params => (
        <TextField
          {...params}
          label="Select an option"
          variant="outlined"
        />
      )}
    />
    </Stack>
      );
     }

``

Any help would be greatly appreciated!

I tried using other stackoverflow questions that were similar, I tried using the documentation and nothing works. I tried different iterations of the same things but nothing will fix this.


来源: stackexchange

问:
why is Past dataset becoming NULL after running h2o.init?
After running h2o.init(), the already(past) created h2o dataframe(dataset) becomes null and is showing error if we use them for other purposes in R std.
As a result, I have to clear the environment and load everything (from scratch)

Is there Coding to extract the old h2o dataframe?

ContentLicense: CC BY-SA 4.0


问:
Generate cucumber with masterthought report after integration test phase
I would like to use the maven masterthought plugin to generate a report of my cucumber tests.
I already made this in a few projects, but, with the one I'm busy now, the cucumber tests are executed within a maven plugin.
The existing code which launch the cucumber tests is :

```<code><profile>
            <id>CUCUMBER</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.2.1</version>
                        <executions>
                            <execution>
                                <phase>integration-test</phase>
                                <goals>
                                    <goal>java</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <classpathScope>test</classpathScope>
                            <executableDependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-core</artifactId>
                            </executableDependency>
                            <mainClass>cucumber.api.cli.Main</mainClass>
                              <arguments>
                                    <argument>--plugin</argument>
                                    <argument>json:${project.build.directory}\cucumber-
                                                 test\reports.json</argument>
                                    <argument>--glue</argument>
                                    <argument>com.myapp.test.cucumber.step</argument>
                                    <argument>--name</argument>
                                    <argument>log</argument>
                                    <argument>classpath:cucumber/</argument>
                            </arguments>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-core</artifactId>
                                <version>1.1.5</version>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
</code>```

So, I would like to add a code like the following, to generate the repport.
but, it doesn't works (folder masterthought-report is created but empty).

```<code><plugin>
                        <groupId>net.masterthought</groupId>
                        <artifactId>maven-cucumber-reporting</artifactId>
                        <version>2.8.0</version>
                        <executions>
                            <execution>
                                <id>2</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>generate</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>${project.build.directory}\masterthought-report</outputDirectory>
                                    <cucumberOutput>${project.build.directory}\cucumber-
                                             test\reports.json</cucumberOutput>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
</code>```

Do you have any idea? I would like to execute the masterthought plugin after the integration phase.

Thanks in advance

Heading

Body:
I would like to use the maven masterthought plugin to generate a report of my cucumber tests.
I already made this in a few projects, but, with the one I'm busy now, the cucumber tests are executed within a maven plugin.
The existing code which launch the cucumber tests is :

<profile>
            <id>CUCUMBER</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.2.1</version>
                        <executions>
                            <execution>
                                <phase>integration-test</phase>
                                <goals>
                                    <goal>java</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <classpathScope>test</classpathScope>
                            <executableDependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-core</artifactId>
                            </executableDependency>
                            <mainClass>cucumber.api.cli.Main</mainClass>
                              <arguments>
                                    <argument>--plugin</argument>
                                    <argument>json:${project.build.directory}\cucumber-
                                                 test\reports.json</argument>
                                    <argument>--glue</argument>
                                    <argument>com.myapp.test.cucumber.step</argument>
                                    <argument>--name</argument>
                                    <argument>log</argument>
                                    <argument>classpath:cucumber/</argument>
                            </arguments>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>info.cukes</groupId>
                                <artifactId>cucumber-core</artifactId>
                                <version>1.1.5</version>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>

So, I would like to add a code like the following, to generate the repport.
but, it doesn't works (folder masterthought-report is created but empty).

<plugin>
                        <groupId>net.masterthought</groupId>
                        <artifactId>maven-cucumber-reporting</artifactId>
                        <version>2.8.0</version>
                        <executions>
                            <execution>
                                <id>2</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>generate</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>${project.build.directory}\masterthought-report</outputDirectory>
                                    <cucumberOutput>${project.build.directory}\cucumber-
                                             test\reports.json</cucumberOutput>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

Do you have any idea? I would like to execute the masterthought plugin after the integration phase.

Thanks in advance

Heading


问:
Same command in terminal, but node js output differently?
So I made a backend to call an API to get access token, in package.json there's:

```<code>"scripts": {
   "dev": "node app.js"
}
</code>```

But when I run command "npm run dev" I don't get the access token (with error socket hang up ECONRESET) but when I run command "node app.js" I could get the access token

Why does this happen when those command actually run "node app.js"?

Body:
So I made a backend to call an API to get access token, in package.json there's:

"scripts": {
   "dev": "node app.js"
}

But when I run command "npm run dev" I don't get the access token (with error socket hang up ECONRESET) but when I run command "node app.js" I could get the access token

Why does this happen when those command actually run "node app.js"?


问:
"digital envelope routines::unsupported" on installing package.json

digital envelope routines::unsupported

Recently, I have lost all the data of my laptop. After setting everything, I tried to start the project and all the sudden this error started to occur.

I have searched about this issue on the internet but most of them say that this issue occurs due to different versions of node. But this is not the case.

I have also tried to pass --openssl-legacy-provider flag but this also doesn't work.

Version

```<code>node: 16.14.0
yarn: 1.22.17
react: 17.0.2
</code>```

Body:
digital envelope routines::unsupported

Recently, I have lost all the data of my laptop. After setting everything, I tried to start the project and all the sudden this error started to occur.

I have searched about this issue on the internet but most of them say that this issue occurs due to different versions of node. But this is not the case.

I have also tried to pass --openssl-legacy-provider flag but this also doesn't work.

Version

node: 16.14.0
yarn: 1.22.17
react: 17.0.2


问:
Selenium Promise <rejected> Failed to Fetch at eval (eval at executeScript (:445:16))
I'm trying to make an automatic bot for posting tweets on Twitter. My idea is to use selenium to repeatedly send fetch requests. I have attempted replaying the fetch request on the console and it works. However, when I sent out a fetch request via selenium, it kept getting rejected. Sending it directly to the selenium console also gets rejected. What could be the problem?

Error:

Promise{<rejected>: TypeError: Failed to Fetch at eval (eval at executeScript (:445:16), <anonymous>:3:37)..}

Source Code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import datetime
import json
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = Options()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
#chrome_options.add_experimental_option('detach', True)
chrome_options.add_argument('--user-data-dir=https://replit.com/@KhaelaFortunela/autovoter#Profile%202')
chrome_options.add_argument("--auto-open-devtools-for-tabs")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://twitter.com/home")

payload = '{"variables":{"tweet_text":"BRI sebagai BUMN mewujudkan komitmen untuk menciptakan lapangan pekerjaan yg bersifat berkelanjutan seperti Agen BRILink, serta penyaluran kredit KUR sebagai modal usaha yang diharapkan dapat memajukan ekonomi rakyat \n#TransformasiBRI127 #ROSBYWANI","media":{"media_entities":[],"possibly_sensitive":false},"withDownvotePerspective":false,"withReactionsMetadata":false,"withReactionsPerspective":false,"withSuperFollowsTweetFields":true,"withSuperFollowsUserFields":true,"semantic_annotation_ids":[],"dark_request":false},"features":{"view_counts_public_visibility_enabled":false,"tweetypie_unmention_optimization_enabled":true,"responsive_web_uc_gql_enabled":true,"vibe_api_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"interactive_text_enabled":true,"responsive_web_text_conversations_enabled":false,"responsive_web_twitter_blue_verified_badge_is_enabled":true,"verified_phone_label_enabled":false,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_enhance_cards_enabled":true},"queryId":"sqNNr7rKZwnDQZkIiyvcrA"}'

fetch_req = '{"headers": {"accept": "*/*","accept-language": "en-US,en;q=0.9","authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA","content-type": "application/json","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","x-csrf-token": "dc535379510138f59a330ed89961a6ef05f26b1d98eaf397c4b6999cdbbea319303dd54ec820339920d848cf5f000da1f15fa3434bf910d8e8d2d61aa2f9638f7c2beb52d000108c01e6dc772b0cf98c","x-twitter-active-user": "yes","x-twitter-auth-type": "OAuth2Session","x-twitter-client-language": "en"},"referrer": "https://mobile.twitter.com/compose/tweet","referrerPolicy": "strict-origin-when-cross-origin","body": "payload","method": "POST", "mode": "cors","credentials": "include"}'

#while True:
for i in range(10):
  t = datetime.datetime.now()
  time_now = t.strftime("%X")
  y = json.loads(payload, strict=False)
  y['variables']['tweet_text'] = time_now + " " + y['variables']['tweet_text']
  new_payload = json.dumps(y)

  z = json.loads(fetch_req, strict=False)
  z['body'] = new_payload
  new_fetch_req = json.dumps(z)

  text = 'console.log(' + 'fetch("https://mobile.twitter.com/i/api/graphql/sqNNr7rKZwnDQZkIiyvcrA/CreateTweet"' + ',' + new_fetch_req + '))'
  driver.execute_script(text)

</code>```

Body:
I'm trying to make an automatic bot for posting tweets on Twitter. My idea is to use selenium to repeatedly send fetch requests. I have attempted replaying the fetch request on the console and it works. However, when I sent out a fetch request via selenium, it kept getting rejected. Sending it directly to the selenium console also gets rejected. What could be the problem?

Error:

Promise{<rejected>: TypeError: Failed to Fetch at eval (eval at executeScript (:445:16), <anonymous>:3:37)..}

Source Code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import datetime
import json
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = Options()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
#chrome_options.add_experimental_option('detach', True)
chrome_options.add_argument('--user-data-dir=https://replit.com/@KhaelaFortunela/autovoter#Profile%202')
chrome_options.add_argument("--auto-open-devtools-for-tabs")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://twitter.com/home")

payload = '{"variables":{"tweet_text":"BRI sebagai BUMN mewujudkan komitmen untuk menciptakan lapangan pekerjaan yg bersifat berkelanjutan seperti Agen BRILink, serta penyaluran kredit KUR sebagai modal usaha yang diharapkan dapat memajukan ekonomi rakyat \n#TransformasiBRI127 #ROSBYWANI","media":{"media_entities":[],"possibly_sensitive":false},"withDownvotePerspective":false,"withReactionsMetadata":false,"withReactionsPerspective":false,"withSuperFollowsTweetFields":true,"withSuperFollowsUserFields":true,"semantic_annotation_ids":[],"dark_request":false},"features":{"view_counts_public_visibility_enabled":false,"tweetypie_unmention_optimization_enabled":true,"responsive_web_uc_gql_enabled":true,"vibe_api_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"interactive_text_enabled":true,"responsive_web_text_conversations_enabled":false,"responsive_web_twitter_blue_verified_badge_is_enabled":true,"verified_phone_label_enabled":false,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_enhance_cards_enabled":true},"queryId":"sqNNr7rKZwnDQZkIiyvcrA"}'

fetch_req = '{"headers": {"accept": "*/*","accept-language": "en-US,en;q=0.9","authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA","content-type": "application/json","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","x-csrf-token": "dc535379510138f59a330ed89961a6ef05f26b1d98eaf397c4b6999cdbbea319303dd54ec820339920d848cf5f000da1f15fa3434bf910d8e8d2d61aa2f9638f7c2beb52d000108c01e6dc772b0cf98c","x-twitter-active-user": "yes","x-twitter-auth-type": "OAuth2Session","x-twitter-client-language": "en"},"referrer": "https://mobile.twitter.com/compose/tweet","referrerPolicy": "strict-origin-when-cross-origin","body": "payload","method": "POST", "mode": "cors","credentials": "include"}'

#while True:
for i in range(10):
  t = datetime.datetime.now()
  time_now = t.strftime("%X")
  y = json.loads(payload, strict=False)
  y['variables']['tweet_text'] = time_now + " " + y['variables']['tweet_text']
  new_payload = json.dumps(y)

  z = json.loads(fetch_req, strict=False)
  z['body'] = new_payload
  new_fetch_req = json.dumps(z)

  text = 'console.log(' + 'fetch("https://mobile.twitter.com/i/api/graphql/sqNNr7rKZwnDQZkIiyvcrA/CreateTweet"' + ',' + new_fetch_req + '))'
  driver.execute_script(text)


问:
EnumDisplayDevices does not return inactive displays in windows
I have a setup where I connect multiple monitors to my system through a USB HUB, there are a total of 5 monitors. However one of them turns blank or is inactive

I am trying to detect that inactive monitor using EnumDisplayDevices but unfortunately the API does not return the inactive one, instead it gives me a list of all the active ones.

Any suggestions??

Below is the code that I tried

```<code>       DISPLAY_DEVICEW adapter = new DISPLAY_DEVICEW();
       adapter.cb = Marshal.SizeOf(adapter);

        uint deviceNum = 0;
        while (EnumDisplayDevicesW(null, deviceNum, ref adapter, 0))
        {
            Console.WriteLine("Adapter name: " + adapter.DeviceName);

            DISPLAY_DEVICEW display = new DISPLAY_DEVICEW();
            display.cb = Marshal.SizeOf(display);

            uint monitorNum = 0;
            while (EnumDisplayDevicesW(adapter.DeviceName, monitorNum, ref display, 0))
            {
                Console.WriteLine("Display name: " + display.DeviceName);
                monitorNum++;
            }
            deviceNum++;
            Console.WriteLine("-------------------------------------");
        }
</code>```

Body:
I have a setup where I connect multiple monitors to my system through a USB HUB, there are a total of 5 monitors. However one of them turns blank or is inactive

I am trying to detect that inactive monitor using EnumDisplayDevices but unfortunately the API does not return the inactive one, instead it gives me a list of all the active ones.

Any suggestions??

Below is the code that I tried

       DISPLAY_DEVICEW adapter = new DISPLAY_DEVICEW();
       adapter.cb = Marshal.SizeOf(adapter);

        uint deviceNum = 0;
        while (EnumDisplayDevicesW(null, deviceNum, ref adapter, 0))
        {
            Console.WriteLine("Adapter name: " + adapter.DeviceName);

            DISPLAY_DEVICEW display = new DISPLAY_DEVICEW();
            display.cb = Marshal.SizeOf(display);

            uint monitorNum = 0;
            while (EnumDisplayDevicesW(adapter.DeviceName, monitorNum, ref display, 0))
            {
                Console.WriteLine("Display name: " + display.DeviceName);
                monitorNum++;
            }
            deviceNum++;
            Console.WriteLine("-------------------------------------");
        }


问:
Android app crashes when using view.getTag().toString();
I am trying to get the tag value from xml file:

XML:

```<code><WebView android:id="@+id/webview"
        android:tag="web_signup"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="false" />
</code>```

JAVA:

```<code>String url_id = view.getTag().toString();

        String url;
        if ("web_forgot".equals(url_id)) {
            url  = getActivity().getString(R.string.web_forgot_pass);
        } else if ("web_signup".equals(url_id)) {
            url  = getActivity().getString(R.string.web_register);
        } else {
            url  = getActivity().getString(R.string.web_main);
        }
</code>```

Unfortunately, the app crashes on line 195 with error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
</code>```

Line 195 is: String url_id = view.getTag().toString();

What I am doing wrong? Why "on a null object reference"?

The same happends when I use: getResources().getResourceName(view.getId());

I tried to change String url; to String url = null;

So, how do I get tag or id from xml file so that I can show different urls depending of the values in xml file?

Body:
I am trying to get the tag value from xml file:

XML:

<WebView android:id="@+id/webview"
        android:tag="web_signup"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="false" />

JAVA:

String url_id = view.getTag().toString();

        String url;
        if ("web_forgot".equals(url_id)) {
            url  = getActivity().getString(R.string.web_forgot_pass);
        } else if ("web_signup".equals(url_id)) {
            url  = getActivity().getString(R.string.web_register);
        } else {
            url  = getActivity().getString(R.string.web_main);
        }

Unfortunately, the app crashes on line 195 with error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

Line 195 is: String url_id = view.getTag().toString();

What I am doing wrong? Why "on a null object reference"?

The same happends when I use: getResources().getResourceName(view.getId());

I tried to change String url; to String url = null;

So, how do I get tag or id from xml file so that I can show different urls depending of the values in xml file?


问:
How does Request Inspector works in Twilio?
I'm new to Twilio, and I'm trying to understand the API. Basically, I have an existing legacy app using a Twilio API v2010 (I'm not sure what is the latest). Looking at the Twilio console, SMS messaging and voice call function works. I check the logs and noticed that the Request Inspector says:

There were no HTTP Requests logged for this event.

I read in the docs, that the Request inspector helps to give details in debugging. I checked my settings and it's enabled. So my question, how does the Request Inspector works? Do I need to add some codes to make it record requests? or is it because the app is using a legacy API?

What the app does, using PHP it creates an API request to send SMS/make call to actual mobile numbers.

I read this question but didn't get what exactly the resolution.


问:
How to pass powershell command in python script - Linux OS
```<code>import datetime
from subprocess import PIPE

def abccompanycloudcmdrun(abccompanycloudcmd):
    abccompanycloudcmdrun_output = subprocess.run(["powershell", "-Command", abccompanycloudcmd], stdout=PIPE, stderr=PIPE,shell=True)
    return abccompanycloudcmdrun_output

if __name__ == '__main__':

    abccompanycloudcmd_success = r"abccompanycloudcmd_success_" + datetime.datetime.today().strftime('%Y-%m-%d') + ".log"
    abccompanycloudcmd_error = r"abccompanycloudcmd_error_" + datetime.datetime.today().strftime('%Y-%m-%d') + ".log"

    abccompanycloudcmd = r**'Get-ADDomainController -Filter * -Server $((Get-ADDomainController -DomainName abccompanycloud.com -Discover).hostname) ` | ft ComputerObjectDN'**
    abccompanycloudcmdrun_output = abccompanycloudcmdrun(abccompanycloudcmd)

    if abccompanycloudcmdrun_output.returncode != 0:
        print("abccompanycloudcmdrun - An error occured: %s", abccompanycloudcmdrun_output.stderr.decode("utf-8"), file = open(abccompanycloudcmd_error, 'a', encoding='utf-8', errors='ignore'))
    else:
        print("abccompanycloudcmdrun generated successfully!", file = open(abccompanycloudcmd_success, 'a', encoding='utf-8', errors='ignore'))
        print(abccompanycloudcmdrun_output.stdout.decode("utf-8"), file = open(abccompanycloudcmd_success, 'a', encoding='utf-8', errors='ignore'))
</code>```

The above works fine without generating any errors in Windows. But doesnt work in Linux. It throws a message :  An error occured: %s b'-Command: powershell: command not found\n'

Question is How to pass the below powershell command in python script?
Get-ADDomainController -Filter * -Server $((Get-ADDomainController -DomainName abccompanycloud.com -Discover).hostname) ` | ft ComputerObjectDN

Body:
import datetime
from subprocess import PIPE

def abccompanycloudcmdrun(abccompanycloudcmd):
    abccompanycloudcmdrun_output = subprocess.run(["powershell", "-Command", abccompanycloudcmd], stdout=PIPE, stderr=PIPE,shell=True)
    return abccompanycloudcmdrun_output

if __name__ == '__main__':

    abccompanycloudcmd_success = r"abccompanycloudcmd_success_" + datetime.datetime.today().strftime('%Y-%m-%d') + ".log"
    abccompanycloudcmd_error = r"abccompanycloudcmd_error_" + datetime.datetime.today().strftime('%Y-%m-%d') + ".log"

    abccompanycloudcmd = r**'Get-ADDomainController -Filter * -Server $((Get-ADDomainController -DomainName abccompanycloud.com -Discover).hostname) ` | ft ComputerObjectDN'**
    abccompanycloudcmdrun_output = abccompanycloudcmdrun(abccompanycloudcmd)

    if abccompanycloudcmdrun_output.returncode != 0:
        print("abccompanycloudcmdrun - An error occured: %s", abccompanycloudcmdrun_output.stderr.decode("utf-8"), file = open(abccompanycloudcmd_error, 'a', encoding='utf-8', errors='ignore'))
    else:
        print("abccompanycloudcmdrun generated successfully!", file = open(abccompanycloudcmd_success, 'a', encoding='utf-8', errors='ignore'))
        print(abccompanycloudcmdrun_output.stdout.decode("utf-8"), file = open(abccompanycloudcmd_success, 'a', encoding='utf-8', errors='ignore'))

The above works fine without generating any errors in Windows. But doesnt work in Linux. It throws a message :  An error occured: %s b'-Command: powershell: command not found\n'

Question is How to pass the below powershell command in python script?
Get-ADDomainController -Filter * -Server $((Get-ADDomainController -DomainName abccompanycloud.com -Discover).hostname) ` | ft ComputerObjectDN


问:
Strapi v4: Creating admin and adding Roles & Permissions while Bootstraping in strapi
Project is based on Typescript
Bootstrap all data for development purpose so that, whoever new working on the project will not be needed to insert all data in strapi admin panel.
Inserting an new data works fine but only when there is admin user is created. I am not able to create admin and roles from code please help.

below is the bootsrap function, currently i am coping .db file which is already filled with define data of admin and roles. Problem with this approach is there is no control over data. Need to fill admin and roles data from code like below i have done with home-page

`

```<code>async bootstrap() {
    try {
      const isFirst = await isFirstRun();

      if (isFirst && process.env.NODE_ENV === 'development') {
        await fs.copyFileSync('./data/data.db', './.tmp/data.db');
        const data = await getHomePage();
        await strapi.services['api::home-page.home-page'].createOrUpdate({
          data,
        });

        console.log(
          '\x1b[32m%s\x1b[0m',
          `Development data copied successfully \nAdmin:${process.env.ADMIN} \npassword: ${process.env.ADMIN_PASS}`,
        );
      }
    } catch (e) {
      console.log(e);
    }
  },
};
</code>```

`

Tried https://github.com/strapi/strapi/issues/3365 this but it's not working for me.
Tried other solutions but not working with strapi v4

Body:
Project is based on Typescript
Bootstrap all data for development purpose so that, whoever new working on the project will not be needed to insert all data in strapi admin panel.
Inserting an new data works fine but only when there is admin user is created. I am not able to create admin and roles from code please help.

below is the bootsrap function, currently i am coping .db file which is already filled with define data of admin and roles. Problem with this approach is there is no control over data. Need to fill admin and roles data from code like below i have done with home-page

`

async bootstrap() {
    try {
      const isFirst = await isFirstRun();

      if (isFirst && process.env.NODE_ENV === 'development') {
        await fs.copyFileSync('./data/data.db', './.tmp/data.db');
        const data = await getHomePage();
        await strapi.services['api::home-page.home-page'].createOrUpdate({
          data,
        });

        console.log(
          '\x1b[32m%s\x1b[0m',
          `Development data copied successfully \nAdmin:${process.env.ADMIN} \npassword: ${process.env.ADMIN_PASS}`,
        );
      }
    } catch (e) {
      console.log(e);
    }
  },
};

`

Tried https://github.com/strapi/strapi/issues/3365 this but it's not working for me.
Tried other solutions but not working with strapi v4


问:
rails clearance confirmation token shows null in db
sign_up is ok. but when I want to sign_in using clearance gem. shows Completed 401 Unauthorized.
my application controller code is:

```<code>class ApplicationController < ActionController::Base
  include Clearance::Controller
  protect_from_forgery with: :null_session

  def authenticate(params)

    if request.headers['AUTH-TOKEN']
      return nil unless user = User.where(remember_token: request.headers['AUTH-TOKEN']).first
      sign_in user
    else
      User.authenticate(params[:session][:email], params[:session][:password])
    end
  end
end

</code>```

enter image description here

i expect login is successful. there will be a value in confirmation_token field in db.

Body:
sign_up is ok. but when I want to sign_in using clearance gem. shows Completed 401 Unauthorized.
my application controller code is:

class ApplicationController < ActionController::Base
  include Clearance::Controller
  protect_from_forgery with: :null_session

  def authenticate(params)

    if request.headers['AUTH-TOKEN']
      return nil unless user = User.where(remember_token: request.headers['AUTH-TOKEN']).first
      sign_in user
    else
      User.authenticate(params[:session][:email], params[:session][:password])
    end
  end
end

enter image description here

i expect login is successful. there will be a value in confirmation_token field in db.


问:
GMS BlockStore: can not retrieve bytes after store success(OnSuccessListener is invoked)
import:

```<code>com.google.android.gms:play-services-auth-blockstore:16.1.0
</code>```

code as follows:

```<code>final BlockstoreClient client = Blockstore.getClient(context);
        final StoreBytesData data = new StoreBytesData
                .Builder()
                .setBytes(backupBytes) // backupBytes.length > 0
                .build();

        client
                .storeBytes(data)
                .addOnSuccessListener(new OnSuccessListener<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        Log.e(TAG, "backup: success store data");
                        client.retrieveBytes().addOnSuccessListener(new OnSuccessListener<byte[]>() {
                            @Override
                            public void onSuccess(byte[] bytes) {
                                Log.e(TAG, "backup: stored-data-length=" + new String(bytes).length());
                            }
                        });
                        doneSignal.countDown();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "backup: fail store data");
                        doneSignal.countDown();
                    }
                })
                .addOnCanceledListener(new OnCanceledListener() {
                    @Override
                    public void onCanceled() {
                        Log.e(TAG, "backup: cancel store data");
                        doneSignal.countDown();
                    }
                });

</code>```

and the output is:

```<code>backup: success store data
backup: stored-data-length=0
</code>```

also the sample code(https://github.com/android/identity-samples/tree/main/BlockStore) does not worked on the same device

the log is here: https://xiaomi.f.mioffice.cn/file/boxk4vvfSszARAJSjAeK7Wi2aLc

after store bytes data successfully, retrieve data can get the same byte array

Body:
import:

com.google.android.gms:play-services-auth-blockstore:16.1.0

code as follows:

final BlockstoreClient client = Blockstore.getClient(context);
        final StoreBytesData data = new StoreBytesData
                .Builder()
                .setBytes(backupBytes) // backupBytes.length > 0
                .build();

        client
                .storeBytes(data)
                .addOnSuccessListener(new OnSuccessListener<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        Log.e(TAG, "backup: success store data");
                        client.retrieveBytes().addOnSuccessListener(new OnSuccessListener<byte[]>() {
                            @Override
                            public void onSuccess(byte[] bytes) {
                                Log.e(TAG, "backup: stored-data-length=" + new String(bytes).length());
                            }
                        });
                        doneSignal.countDown();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "backup: fail store data");
                        doneSignal.countDown();
                    }
                })
                .addOnCanceledListener(new OnCanceledListener() {
                    @Override
                    public void onCanceled() {
                        Log.e(TAG, "backup: cancel store data");
                        doneSignal.countDown();
                    }
                });

and the output is:

backup: success store data
backup: stored-data-length=0

also the sample code(https://github.com/android/identity-samples/tree/main/BlockStore) does not worked on the same device

the log is here: https://xiaomi.f.mioffice.cn/file/boxk4vvfSszARAJSjAeK7Wi2aLc

after store bytes data successfully, retrieve data can get the same byte array


问:
DeteKt: сheck for the use of the fragment constructor in Android
Is it possible to create DeteKt rule for checking is the Android fragment constructor used directly in the code instead newInstance?

I would like to create checks that prohibit the creation of a custom constructor for a fragment as well as the direct creation of a fragment in code.


问:
How to get the B-LTA in Itext 5.5.13.2 using the C#
I successfully reach the PAdES level B-B, B-T, B-LT in the itext using the below code.

```<code>// st is PdfStamper
var adobeLtvEnabling = new AdobeLtvEnabling(st);
adobeLtvEnabling.enable(ocsp, crl);
</code>```

Unable to get level B-LTA using itext.

The @mki original comment.

As mentioned, AdobeLtvEnabling ignores time stamps; signature time stamps to be more exact. To process them, too, you need to extend the loop in enable to not only walk the certificate path of pdfPKCS7.getSigningCertificate() but also of the signing certificate of pdfPKCS7.getTimeStampToken() if applicable. Of course, it is possible that in your case this is not necessary: if the TSA certificate immediately is on the Trusted Lists (and not merely an ancestor in its certificate path), then no extra validation information is required. This is the case for some but not for all TSAs.

The @mki suggested extending the loop and using Java pdfPKCS7.getTimeStampToken() in the post https://stackoverflow.com/questions/71351592/itext-pades-baseline-lt-lta

I found pdfPKCS7.TimeStampToken() in C# but no idea about how to use it and where to use it to get the  B-LTA levels.

I am looking ready to use code which is works with the Itext 5.5.13.2 and C# and get the B-LTA levels.

Is anyone has already done it? Please share the code.

Thanks in advance.

Body:
I successfully reach the PAdES level B-B, B-T, B-LT in the itext using the below code.

// st is PdfStamper
var adobeLtvEnabling = new AdobeLtvEnabling(st);
adobeLtvEnabling.enable(ocsp, crl);

Unable to get level B-LTA using itext.

The @mki original comment.

As mentioned, AdobeLtvEnabling ignores time stamps; signature time stamps to be more exact. To process them, too, you need to extend the loop in enable to not only walk the certificate path of pdfPKCS7.getSigningCertificate() but also of the signing certificate of pdfPKCS7.getTimeStampToken() if applicable. Of course, it is possible that in your case this is not necessary: if the TSA certificate immediately is on the Trusted Lists (and not merely an ancestor in its certificate path), then no extra validation information is required. This is the case for some but not for all TSAs.

The @mki suggested extending the loop and using Java pdfPKCS7.getTimeStampToken() in the post https://stackoverflow.com/questions/71351592/itext-pades-baseline-lt-lta

I found pdfPKCS7.TimeStampToken() in C# but no idea about how to use it and where to use it to get the  B-LTA levels.

I am looking ready to use code which is works with the Itext 5.5.13.2 and C# and get the B-LTA levels.

Is anyone has already done it? Please share the code.

Thanks in advance.


问:
React app deployment through tom cat server?
How to deploy react app in tomcat server by creating war file.

We tried npm run compile
In package.json
"compile" : "npm run build && cd build && jar -cvf web.war"

Its creating build  in war file after deploying in tomcat webinf

But its not getting react content only title is displaying

React Ui and Javabackend should get deploy in tomcat


问:
Facebook login flow doesn't work for my Android app - web authentication
I have an android game and have integrated the Android Facebook SDK.  When you ask to login using the fb login button, it pops up chrome to enter your credentials.  If I enter them correctly it simply refreshes the web page, it doesn't redirect back to my app to actually login.

If however I hit the 3 dots upper right of the web page and "request desktop site" and do the same login then it works.

It works fine in the simulator running tiramisu but not on a device running Android 8.1.0 (API level 27).. so some of my users on these older versions aren't able to login without some extra guidance to load the desktop version of that web page.

Anyone run into this?  currently using

implementation 'com.facebook.android:facebook-login:latest.release'

It appears to pull in 15.1.0 of the library


问:
call list item as numpy array
I have some matrixes of which names are stored in a list.

```<code>print(result)

</code>```

output:

['cyl9', 'cyl10']

```<code>
Now how to call these arrays??

Like I Have Matrix In The name of result list items.

</code>```

A = np.array(cyl9, dtype = 'float64')

```<code>the results is
</code>```

Output:

array([[1.00000000e+00, 2.99880415e-01, 1.55988738e-01, 2.00000000e+00],
[2.00000000e+00, 2.99521804e-01, 1.61967918e-01]])

```<code>
</code>```

Title: call list item as numpy array

Body:
I have some matrixes of which names are stored in a list.

print(result)

output:

['cyl9', 'cyl10']

Now how to call these arrays??

Like I Have Matrix In The name of result list items.

A = np.array(cyl9, dtype = 'float64')

the results is

Output:

array([[1.00000000e+00, 2.99880415e-01, 1.55988738e-01, 2.00000000e+00],
[2.00000000e+00, 2.99521804e-01, 1.61967918e-01]])


问:
TypeError: Cannot read properties of undefined (reading '__asyncLoader') in VueJS
I'm implementing a store using reactive API to implement minimal state management.

Here is the code for my store

export const store = reactive({
  cart: [],
  total: 0,
  removeFromCart(id) {
    this.cart = this.cart.filter((item) => item.id !== id);
    this.updateTotal();
  },
  updateTotal() {
    let total = 0;
    for (const item of this.cart) {
      total += item.price * item.quantity;
    }
    this.total = total;
  },
});
```
<p>Code from Vue template</p>
<pre class="lang-html prettyprint-override"><code><tr
  v-for="product in store.cart"
  :key="product.id"
  class="border-b border-t bg-white"
>
  <th
    scope="row"
    class="h-24 w-20 whitespace-nowrap py-4 px-6 font-medium text-gray-900"
  >
    <img :src="product.image" :alt="product.title" />
  </th>
  <td class="py-4 px-6 font-bold">
    {{ product.title }}
  </td>
  <td class="flex-nowrap py-4 px-6 font-bold">
    <i
      @click="store.reduceQty(product.id)"
      class="bi bi-chevron-left mr-3 cursor-pointer"
    ></i>
    <span>{{ product.quantity }}</span>
    <i
      @click="store.addQty(product.id)"
      class="bi bi-chevron-right ml-3 cursor-pointer"
    ></i>
  </td>
  <td class="py-4 px-6 font-bold">${{ product.price }}</td>
  <td class="py-4 px-6">
    <i
      @click="store.removeFromCart(product.id)"
      class="bi bi-x-lg cursor-pointer"
    ></i>
  </td>
</tr>
</code>```

When I remove the last remaining item from the cart it shows the following error in the console which says "TypeError: Cannot read properties of undefined (reading '__asyncLoader')" and in the error stack the origin of the error is removeFromCart() and the app stops working

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__asyncLoader')
    at isAsyncWrapper (runtime-core.esm-bundler.js:2272:40)
    at unmount (runtime-core.esm-bundler.js:6090:40)
    at unmountComponent (runtime-core.esm-bundler.js:6212:13)
    at unmount (runtime-core.esm-bundler.js:6097:13)
    at unmountChildren (runtime-core.esm-bundler.js:6241:13)
    at unmount (runtime-core.esm-bundler.js:6115:17)
    at patch (runtime-core.esm-bundler.js:5070:13)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5711:17)
    at ReactiveEffect.run (reactivity.esm-bundler.js:187:25)
    at instance.update (runtime-core.esm-bundler.js:5745:56)
isAsyncWrapper @ runtime-core.esm-bundler.js:2272
unmount @ runtime-core.esm-bundler.js:6090
unmountComponent @ runtime-core.esm-bundler.js:6212
unmount @ runtime-core.esm-bundler.js:6097
unmountChildren @ runtime-core.esm-bundler.js:6241
unmount @ runtime-core.esm-bundler.js:6115
patch @ runtime-core.esm-bundler.js:5070
componentUpdateFn @ runtime-core.esm-bundler.js:5711
run @ reactivity.esm-bundler.js:187
instance.update @ runtime-core.esm-bundler.js:5745
callWithErrorHandling @ runtime-core.esm-bundler.js:157
flushJobs @ runtime-core.esm-bundler.js:390
Promise.then (async)
queueFlush @ runtime-core.esm-bundler.js:282
queueJob @ runtime-core.esm-bundler.js:276
(anonymous) @ runtime-core.esm-bundler.js:5743
triggerEffect @ reactivity.esm-bundler.js:397
triggerEffects @ reactivity.esm-bundler.js:387
trigger @ reactivity.esm-bundler.js:355
set2 @ reactivity.esm-bundler.js:526
removeFromCart @ store.js:30
onClick @ CartView.vue:48
callWithErrorHandling @ runtime-core.esm-bundler.js:157
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166
invoker @ runtime-dom.esm-bundler.js:345
```

Please help me to fix this issue... Thank you so much for your attention and participation in advance.

Body:
I'm implementing a store using reactive API to implement minimal state management.

Here is the code for my store

export const store = reactive({
  cart: [],
  total: 0,
  removeFromCart(id) {
    this.cart = this.cart.filter((item) => item.id !== id);
    this.updateTotal();
  },
  updateTotal() {
    let total = 0;
    for (const item of this.cart) {
      total += item.price * item.quantity;
    }
    this.total = total;
  },
});

Code from Vue template

    {{ product.title }}

    {{ product.quantity }}

  ${{ product.price }}

When I remove the last remaining item from the cart it shows the following error in the console which says "TypeError: Cannot read properties of undefined (reading '__asyncLoader')" and in the error stack the origin of the error is removeFromCart() and the app stops working

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '__asyncLoader')
    at isAsyncWrapper (runtime-core.esm-bundler.js:2272:40)
    at unmount (runtime-core.esm-bundler.js:6090:40)
    at unmountComponent (runtime-core.esm-bundler.js:6212:13)
    at unmount (runtime-core.esm-bundler.js:6097:13)
    at unmountChildren (runtime-core.esm-bundler.js:6241:13)
    at unmount (runtime-core.esm-bundler.js:6115:17)
    at patch (runtime-core.esm-bundler.js:5070:13)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5711:17)
    at ReactiveEffect.run (reactivity.esm-bundler.js:187:25)
    at instance.update (runtime-core.esm-bundler.js:5745:56)
isAsyncWrapper @ runtime-core.esm-bundler.js:2272
unmount @ runtime-core.esm-bundler.js:6090
unmountComponent @ runtime-core.esm-bundler.js:6212
unmount @ runtime-core.esm-bundler.js:6097
unmountChildren @ runtime-core.esm-bundler.js:6241
unmount @ runtime-core.esm-bundler.js:6115
patch @ runtime-core.esm-bundler.js:5070
componentUpdateFn @ runtime-core.esm-bundler.js:5711
run @ reactivity.esm-bundler.js:187
instance.update @ runtime-core.esm-bundler.js:5745
callWithErrorHandling @ runtime-core.esm-bundler.js:157
flushJobs @ runtime-core.esm-bundler.js:390
Promise.then (async)
queueFlush @ runtime-core.esm-bundler.js:282
queueJob @ runtime-core.esm-bundler.js:276
(anonymous) @ runtime-core.esm-bundler.js:5743
triggerEffect @ reactivity.esm-bundler.js:397
triggerEffects @ reactivity.esm-bundler.js:387
trigger @ reactivity.esm-bundler.js:355
set2 @ reactivity.esm-bundler.js:526
removeFromCart @ store.js:30
onClick @ CartView.vue:48
callWithErrorHandling @ runtime-core.esm-bundler.js:157
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166
invoker @ runtime-dom.esm-bundler.js:345

Please help me to fix this issue... Thank you so much for your attention and participation in advance.


问:
parsing, getting JSON, swift
I have problem getting Json with a generic function. I attached the code below. the problem in line " guard let JsonResponse = try? response.result.value". it does not work. gives me "Type of expression is ambiguous without more context"
this is the code:

```<code>class ServicesManager<T: TargetType>  {
    func fetchingData<M: Decodable>(target: T, response: M.Type, completion: @escaping (Result<(M?, NSError)>?) -> Void) {
        let method = Alamofire.HTTPMethod(rawValue: target.method.rawValue)
        let parameters = buildParameters(task: target.task)
        Alamofire.request(target.domian + target.path, method: method!,
                          // .0  realting to parameters and the .1 for the ecndoding
                          parameters: parameters.0, encoding: parameters.1).responseJSON { (response) in
            //fetching the result and encoding it and return it in the completion
            guard let statusCode = response.response?.statusCode else {
                // Add Custom Error
                completion(.failure(NSError()))
                return
            }

            if statusCode == 200 {
                // Successful request
                guard let JsonResponse = try? response.result.value else {
                    // Add Custom Error in case failed getting the JSONResponse
                    completion(.failure(NSError()))
                    return
              }
               guard let JsonData = try?.JSONSerialization.data(withJSONObject: JsonResponse, options: []) else {
                   // Add Custom Error
                   completion(.failure(NSError()))
                   return
               }
                // M: means decoadable
                guard let responseObject = try?.JSONDecoder.decode(M.self, from: JsonData) else {
                  // Add Custom Error
                    completion(.failure(NSError()))
                    return
             }
               // decode the result and send it back to the user
               DispatchQueue.main.async {
                    completion(.success(responseObject))
               }
           }

           else {
                // again Add custom error based on the statusCode such as 404
               completion(.failure(NSError()))
            }
        }

    }
    //MARK: -create the parameters method
    private func buildParameters(task: Task) -> ([String: Any], ParameterEncoding){
        switch task {
        case .requestPlain:
            return ([:], URLEncoding.default) // no parameters, URLEncoding(Json, query..)
        case .requestParameters(parameters: let parameters, encoding: let encoding):
            return (parameters, encoding) // giv it parameter ,encoding such as JSON
        }
    }
}

</code>```

I tried to get the result.

Title: parsing, getting JSON, swift

Body:
I have problem getting Json with a generic function. I attached the code below. the problem in line " guard let JsonResponse = try? response.result.value". it does not work. gives me "Type of expression is ambiguous without more context"
this is the code:

class ServicesManager<T: TargetType>  {
    func fetchingData<M: Decodable>(target: T, response: M.Type, completion: @escaping (Result<(M?, NSError)>?) -> Void) {
        let method = Alamofire.HTTPMethod(rawValue: target.method.rawValue)
        let parameters = buildParameters(task: target.task)
        Alamofire.request(target.domian + target.path, method: method!,
                          // .0  realting to parameters and the .1 for the ecndoding
                          parameters: parameters.0, encoding: parameters.1).responseJSON { (response) in
            //fetching the result and encoding it and return it in the completion
            guard let statusCode = response.response?.statusCode else {
                // Add Custom Error
                completion(.failure(NSError()))
                return
            }

            if statusCode == 200 {
                // Successful request
                guard let JsonResponse = try? response.result.value else {
                    // Add Custom Error in case failed getting the JSONResponse
                    completion(.failure(NSError()))
                    return
              }
               guard let JsonData = try?.JSONSerialization.data(withJSONObject: JsonResponse, options: []) else {
                   // Add Custom Error
                   completion(.failure(NSError()))
                   return
               }
                // M: means decoadable
                guard let responseObject = try?.JSONDecoder.decode(M.self, from: JsonData) else {
                  // Add Custom Error
                    completion(.failure(NSError()))
                    return
             }
               // decode the result and send it back to the user
               DispatchQueue.main.async {
                    completion(.success(responseObject))
               }
           }

           else {
                // again Add custom error based on the statusCode such as 404
               completion(.failure(NSError()))
            }
        }

    }
    //MARK: -create the parameters method
    private func buildParameters(task: Task) -> ([String: Any], ParameterEncoding){
        switch task {
        case .requestPlain:
            return ([:], URLEncoding.default) // no parameters, URLEncoding(Json, query..)
        case .requestParameters(parameters: let parameters, encoding: let encoding):
            return (parameters, encoding) // giv it parameter ,encoding such as JSON
        }
    }
}

I tried to get the result.


问:
Too few options for Merge Request reverting in GitLab WebGUI
There's the following case:

There are two main branches in the project: master and dev.

A user created their own feature branch (let's name it featureBranch), probably derived from dev branch, worked on that for some time, made some changes and pushed several commits. As there was a Merge Request open for this feature branch in GitLab, everything is reported there.

Then, suddenly, the user merged their featureBranch into dev, probably as a mistake while rebasing their branch.

I was trying to revert the changes using GitLab's GUI, but when I press the Revert button (next to the Cherry-pick and Delete source branch buttons), I only have option to revert the changes in either master or some bugfix branch. There's nothing about dev branch nor the featureBranch.

The same options I have while trying to revert the most recent commit: only the master and that bugfix branch.

How to achieve the state before the Merge Request was done?


问:
Model3D - Compile Error on PowerPoint for Mac Version 16.661
The code runs on Windows in Microsoft Office 2016 and above (compatible with 3D Objects). However, on PowerPoint for Mac Version 16.661, the following error is shown.

```<code>ActivePresentation.SlideShowWindow.View.Slide.Shapes("dice" & i).Model3D.RotationX = Int(100)
</code>```

Body:
The code runs on Windows in Microsoft Office 2016 and above (compatible with 3D Objects). However, on PowerPoint for Mac Version 16.661, the following error is shown.

ActivePresentation.SlideShowWindow.View.Slide.Shapes("dice" & i).Model3D.RotationX = Int(100)


问:
Convert JSON to XML .net
I want to convert from JSON to XML but the return keep showing in JSON. No Error or bug</p>
```<code>protected string convertToJSONorXML(object convertThisObj, returnDataFormat returnFormat, bool jsonformatting = false)
        {
            string returnString = "";

            if (returnFormat == returnDataFormat.JsonFormat)
            {
                return JsonConvert.SerializeObject(convertThisObj,
                                                    (jsonformatting) ? Formatting.Indented : Formatting.None,
                                                    new JsonSerializerSettings { NullValueHandling = (jsonformatting) ? NullValueHandling.Ignore : NullValueHandling.Include }
                                                   );
            }

            returnString = toXML(convertThisObj);
            return returnString;
        }
</code>```

Title: Convert JSON to XML .net

Body:
I want to convert from JSON to XML but the return keep showing in JSON. No Error or bug

protected string convertToJSONorXML(object convertThisObj, returnDataFormat returnFormat, bool jsonformatting = false)
        {
            string returnString = "";

            if (returnFormat == returnDataFormat.JsonFormat)
            {
                return JsonConvert.SerializeObject(convertThisObj,
                                                    (jsonformatting) ? Formatting.Indented : Formatting.None,
                                                    new JsonSerializerSettings { NullValueHandling = (jsonformatting) ? NullValueHandling.Ignore : NullValueHandling.Include }
                                                   );
            }

            returnString = toXML(convertThisObj);
            return returnString;
        }


问:
Unity iOS native share plugin using swift and objective-c
I have a simple swift + objective-c plugin for my unity project which works. Below is the code for that -

c# -

```<code>using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using AOT;
using System;
using System.Text;

public class PluginHelper : MonoBehaviour
{
    public TextMeshProUGUI myText;

    public Button shareButton;

    static PluginHelper inst;

    void Awake() {
        inst = this;
    }

    [DllImport("__Internal")]
    private static extern int shareIOS(int a, int b, Action<string> completionHandler);

    [MonoPInvokeCallback ( typeof ( Action<string> ) )]
    private static void completionHandler ( string s )
    {
        Debug.Log("completed");
        inst.myText.text = "Shared " + s;
    }

    public static void Share() {
        Debug.Log("sharing");
        shareIOS(10, 20, completionHandler);
    }
}
</code>```

objective-c -

```<code>#import <Foundation/Foundation.h>
#include "UnityFramework/UnityFramework-Swift.h"

extern "C"
{
    typedef void (*CallbackFunction)();
    typedef void (*CallbackFunctionWithString)( const char * );
    typedef void (*CallbackFunctionWithInt)( NSInteger );
    typedef void (*CallbackFunctionWithFloat)( float );

    // Sometimes I also wanted to send back a 'success' bool, with the string data, so I did that like this:
    typedef void (*CallbackFunctionWithBoolAndString)( bool, const char * );
    // etc ...

    #pragma mark - Functions
    void shareIOS( int a , int b, CallbackFunctionWithString onComplete )
    {
        [[UnityPlugin shared] Share:a:b:onComplete];
    }
}
</code>```

swift code -

```<code>import Foundation

@objc public class UnityPlugin : NSObject {

    public typealias CCallbackFunctionWithString = @convention(c) (UnsafePointer<CChar>) -> Void;

    @objc public static let shared = UnityPlugin()
    @objc public func Share(_ a:Int, _ b:Int, _ onComplete:@escaping CCallbackFunctionWithString) -> Void {

        onComplete(String(a+b));
    }
}
</code>```

Now I want to add functionality in swift code to let users share content (image, text, link, etc).

I went through this link which suggested using UIActivityViewController so I changed my swift code to -

```<code>import Foundation

@objc public class UnityPlugin : NSObject {

    public typealias CCallbackFunctionWithString = @convention(c) (UnsafePointer<CChar>) -> Void;

    @objc public static let shared = UnityPlugin()
    @objc public func Share(_ a:Int, _ b:Int, _ onComplete:@escaping CCallbackFunctionWithString) -> Void {
        let items = ["This app is my favorite"]
        let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
        present(ac, animated: true)
        onComplete(String(a+b));
    }
}
</code>```

But this throws compilation error - Cannot find 'present' in scope

I tried inheriting it like -

@objc public class UnityPlugin : NSObject, UIViewController but found out that swift does not support multiple inheritance.

I found many examples of doing this by objective-c alone but I was wondering if it is possible to do it using swift also. If yes, then how?

Thanks

Body:
I have a simple swift + objective-c plugin for my unity project which works. Below is the code for that -

c# -

using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using AOT;
using System;
using System.Text;

public class PluginHelper : MonoBehaviour
{
    public TextMeshProUGUI myText;

    public Button shareButton;

    static PluginHelper inst;

    void Awake() {
        inst = this;
    }

    [DllImport("__Internal")]
    private static extern int shareIOS(int a, int b, Action<string> completionHandler);

    [MonoPInvokeCallback ( typeof ( Action<string> ) )]
    private static void completionHandler ( string s )
    {
        Debug.Log("completed");
        inst.myText.text = "Shared " + s;
    }

    public static void Share() {
        Debug.Log("sharing");
        shareIOS(10, 20, completionHandler);
    }
}

objective-c -

#import <Foundation/Foundation.h>
#include "UnityFramework/UnityFramework-Swift.h"

extern "C"
{
    typedef void (*CallbackFunction)();
    typedef void (*CallbackFunctionWithString)( const char * );
    typedef void (*CallbackFunctionWithInt)( NSInteger );
    typedef void (*CallbackFunctionWithFloat)( float );

    // Sometimes I also wanted to send back a 'success' bool, with the string data, so I did that like this:
    typedef void (*CallbackFunctionWithBoolAndString)( bool, const char * );
    // etc ...

    #pragma mark - Functions
    void shareIOS( int a , int b, CallbackFunctionWithString onComplete )
    {
        [[UnityPlugin shared] Share:a:b:onComplete];
    }
}

swift code -

import Foundation

@objc public class UnityPlugin : NSObject {

    public typealias CCallbackFunctionWithString = @convention(c) (UnsafePointer<CChar>) -> Void;

    @objc public static let shared = UnityPlugin()
    @objc public func Share(_ a:Int, _ b:Int, _ onComplete:@escaping CCallbackFunctionWithString) -> Void {

        onComplete(String(a+b));
    }
}

Now I want to add functionality in swift code to let users share content (image, text, link, etc).

I went through this link which suggested using UIActivityViewController so I changed my swift code to -

import Foundation

@objc public class UnityPlugin : NSObject {

    public typealias CCallbackFunctionWithString = @convention(c) (UnsafePointer<CChar>) -> Void;

    @objc public static let shared = UnityPlugin()
    @objc public func Share(_ a:Int, _ b:Int, _ onComplete:@escaping CCallbackFunctionWithString) -> Void {
        let items = ["This app is my favorite"]
        let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
        present(ac, animated: true)
        onComplete(String(a+b));
    }
}

But this throws compilation error - Cannot find 'present' in scope

I tried inheriting it like -

@objc public class UnityPlugin : NSObject, UIViewController but found out that swift does not support multiple inheritance.

I found many examples of doing this by objective-c alone but I was wondering if it is possible to do it using swift also. If yes, then how?

Thanks


问:
Joining two polars dataframes via a matching key and range overlaps on specified columns
Suppose I have two dataframes generated with the code below:

```<code>df=pl.DataFrame({'ID':[1, 2, 1, 2, 1, 2, 1, 1, 2, 2],
                 'Reference Value':[1.2, 3.5, 2.2, 1.4, 1.5, 3.7, 1.9, 1.1, 2.7, 3.8]
                })
#Reference table:

df2=pl.DataFrame({'ID':[1, 1, 1, 2, 2, 2, 3, 3, 3],
                 'Lower Reference Range':[1, 2, 3, 1, 2, 3, 1, 2, 3],
                 'Upper Reference Range':[2, 3, 4, 2, 3, 4, 2, 3, 4],
                 'Map Value':['a1','b1','c1','a2','b2', 'c2', 'a3', 'b3', 'c3']
                })
</code>```

Which generates a dataframe as such:

```<code>df1:
┌─────┬─────────────────┐
│ ID  ┆ Reference Value │
│ --- ┆ ---             │
│ i64 ┆ f64             │
╞═════╪═════════════════╡
│ 1   ┆ 1.2             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.5             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2.2             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1.4             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.9             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.1             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 2.7             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.8             │
└─────┴─────────────────┘

df2:
┌─────┬───────────────────────┬───────────────────────┬───────────┐
│ ID  ┆ Lower Reference Range ┆ Upper Reference Range ┆ Map Value │
│ --- ┆ ---                   ┆ ---                   ┆ ---       │
│ i64 ┆ i64                   ┆ i64                   ┆ str       │
╞═════╪═══════════════════════╪═══════════════════════╪═══════════╡
│ 1   ┆ 1                     ┆ 2                     ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2                     ┆ 3                     ┆ b1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 3                     ┆ 4                     ┆ c1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1                     ┆ 2                     ┆ a2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...                   ┆ ...                   ┆ ...       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3                     ┆ 4                     ┆ c2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 1                     ┆ 2                     ┆ a3        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 2                     ┆ 3                     ┆ b3        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 3                     ┆ 4                     ┆ c3        │
</code>```

I would like to map df1 to df2 such that where the IDs match up and the value of Reference Value is between the lower and upper range in the reference table, the map value is assigned. As below:

```<code>┌─────┬─────────────────┬───────────┐
│ ID  ┆ Reference Value ┆ Map Value │
│ --- ┆ ---             ┆ ---       │
│ i64 ┆ f64             ┆ str       │
╞═════╪═════════════════╪═══════════╡
│ 1   ┆ 1.2             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.5             ┆ c2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2.2             ┆ b1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1.4             ┆ a2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...             ┆ ...       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.9             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.1             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 2.7             ┆ b2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.8             ┆ c2        │
└─────┴─────────────────┴───────────┘
</code>```

I've implemented a simple naïve approach via the when and then method as below:

```<code>def simple_when_then_mapper(df,df2,ref_id,ref_value,lower_range_col,upper_range_col,mapping_col):
    '''
    df = dataframe to map values unto
    df2: reference dataframe
    ref_id, ref_value,lower_range_col,upper_range_col,mapping_col: str referencing the column containing the Reference ID, Reference Value, etc
    '''
    for i in range(df2.shape[0]):
        if 'query' not in locals():
            query=(pl.when((pl.col(ref_id)==df2[ref_id][i]) &
                          (pl.col(ref_value)>df2[lower_range_col][i])&
                          (pl.col(ref_value)<=df2[upper_range_col][i])
                         )
                   .then(df2[mapping_col][i]))
        else:
            query=(query.when((pl.col(ref_id)==df2[ref_id][i]) &
                             (pl.col(ref_value)>df2[lower_range_col][i])&
                             (pl.col(ref_value)<=df2[upper_range_col][i])
                            )
                   .then(df2[mapping_col][i]))
    query=query.otherwise(None).alias(mapping_col)
    return df.with_column(query)
</code>```

This works but my concern is when the tables and cardinality are sufficiently high, I'll run into issues. From my testing, when-then nesting of ~400 starts to trigger stack overflows on my machine. Is there a more proper and scalable way to do the above?

Body:
Suppose I have two dataframes generated with the code below:

df=pl.DataFrame({'ID':[1, 2, 1, 2, 1, 2, 1, 1, 2, 2],
                 'Reference Value':[1.2, 3.5, 2.2, 1.4, 1.5, 3.7, 1.9, 1.1, 2.7, 3.8]
                })
#Reference table:

df2=pl.DataFrame({'ID':[1, 1, 1, 2, 2, 2, 3, 3, 3],
                 'Lower Reference Range':[1, 2, 3, 1, 2, 3, 1, 2, 3],
                 'Upper Reference Range':[2, 3, 4, 2, 3, 4, 2, 3, 4],
                 'Map Value':['a1','b1','c1','a2','b2', 'c2', 'a3', 'b3', 'c3']
                })

Which generates a dataframe as such:

df1:
┌─────┬─────────────────┐
│ ID  ┆ Reference Value │
│ --- ┆ ---             │
│ i64 ┆ f64             │
╞═════╪═════════════════╡
│ 1   ┆ 1.2             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.5             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2.2             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1.4             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.9             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.1             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 2.7             │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.8             │
└─────┴─────────────────┘

df2:
┌─────┬───────────────────────┬───────────────────────┬───────────┐
│ ID  ┆ Lower Reference Range ┆ Upper Reference Range ┆ Map Value │
│ --- ┆ ---                   ┆ ---                   ┆ ---       │
│ i64 ┆ i64                   ┆ i64                   ┆ str       │
╞═════╪═══════════════════════╪═══════════════════════╪═══════════╡
│ 1   ┆ 1                     ┆ 2                     ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2                     ┆ 3                     ┆ b1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 3                     ┆ 4                     ┆ c1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1                     ┆ 2                     ┆ a2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...                   ┆ ...                   ┆ ...       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3                     ┆ 4                     ┆ c2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 1                     ┆ 2                     ┆ a3        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 2                     ┆ 3                     ┆ b3        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3   ┆ 3                     ┆ 4                     ┆ c3        │

I would like to map df1 to df2 such that where the IDs match up and the value of Reference Value is between the lower and upper range in the reference table, the map value is assigned. As below:

┌─────┬─────────────────┬───────────┐
│ ID  ┆ Reference Value ┆ Map Value │
│ --- ┆ ---             ┆ ---       │
│ i64 ┆ f64             ┆ str       │
╞═════╪═════════════════╪═══════════╡
│ 1   ┆ 1.2             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.5             ┆ c2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 2.2             ┆ b1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 1.4             ┆ a2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ...             ┆ ...       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.9             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1.1             ┆ a1        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 2.7             ┆ b2        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2   ┆ 3.8             ┆ c2        │
└─────┴─────────────────┴───────────┘

I've implemented a simple naïve approach via the when and then method as below:

def simple_when_then_mapper(df,df2,ref_id,ref_value,lower_range_col,upper_range_col,mapping_col):
    '''
    df = dataframe to map values unto
    df2: reference dataframe
    ref_id, ref_value,lower_range_col,upper_range_col,mapping_col: str referencing the column containing the Reference ID, Reference Value, etc
    '''
    for i in range(df2.shape[0]):
        if 'query' not in locals():
            query=(pl.when((pl.col(ref_id)==df2[ref_id][i]) &
                          (pl.col(ref_value)>df2[lower_range_col][i])&
                          (pl.col(ref_value)<=df2[upper_range_col][i])
                         )
                   .then(df2[mapping_col][i]))
        else:
            query=(query.when((pl.col(ref_id)==df2[ref_id][i]) &
                             (pl.col(ref_value)>df2[lower_range_col][i])&
                             (pl.col(ref_value)<=df2[upper_range_col][i])
                            )
                   .then(df2[mapping_col][i]))
    query=query.otherwise(None).alias(mapping_col)
    return df.with_column(query)

This works but my concern is when the tables and cardinality are sufficiently high, I'll run into issues. From my testing, when-then nesting of ~400 starts to trigger stack overflows on my machine. Is there a more proper and scalable way to do the above?


问:
ClickHouse source code: where is IBlockInputStream interface?
At the end of 2021, the DataStreams folder was removed from the ClickHouse source code update. What has replaced streams such as BlockInputStream、BlockOutputStream? Thank you!

I wonder what new things are being used to replace Block Stream. Where is it in the source code? I'm new to C++ and databases， recently read the source code for ClickHouse.


问:
How to add label to a FeatureLayout using object in JavaScript
How can I add a label to a FeatureLayout using an object? I don't have just one featureLayout, so I created an object with multiple layouts like this

```<code>const layersByYears = [
    { year: 1918, layers: [
        { layerID: "1", opacity: 1.0, name: "name1", featureLayer: null,labelingInfo: labelClass },
        { layerID: "2", opacity: 1.0, name: "name2", featureLayer: null },
        { layerID: "3", opacity: 1.0, name: "name3", featureLayer: null },
        { layerID: "4", opacity: 1.0, name: "name4", featureLayer: null }
    ] },...]

</code>```

Then I have variable labelClass like this:

```<code>const labelClass = {
    symbol: {
        type: "text",  // autocasts as new TextSymbol()
        color: "black",
        font: {  // autocast as new Font()
          family: "Playfair Display",
          size: 12,
          weight: "bold"
        }
      },
      labelPlacement: "above-center",
      labelExpressionInfo: {
        expression: "42"
      }
}
</code>```

And last I created layer like this:

```<code>const createFL = (layer) => {
        if(layer.featureLayer !== null && layer.featureLayer !== undefined)
            return;
        layer.featureLayer = new FeatureLayer({
            portalItem: {
                id: layer.layerID,
                opacity: layer.opacity !== undefined ? layer.opacity : 1.0,
                visible: false,
            }, labelingInfo: layer.labelingInfo
     })
    }
</code>```

I am not sure what I have wrong. I can see the layer from ArcGis online but I cannot see the labels in my graph. The graph is simple point graph. The labelClass variable is declared prior to layersByYears variable.

Body:
How can I add a label to a FeatureLayout using an object? I don't have just one featureLayout, so I created an object with multiple layouts like this

const layersByYears = [
    { year: 1918, layers: [
        { layerID: "1", opacity: 1.0, name: "name1", featureLayer: null,labelingInfo: labelClass },
        { layerID: "2", opacity: 1.0, name: "name2", featureLayer: null },
        { layerID: "3", opacity: 1.0, name: "name3", featureLayer: null },
        { layerID: "4", opacity: 1.0, name: "name4", featureLayer: null }
    ] },...]

Then I have variable labelClass like this:

const labelClass = {
    symbol: {
        type: "text",  // autocasts as new TextSymbol()
        color: "black",
        font: {  // autocast as new Font()
          family: "Playfair Display",
          size: 12,
          weight: "bold"
        }
      },
      labelPlacement: "above-center",
      labelExpressionInfo: {
        expression: "42"
      }
}

And last I created layer like this:

const createFL = (layer) => {
        if(layer.featureLayer !== null && layer.featureLayer !== undefined)
            return;
        layer.featureLayer = new FeatureLayer({
            portalItem: {
                id: layer.layerID,
                opacity: layer.opacity !== undefined ? layer.opacity : 1.0,
                visible: false,
            }, labelingInfo: layer.labelingInfo
     })
    }

I am not sure what I have wrong. I can see the layer from ArcGis online but I cannot see the labels in my graph. The graph is simple point graph. The labelClass variable is declared prior to layersByYears variable.


问:
VBA - How to hide or delete Userform TextBox Cursor in an while its value is updating
I have a userform with a textbox in it to inform users what is happening in my code in background. I added a change event on my textbox and set AutoSize property of my userform to Enabled and wrote a code to resize my textbox and userform according to the length of the textbox's text at each stage. The only remaining problem is that there is always a blinking cursor at the end of the textbox at each stage. How do I hide or delete this cursor while updating the textbox text? I know that there is a solution which suggests to put another textbox and put a .setfocus on it in userform_initialize subroutine but this can not solve my problem since my userform and textbox is continuously updating.


问:
Tracing guest instructions in KVM
I'm trying to get a trace of instructions executed by a userspace program running inside KVM. For this purpose, I've enabled the KVM_GUESTDBG_SINGLESTEP and I'm reading the value of PC at every KVM_EXIT_DEBUG.

I start the userspace process inside the VM while I'm logging these PC values and stop the VM after a few seconds. The userspace process simply loops infinitely, therefore I should be seeing quite a number of duplicate instruction addresses.

However, when I looked at the instruction addresses that were dumped, the instructions with the most frequency are the following

```<code>    744 pc = 0xffffffff81369bf5
   1289 pc = 0xffffffff81369eb2
</code>```

And when I looked up these addresses inside GDB, I found the following information

```<code>0xffffffff81369bf5 <vm_notify+21>:  mov    eax,0x1
-----------
0xffffffff81369eb2 <vm_interrupt+34>:   mov    rax,QWORD PTR [rsi+0x308]
</code>```

I'm not familiar with these functions and I was wondering why they keep showing up in the output instead of the physical address of the userspace program.

Is there maybe another way to trace the instructions executed by the guest userspace program ?

Title: Tracing guest instructions in KVM

Body:
I'm trying to get a trace of instructions executed by a userspace program running inside KVM. For this purpose, I've enabled the KVM_GUESTDBG_SINGLESTEP and I'm reading the value of PC at every KVM_EXIT_DEBUG.

I start the userspace process inside the VM while I'm logging these PC values and stop the VM after a few seconds. The userspace process simply loops infinitely, therefore I should be seeing quite a number of duplicate instruction addresses.

However, when I looked at the instruction addresses that were dumped, the instructions with the most frequency are the following

    744 pc = 0xffffffff81369bf5
   1289 pc = 0xffffffff81369eb2

And when I looked up these addresses inside GDB, I found the following information

0xffffffff81369bf5 <vm_notify+21>:  mov    eax,0x1
-----------
0xffffffff81369eb2 <vm_interrupt+34>:   mov    rax,QWORD PTR [rsi+0x308]

I'm not familiar with these functions and I was wondering why they keep showing up in the output instead of the physical address of the userspace program.

Is there maybe another way to trace the instructions executed by the guest userspace program ?


问:
Extend a proto message without knowing the last field number
I know that the protocol buffer supports extend keyword to extend a message in a different file. This is somewhat documented here. This is for proto2.

But one problem is that I have remember the field number while I am extending it. I was wondering if there is a way to extend the proto message in a different place without knowing the field number. In the current method extensions 100 to 199; in the above example is hardcoded and for every message this may be different. So for extension, we need to keep in mind the lower and upper limit. This is a hassle for those who is extending it.

So I am looking for a more generic way of extending proto message