问:
GetX - Passing Values Across ViewModels
I'm new to Getx & I'm trying to pass three String variables created in FirstViewModel into SecondViewModel how do I achieve this ?

```<code>class FirstViewModel extends GetxController with StateMixin<List<PhotoModel>> {...}
</code>```
```<code>class SecondViewModel extends GetxController {...}
</code>```

答:
In your second viewmodel:</p>
```<code>class SecondViewModel extends GetxController {
     final FirstViewModel firstViewModel = Get.find();

     final firstString = Rxn<String>();

     final photoModels = <PhotoModel>[].obs;

   @override
   onInit(){
          firstString.value = firstViewModel.firstString.value; // If you are using Rx

          photoModels.assignAll(firstViewModel.state); // Get the state from `StateMixin`

 }
</code>```

Title: GetX - Passing Values Across ViewModels

Body:
I'm new to Getx & I'm trying to pass three String variables created in FirstViewModel into SecondViewModel how do I achieve this ?

class FirstViewModel extends GetxController with StateMixin<List<PhotoModel>> {...}

class SecondViewModel extends GetxController {...}

Body:
In your second viewmodel:

class SecondViewModel extends GetxController {
     final FirstViewModel firstViewModel = Get.find();

     final firstString = Rxn<String>();

     final photoModels = <PhotoModel>[].obs;

   @override
   onInit(){
          firstString.value = firstViewModel.firstString.value; // If you are using Rx

          photoModels.assignAll(firstViewModel.state); // Get the state from `StateMixin`

 }


来源: stackexchange

问:
i dont understand how can I put an amount in these letters?
```<code>totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)
</code>```

These letters are discounts ,students,old people,pwds,and vips

答: On the second line, discountAmt is assigned a string value. That string value remains its value throughout the code. And so when you do totalBought - discountAtm, you do a number minus a string, which doesn't make sense. Also, you need to distinguish between == and =. What you can do is replace all those S == 10, O == 5, etc. with discoutAmt = 10, discountAmt = 5, etc. Or, you can dedicate a separate variable to the discount amount, if you don't want to override the discount code.

ContentLicense: CC BY-SA 4.0

Body:
totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)

These letters are discounts ,students,old people,pwds,and vips


问:
React JSX - make substring in bold
While creating custom autocomplete component I stuck with this problem: I got a string and substring(first part of the string, the one that user enters in autocompete field), and I need to show that part in bold in results list.

But I cannot use str.replace like

```<code>    var re = new RegExp(find, 'g');
    return str.replace(re, '<b>'+find+'</b>');
</code>```

because it will return string and I need JSX.

So basically the problem is - I have JSX and I need to make some part of it in bold. I need a function that takes JSX and like inject  tag in it in special places

This is what I got so far

```<code>    boldJSX(str, find){
        if(!find) return str;
        return <span><b>{find}</b>{str.slice(find.length)}</span>
    }
</code>```

答:
Expanding upon @mantas-giniūnas solution, I've enhanced it to maintain letter-casing.</p>
```<code>function BoldedText({ text, shouldBeBold }) {
  const textArray = text.split(RegExp(shouldBeBold, "ig"));
  const match = text.match(RegExp(shouldBeBold, "ig"));

  return (
    <span>
      {textArray.map((item, index) => (
        <>
          {item}
          {index !== textArray.length - 1 && match && (
            <b>{match[index]}</b>
          )}
        </>
      ))}
    </span>
  );
}
</code>```

Title: React JSX - make substring in bold

Body:
While creating custom autocomplete component I stuck with this problem: I got a string and substring(first part of the string, the one that user enters in autocompete field), and I need to show that part in bold in results list.

But I cannot use str.replace like

    var re = new RegExp(find, 'g');
    return str.replace(re, ''+find+'');

because it will return string and I need JSX.

So basically the problem is - I have JSX and I need to make some part of it in bold. I need a function that takes JSX and like inject  tag in it in special places

This is what I got so far

    boldJSX(str, find){
        if(!find) return str;
        return {find}{str.slice(find.length)}
    }

Body:
Expanding upon @mantas-giniūnas solution, I've enhanced it to maintain letter-casing.

function BoldedText({ text, shouldBeBold }) {
  const textArray = text.split(RegExp(shouldBeBold, "ig"));
  const match = text.match(RegExp(shouldBeBold, "ig"));

  return (
    <span>
      {textArray.map((item, index) => (
        <>
          {item}
          {index !== textArray.length - 1 && match && (
            <b>{match[index]}</b>
          )}
        </>
      ))}
    </span>
  );
}


问:
How can I perform filtering/searching school by writing the email address in flutter?
I would like to implement filtering/searching the university by typing its name like this picture below using flutter as a beginner. I would like it to auto-filter then display the school name even when I don't type the whole email address. It is quite hard to find good examples for what I want to do. Does anyone know of good examples that implemented something like I want?

Thank you

答:
This a simple search in list items based on the text written. Below is the solution i use to search items in a list and update the list accordingly.

Assume you have a list of Emails.
List emails = [];    A list which consist of emails from server/source

List emailsToShow = [];  List of emails you update with every letter typed.

```<code>searchEmail(String typedLetters) {
if (typedLetters.length > 0) {
  emailsToShow.clear();

  emailsToShow.addAll(emails
      .where((element) =>
          element.toLowerCase().contains(typedLetters.toLowerCase()))
      .toList());
     setState((){});

      }
  }
</code>```

Now call this function from onChanged method of TextField and show emailsToShow list in ListView/ListView.builder and you are good to go.

Body:
This a simple search in list items based on the text written. Below is the solution i use to search items in a list and update the list accordingly.

Assume you have a list of Emails.
List emails = [];    A list which consist of emails from server/source

List emailsToShow = [];  List of emails you update with every letter typed.

searchEmail(String typedLetters) {
if (typedLetters.length > 0) {
  emailsToShow.clear();

  emailsToShow.addAll(emails
      .where((element) =>
          element.toLowerCase().contains(typedLetters.toLowerCase()))
      .toList());
     setState((){});

      }
  }

Now call this function from onChanged method of TextField and show emailsToShow list in ListView/ListView.builder and you are good to go.


问:
SSR crashing in Next.js on unsuccessful GraphQL request (HTTP code 500) using Apollo Client
Well, I'm a little dumpy. I will try to explain my problem as clearly as possible.

I use Apollo client to do my GraphQL queries. I also use NextJS.
I have a page that needs to be rendered on the server side for SEO reasons.

So I have a getProductFromSlug function that allows me to execute my request.

```<code>export const getProductFromSlug = async (slug: string) => {
  try {
    const { data, error } = await apolloClient.query<{
      product: Product
    }>({
      query: GET_PRODUCT_BY_SLUG_QUERY,
      variables: {
        slug,
      },
    })

    if (error) {
      return { errors: [error.message] }
    }

    if (!('product' in data) || data.product === null) {
      return { errors: ['Product with specified url not found'] }
    }

    return {
      data,
    }
  } catch (error) {
    // @ts-ignore
    const formattedErrors: ApolloError = isApolloError(error)
      ? error.graphQLErrors.map((error) => error.message)
      : [`Unhandled error : ${error}`]

    return {
      errors: formattedErrors,
    }
  }
}
</code>```

Here's getServerSideProps to pass data to page

```<code>export const getServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const requestData = await getProductFromSlug(context.params.slug as string)
  return 'errors' in requestData
    ? { notFound: true, props: requestData }
    : { props: requestData }
}
</code>```

The problem is that when I have a HTTP code 500 from the endpoint, the SSR is crashing and on Vercel, it's causing a serverless crash error.

Error: Response not successful: Received status code 500
This error happened while generating the page. Any console logs will be displayed in the terminal window

If needed, here's my entry point (_app.tsx):

```<code>function MyApp(props: AppProps) {
  return (
    <ApolloProvider client={apolloClient}>
      <RecoilRoot>
        <RecoilNexus />
        <AuthenticationFromStorage />
        <Layout>
          <props.Component {...props.pageProps} />
        </Layout>
      </RecoilRoot>
    </ApolloProvider>
  )
}
</code>```

You can see my Apollo Client here : https://gist.github.com/SirMishaa/d67e7229307b77b43a0b594d0c9e6943

Stack trace of yarn run dev (next dev -p 3005) :

```<code>ServerError: Response not successful: Received status code 500
    at Object.throwServerError (C:\Users\misha\Documents\dev\rekk-next\node_modules\@apollo\client\link\utils\utils.cjs:45:17)
    at C:\Users\misha\Documents\dev\rekk-next\node_modules\@apollo\client\link\http\http.cjs:31:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
error - uncaughtException: ServerError: Response not successful: Received status code 500
error Command failed with exit code 1.
</code>```

NOTE :
After some try with console.log in try and catch scope, it shows nothing in the Next SSR console, so the internal error of Apollo is not caught for some reason.

I appreciate your help, thank you!

答:
UPDATE

The issue was that PusherLink was not continuing the execution in the chain when there was an error. Adding the error and complete handlers solved the problem.

```<code>      forward(operation).subscribe({
        next: (data) => {
          ...
          this.subscribeToChannel(subscriptionChannel, observer)
        },
        // these two were missing
        error: (error) => observer.error(error),
        complete: () => observer.complete(),
      })
</code>```

JIC, I also added a missing condition the code from the other link taken as a reference has

```<code>    subscribeObservable.subscribe = (observerOrNext, onError, onComplete) => {
      if (typeof(observerOrNext) == "function") {
        prevSubscribe(observerOrNext, onError, onComplete)
      } else {
        prevSubscribe(observerOrNext)
      }
</code>```

OLD ANSWER

Your code inside the catch block could be throwing an error, and that's what is breaking. I'm unsure about this condition Array.isArray(apolloError), maybe you meant Array.isArray(apolloError.graphQLErrors)

You could try the isApolloError utility to be a little more clear and get some hints from TS types.

import { isApolloError } from '@apollo/client';
...
        const formattedErrors = isApolloError(e)
          ? e.graphQLErrors.map(error => error.message)
          : [`Unhandled error : ${e}`];

        return {
          errors: formattedErrors,
        };
```

Body:
Well, I'm a little dumpy. I will try to explain my problem as clearly as possible.

I use Apollo client to do my GraphQL queries. I also use NextJS.
I have a page that needs to be rendered on the server side for SEO reasons.

So I have a getProductFromSlug function that allows me to execute my request.

export const getProductFromSlug = async (slug: string) => {
  try {
    const { data, error } = await apolloClient.query<{
      product: Product
    }>({
      query: GET_PRODUCT_BY_SLUG_QUERY,
      variables: {
        slug,
      },
    })

    if (error) {
      return { errors: [error.message] }
    }

    if (!('product' in data) || data.product === null) {
      return { errors: ['Product with specified url not found'] }
    }

    return {
      data,
    }
  } catch (error) {
    // @ts-ignore
    const formattedErrors: ApolloError = isApolloError(error)
      ? error.graphQLErrors.map((error) => error.message)
      : [`Unhandled error : ${error}`]

    return {
      errors: formattedErrors,
    }
  }
}

Here's getServerSideProps to pass data to page

export const getServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const requestData = await getProductFromSlug(context.params.slug as string)
  return 'errors' in requestData
    ? { notFound: true, props: requestData }
    : { props: requestData }
}

The problem is that when I have a HTTP code 500 from the endpoint, the SSR is crashing and on Vercel, it's causing a serverless crash error.

Error: Response not successful: Received status code 500
This error happened while generating the page. Any console logs will be displayed in the terminal window

If needed, here's my entry point (_app.tsx):

function MyApp(props: AppProps) {
  return (
    <ApolloProvider client={apolloClient}>
      <RecoilRoot>
        <RecoilNexus />
        <AuthenticationFromStorage />
        <Layout>
          <props.Component {...props.pageProps} />
        </Layout>
      </RecoilRoot>
    </ApolloProvider>
  )
}

You can see my Apollo Client here : https://gist.github.com/SirMishaa/d67e7229307b77b43a0b594d0c9e6943

Stack trace of yarn run dev (next dev -p 3005) :

ServerError: Response not successful: Received status code 500
    at Object.throwServerError (C:\Users\misha\Documents\dev\rekk-next\node_modules\@apollo\client\link\utils\utils.cjs:45:17)
    at C:\Users\misha\Documents\dev\rekk-next\node_modules\@apollo\client\link\http\http.cjs:31:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
error - uncaughtException: ServerError: Response not successful: Received status code 500
error Command failed with exit code 1.

NOTE :
After some try with console.log in try and catch scope, it shows nothing in the Next SSR console, so the internal error of Apollo is not caught for some reason.

I appreciate your help, thank you!

Body:
UPDATE

The issue was that PusherLink was not continuing the execution in the chain when there was an error. Adding the error and complete handlers solved the problem.

      forward(operation).subscribe({
        next: (data) => {
          ...
          this.subscribeToChannel(subscriptionChannel, observer)
        },
        // these two were missing
        error: (error) => observer.error(error),
        complete: () => observer.complete(),
      })

JIC, I also added a missing condition the code from the other link taken as a reference has

    subscribeObservable.subscribe = (observerOrNext, onError, onComplete) => {
      if (typeof(observerOrNext) == "function") {
        prevSubscribe(observerOrNext, onError, onComplete)
      } else {
        prevSubscribe(observerOrNext)
      }

OLD ANSWER

Your code inside the catch block could be throwing an error, and that's what is breaking. I'm unsure about this condition Array.isArray(apolloError), maybe you meant Array.isArray(apolloError.graphQLErrors)

You could try the isApolloError utility to be a little more clear and get some hints from TS types.

import { isApolloError } from '@apollo/client';
...
        const formattedErrors = isApolloError(e)
          ? e.graphQLErrors.map(error => error.message)
          : [`Unhandled error : ${e}`];

        return {
          errors: formattedErrors,
        };


问:
GitHub: Difference between Accept current changes and Incoming changes
Problem occurs when codes are conflict.

As you see in image given above that four options are there

Accept incoming changes

Accept current changes

Accept Both changes

Compare changes

I want to know the difference between Accept Current changes and Accept Incoming changes

答:
You are on a feature branch

1. git pull origin master

Current changes

Changes on your current feature branch.

Incoming changes

Changes you are pulling from i.e the master branch

2. git pull origin master --rebase

During rebase your feature branch changes are applied on top of the commits that are already there in master branch.

Current changes

Changes on the master branch.

Incoming changes

Changes on the feature branch.

* After a rebase, you need to force push your branch. Use --force-with-lease instead of --force


问:
Is it a good practise to loop through a list and in between the loop you append data to that list?
```<code>a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()
</code>```

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

答:
Do not modify the thing you are iterating over.  Bad things can and do happen.  In your case you are lengthening the list (a.append(i))  as you iterate over it.  Probably, the iteration will never reach the end of the loop and you have
an infinite loop  (but anything can happen).   My understanding is that you want to move all items or the list before a possible 0 to the end of the list.  Do this by finding the index or 0 in the list and then slicing.</p>
```<code>    def move_to_back(lst):

        if 0 in lst:
           i=lst.index(0)
        else:
           return lst

        return  lst[i:] + lst(:i]
</code>```

Body:
a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

Body:
Do not modify the thing you are iterating over.  Bad things can and do happen.  In your case you are lengthening the list (a.append(i))  as you iterate over it.  Probably, the iteration will never reach the end of the loop and you have
an infinite loop  (but anything can happen).   My understanding is that you want to move all items or the list before a possible 0 to the end of the list.  Do this by finding the index or 0 in the list and then slicing.

    def move_to_back(lst):

        if 0 in lst:
           i=lst.index(0)
        else:
           return lst

        return  lst[i:] + lst(:i]


问:
How to make a email calendar invite automatically accepted (php)?
I'm sending a calendar invite via email but I want it automatically be accepted.

Is there something I can change in my code? My code looks like this:

```<code>function sendIcalEmail ($firstname, $lastname, $email, $meeting_date, $meeting_name, $meeting_duration)  {
    $from_name = “My Name”;
    $from_address = “myname@mydomain.com”;
    $subject = “Meeting Booking”; //Doubles as email subject and meeting subject in calendar
    $meeting_description = “Here is a brief description of my meeting\n\n”;
    $meeting_location = “My Office”; //Where will your meeting take place

    //Convert MYSQL datetime and construct iCal start, end and issue dates
    $meetingstamp = strtotime($meeting_date . ” UTC”);
    $dtstart= gmdate(”Ymd\THis\Z”,$meetingstamp);
    $dtend= gmdate(”Ymd\THis\Z”,$meetingstamp+$meeting_duration);
    $todaystamp = gmdate(”Ymd\THis\Z”);

    //Create unique identifier
    $cal_uid = date(’Ymd’).’T’.date(’His’).”-”.rand().”@mydomain.com”;

    //Create Mime Boundry
    $mime_boundary = “—-Meeting Booking—-”.md5(time());

    //Create Email Headers
    $headers = “From: “.$from_name.” <”.$from_address.”>\n”;
    $headers .= “Reply-To: “.$from_name.” <”.$from_address.”>\n”;

    $headers .= “MIME-Version: 1.0\n”;
    $headers .= “Content-Type: multipart/alternative; boundary=\”$mime_boundary\”\n”;
    $headers .= “Content-class: urn:content-classes:calendarmessage\n”;

    //Create Email Body (HTML)
    $message .= “–$mime_boundary\n”;
    $message .= “Content-Type: text/html; charset=UTF-8\n”;
    $message .= “Content-Transfer-Encoding: 8bit\n\n”;

    $message .= “<html>\n”;
    $message .= “<body>\n”;
    $message .= ‘<p>Dear ‘.$firstname.’ ‘.$lastname.’,</p>’;
    $message .= ‘<p>Here is my HTML Email / Used for Meeting Description</p>’;
    $message .= “</body>\n”;
    $message .= “</html>\n”;
    $message .= “–$mime_boundary\n”;

    //Create ICAL Content (Google rfc 2445 for details and examples of usage, beware of adding tabs)
    $ical =    ‘BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:’.$from_address.’
DTSTART:’.$dtstart.’
DTEND:’.$dtend.’
LOCATION:’.$meeting_location.’
TRANSP:OPAQUE
SEQUENCE:0
UID:’.$cal_uid.’
DTSTAMP:’.$todaystamp.’
DESCRIPTION:’.$meeting_description.’
SUMMARY:’.$subject.’
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR’;

    $message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n';
    $message .= 'Content-Transfer-Encoding: 8bit\n\n';
    $message .= $ical;

    //SEND MAIL
    $mail_sent = @mail( $email, $subject, $message, $headers );

    if($mail_sent)     {
        return true;
    } else {
        return false;
    }

}
</code>```

答:
Hi for calendar auto acceptance you should add the given lines in your code to create ics file.
ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName1 c;EMAIL=example1@mail.com:MAILTO:example1@mail.com

ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName2 c;EMAIL=example2@mail.comMAILTO:example2@mail.com

Body:
I'm sending a calendar invite via email but I want it automatically be accepted.

Is there something I can change in my code? My code looks like this:

function sendIcalEmail ($firstname, $lastname, $email, $meeting_date, $meeting_name, $meeting_duration)  {
    $from_name = “My Name”;
    $from_address = “myname@mydomain.com”;
    $subject = “Meeting Booking”; //Doubles as email subject and meeting subject in calendar
    $meeting_description = “Here is a brief description of my meeting\n\n”;
    $meeting_location = “My Office”; //Where will your meeting take place

    //Convert MYSQL datetime and construct iCal start, end and issue dates
    $meetingstamp = strtotime($meeting_date . ” UTC”);
    $dtstart= gmdate(”Ymd\THis\Z”,$meetingstamp);
    $dtend= gmdate(”Ymd\THis\Z”,$meetingstamp+$meeting_duration);
    $todaystamp = gmdate(”Ymd\THis\Z”);

    //Create unique identifier
    $cal_uid = date(’Ymd’).’T’.date(’His’).”-”.rand().”@mydomain.com”;

    //Create Mime Boundry
    $mime_boundary = “—-Meeting Booking—-”.md5(time());

    //Create Email Headers
    $headers = “From: “.$from_name.” <”.$from_address.”>\n”;
    $headers .= “Reply-To: “.$from_name.” <”.$from_address.”>\n”;

    $headers .= “MIME-Version: 1.0\n”;
    $headers .= “Content-Type: multipart/alternative; boundary=\”$mime_boundary\”\n”;
    $headers .= “Content-class: urn:content-classes:calendarmessage\n”;

    //Create Email Body (HTML)
    $message .= “–$mime_boundary\n”;
    $message .= “Content-Type: text/html; charset=UTF-8\n”;
    $message .= “Content-Transfer-Encoding: 8bit\n\n”;

    $message .= “\n”;
    $message .= “\n”;
    $message .= ‘
Dear ‘.$firstname.’ ‘.$lastname.’,
’;
    $message .= ‘
Here is my HTML Email / Used for Meeting Description
’;
    $message .= “\n”;
    $message .= “\n”;
    $message .= “–$mime_boundary\n”;

    //Create ICAL Content (Google rfc 2445 for details and examples of usage, beware of adding tabs)
    $ical =    ‘BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:’.$from_address.’
DTSTART:’.$dtstart.’
DTEND:’.$dtend.’
LOCATION:’.$meeting_location.’
TRANSP:OPAQUE
SEQUENCE:0
UID:’.$cal_uid.’
DTSTAMP:’.$todaystamp.’
DESCRIPTION:’.$meeting_description.’
SUMMARY:’.$subject.’
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR’;

    $message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n';
    $message .= 'Content-Transfer-Encoding: 8bit\n\n';
    $message .= $ical;

    //SEND MAIL
    $mail_sent = @mail( $email, $subject, $message, $headers );

    if($mail_sent)     {
        return true;
    } else {
        return false;
    }

}


问:
How to remove background: transparent?

leaflet popup close button is not displayed. But, when I uncheck background: transparent; the close button is displayed. I already tried background: unset;, but it doesn't work. How can I remove  background: transparent;?

The code below is from https://unpkg.com/leaflet@1.7.1/dist/leaflet.css

```<code>.leaflet-container a.leaflet-popup-close-button {
    position: absolute;
    top: 0;
    right: 0;
    padding: 4px 4px 0 0;
    border: none;
    text-align: center;
    width: 18px;
    height: 14px;
    font: 16px/14px Tahoma, Verdana, sans-serif;
    color: #c3c3c3;
    text-decoration: none;
    font-weight: bold;
    background: transparent;
}
</code>```

答:
You can overwrite the css

```<code>.leaflet-container a.leaflet-popup-close-button {
   background: yourOwnColor / url;
}
</code>```

If you want to avoid global change then wrap up the component with a div and set a flag class to it.

```<code>.yourFlagClass .leaflet-container a.leaflet-popup-close-button {
   background: yourOwnColor / url;
}
</code>```

Title: How to remove background: transparent?

Body:
leaflet popup close button is not displayed. But, when I uncheck background: transparent; the close button is displayed. I already tried background: unset;, but it doesn't work. How can I remove  background: transparent;?

The code below is from https://unpkg.com/leaflet@1.7.1/dist/leaflet.css

.leaflet-container a.leaflet-popup-close-button {
    position: absolute;
    top: 0;
    right: 0;
    padding: 4px 4px 0 0;
    border: none;
    text-align: center;
    width: 18px;
    height: 14px;
    font: 16px/14px Tahoma, Verdana, sans-serif;
    color: #c3c3c3;
    text-decoration: none;
    font-weight: bold;
    background: transparent;
}

Body:
You can overwrite the css

.leaflet-container a.leaflet-popup-close-button {
   background: yourOwnColor / url;
}

If you want to avoid global change then wrap up the component with a div and set a flag class to it.

.yourFlagClass .leaflet-container a.leaflet-popup-close-button {
   background: yourOwnColor / url;
}


问:
Any way to find out top running process?
I need to get the top running process on the windows system. Is there any way to find out this?</p>

答:
I would suggest you to elaborate further your questions since it could be related to several topics in general.

Basically, through User interface you can go to windows>Windows Task Manager>click on processes tab and see in real time the consumption on them. By default, the Processes tab displays a list of the running processes and their actual resource utilization depending on the OS version:

```<code>Image Name – the binary executable file of the running process
User Name – the user of the current process
CPU – processor time utilization as a percentage of total CPU resource
Memory – physical memory utilization in Kilobytes
Disk
Network
</code>```

To do this task through command:
-Select the start menu and type “command”
-hover the mouse over Command Prompt so it’s highlighted and then select Run as administrator on the right (You may need to select Yes on a pop-up window to approve running Command Prompt as administrator)
-Once the command prompt is open, type tasklist and press enter to see a list of processes running on your system.

As an example, in here you will find more than one way to get the running processes on the windows system (Windows XP, Windows 7, Windows 8, and Windows 10) and then save it to a file if needed.

Body:
I would suggest you to elaborate further your questions since it could be related to several topics in general.

Basically, through User interface you can go to windows>Windows Task Manager>click on processes tab and see in real time the consumption on them. By default, the Processes tab displays a list of the running processes and their actual resource utilization depending on the OS version:

Image Name – the binary executable file of the running process
User Name – the user of the current process
CPU – processor time utilization as a percentage of total CPU resource
Memory – physical memory utilization in Kilobytes
Disk
Network

To do this task through command:
-Select the start menu and type “command”
-hover the mouse over Command Prompt so it’s highlighted and then select Run as administrator on the right (You may need to select Yes on a pop-up window to approve running Command Prompt as administrator)
-Once the command prompt is open, type tasklist and press enter to see a list of processes running on your system.

As an example, in here you will find more than one way to get the running processes on the windows system (Windows XP, Windows 7, Windows 8, and Windows 10) and then save it to a file if needed.


问:
How do I search for files in Visual Studio Code?
I am used to Resharper where I can search for files, not the content, but the filename, which makes it quick to open new files.

Is this feature implemented in Visual Studio Code and is there a shortcut for it?

答:
Method1

Go->Go to File OR cntrl+p

Search your file

Method2

view->command palette OR cntrl+shift+p

type "Go to file"

Search your file

ContentLicense: CC BY-SA 3.0


问:
I tried everything but it's show this error in React-Native
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native</p>
```<code>error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

  * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##
</code>```

答:
Check you need to edit the uses-sdk in the AndroidManifest.xml like your build.gradle

```<code><uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14" />
</code>```

and the android section, particularly minSdkVersion and targetSdkVersion in the build.gradle file

```<code>android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 14
    }
}
</code>```

Body:
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native

error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

  * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##

Body:
Check you need to edit the uses-sdk in the AndroidManifest.xml like your build.gradle

<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14" />

and the android section, particularly minSdkVersion and targetSdkVersion in the build.gradle file

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 14
    }
}


问:
Convert ANY DICTIONARY type into table format in DolphinDB
I imported table A to function B and each input is of any dictionary type. I am able to construct a table with the returned fields and the labels of the original records. It returned a large table, and I can get the expected result after doing the left join with table A. I also defined a udf B which can perform corresponding processes according to the record in table A, and return several fields to be added to the table. What I used is ploop(B, A).unionAll(false).

However, I want to directly construct a table with the input of the ANY DICTIONARY variables in table A and add fields directly into the B function. How can I obtain the result in an efficient way?

答:
If you want to use the key of ANY DICT for the column name, please try:

```<code>tbl = table(0:2, d.keys(0, `INT`INT)
</code>```

You don't need for loop for vs here, you can directly call vs = d.values() to obtain it when using DolphinDB.

Body:
If you want to use the key of ANY DICT for the column name, please try:

tbl = table(0:2, d.keys(0, `INT`INT)

You don't need for loop for vs here, you can directly call vs = d.values() to obtain it when using DolphinDB.


问:
Best way to transfer data between servlet and jsp?
First try:

I'm generating data in servlet and then set it in request as attribute and send that request to jsp by calling requestDispatcher as follows:

```<code>request.setAttribute("data",data);
request.getRequestDispatcher("/page.jsp").forward(request, response);
</code>```

Now access it in jsp and display data.

This works fine but everytime user refreshes page it gets an alert saying you are resubmitting the form and ask for confirmation. This is annoying.

Second try:

Put data in session and access that in jsp page. In this way session gets very heavy as the data amount is big.

So my question is what is the best way to pass data from servlet to jsp?
Here data is object list.

答:
Your first solution is the good one. Using the session to hold data specific to a single request is not a good practice. The fact that users get a confirmation message has nothing to do with the way data are passed from servlet to JSP. It has to do with the fact that the page they're looking at and refreshing was the result of a POST request.

Use the Redirect after Post (or Post-Redirect-Get) pattern to avoid this problem.

For example, suppose you're saving a new product, and after the product is saved (using a POST request), you would like to display the product's category page. It would go this way:

submit the "Save product" form

store the product in database, adn get its category ID (456)

send a redirect to the URL productCategory?categoryId=456

the user automatically goes to the above URL

Get the data for the category 456 from the database

Put this data in a request attribute and forward the the productCategory.jsp page

User sees the product category page, with the new product he just saved. If he refreshes, it redisplay the category without confirmation, and without resubmitting the "Save product" form.

Body:
First try:

I'm generating data in servlet and then set it in request as attribute and send that request to jsp by calling requestDispatcher as follows:

request.setAttribute("data",data);
request.getRequestDispatcher("/page.jsp").forward(request, response);

Now access it in jsp and display data.

This works fine but everytime user refreshes page it gets an alert saying you are resubmitting the form and ask for confirmation. This is annoying.

Second try:

Put data in session and access that in jsp page. In this way session gets very heavy as the data amount is big.

So my question is what is the best way to pass data from servlet to jsp?
Here data is object list.


问:
Docker Compose: depends_on with condition -> invalid type, should be an array
I have the following compose file:

version: "3"

services:

  zookeeper:
    image: docker-dev.art.intern/wurstmeister/zookeeper:latest
    ports:
      - 2181:2181

  kafka:
    image: docker-dev.art.intern/wurstmeister/kafka:latest
    ports:
      - 9092:9092
    environment:
      - KAFKA_LISTENERS=PLAINTEXT://:9092
      - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092
      - KAFKA_ADVERTISED_HOST_NAME=kafka
      - KAFKA_ADVERTISED_PORT=9092
      - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
    depends_on:
      - zookeeper

  app:
    build:
      context: ./
      dockerfile: app/Dockerfile
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4020/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 5
    depends_on:
      - kafka
      - zookeeper

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      app:
        condition: service_healthy
```
<p>As you can see im implementing a healthcheck for the app and I use <code>service_healthy</code> condition.
But that leads to the error:</p>
```The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be an array
```
<p>Is there a way to fix that issue?</p>
<p>If I change to array sanytax:</p>
<pre class="lang-yaml prettyprint-override"><code>...

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy

</code>```

The error changes to:

```<code>The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be a string
</code>```

答:
Edit: this only solves the YAML error, and still doesn't produce a working docker-compose since depends_on is not valid in Compose version 3. You need either Compose version 2.1 or the Compose Specification.

You're missing a - to make depends_on an array:

```<code>  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy
</code>```

Notice the - before app. Without it, services.app-test.depends_on will be an object, not an array. Also pay attention to the amount of spaces: if condition is in the same column as app, you will also get an undesired result.

When decoding your YAML, this is what you get (in JSON):

{
  "app-test": {
    "build": {
      "context": "./",
      "dockerfile": "test/Dockerfile"
    },
    "depends_on": {
      "app": {
        "condition": "service_healthy"
      }
    }
  }
}
```
<p>With the added <code>-</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
  "app-test": {
    "build": {
      "context": "./",
      "dockerfile": "test/Dockerfile"
    },
    "depends_on": [
      {
        "app": {
          "condition": "service_healthy"
        }
      }
    ]
  }
}
</code>```

Body:
I have the following compose file:

version: "3"

services:

  zookeeper:
    image: docker-dev.art.intern/wurstmeister/zookeeper:latest
    ports:
      - 2181:2181

  kafka:
    image: docker-dev.art.intern/wurstmeister/kafka:latest
    ports:
      - 9092:9092
    environment:
      - KAFKA_LISTENERS=PLAINTEXT://:9092
      - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092
      - KAFKA_ADVERTISED_HOST_NAME=kafka
      - KAFKA_ADVERTISED_PORT=9092
      - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
    depends_on:
      - zookeeper

  app:
    build:
      context: ./
      dockerfile: app/Dockerfile
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4020/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 5
    depends_on:
      - kafka
      - zookeeper

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      app:
        condition: service_healthy

As you can see im implementing a healthcheck for the app and I use service_healthy condition.
But that leads to the error:

The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be an array

Is there a way to fix that issue?

If I change to array sanytax:

...

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy

The error changes to:

The Compose file '.\docker-compose.yml' is invalid because:
services.app-test.depends_on contains an invalid type, it should be a string

Body:
Edit: this only solves the YAML error, and still doesn't produce a working docker-compose since depends_on is not valid in Compose version 3. You need either Compose version 2.1 or the Compose Specification.

You're missing a - to make depends_on an array:

  app-test:
    build:
      context: ./
      dockerfile: test/Dockerfile
    depends_on:
      - app:
          condition: service_healthy

Notice the - before app. Without it, services.app-test.depends_on will be an object, not an array. Also pay attention to the amount of spaces: if condition is in the same column as app, you will also get an undesired result.

When decoding your YAML, this is what you get (in JSON):

{
  "app-test": {
    "build": {
      "context": "./",
      "dockerfile": "test/Dockerfile"
    },
    "depends_on": {
      "app": {
        "condition": "service_healthy"
      }
    }
  }
}

With the added -:

{
  "app-test": {
    "build": {
      "context": "./",
      "dockerfile": "test/Dockerfile"
    },
    "depends_on": [
      {
        "app": {
          "condition": "service_healthy"
        }
      }
    ]
  }
}


问:
How to attend best practice for not using UI code in the Controller with GetX flutter when I need to show a Dialog if my task complete.?
For a simple Email login with OTP code I have a structure as follows.

View

await _signUpCntrl.signUp(email, password);

Controller

_showOtpDialog(email);

_showOtpDialog func

```<code> return Get.dialog(
        AlertDialog(
</code>```

So the thing is _showOtpDialog function is inside a controller file. ie. /Controllers/controller_file.dart

I want do something like a blocListener, call the _showOtpDialog from a screen(view) file on signup success. (also relocate the _showOtpDialog to a view file)

Using GetX I have to use one of the builders either obs or getbuilder. Which is I think not a good approach to show a dialog box.

On internet it says Workers are the alternative to BlocListener. However Workers function resides on Controller file and with that the dialog is still being called on the controller file.

As OTP dialog will have its own state and a controller I wanted to put it inside a /view/viewfile.dart
How do I obtain this?
I tried using StateMixin but when I call Get.dialog() it throw an error.

visitChildElements() called during build

答:
First thing, you will need to enhance the quality of your question by making things more clearly. Add the code block and the number list, highlight those and making emphasize texts are bold. Use the code block instead of quote.

Seconds things, Depends on the state management you are using, we will have different approaches:

Bloc (As you already added to the question tag). By using this state management, you controller ( business logic handler) will act like the view model in the MVVM architecture. In terms of that, You will need to emit a state (e.g: Sent success event). Afterward, the UI will listen to the changes and update it value according to the event you have emitted. See this Bloc example

GetX (As your code and question pointed out): GetX will acts a little bit different. you have multiple ways to implement this:

Using callbacks (passed at the start when calling the send otp function)

Declare a general dialog for your application ( this is the most used when it comes to realization) and calling show Dialog from Bloc

Using Rx. You will define a Reactive Variable for e.g final success = RxBool(true). Then the view will listen and update whenever the success changes.

controller.dart

```<code>class MyController extends GetxController {
    final success = RxBool(false);

    void sendOtp() async {
        final result = await repository.sendOTP();
        success.update((val) => {true});
    }
}
</code>```

view.dart

```<code>  class MyUI extends GetView<MyController> {
      @override
      Widget build(BuildContext context) {
          ever(controller.success, (bool success) {
          // This will update things whenever success is updated
              if (success) {
                  Get.dialog(AlertDialog());
              }
          });

          return Container();
      }
  }
</code>```

Body:
For a simple Email login with OTP code I have a structure as follows.

View

await _signUpCntrl.signUp(email, password);

Controller

_showOtpDialog(email);

_showOtpDialog func

 return Get.dialog(
        AlertDialog(

So the thing is _showOtpDialog function is inside a controller file. ie. /Controllers/controller_file.dart

I want do something like a blocListener, call the _showOtpDialog from a screen(view) file on signup success. (also relocate the _showOtpDialog to a view file)

Using GetX I have to use one of the builders either obs or getbuilder. Which is I think not a good approach to show a dialog box.

On internet it says Workers are the alternative to BlocListener. However Workers function resides on Controller file and with that the dialog is still being called on the controller file.

As OTP dialog will have its own state and a controller I wanted to put it inside a /view/viewfile.dart
How do I obtain this?
I tried using StateMixin but when I call Get.dialog() it throw an error.

visitChildElements() called during build

Body:
First thing, you will need to enhance the quality of your question by making things more clearly. Add the code block and the number list, highlight those and making emphasize texts are bold. Use the code block instead of quote.

Seconds things, Depends on the state management you are using, we will have different approaches:

Bloc (As you already added to the question tag). By using this state management, you controller ( business logic handler) will act like the view model in the MVVM architecture. In terms of that, You will need to emit a state (e.g: Sent success event). Afterward, the UI will listen to the changes and update it value according to the event you have emitted. See this Bloc example

GetX (As your code and question pointed out): GetX will acts a little bit different. you have multiple ways to implement this:

Using callbacks (passed at the start when calling the send otp function)

Declare a general dialog for your application ( this is the most used when it comes to realization) and calling show Dialog from Bloc

Using Rx. You will define a Reactive Variable for e.g final success = RxBool(true). Then the view will listen and update whenever the success changes.

controller.dart

class MyController extends GetxController {
    final success = RxBool(false);

    void sendOtp() async {
        final result = await repository.sendOTP();
        success.update((val) => {true});
    }
}

view.dart

  class MyUI extends GetView<MyController> {
      @override
      Widget build(BuildContext context) {
          ever(controller.success, (bool success) {
          // This will update things whenever success is updated
              if (success) {
                  Get.dialog(AlertDialog());
              }
          });

          return Container();
      }
  }


问:
Using a secondary APN just for a specific Android Application
Is it possibile to use a secondary APN just for a specific Android Application and let the current APN to be used by the other applications (in the same time)?

If it is, how?

I would like to know a code about how to set that secondary APN without to change the current one, thank you.

答:
It's possible via 3rd-party VPN but i don't think that there's custom APN VPN Changer. However, there's several VPN Client that has this feature such as clash, it has connection rules wich traffic that you want to use for each apps. It's defined by package name com.android.your_game_package using a yaml or json config inside clash. It's support for XRay, V2ray, Trojan VPN Protocol. Read more about it here:

https://github.com/Dreamacro/clash
https://github.com/Kr328/ClashForAndroid


问:
FileProviderExtension won't be loaded in macOS 12.2
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

```<code>@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}
</code>```

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.

答:
I think I managed to this problem.

The key point is AppGroup. FileProvider requires AppGroup capabilities.

I think that a step to reproduce the issue likes below.

Launch provider without AppGroup at first time, and face the FileProvider error.

Add AppGroup capabilities and relaunch.

Still got the error.

New project with adding AppGroup capabilities at first launch won't fail.

Body:
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.


问:
TestNG 7.0.1 deprecated method for getRetryAnalyzer()
The following method getRetryAnalyzer are deprecated in testng 7.0.1. Here is my code:

```<code>public ITestAnnotation annotations;

@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
    annotations =annotation;
    if(null == annotation.getRetryAnalyzer()) {
        annotation.setRetryAnalyzer(Retry.class);
    }
}

@Override
public void onTestStart(ITestResult result) {
}

@Override
public void onTestSuccess(ITestResult result) {
    ((Retry) annotations.getRetryAnalyzer()).reset();

}

@Override
public void onTestFailure(ITestResult result) {
    ((Retry) annotations.getRetryAnalyzer()).reset();
}
</code>```

I tried to replace it with getRetryAnalyzerClass() but it was not working. Can anyone tell me how I can fix this deprecated method?

答:
This method stands deprecated as of TestNG 7.0.0. Please use {ITestAnnotation.getRetryAnalyzerClass()} instead.

Check the following link

the code will be as following:

```<code>Class<? extends IRetryAnalyzer> retry = testannotation.getRetryAnalyzerClass();
</code>```

Body:
The following method getRetryAnalyzer are deprecated in testng 7.0.1. Here is my code:

public ITestAnnotation annotations;

@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
    annotations =annotation;
    if(null == annotation.getRetryAnalyzer()) {
        annotation.setRetryAnalyzer(Retry.class);
    }
}

@Override
public void onTestStart(ITestResult result) {
}

@Override
public void onTestSuccess(ITestResult result) {
    ((Retry) annotations.getRetryAnalyzer()).reset();

}

@Override
public void onTestFailure(ITestResult result) {
    ((Retry) annotations.getRetryAnalyzer()).reset();
}

I tried to replace it with getRetryAnalyzerClass() but it was not working. Can anyone tell me how I can fix this deprecated method?

Body:
This method stands deprecated as of TestNG 7.0.0. Please use {ITestAnnotation.getRetryAnalyzerClass()} instead.

Check the following link

the code will be as following:

Class<? extends IRetryAnalyzer> retry = testannotation.getRetryAnalyzerClass();


问:
Take the first and last character of a word to see if it's sequential in that word
I'm new to coding so this is probably a really easy question for you all. But I'm trying to take the first and last character of a word and see if it's sequential in that word (not alphabetically). For example, 'banana' would be sequential because 'ba' appears in the word. However, 'house' would not be sequential because 'he' does not appear in the word. If a word is sequential, it returns "True", if not "False". I'm writing this in python. Thanks!</p>

答:
```<code>def seq(s):
   if (s[0]+s[-1]) in s:
      return True
   return False
print(seq(s))
</code>```


问:
VueJs - import component in asp.net core project
I have asp.net core project, which uses vuejs framework (javascript)
This is a sample of the page structure (with everything stripped out for simplicity)

//Index.cshtml

```

<pre class="lang-vue prettyprint-override"><code>//page-1.js
(function () {
    var Page1Vue = new Vue({
        el: "#page-1",
});
})();
</code>```

everything works fine (mounted, all methods etc)

I want to bring in this external component https://vue-multiselect.js.org/, but cannot get it to work.
Has anyone any pointers on to integrate an external component into an existing instance.

答:
import external library in _Layout.cshtml, please import esm.js library

```
<ul>
<li>insert <em><strong>multiselect</strong></em> node into <em>Index.cshtml</em></li>
</ul>
<pre class="lang-html prettyprint-override"><code><div id="app">
     <multiselect v-model="value" :options="options"></multiselect>
</div>
</code>```

create Vue Component into Index.cshtml

@section Scripts
{
    <link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">
}
```

the result as below

Body:
I have asp.net core project, which uses vuejs framework (javascript)
This is a sample of the page structure (with everything stripped out for simplicity)

//Index.cshtml

//page-1.js
(function () {
    var Page1Vue = new Vue({
        el: "#page-1",
});
})();

everything works fine (mounted, all methods etc)

I want to bring in this external component https://vue-multiselect.js.org/, but cannot get it to work.
Has anyone any pointers on to integrate an external component into an existing instance.

Body:
import external library in _Layout.cshtml, please import esm.js library

 <script type="importmap">
      {
        "imports": {
          "vue": "/lib/vue.esm.browser.js_2.6.11/vue.esm-browser.js",
          "vue-multiselect":"https://cdnjs.cloudflare.com/ajax/libs/vue-multiselect/3.0.0-alpha.2/vue-multiselect.esm.min.js"
        }
      }
 </script>

insert multiselect node into Index.cshtml

<div id="app">
     <multiselect v-model="value" :options="options"></multiselect>
</div>

create Vue Component into Index.cshtml

<script type="module">
      import { createApp } from 'vue'
      import VueMultiselect from 'vue-multiselect'
       createApp({
                  data () {
                    return {
                    value: null,
                           options: ['list', 'of', 'options']
                    }
                  }
        })
        .component('multiselect', VueMultiselect)
        .mount('#app')
</script>

@section Scripts
{
    <link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">
}

the result as below


问:
Make change directly to GitHub branch
Let's say I have my main branch in GitHub. Me and my friend want to make a second branch called testing where we can mess around with other code before merging it to the main branch. How can I add code to this testing branch. For example, lets say there is an HTML page in the testing branch and the main branch. How can I make changes to the one in the testing branch without touching the one in the main?

I saw slightly similar questions like Github push changes to someone else's branch but that did not help me.

I am using windows if that makes a difference.

答:
The proper way to do that is to pull the code to your local machine, make changes and push back to the remotes repository new branch.

git pull Get code from GitHub repository to your local machine

git checkout -b testing Switch to new branch. Make changes in your files here

git commit -a -m "Some feature" Commit changes to your testing branch

git push --set-upstream origin testing Push changes to GitHub to the new branch called "testing"

Title: Make change directly to GitHub branch


问:
Adding an image to laravel-excel header
I'm making an excel export using the Maatwebsite/Laravel-Excel version 3.1. I am trying to add an image to the header of every page but it doesn't seem to work. </p>

<p>I tried following the phpspreadsheet documentation for inserting image, but that doesn't seem to work. </p>

```<code>$drawing->setName('PhpSpreadsheet logo');
$drawing->setPath('./images/PhpSpreadsheet_logo.png');
$drawing->setHeight(36);
$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT);```
</code>```

答:
this worked for me.

$filename = 'File Name';

Excel::create($filename, function($excel){

   $excel->sheet('sheet name', function($sheet){
        $objDrawing = new PHPExcel_Worksheet_Drawing;
        $objDrawing->setPath(public_path('img/headerKop.png')); //your image path
        $objDrawing->setCoordinates('A2');
        $objDrawing->setWorksheet($sheet);
   });

})->export('xls');```

Title: Adding an image to laravel-excel header

Body:
I'm making an excel export using the Maatwebsite/Laravel-Excel version 3.1. I am trying to add an image to the header of every page but it doesn't seem to work.

I tried following the phpspreadsheet documentation for inserting image, but that doesn't seem to work.

$drawing->setName('PhpSpreadsheet logo');
$drawing->setPath('./images/PhpSpreadsheet_logo.png');
$drawing->setHeight(36);
$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT);```


问:
How to get background image to 100vh on smaller screens but 50vh on large screens?
Learning bootstrap, I am trying to make a hero section on my website where if you are on the large screen breakpoint, the background image on the hero section will be 50% of the web page, but on smaller screens it will change to 100% of the webpage.

I think the problem lies with me setting height:50vh, I just simply don't know what to write on the bootstrap portion where if the screen switches to small, the height becomes 100.

Thank you!

.bg-image {
  width: 100%;
  height: 50vh;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-image: linear-gradient(to bottom, rgba(118, 118, 121, 0.432), rgba(82, 76, 80, 0.73)), url('https://via.placeholder.com/800/ff0000');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="bg-image p-5 text-light ">
  <div class="container text-center pt-5 h-100 ">
    <h1 class="m-5">I Need Help </h1>
    <button class="btn-primary rounded-pill">Book Us</button>
  </div>
</div></code>```

答:
You can use media queries. In your CSS file, at whatever screen size you want you can add -

```<code>@media screen(min-height: the_height_you_want) {
    .bg-image {
        height: 50vh;
    }
}
</code>```

For more details on media queries, you should see this tutorial - https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Body:
Learning bootstrap, I am trying to make a hero section on my website where if you are on the large screen breakpoint, the background image on the hero section will be 50% of the web page, but on smaller screens it will change to 100% of the webpage.

I think the problem lies with me setting height:50vh, I just simply don't know what to write on the bootstrap portion where if the screen switches to small, the height becomes 100.

Thank you!

.bg-image {
  width: 100%;
  height: 50vh;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-image: linear-gradient(to bottom, rgba(118, 118, 121, 0.432), rgba(82, 76, 80, 0.73)), url('https://via.placeholder.com/800/ff0000');
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

I Need Help

    <button class="btn-primary rounded-pill">Book Us</button>

Body:
You can use media queries. In your CSS file, at whatever screen size you want you can add -

@media screen(min-height: the_height_you_want) {
    .bg-image {
        height: 50vh;
    }
}

For more details on media queries, you should see this tutorial - https://www.w3schools.com/css/css_rwd_mediaqueries.asp


问:
How to get a button state to save after signing out and sign back in?
I have a save button that when tapped, will save the text in a label (quoteLabel) to a user account in Firebase. The button will then hide and the unsave button will no longer be hidden so that the user can unsave if desired. Both of these buttons are able to post and delete data as desired, however, if I sign-out of the app and sign back in, the buttons are reset to their original status. How do I get the button to stay in the last state it was set to?  I can't seem to get this to work. Please let me know if more information is needed, I'm still new to all this.

Edit: Updated with suggestions from below. I still can't seem to get this to work properly. When I tap just one button, they all end up being saved as tapped when I sign back in. I added how I assigned a key as well.

```<code>import Foundation
import UIKit
import FirebaseDatabase
import FirebaseAuth

class QuotesCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var save: UIButton!
@IBOutlet weak var unsave: UIButton!
@IBAction func saveButton(_ sender: UIButton) {
UserDefaults.standard.set(true, forKey: uuid)

save.isHidden = true
unsave.isHidden = false

var ref: DatabaseReference?
ref = Database.database().reference()

if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{

guard let user = Auth.auth().currentUser?.uid else { return }
ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").setValue(quoteLabel.text!)

}

}

@IBAction func UnsaveButton(_ sender: UIButton) {
UserDefaults.standard.set(false, forKey: uuid)

save.isHidden = false
unsave.isHidden = true

var ref: DatabaseReference?
ref = Database.database().reference()

if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").removeValue()

}

}

func setup(with quote: Quotes){
let saveButtonShowing = UserDefaults.standard.bool(forKey: uuid)
if(saveButtonShowing){ // Retrieves the state variable from the hard drive and sets the button visibility accordingly
    save.isHidden = true
    unsave.isHidden = false
} else {
    save.isHidden = false
    unsave.isHidden = true
}

quoteLabel.text = quote.quote

}
}
</code>```

This is how I tried to add a key to each quote:

```<code>import UIKit
import Foundation

let uuid = UUID().uuidString

struct Quotes {
let quote: String
let identifier: String

}

let quotes: [Quotes] = [
Quotes(quote: "The best time to plant a tree was 20 years ago - The next best time is today - Unknown", identifier:  uuid),
                        Quotes(quote:    "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe",identifier: uuid),
                        Quotes(quote: "Buy less, choose well, make it last - Vivienne Westwood", identifier: uuid),
                        Quotes(quote: "The future depends on what we do in the present - Mahatma Gandhi", identifier: uuid),
]
</code>```

答:
The problem is that the .isHidden property of the UIButton's is a state variable, meaning it is saved in RAM. This means that once you exit the application and reopen it, your app will startup again with the default state variable settings.

If you wish to persist the state of these variables, you'll need to save the button states to the phone's hard drive. UserDefaults makes this easy.

```<code>@IBAction func saveButton(_ sender: UIButton) {
    UserDefaults.standard.set(true, forKey: "saveButtonHidden") // Saves the state to the hard drive

    save.isHidden = true
    unsave.isHidden = false

    var ref: DatabaseReference?
    ref = Database.database().reference()

    if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
        guard let user = Auth.auth().currentUser?.uid else { return }
        ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").chi.ld("Quote1").setValue(quoteLabel.text!)
    }

}

@IBAction func UnsaveButton(_ sender: UIButton) {
    UserDefaults.standard.set(false, forKey: "saveButtonHidden") // Saves the state to the hard drive

    save.isHidden = false
    unsave.isHidden = true

    var ref: DatabaseReference?
    ref = Database.database().reference()

    if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
        ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").removeValue()
    }

    if quoteLabel.text as! NSObject == ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1") {
        save.isHidden = true
        unsave.isHidden = false
    }
}

func setup(with quote: Quotes){
    let saveButtonShowing = UserDefault.standard.bool(forKey: "saveButtonHidden")
    if(saveButtonHidden){ // Retrieves the state variable from the hard drive and sets the button visibility accordingly
        save.isHidden = true
        unsave.isHidden = false
    } else {
        save.isHidden = false
        unsave.isHidden = true
    }

    quoteLabel.text = quote.quote
}
</code>```

Body:
I have a save button that when tapped, will save the text in a label (quoteLabel) to a user account in Firebase. The button will then hide and the unsave button will no longer be hidden so that the user can unsave if desired. Both of these buttons are able to post and delete data as desired, however, if I sign-out of the app and sign back in, the buttons are reset to their original status. How do I get the button to stay in the last state it was set to?  I can't seem to get this to work. Please let me know if more information is needed, I'm still new to all this.

Edit: Updated with suggestions from below. I still can't seem to get this to work properly. When I tap just one button, they all end up being saved as tapped when I sign back in. I added how I assigned a key as well.

import Foundation
import UIKit
import FirebaseDatabase
import FirebaseAuth

class QuotesCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var save: UIButton!
@IBOutlet weak var unsave: UIButton!
@IBAction func saveButton(_ sender: UIButton) {
UserDefaults.standard.set(true, forKey: uuid)

save.isHidden = true
unsave.isHidden = false

var ref: DatabaseReference?
ref = Database.database().reference()

if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{

guard let user = Auth.auth().currentUser?.uid else { return }
ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").setValue(quoteLabel.text!)

}

}

@IBAction func UnsaveButton(_ sender: UIButton) {
UserDefaults.standard.set(false, forKey: uuid)

save.isHidden = false
unsave.isHidden = true

var ref: DatabaseReference?
ref = Database.database().reference()

if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").removeValue()

}

}

func setup(with quote: Quotes){
let saveButtonShowing = UserDefaults.standard.bool(forKey: uuid)
if(saveButtonShowing){ // Retrieves the state variable from the hard drive and sets the button visibility accordingly
    save.isHidden = true
    unsave.isHidden = false
} else {
    save.isHidden = false
    unsave.isHidden = true
}

quoteLabel.text = quote.quote

}
}

This is how I tried to add a key to each quote:

import UIKit
import Foundation

let uuid = UUID().uuidString

struct Quotes {
let quote: String
let identifier: String

}

let quotes: [Quotes] = [
Quotes(quote: "The best time to plant a tree was 20 years ago - The next best time is today - Unknown", identifier:  uuid),
                        Quotes(quote:    "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe",identifier: uuid),
                        Quotes(quote: "Buy less, choose well, make it last - Vivienne Westwood", identifier: uuid),
                        Quotes(quote: "The future depends on what we do in the present - Mahatma Gandhi", identifier: uuid),
]

Body:
The problem is that the .isHidden property of the UIButton's is a state variable, meaning it is saved in RAM. This means that once you exit the application and reopen it, your app will startup again with the default state variable settings.

If you wish to persist the state of these variables, you'll need to save the button states to the phone's hard drive. UserDefaults makes this easy.

@IBAction func saveButton(_ sender: UIButton) {
    UserDefaults.standard.set(true, forKey: "saveButtonHidden") // Saves the state to the hard drive

    save.isHidden = true
    unsave.isHidden = false

    var ref: DatabaseReference?
    ref = Database.database().reference()

    if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
        guard let user = Auth.auth().currentUser?.uid else { return }
        ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").chi.ld("Quote1").setValue(quoteLabel.text!)
    }

}

@IBAction func UnsaveButton(_ sender: UIButton) {
    UserDefaults.standard.set(false, forKey: "saveButtonHidden") // Saves the state to the hard drive

    save.isHidden = false
    unsave.isHidden = true

    var ref: DatabaseReference?
    ref = Database.database().reference()

    if quoteLabel.text == "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"{
        ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1").removeValue()
    }

    if quoteLabel.text as! NSObject == ref!.child("users").child(Auth.auth().currentUser!.uid).child("Quote").child("Quote1") {
        save.isHidden = true
        unsave.isHidden = false
    }
}

func setup(with quote: Quotes){
    let saveButtonShowing = UserDefault.standard.bool(forKey: "saveButtonHidden")
    if(saveButtonHidden){ // Retrieves the state variable from the hard drive and sets the button visibility accordingly
        save.isHidden = true
        unsave.isHidden = false
    } else {
        save.isHidden = false
        unsave.isHidden = true
    }

    quoteLabel.text = quote.quote
}


问:
Python convert string holding nested json to dict
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]
```
<p>And I want to convert it to this (it can have any number of nested dictionaries and lists):</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]
</code>```

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue
```

答:
No idea if this'll work for your more complicated cases, but I was able to use ast.literal_eval() and some really janky chained str.replace calls:

import ast

def replace(s):
    return ast.literal_eval(s.replace(r'"{', "{").replace(r'}"', "}"))

x = [{"keyA": "Example",
      "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"},
     {"keyA": "Example2",
      "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"}]

for d in x:
    for key, value in d.items():
        if "{" in value:
            d[key] = replace(value)
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>In [4]: x
Out[4]:
[{'keyA': 'Example',
  'keyB': {'keyC': 2, 'keyD': {'keyE': {'name': 'foo'}}, 'keyF': 0}},
 {'keyA': 'Example2',
  'keyB': {'keyC': 6, 'keyD': {'keyE': {'name': 'bar'}}, 'keyF': 5}}]

In [5]: x[0]["keyB"]["keyD"]["keyE"]["name"]
Out[5]: 'foo'
</code>```

Body:
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]

And I want to convert it to this (it can have any number of nested dictionaries and lists):

[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue

Body:
No idea if this'll work for your more complicated cases, but I was able to use ast.literal_eval() and some really janky chained str.replace calls:

import ast

def replace(s):
    return ast.literal_eval(s.replace(r'"{', "{").replace(r'}"', "}"))

x = [{"keyA": "Example",
      "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"},
     {"keyA": "Example2",
      "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"}]

for d in x:
    for key, value in d.items():
        if "{" in value:
            d[key] = replace(value)

Output:

In [4]: x
Out[4]:
[{'keyA': 'Example',
  'keyB': {'keyC': 2, 'keyD': {'keyE': {'name': 'foo'}}, 'keyF': 0}},
 {'keyA': 'Example2',
  'keyB': {'keyC': 6, 'keyD': {'keyE': {'name': 'bar'}}, 'keyF': 5}}]

In [5]: x[0]["keyB"]["keyD"]["keyE"]["name"]
Out[5]: 'foo'


问:
selenium ruby find parent of element
How do I get the parent element of any given element in selenium with ruby?

Let's say I have this:

```<code><ul>
<li id="a"></li>
</ul>
</code>```

and I can get the li with driver.find_element(id: "a"), how do I get the parent of that element that I found?

答:
This code will help you to find the parent element

```<code>element = driver.find_element(id: "a")
element.find_element(xpath: "./..")
</code>```

This code will help you to verify the element html

```<code>p element.find_element(xpath: "./..").attribute("innerHTML")
</code>```

Title: selenium ruby find parent of element

Body:
How do I get the parent element of any given element in selenium with ruby?

Let's say I have this:

and I can get the li with driver.find_element(id: "a"), how do I get the parent of that element that I found?

Body:
This code will help you to find the parent element

element = driver.find_element(id: "a")
element.find_element(xpath: "./..")

This code will help you to verify the element html

p element.find_element(xpath: "./..").attribute("innerHTML")


问:
Dealing with object return from axios
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

```<code>async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},
</code>```

My componnent data is:

```<code>data() {
    return {
        posts: {}
    }
},
</code>```

My v-for is:

```<code><article v-for="(post, index) in posts" :key="index">
</code>```

And the error I'm getting is:

```<code>[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"
</code>```

If I fill my componnent data with the json as object manually works fine, example:

```<code>data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},
</code>```

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.

答:
Since its a list of objects shouldn't it be like this? :</p>
```<code>data() {
    return {
        posts: {[]}
    }
},
</code>```

Title: Dealing with object return from axios

Body:
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},

My componnent data is:

data() {
    return {
        posts: {}
    }
},

My v-for is:

And the error I'm getting is:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"

If I fill my componnent data with the json as object manually works fine, example:

data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.

Body:
Since its a list of objects shouldn't it be like this? :

data() {
    return {
        posts: {[]}
    }
},


问:
Lock Mouse in primary screen
I have an application which use secondary monitor to display content. I dont want user to move curser to secondary monitor. I need to restrict the user to use mouse in primary monitor only. How can i do this.

Thanks

答:
http://pinvoke.net/default.aspx/user32/GetCursorPos.html

http://pinvoke.net/default.aspx/user32/SetCursorPos.html

Use PInvoke to import the calls from the library and simply check the cursor position and adjust accordingly. You might need the resolution size of the monitor to check if it's within the bounds of the first or second screen.

Title: Lock Mouse in primary screen


问:
Counting values based on certain conditions in R?
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

```<code>patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56
</code>```

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

答:
Here's a tidyverse approach.

First you need to group_by(patient) so that R will calculate patient as a group. Then use summarise() to calculate the count of codes n() in each patient, and also count the occurrence of 26 in each patient (sum(code == 26)).

```<code>library(tidyverse)

df %>% group_by(patient) %>%
  summarize(Total_codes = n(),
            Codes_of_interest = sum(code == 26))

# A tibble: 4 x 3
  patient Total_codes Codes_of_interest
    <int>       <int>             <int>
1       1           5                 2
2       2           3                 1
3       3           4                 1
4       4           4                 0
</code>```

Body:
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

Body:
Here's a tidyverse approach.

First you need to group_by(patient) so that R will calculate patient as a group. Then use summarise() to calculate the count of codes n() in each patient, and also count the occurrence of 26 in each patient (sum(code == 26)).

library(tidyverse)

df %>% group_by(patient) %>%
  summarize(Total_codes = n(),
            Codes_of_interest = sum(code == 26))

# A tibble: 4 x 3
  patient Total_codes Codes_of_interest
    <int>       <int>             <int>
1       1           5                 2
2       2           3                 1
3       3           4                 1
4       4           4                 0


问:
How to know if two spatial points are coinciding in an array of 50000 points?
Let us say I have 50000 "3D spatial coordinates" in a 1D array. I want two know if there are two points that are coinciding. If yes, which ones, or how many pairs?

I know I can use the distance formula but that would be really costly and will create a 2D array of 50k X 50k i.e. each column for relative distance of every single point w.r.t other points.

I am looking for an efficient algorithm.

答:
The first way: use hashtable/map/dictionary. O(n) amortized complexity, O(n) memory

Put points there one-by-one. If there is no such key in dictionary yet, add pair (coordinates; value=1), otherwise increment value field.

In Python, for example, there is Counter intended for this kind of problems.

The second way: sorting. O(nlogn) usual complexity.

Sort points, using special comparator: compare X-coordinate first, in case of eqiality compare Y-coordinate, in case of equality compare Z. After that walk through sorted array, similar points will stand together.

In Python default comparator for such structures works as needed.


问:
Problem with my project on android studio
I am trying to edit a project on android studio, but I keep getting these errors:

Could not HEAD 'https://chartboostmobile.bintray.com/Chartboost/com/tapjoy/tapjoy-android-sdk/12.8.0/tapjoy-android-sdk-12.8.0.pom'.
Received status code 502 from server: Bad Gateway
Disable Gradle 'offline mode' and sync project

also it is telling me to upgrade Gradle version, the current version is 4.2.2

答:
Could not HEAD 'https://chartboostmobile.bintray.com/Chartboost/com/tapjoy/tapjoy-android-sdk/12.8.0/tapjoy-android-sdk-12.8.0.pom'. Received status code 502 from server: Bad Gateway Disable Gradle 'offline mode' and sync project

This is caused by bad net connect. You could download the sdk directly from the offical site and manually integrate it via referring to this guide.

also it telling me to upgrade gradle version the current version is 4.2.2

This is only a suggestion and not mandatory.


问:
i dont understand how can I put an amount in these letters?
```<code>totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)
</code>```

These letters are discounts ,students,old people,pwds,and vips

答:
First of all, you are using == which returns a boolean, use = to assign a variable.
Secondly, no need to create different variables. Just use one S to assign discounts.

Refer to the solution below:

```<code>totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")

if discountAmt == "S":
    S = 10
elif discountAmt == "O":
    S = 5
elif discountAmt == "M":
    S = 15
elif discountAmt == "E":
    S = 20

totalPrice = totalBought - S
print(totalPrice)
</code>```

Body:
totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)

These letters are discounts ,students,old people,pwds,and vips

Body:
First of all, you are using == which returns a boolean, use = to assign a variable.
Secondly, no need to create different variables. Just use one S to assign discounts.

Refer to the solution below:

totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")

if discountAmt == "S":
    S = 10
elif discountAmt == "O":
    S = 5
elif discountAmt == "M":
    S = 15
elif discountAmt == "E":
    S = 20

totalPrice = totalBought - S
print(totalPrice)