问:
Viewing a bitmap in a fixed space in mfc
I am trying to design an application that loads bitmap images. I have bitmaps of varying sizes but I want them to be displayed on a constant space ( like a rectangle of size 500x500). I've tried StretchBlt() in the following way but the results are disappointing and the images are still of varying sizes. The code is mentioned below. Thanks in advance.

```<code>DcForClientClientDc.StretchBlt(0, 0 , 500, 500, &bmDC, 0, 0, 1000, 1000, SRCCOPY);
</code>```

答: You should pass to StretchBlt the actual size of the image you want to scale, but you are using 1000 x 1000.

Body:
I am trying to design an application that loads bitmap images. I have bitmaps of varying sizes but I want them to be displayed on a constant space ( like a rectangle of size 500x500). I've tried StretchBlt() in the following way but the results are disappointing and the images are still of varying sizes. The code is mentioned below. Thanks in advance.

DcForClientClientDc.StretchBlt(0, 0 , 500, 500, &bmDC, 0, 0, 1000, 1000, SRCCOPY);


来源: stackexchange

问:
Xcode 13: Build hangs with "iPhone is busy: making Apple Watch ready for development"
Issue: The build hangs with "iPhone is busy: making Apple Watch ready for development"

Further facts:

iOS 14.8

iPhone 8

watchOS 7.6.2

Xcode 13

Apple Watch Series 3 + Cellular (42mm)

Does anyone know a solution for that issue?

Many of the developers have the same issue:

https://developer.apple.com/forums/thread/691452

答:
This is what works for me:

Turn off the Bluetooth from settings in your iPhone from Settings -> Bluetooth (Don't turn it off from the control center)

Quit Xcode

Launch it again

Build and Run

ContentLicense: CC BY-SA 4.0


问:
Is there a way to remove unknown event listeners from objects?
I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.

```<code>public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}
</code>```

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.

Suggestions?

答:
K2xL EventManager Class
http://k2xl.com/wordpress/2008/07/02/as3-eventmanager-class-removealllisteners/</p>

OwnerDisplayName: sean

ContentLicense: CC BY-SA 3.0

Body:
I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.

public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.

Suggestions?


问:
'window.Vue.use is not a function' error on a Vue2 project
I have an application running in the Azure web app, it was working well and today the website is down suddenly with an error:

window.Vue.use is not a function

The App uses Vuetify as the frontend.

Does anyone know why? Is there a quick fix?

答:
Vue.use is from Vue 2's API, and that's now only available via an application instance in Vue 3. The error suggests your app is written with Vue 2's API, while Vue 3 is actually loaded. The timing of the error coincides with the yesterday's update to the vue package in NPM.

As of 7-FEB-2022, version 3 is the default in NPM (i.e., 3.2.30 is now the latest version), replacing Vue 2. Your app is likely pulling in vue from a CDN, and the URL is missing a version specifier (or you're using @latest):

 ⛔ defaults to latest
 ⛔ no longer Vue 2
```
<p>To ensure you're using Vue 2, include the <code>@2</code> (or <code>@2.6.14</code>) version specifier in the URL:</p>
<pre class="lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2"></script>

<script src="https://unpkg.com/vue@2.6.14"></script>

</code>```

Body:
Vue.use is from Vue 2's API, and that's now only available via an application instance in Vue 3. The error suggests your app is written with Vue 2's API, while Vue 3 is actually loaded. The timing of the error coincides with the yesterday's update to the vue package in NPM.

As of 7-FEB-2022, version 3 is the default in NPM (i.e., 3.2.30 is now the latest version), replacing Vue 2. Your app is likely pulling in vue from a CDN, and the URL is missing a version specifier (or you're using @latest):

<script src="https://unpkg.com/vue"></script> ⛔ defaults to latest
<script src="https://unpkg.com/vue@latest"></script> ⛔ no longer Vue 2

To ensure you're using Vue 2, include the @2 (or @2.6.14) version specifier in the URL:

<script src="https://unpkg.com/vue@2"></script>

<script src="https://unpkg.com/vue@2.6.14"></script>


问:
React array map inside map value not rendering
I have an object Array list and this array list includes duplicate values. So I need to render only unique values. But it's not working.</p>
```<code>{promotions.map((row) => (
  <div>
    <h1>{row.name}</h1>  //This is working
    {row.products.map(() => {
      const pp = row.products.filter( (ele, ind) => ind === row.products.findIndex( elem => elem.productId === ele.productId))

      pp.map((data)=>{
        return(
          <Chip
            key={`${row.productId}_${data.productId}`}
            classes={{ root: classes.productsChipRoot }}
            label={data.productName}
            style={{ margin: 3, backgroundColor: '#BBD7FB' }}
          />
        )
      })
    })}
  </div>
))}
</code>```

答:
```<code>{promotions.map((row) => (
      <div>
        <h1>{row.name}</h1>  //This is working
        {row.products.map(() => {
          const pp = row.products.filter( (ele, ind) => ind === row.products.findIndex( elem => elem.productId === ele.productId))

          return pp.map((data)=>{
            return(
              <Chip
                key={`${row.productId}_${data.productId}`}
                classes={{ root: classes.productsChipRoot }}
                label={data.productName}
                style={{ margin: 3, backgroundColor: '#BBD7FB' }}
              />
            )
          })
        })}
      </div>
    ))}
</code>```

Body:
I have an object Array list and this array list includes duplicate values. So I need to render only unique values. But it's not working.

{promotions.map((row) => (

{row.name}
  //This is working
    {row.products.map(() => {
      const pp = row.products.filter( (ele, ind) => ind === row.products.findIndex( elem => elem.productId === ele.productId))

      pp.map((data)=>{
        return(
          <Chip
            key={`${row.productId}_${data.productId}`}
            classes={{ root: classes.productsChipRoot }}
            label={data.productName}
            style={{ margin: 3, backgroundColor: '#BBD7FB' }}
          />
        )
      })
    })}

))}


问:
Setting swagger config parameters in SpringDoc
I am trying to override Swagger configuration in SpringDoc as described in:

https://springdoc.org/#swagger-ui-properties

I am setting these in the code in (kotlin class) init block

```<code>init {
    System.setProperty("springdoc.swagger-ui.path", "/services/$serviceName")
    System.setProperty("springdoc.swagger-ui.url", "/services/$serviceName/v3/api-docs")
    System.setProperty("springdoc.swagger-ui.configUrl", "/services/$serviceName/v3/api-docs/swagger-config")
    // Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters.
    System.setProperty("springdoc.swagger-ui.showCommonExtensions", "true")
}
</code>```

However it seems to be completely ignored and none of the fields are taken into account. What is the place these should be set correctly?

Note that I need to set the config properties according to the SERVICE_NAME env var, so I cannot use the static properties file.

Full config here: https://gist.github.com/knyttl/852f67f1688ea6e808b8eb89068e90d1

答:
As suggested by the SpringDoc author in https://github.com/springdoc/springdoc-openapi/issues/1485, this can be done as follows:

    @Bean
    open fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
        // For details, see https://springdoc.org/#swagger-ui-properties
        // Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters.
        config.showCommonExtensions = true
        // Allows to configure source for the documentation via query params (?url=/v3/api-docs).
        config.queryConfigEnabled = true
        return config
    }
```

Body:
I am trying to override Swagger configuration in SpringDoc as described in:

https://springdoc.org/#swagger-ui-properties

I am setting these in the code in (kotlin class) init block

init {
    System.setProperty("springdoc.swagger-ui.path", "/services/$serviceName")
    System.setProperty("springdoc.swagger-ui.url", "/services/$serviceName/v3/api-docs")
    System.setProperty("springdoc.swagger-ui.configUrl", "/services/$serviceName/v3/api-docs/swagger-config")
    // Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters.
    System.setProperty("springdoc.swagger-ui.showCommonExtensions", "true")
}

However it seems to be completely ignored and none of the fields are taken into account. What is the place these should be set correctly?

Note that I need to set the config properties according to the SERVICE_NAME env var, so I cannot use the static properties file.

Full config here: https://gist.github.com/knyttl/852f67f1688ea6e808b8eb89068e90d1


问:
How to convert a 24 hour time to 12 hour in VB.net as hh:mm AM/PM
So let's say I have 1400, I want to convert it into 2:00PM

I tried the following:

```<code>Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing)
</code>```

And it would give me this:

6/12/2012 02:00:00 PM

I do not want the date part, neither do I need the seconds. All I need is 2:00PM

How could I achieve this? Thanks!

答:
```<code>stackoverflowuser:
You Can Use String.Format() Function Without ParseExtract() Function

VB.NET:-

Dim time As String = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) '12:00 PM'
Dim time_1 As String = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", Date.Now) '12:00:25 PM'
Dim time_2 As String = String.Format("{0:mm}:{0:ss}.{0:fff}", Date.Now) '00:25.986 - Mostly Used In Stopwatches'
CSharp (C#):-

String time = String.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // 12:00 PM
String time_1 = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", DateTime.Now); // 12:00:25 PM
String time_2 = String.Format("{0:mm}:{0:ss}.{0:fff}", DateTime.Now); // 00:25.986 - Mostly Used In Stopwatches
Above Codes Are Examples, You Can Use Above Codes To Experiment/Observe/Make Applications With It
</code>```

You Can Use Also In:

VB.NET:-

```<code>Label1.Text = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) 'Display: 12:00 PM'
</code>```

CSharp (C#):-

```<code>label1.Text = SString.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // Display: 12:00 PM
</code>```

You Will Get The Formatted Timings In Any Label In Both VB.NET And C#

Body:
So let's say I have 1400, I want to convert it into 2:00PM

I tried the following:

Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing)

And it would give me this:

6/12/2012 02:00:00 PM

I do not want the date part, neither do I need the seconds. All I need is 2:00PM

How could I achieve this? Thanks!

Body:
stackoverflowuser:
You Can Use String.Format() Function Without ParseExtract() Function

VB.NET:-

Dim time As String = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) '12:00 PM'
Dim time_1 As String = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", Date.Now) '12:00:25 PM'
Dim time_2 As String = String.Format("{0:mm}:{0:ss}.{0:fff}", Date.Now) '00:25.986 - Mostly Used In Stopwatches'
CSharp (C#):-

String time = String.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // 12:00 PM
String time_1 = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", DateTime.Now); // 12:00:25 PM
String time_2 = String.Format("{0:mm}:{0:ss}.{0:fff}", DateTime.Now); // 00:25.986 - Mostly Used In Stopwatches
Above Codes Are Examples, You Can Use Above Codes To Experiment/Observe/Make Applications With It

You Can Use Also In:

VB.NET:-

Label1.Text = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) 'Display: 12:00 PM'

CSharp (C#):-

label1.Text = SString.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // Display: 12:00 PM

You Will Get The Formatted Timings In Any Label In Both VB.NET And C#


问:
spyder ModuleNotFoundError: No module named 'object_detection '
```<code>!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x {IMAGE_PATH + '/train'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/train.record'}
!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x{IMAGE_PATH + '/test'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/test.record'}

!cd Tensorflow && git clone https://github.com/tensorflow/models
CUSTOM_MODEL_NAME = 'my_ssd_mobnet'
!mkdir {'Tensorflow\workspace\models\\'+CUSTOM_MODEL_NAME}
!cp {PRETRAINED_MODEL_PATH+'/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config'} {MODEL_PATH+'/'+CUSTOM_MODEL_NAME}
</code>```

enter image description here

i install tenserflow  and protobuf

答:
That error is caused because tensorflow-object-detection has not been installed.

Follow this page to install

Body:
!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x {IMAGE_PATH + '/train'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/train.record'}
!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x{IMAGE_PATH + '/test'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/test.record'}

!cd Tensorflow && git clone https://github.com/tensorflow/models
CUSTOM_MODEL_NAME = 'my_ssd_mobnet'
!mkdir {'Tensorflow\workspace\models\\'+CUSTOM_MODEL_NAME}
!cp {PRETRAINED_MODEL_PATH+'/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config'} {MODEL_PATH+'/'+CUSTOM_MODEL_NAME}

enter image description here

i install tenserflow  and protobuf


问:
how to change the value of  in javascript?
i have an element in html as shown below.

```<code><tr><td class="HELPTEXT"><span lang="HLPMTXT1" id="HLPMTXT1"></span></td></tr>
</code>```

i want to change the value of lang according to particular condition.
I tried as given below.but its not working.

Could anyone help me for changing the value of lang attribute of span?

答:
You should use setAttribute(name, value) to do that, so your code would look like:

```<code>document.getElementById("HLPMTXT1").setAttribute("lang", "HLPMTXT2");
</code>```

You can also use getAttribute(name) to retrieve the value using JavaScript.

https://developer.mozilla.org/en/DOM/element.setAttribute

https://developer.mozilla.org/en/DOM/element.getAttribute

Edit: It's also possible that your script is not working because you're trying to access the element before it exists in the DOM. Best way to insure that your element exists is by either: a) putting your script tag after the element, b) using the unload event to delay execution of your JS until everything is loaded, or c) use the DOMContentLoaded event. The latter, however, is a bit tricky to get to work cross-browser (without reusing somebody else's code that already addresses those problems) so you might want to read up on it first.

Title: how to change the value of <span lang> in javascript?

Body:
i have an element in html as shown below.

i want to change the value of lang according to particular condition.
I tried as given below.but its not working.

Could anyone help me for changing the value of lang attribute of span?

Body:
You should use setAttribute(name, value) to do that, so your code would look like:

document.getElementById("HLPMTXT1").setAttribute("lang", "HLPMTXT2");

You can also use getAttribute(name) to retrieve the value using JavaScript.

https://developer.mozilla.org/en/DOM/element.setAttribute

https://developer.mozilla.org/en/DOM/element.getAttribute

Edit: It's also possible that your script is not working because you're trying to access the element before it exists in the DOM. Best way to insure that your element exists is by either: a) putting your script tag after the element, b) using the unload event to delay execution of your JS until everything is loaded, or c) use the DOMContentLoaded event. The latter, however, is a bit tricky to get to work cross-browser (without reusing somebody else's code that already addresses those problems) so you might want to read up on it first.


答:
```<code> {promotions.map((row) => (
    <dev>
       <h1>{row.name}</h1>  //This is working
{row.products.map(() => {
          let tmpArray = []
          row.products.map(pro => {
             if(tmpArray.filter(p => p.productId === pro.productId).length === 0){
                tmpArray.push(pro)
             }
          })

          tmpArray.map((data)=>{
           return(
                            <Chip
                              key={`${row.productId}_${data.productId}`}
                              classes={{ root: classes.productsChipRoot }}
                              label={data.productName}
                              style={{ margin: 3, backgroundColor: '#BBD7FB' }}
                            />

                          )
                        })
                      })}
   </div>
</code>```

Title: React array map inside map value not rendering


答:
You can do more easily if use Set constructor

let array = ['A', 'B', 'A', 'C', 'B'];
let uniqArray= [...new Set(array )];

console.log(uniqArray);```


问:
Cannot send emails to CC recipients
I have searched for similar duplicated about this question and nothing works.

Here is my code to automate a email. I have initiated the data and the method as follow,

```<code><?php

$reportdate=date('Y-m-d',strtotime("-1 days"));

  $To = 'abc@gmail.com';
$Cc = 'xyz@dialog.lk';

$Subject = 'Data as at '.$reportdate;

//this functin processes the server return codes and generates errors if needed
function server_parse($socket, $expected_response)
{
    $server_response = '';
    while (substr($server_response, 3, 1) != ' ')
    {
        if (!($server_response = fgets($socket, 256)))
            echo 'Couldn\'t get mail server response codes. Please contact the forum administrator.', __FILE__, __LINE__;
                        //exit;
    }

    if (!(substr($server_response, 0, 3) == $expected_response))
        echo 'Unable to send e-mail. Please contact the forum administrator with the following error message reported by the SMTP server: "'.$server_response.'"', __FILE__, __LINE__;
                //exit;
}

//
// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
// They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards.
// -------> This message is from punBB developer
//
function smtp_mail($to,$cc, $subject, $message, $headers = '')
{
    $recipients = explode(',', $to);
         $recipientscc = explode(',', $cc);
    $user = '<your mail id>';
    $pass = '<your password>';
    $smtp_host = 'xxx@dy.lk';
    $smtp_port = 25;

    if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
        echo "Could not connect to smtp host '$smtp_host' ($errno) ($errstr)", __FILE__, __LINE__;

    server_parse($socket, '220');

    fwrite($socket, 'EHLO '.$smtp_host."\r\n");
    server_parse($socket, '250');

    // fwrite($socket, 'AUTH LOGIN'."\r\n");
    // server_parse($socket, '334');

    // fwrite($socket, base64_encode($user)."\r\n");
    // server_parse($socket, '334');

    // fwrite($socket, base64_encode($pass)."\r\n");
    // server_parse($socket, '235');

    fwrite($socket, 'MAIL FROM: <sss@xc.lk>'."\r\n");
    server_parse($socket, '250');

    foreach ($recipients as $email)
    {
        fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
        server_parse($socket, '250');
    }

    fwrite($socket, 'DATA'."\r\n");
    server_parse($socket, '354');

   // fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
//fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".'cc: <'.implode('>, <', $recipientscc).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
   fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".'cc: <'.implode('>, <', $recipientscc).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");

    fwrite($socket, '.'."\r\n");
    server_parse($socket, '250');

    fwrite($socket, 'QUIT'."\r\n");
    fclose($socket);

    return true;
}

$headers= "MIME-Version: 1.0" . "\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers.= "From: <cc@xyz.lk>" . "\r\n";

$messagenew='Dear All,';

$messagenew.=nl2br(" \r\n \r\n");

$messagenew.=nl2br(" \r\n \r\n");
$messagenew.='Best Regards,';
$messagenew.=nl2br(" \r\n");
$messagenew.='This is an automated email, Please do not reply ... ';

// Send the mail
if(smtp_mail($To,$Cc, $Subject, $messagenew, $headers))
{
$pieces = explode(",", $To);
$NumofMails=count($pieces);
}
else
{
    echo "Some error occurred";
}
?>
</code>```

This works fine. But I am not getting any email to Cc recipients. Can someone help me?I have tried by replacing the headers as well. But when I copy all the Cc recipients to $TO this works fine as well.

答:
For the record, I am no expert on the SMTP protocol, however it seems you are missing to actually send out the CC recipients.

Try adding another foreach loop like this:

```<code>foreach ($recipients as $email)
{
    fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
    server_parse($socket, '250');
}

foreach ($recipientscc as $email)
{
    fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
    server_parse($socket, '250');
}
</code>```

According to a quick google search on the matter, the difference between 'To', 'CC' and 'BCC' is actually just in the headers, just like the subject.

Please refer to https://mailtrap.io/blog/cc-bcc-in-smtp/ for the details I found. (It's not much, but it's something)

Title: Cannot send emails to CC recipients

Body:
I have searched for similar duplicated about this question and nothing works.

Here is my code to automate a email. I have initiated the data and the method as follow,

<?php

$reportdate=date('Y-m-d',strtotime("-1 days"));

  $To = 'abc@gmail.com';
$Cc = 'xyz@dialog.lk';

$Subject = 'Data as at '.$reportdate;

//this functin processes the server return codes and generates errors if needed
function server_parse($socket, $expected_response)
{
    $server_response = '';
    while (substr($server_response, 3, 1) != ' ')
    {
        if (!($server_response = fgets($socket, 256)))
            echo 'Couldn\'t get mail server response codes. Please contact the forum administrator.', __FILE__, __LINE__;
                        //exit;
    }

    if (!(substr($server_response, 0, 3) == $expected_response))
        echo 'Unable to send e-mail. Please contact the forum administrator with the following error message reported by the SMTP server: "'.$server_response.'"', __FILE__, __LINE__;
                //exit;
}

//
// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
// They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards.
// -------> This message is from punBB developer
//
function smtp_mail($to,$cc, $subject, $message, $headers = '')
{
    $recipients = explode(',', $to);
         $recipientscc = explode(',', $cc);
    $user = '<your mail id>';
    $pass = '<your password>';
    $smtp_host = 'xxx@dy.lk';
    $smtp_port = 25;

    if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
        echo "Could not connect to smtp host '$smtp_host' ($errno) ($errstr)", __FILE__, __LINE__;

    server_parse($socket, '220');

    fwrite($socket, 'EHLO '.$smtp_host."\r\n");
    server_parse($socket, '250');

    // fwrite($socket, 'AUTH LOGIN'."\r\n");
    // server_parse($socket, '334');

    // fwrite($socket, base64_encode($user)."\r\n");
    // server_parse($socket, '334');

    // fwrite($socket, base64_encode($pass)."\r\n");
    // server_parse($socket, '235');

    fwrite($socket, 'MAIL FROM: <sss@xc.lk>'."\r\n");
    server_parse($socket, '250');

    foreach ($recipients as $email)
    {
        fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
        server_parse($socket, '250');
    }

    fwrite($socket, 'DATA'."\r\n");
    server_parse($socket, '354');

   // fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
//fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".'cc: <'.implode('>, <', $recipientscc).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
   fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".'cc: <'.implode('>, <', $recipientscc).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");

    fwrite($socket, '.'."\r\n");
    server_parse($socket, '250');

    fwrite($socket, 'QUIT'."\r\n");
    fclose($socket);

    return true;
}

$headers= "MIME-Version: 1.0" . "\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers.= "From: <cc@xyz.lk>" . "\r\n";

$messagenew='Dear All,';

$messagenew.=nl2br(" \r\n \r\n");

$messagenew.=nl2br(" \r\n \r\n");
$messagenew.='Best Regards,';
$messagenew.=nl2br(" \r\n");
$messagenew.='This is an automated email, Please do not reply ... ';

// Send the mail
if(smtp_mail($To,$Cc, $Subject, $messagenew, $headers))
{
$pieces = explode(",", $To);
$NumofMails=count($pieces);
}
else
{
    echo "Some error occurred";
}
?>

This works fine. But I am not getting any email to Cc recipients. Can someone help me?I have tried by replacing the headers as well. But when I copy all the Cc recipients to $TO this works fine as well.

Body:
For the record, I am no expert on the SMTP protocol, however it seems you are missing to actually send out the CC recipients.

Try adding another foreach loop like this:

foreach ($recipients as $email)
{
    fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
    server_parse($socket, '250');
}

foreach ($recipientscc as $email)
{
    fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
    server_parse($socket, '250');
}

According to a quick google search on the matter, the difference between 'To', 'CC' and 'BCC' is actually just in the headers, just like the subject.

Please refer to https://mailtrap.io/blog/cc-bcc-in-smtp/ for the details I found. (It's not much, but it's something)


问:
Using flask to use a function
I am attempting to use functions inside of flask, but I don't know how to properly do it.

How do I define the functions,

Example

```<code>def foo(a, b):
    ...
</code>```

答:
```<code>from flask import *
app = Flask(__name__)

@app.route("/")
def index():
  return "<h1>Hello World</h1>"

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=8080, debug=False)
</code>```

for example index is a function example that will run in the specified address below.

Title: Using flask to use a function

Body:
I am attempting to use functions inside of flask, but I don't know how to properly do it.

How do I define the functions,

Example

def foo(a, b):
    ...

Body:
from flask import *
app = Flask(__name__)

@app.route("/")
def index():
  return "<h1>Hello World</h1>"

if __name__ == "__main__":
  app.run(host="0.0.0.0", port=8080, debug=False)

for example index is a function example that will run in the specified address below.


问:
Open link getting via ajax response in colorbox not working
I have three php scripts. lectures.php , lectures-ajax.php and lectures-play.php

In lectures.php, data get retrieved from lectures-ajax.php via jquery ajax after selecting option from dropdown.

In retrieved data via ajax contains a link. I want to open that link (i.e. Play Now button link) in colorbox. But it is not working.

code in lectures.php :

head section :

```<code> <link rel="stylesheet" href="source-floatbox/colorbox.css" />
 <script src="js/jquery.min.js"></script>
 <script src="source-floatbox/jquery.colorbox.js"></script>

 <script>
 var $ar = jQuery.noConflict();
 $ar(document).ready(function(){
       $ar('#loader').hide();
       $ar("#sthaan_table").on('change', function() {
        var sthaan_table_value=$ar("#sthaan_table").val();
        var dataString = 'sthaan_table_value='+ sthaan_table_value;

    if ($ar('#sthaan_table').is(':empty')){
        $ar("#sthaan_details").hide();
        $ar('.sthaan_details_empty').show();
        $ar("#sthaan_details'").empty();
   }else{
     $ar.ajax({
        beforeSend: function() {
            $ar('#loader').show();
            $ar("#sthaan_details").hide();
            $ar('.sthaan_details_empty').hide();
        },
        complete: function(){
            $ar('#loader').hide();
        },
        type: "POST",
        url: "lectures-ajax.php",
        data: dataString,
        cache: false,
        success: function(html){
            $ar("#sthaan_details").html(html);
            $ar("#sthaan_details").show();
            $ar('.sthaan_details_empty').hide();
        }
      });
    }
  });
});
</script>
</code>```

In body section :

```<code>   <select name='sthaan' id='sthaan_table' class="form-control" >
        <option value="">Select Sthaan</option>
        <option value="cumulative">Cumulative</option>
        <option value="sutra">Sutra Sthaan</option>
        <option value="shaareer">Shaareer Sthaan</option>
        <option value="nidaan">Nidaan Sthaan</option>
        <option value="chikitsa">Chikitsa Sthaan</option>
        <option value="kalpa">Kalpa Sthaan</option>
        <option value="uttar">Uttar Sthaan</option>
   </select>

   <div id="loader" class="loader"><img src="images/red1.gif" style="width:100px; height:100px;"></div>

   <div class="sthaan_details" id="sthaan_details"></div>

   <div class="status alert alert-danger sthaan_details_empty" style="display:none;">Select Sthaan First</div>
</code>```

code in lectures-ajax.php :

```<code><?php
 include("db.php");

 if (isset($_POST["sthaan_table_value"])){
    $sthaan_selected = $database->filter($_POST["sthaan_table_value"]);

  ?>

    <div style="background-color:#26b864; color:#FFFFFF; font-size:15px; padding:5px; font-weight:600;">Audio Lectures - <b><?php echo $sthaan_selected ;?></b></div><br>

 <?php
  $q1 =  "SELECT * FROM  $audiotable where sthaan='$sthaan_selected' and showhide='0' order by upload_date ASC";

  $counts = 1;
  $len = $database->num_rows($q1);

  if($len !=0){
       $results = $database->get_results($q1);
  ?>

 <table class="audiorec ff">
 <thead>
     <tr>
        <th scope="col" style="width:5%;">Sr.No.</th>
        <th scope="col" style="width:45%;">Lecture Details</th>
        <th scope="col" style="color:#FFFFFF; width:16%; text-align:center;">Play Now</th>
    </tr>
</thead>
<tbody>
 <?php
  foreach ($results as $data){
 ?>
    <tr>
        <td scope="row" data-label="Sr.No."><?php echo $counts;?></td>
        <td data-label="Lecture Details"><?php echo ucwords(stripslashes($data['file_subject']));?></td>

        <td data-label="Play Now">
          <a href="javascript:void(0);" data-url="lectures-play.php?loginpasskey=<?php echo $token;?>&play-audio=<?php echo $data['lecture_id'];?>" target="_top"  class="btn btn-success colorbox-my">Play</a>
        <script>

        $(document).on("click", ".colorbox-my", function(){
            $('.colorbox-my').colorbox({

                href: $(this).data('url'),
                iframe: true,
                innerWidth: '95%',
                innerHeight:'70%',
                opacity : 0,
                fixed:true,
                escKey: false,
                overlayClose: false,
        });
    });
</script>
        </td>
    </tr>
     <?php $counts++;} ?>
 </tbody>
 </table>

<?php
   }
  }
 ?>

</code>```

If displaying all results on lectures.php by default (without using sorting / filter option with dropdown and without using lectures-ajax.php, jquery - ajax) colorbox working.

Your kind help appreciated...

答:
cut $(document).on("click", ".colorbox-my", function(){

$('.colorbox-my').colorbox({

```<code>            href: $(this).data('url'),
            iframe: true,
            innerWidth: '95%',
            innerHeight:'70%',
            opacity : 0,
            fixed:true,
            escKey: false,
            overlayClose: false,
    }); code from lectures-ajax.php and use it in lectures.php script section it will work
</code>```

Body:
I have three php scripts. lectures.php , lectures-ajax.php and lectures-play.php

In lectures.php, data get retrieved from lectures-ajax.php via jquery ajax after selecting option from dropdown.

In retrieved data via ajax contains a link. I want to open that link (i.e. Play Now button link) in colorbox. But it is not working.

code in lectures.php :

head section :

 <link rel="stylesheet" href="source-floatbox/colorbox.css" />

In body section :

   <select name='sthaan' id='sthaan_table' class="form-control" >
        <option value="">Select Sthaan</option>
        <option value="cumulative">Cumulative</option>
        <option value="sutra">Sutra Sthaan</option>
        <option value="shaareer">Shaareer Sthaan</option>
        <option value="nidaan">Nidaan Sthaan</option>
        <option value="chikitsa">Chikitsa Sthaan</option>
        <option value="kalpa">Kalpa Sthaan</option>
        <option value="uttar">Uttar Sthaan</option>
   </select>

Select Sthaan First

code in lectures-ajax.php :

<?php
 include("db.php");

 if (isset($_POST["sthaan_table_value"])){
    $sthaan_selected = $database->filter($_POST["sthaan_table_value"]);

  ?>

Audio Lectures - <?php echo $sthaan_selected ;?>

 <?php
  $q1 =  "SELECT * FROM  $audiotable where sthaan='$sthaan_selected' and showhide='0' order by upload_date ASC";

  $counts = 1;
  $len = $database->num_rows($q1);

  if($len !=0){
       $results = $database->get_results($q1);
  ?>

        Sr.No.
        Lecture Details
        Play Now

 <?php
  foreach ($results as $data){
 ?>

        <?php echo $counts;?>
        <?php echo ucwords(stripslashes($data['file_subject']));?>

          <a href="javascript:void(0);" data-url="lectures-play.php?loginpasskey=<?php echo $token;?>&play-audio=<?php echo $data['lecture_id'];?>" target="_top"  class="btn btn-success colorbox-my">Play

     <?php $counts++;} ?>

<?php
   }
  }
 ?>

If displaying all results on lectures.php by default (without using sorting / filter option with dropdown and without using lectures-ajax.php, jquery - ajax) colorbox working.

Your kind help appreciated...

Body:
cut $(document).on("click", ".colorbox-my", function(){

$('.colorbox-my').colorbox({

            href: $(this).data('url'),
            iframe: true,
            innerWidth: '95%',
            innerHeight:'70%',
            opacity : 0,
            fixed:true,
            escKey: false,
            overlayClose: false,
    }); code from lectures-ajax.php and use it in lectures.php script section it will work


问:
regex remove ref tags php
Input string:

```<code><ref> Hi this one to be rmoved} {{sdjfhk arbit shit}} [whatever] </ref> But this one to be preserved. <ref> again this has to be removed. </ref>
</code>```

Output String:

```<code>But this one to be preserved.
</code>```

i tried:  $str = preg_replace('/^<ref.*?ref>$/', '', $str);

答:
You were very close. You just want to drop your ^ and $ characters.

```<code>$str = '<ref> Hi this one to be rmoved} {{sdjfhk arbit shit}} [whatever] </ref> But this one to be preserved. <ref> again this has to be removed. </ref>';

print preg_replace('/<ref.*?ref>/', '', $str);
//=> But this one to be preserved.
</code>```

See it working here on tehplayground.com

Side note: Since you're looking for HTML tags, you should technically be using a DOM parser for this.

PHP Simple HTML DOM Parser is great for this kind fo task :)

Title: regex remove ref tags php

Body:
Input string:

<ref> Hi this one to be rmoved} {{sdjfhk arbit shit}} [whatever] </ref> But this one to be preserved. <ref> again this has to be removed. </ref>

Output String:

But this one to be preserved.

i tried:  $str = preg_replace('/^<ref.*?ref>$/', '', $str);

Body:
You were very close. You just want to drop your ^ and $ characters.

$str = '<ref> Hi this one to be rmoved} {{sdjfhk arbit shit}} [whatever] </ref> But this one to be preserved. <ref> again this has to be removed. </ref>';

print preg_replace('/<ref.*?ref>/', '', $str);
//=> But this one to be preserved.

See it working here on tehplayground.com

Side note: Since you're looking for HTML tags, you should technically be using a DOM parser for this.

PHP Simple HTML DOM Parser is great for this kind fo task :)


问:
TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'
models.py file

```<code>class Product(models.Model):
    """
    This is The Product table contining all product items.
    """
    name = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    brand = models.ForeignKey(to='brands.BrandProfile',
                              on_delete=models.DO_NOTHING, related_name='brand_product')
    # brand=models.CharField(max_length=30)
    category = models.ForeignKey(
        to='products.Category', on_delete=models.DO_NOTHING)
    # sizes = ArrayField(
    #     models.CharField(max_length=10),
    # )
    # colors = ArrayField(
    #     models.CharField(max_length=56)
    # )

    is_available = models.BooleanField(default=True)
    market_price = models.IntegerField()
    selling_price = models.IntegerField()
    description = models.TextField()

    # stock_status , visibility_status
    # product won't delete if category deleted, we have to do it manually.

    visiblity = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:

        ordering = ('-created_at',)
        verbose_name = "Product"
        verbose_name_plural = "Products"

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(str(self.name.lower()) + str(uuid.uuid4()))

        return super().save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

    @property
    def discount_percent(self):
        if self.selling_price:
            discount_percent = 100 - \
                (self.selling_price * 100) / self.market_price
            return int(discount_percent)
        return 0

class ProductImage(models.Model):
    """
    The Product Image Table
    """
    product = models.ForeignKey(
        Product, on_delete=models.CASCADE, related_name='product_images')
    image = models.ImageField(
        upload_to=brand_product_image_file_path, blank=False, null=False)
    product_color = models.CharField(max_length=56)
    alt_text = models.CharField(max_length=24)
    is_featured = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Product Image"
        verbose_name_plural = "Product Images"

    def __str__(self):
        return str(self.alt_text)

</code>```

serializers.py file

```<code>
class ProductImageSerializer(serializers.ModelSerializer):
    # product=serializers.SerializerMethodField(required=False)

    class Meta:
        model = ProductImage
        exclude = ('created_at', 'updated_at')
        read_only_fields = ['id', ]

class ProductSerializer(serializers.ModelSerializer):
    product_images = ProductImageSerializer(many=True)
    discount_percent = serializers.SerializerMethodField()
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(),
        slug_field='slug')
    brand = serializers.SlugRelatedField(
        queryset=BrandProfile.objects.all(),
        slug_field='brand_username')

    class Meta:
        model = Product
        fields = '__all__'

    def get_discount_percent(self, obj):
        return obj.discount_percent

    def create(self, validated_data):
        # print(validated_data)
        product_images = validated_data.pop('product_images', None)
        # print(f"product_images: {product_images}")

        product = Product.objects.create(**validated_data)

        # print(f"product: {product}")

        for item in product_images:
            item['product'] = product
            # print(product)
            print(item)
            for i in item:
                print(i)
            # print(ProductImageSerializer.create(self, **item))
            print(ProductImageSerializer.create(**item))
            ProductImageSerializer.create(ProductImageSerializer(), **item)

        return product

    # def create(self, validated_data):
    #     image_data = validated_data.pop('images', None)

    #     images = []
    #     for img in image_data:
    #         image = ProductImageSerializer.create(
    #             ProductImageSerializer(), validated_data=img)
    #         image.save()
    #         images.append(image)

    #     product = Product.objects.create(images=images, **validated_data)
    #     return product

    def update(self, instance, validated_data):
        product_images = validated_data.pop('product_images')
        print(product_images)
        instance.name = validated_data.get('name', instance.name)
        instance.title = validated_data.get('title', instance.title)
        instance.brand = validated_data.get('brand', instance.brand)
        instance.category = validated_data.get('category', instance.category)
        # instance.sizes = validated_data.get('sizes', instance.sizes)
        # instance.colors = validated_data.get('colors', instance.colors)
        instance.is_available = validated_data.get(
            'is_available', instance.is_available)
        instance.market_price = validated_data.get(
            'market_price', instance.market_price)
        instance.selling_price = validated_data.get(
            'selling_price', instance.selling_price)
        instance.description = validated_data.get(
            'description', instance.description)
        instance.visiblity = validated_data.get(
            'visiblity', instance.visiblity)
        instance.save()

        keep_images = []
        for image in product_images:
            if "id" in image.keys():
                if ProductImage.objects.filter(id=image["id"]).exists():
                    i = ProductImage.objects.get(id=image["id"])
                    i.image = image.get('image', i.image)
                    i.product_color = image.get(
                        'product_color', i.product_color)
                    i.alt_text = image.get('alt_text', i.alt_text)
                    i.is_featured = image.get('is_featured', i.is_featured)
                    i.save()
                    keep_images.append(i.id)
                else:
                    continue
            else:
                i = ProductImage.objects.create(**image, product=instance)
                keep_images.append(i.id)

        for image in instance.images:
            if image.id not in keep_images:
                image.delete()

        return instance

</code>```

views.py file

```<code>class ProductModelViewset(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    parser_classes = [FormParser, MultiPartParser, JSONParser]
    http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options']
    pagination_class = ProductPagination
    lookup_field = "slug"

    def get_serializer_class(self):
        # if self.action
        return super().get_serializer_class()

    def get_queryset(self):

        if self.request.user.is_authenticated and self.request.user.is_brand or self.request.user.is_staff:
            queryset = Product.objects.all()

        else:
            queryset = Product.objects.filter(visiblity=True)

        return queryset

    def get_permissions(self):

        if self.action == 'create':

            self.permission_classes = [
                IsAuthenticated, IsStaffOrIsBrandUser]

        elif self.action in ['update', 'destroy']:

            if self.request.user.is_authenticated and self.request.user.is_brand:
                self.permission_classes = [
                    IsAuthenticated, IsBrandUser, AccessOwnProduct]
            else:
                self.permission_classes = [
                    IsAuthenticated, IsAdminUser]

        else:

            self.permission_classes = [IsAuthenticatedOrReadOnly]

        return super(ProductModelViewset, self).get_permissions()

    def update(self, request, *args, **kwargs):

        return super().update(request, *args, **kwargs)

    @action(detail=True, methods=['GET'], name='Related Products')
    def related_products(self, request, slug):

        product_queryset = Product.objects.filter(visiblity=True)
        product = product_queryset.get(slug=slug)
        category_products = product_queryset.filter(
            category=product.category)
        category_products_s = self.serializer_class(
            category_products, many=True, context={'request': request})
        res_context = {
            "product": product.title,
            "category": product.category.title,
            "related_products": category_products_s.data
        }
        return Response(res_context, status=status.HTTP_200_OK)

</code>```

url

http://127.0.0.1:8000/api/v1/products/products/ [POST] (authenticated and is_brand=True)

After givivg post request in this link, i am facing error, i have used here nested serializer.

TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'
command prompt error

```<code>Internal Server Error: /api/v1/products/products/
Traceback (most recent call last):
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
    self.perform_create(serializer)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
    serializer.save()
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "D:\Django\merchbd\core-backend\app\products\serializers.py", line 77, in create
    print(ProductImageSerializer.create(**item))
TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'
</code>```

please help me , how to solve this problem?

答:
Default serializer create method is:

```<code>def create(self, validated_data):
    return Model(**validated_data)
</code>```

Let's say that your item is {'image': 'image.jpg', 'name': 'cool image'}

So

```<code>print(ProductImageSerializer.create(**item))
</code>```

is the same as

```<code>print(ProductImageSerializer.create(image=item['image'], name=item['name']))
</code>```

but correct code is

```<code># instantiate class to be able parse self
serializer = ProductImageSerializer(data=item)
# check if data is correct
serializer.is_valid()
# run create method
print(serializer.create(validated_data=serializer.validated_data))
</code>```

PS. and of course next line ProductImageSerializer.create(ProductImageSerializer(), **item) is not correct too

Body:
models.py file

class Product(models.Model):
    """
    This is The Product table contining all product items.
    """
    name = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    brand = models.ForeignKey(to='brands.BrandProfile',
                              on_delete=models.DO_NOTHING, related_name='brand_product')
    # brand=models.CharField(max_length=30)
    category = models.ForeignKey(
        to='products.Category', on_delete=models.DO_NOTHING)
    # sizes = ArrayField(
    #     models.CharField(max_length=10),
    # )
    # colors = ArrayField(
    #     models.CharField(max_length=56)
    # )

    is_available = models.BooleanField(default=True)
    market_price = models.IntegerField()
    selling_price = models.IntegerField()
    description = models.TextField()

    # stock_status , visibility_status
    # product won't delete if category deleted, we have to do it manually.

    visiblity = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:

        ordering = ('-created_at',)
        verbose_name = "Product"
        verbose_name_plural = "Products"

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(str(self.name.lower()) + str(uuid.uuid4()))

        return super().save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

    @property
    def discount_percent(self):
        if self.selling_price:
            discount_percent = 100 - \
                (self.selling_price * 100) / self.market_price
            return int(discount_percent)
        return 0

class ProductImage(models.Model):
    """
    The Product Image Table
    """
    product = models.ForeignKey(
        Product, on_delete=models.CASCADE, related_name='product_images')
    image = models.ImageField(
        upload_to=brand_product_image_file_path, blank=False, null=False)
    product_color = models.CharField(max_length=56)
    alt_text = models.CharField(max_length=24)
    is_featured = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Product Image"
        verbose_name_plural = "Product Images"

    def __str__(self):
        return str(self.alt_text)

serializers.py file

class ProductImageSerializer(serializers.ModelSerializer):
    # product=serializers.SerializerMethodField(required=False)

    class Meta:
        model = ProductImage
        exclude = ('created_at', 'updated_at')
        read_only_fields = ['id', ]

class ProductSerializer(serializers.ModelSerializer):
    product_images = ProductImageSerializer(many=True)
    discount_percent = serializers.SerializerMethodField()
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(),
        slug_field='slug')
    brand = serializers.SlugRelatedField(
        queryset=BrandProfile.objects.all(),
        slug_field='brand_username')

    class Meta:
        model = Product
        fields = '__all__'

    def get_discount_percent(self, obj):
        return obj.discount_percent

    def create(self, validated_data):
        # print(validated_data)
        product_images = validated_data.pop('product_images', None)
        # print(f"product_images: {product_images}")

        product = Product.objects.create(**validated_data)

        # print(f"product: {product}")

        for item in product_images:
            item['product'] = product
            # print(product)
            print(item)
            for i in item:
                print(i)
            # print(ProductImageSerializer.create(self, **item))
            print(ProductImageSerializer.create(**item))
            ProductImageSerializer.create(ProductImageSerializer(), **item)

        return product

    # def create(self, validated_data):
    #     image_data = validated_data.pop('images', None)

    #     images = []
    #     for img in image_data:
    #         image = ProductImageSerializer.create(
    #             ProductImageSerializer(), validated_data=img)
    #         image.save()
    #         images.append(image)

    #     product = Product.objects.create(images=images, **validated_data)
    #     return product

    def update(self, instance, validated_data):
        product_images = validated_data.pop('product_images')
        print(product_images)
        instance.name = validated_data.get('name', instance.name)
        instance.title = validated_data.get('title', instance.title)
        instance.brand = validated_data.get('brand', instance.brand)
        instance.category = validated_data.get('category', instance.category)
        # instance.sizes = validated_data.get('sizes', instance.sizes)
        # instance.colors = validated_data.get('colors', instance.colors)
        instance.is_available = validated_data.get(
            'is_available', instance.is_available)
        instance.market_price = validated_data.get(
            'market_price', instance.market_price)
        instance.selling_price = validated_data.get(
            'selling_price', instance.selling_price)
        instance.description = validated_data.get(
            'description', instance.description)
        instance.visiblity = validated_data.get(
            'visiblity', instance.visiblity)
        instance.save()

        keep_images = []
        for image in product_images:
            if "id" in image.keys():
                if ProductImage.objects.filter(id=image["id"]).exists():
                    i = ProductImage.objects.get(id=image["id"])
                    i.image = image.get('image', i.image)
                    i.product_color = image.get(
                        'product_color', i.product_color)
                    i.alt_text = image.get('alt_text', i.alt_text)
                    i.is_featured = image.get('is_featured', i.is_featured)
                    i.save()
                    keep_images.append(i.id)
                else:
                    continue
            else:
                i = ProductImage.objects.create(**image, product=instance)
                keep_images.append(i.id)

        for image in instance.images:
            if image.id not in keep_images:
                image.delete()

        return instance

views.py file

class ProductModelViewset(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    parser_classes = [FormParser, MultiPartParser, JSONParser]
    http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options']
    pagination_class = ProductPagination
    lookup_field = "slug"

    def get_serializer_class(self):
        # if self.action
        return super().get_serializer_class()

    def get_queryset(self):

        if self.request.user.is_authenticated and self.request.user.is_brand or self.request.user.is_staff:
            queryset = Product.objects.all()

        else:
            queryset = Product.objects.filter(visiblity=True)

        return queryset

    def get_permissions(self):

        if self.action == 'create':

            self.permission_classes = [
                IsAuthenticated, IsStaffOrIsBrandUser]

        elif self.action in ['update', 'destroy']:

            if self.request.user.is_authenticated and self.request.user.is_brand:
                self.permission_classes = [
                    IsAuthenticated, IsBrandUser, AccessOwnProduct]
            else:
                self.permission_classes = [
                    IsAuthenticated, IsAdminUser]

        else:

            self.permission_classes = [IsAuthenticatedOrReadOnly]

        return super(ProductModelViewset, self).get_permissions()

    def update(self, request, *args, **kwargs):

        return super().update(request, *args, **kwargs)

    @action(detail=True, methods=['GET'], name='Related Products')
    def related_products(self, request, slug):

        product_queryset = Product.objects.filter(visiblity=True)
        product = product_queryset.get(slug=slug)
        category_products = product_queryset.filter(
            category=product.category)
        category_products_s = self.serializer_class(
            category_products, many=True, context={'request': request})
        res_context = {
            "product": product.title,
            "category": product.category.title,
            "related_products": category_products_s.data
        }
        return Response(res_context, status=status.HTTP_200_OK)

url

http://127.0.0.1:8000/api/v1/products/products/ [POST] (authenticated and is_brand=True)

After givivg post request in this link, i am facing error, i have used here nested serializer.

TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'
command prompt error

Internal Server Error: /api/v1/products/products/
Traceback (most recent call last):
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
    self.perform_create(serializer)
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
    serializer.save()
  File "D:\Django\merchbd\core-backend\venv\lib\site-packages\rest_framework\serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "D:\Django\merchbd\core-backend\app\products\serializers.py", line 77, in create
    print(ProductImageSerializer.create(**item))
TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'

please help me , how to solve this problem?

Body:
Default serializer create method is:

def create(self, validated_data):
    return Model(**validated_data)

Let's say that your item is {'image': 'image.jpg', 'name': 'cool image'}

So

print(ProductImageSerializer.create(**item))

is the same as

print(ProductImageSerializer.create(image=item['image'], name=item['name']))

but correct code is

# instantiate class to be able parse self
serializer = ProductImageSerializer(data=item)
# check if data is correct
serializer.is_valid()
# run create method
print(serializer.create(validated_data=serializer.validated_data))

PS. and of course next line ProductImageSerializer.create(ProductImageSerializer(), **item) is not correct too


问:
error when trying to install "npm node-sass --save-dev"
Please Help! I am trying to install npm sass package and I get this error 'gyp err'</p>

答:
The error in the image is related to node-gyp instead of node-sass, and to install node-gyp we need to install python firstly.

see this ref.


问:
reverse the order of div's children
How can you reverse the order of a div's children with pure CSS?

For example:

I want

```<code><div id="parent">
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
</div>
</code>```

to be displayed as:

```<code>D

C

B

A
</code>```

I've created a demo on JSfiddle:
http://jsfiddle.net/E7cVs/2/

答:
You can use flex-direction to reverse elements.

The flex-direction property accepts four possible values:

```<code>row : same as text direction (default)
row-reverse : opposite to text direction.
column : same as row but top to bottom.
column-reverse : same as row-reverse top to bottom.
</code>```

Title: reverse the order of div's children

Body:
How can you reverse the order of a div's children with pure CSS?

For example:

I want

A

B

C

D

to be displayed as:

D

C

B

A

I've created a demo on JSfiddle:
http://jsfiddle.net/E7cVs/2/

Body:
You can use flex-direction to reverse elements.

The flex-direction property accepts four possible values:

row : same as text direction (default)
row-reverse : opposite to text direction.
column : same as row but top to bottom.
column-reverse : same as row-reverse top to bottom.


问:
removeRow using XSSF libraries is not working
I tried the below code, but it's not working

```<code>    File src = new File("E:\\TestData.xlsx");
    FileInputStream fs = new FileInputStream(src);
    XSSFWorkbook workbook = new XSSFWorkbook(fs);
    XSSFSheet sheet = workbook.getSheet("test");
    XSSFRow row = sheet.getRow(1);
    sheet.removeRow(row);
</code>```

Note: Not getting any error also

答:
```<code>You need to save file after row deletion
FileOutputStream outputStream = new FileOutputStream(File Path);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
</code>```

Body:
I tried the below code, but it's not working

    File src = new File("E:\\TestData.xlsx");
    FileInputStream fs = new FileInputStream(src);
    XSSFWorkbook workbook = new XSSFWorkbook(fs);
    XSSFSheet sheet = workbook.getSheet("test");
    XSSFRow row = sheet.getRow(1);
    sheet.removeRow(row);

Note: Not getting any error also


问:
The argument type 'Null' can't be assigned to the parameter type 'Key'
I want to call CreateProfile() in my main.dart.. but it gives me an  error.. the below image showing the error in main.dart and I have included my createprofile.dart code for you to refer.

The argument type 'Null' can't be assigned to the parameter type
'Key'.

starting code of CreateProfile.dart

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

  @override
  _CreateProfileState createState() => _CreateProfileState();
}

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),
</code>```

答: You can use ValueKey: A key that uses a simple value such as a String. You can learn more here  -> https://www.youtube.com/watch?v=kn0EOS-ZiIc

Body:
I want to call CreateProfile() in my main.dart.. but it gives me an  error.. the below image showing the error in main.dart and I have included my createprofile.dart code for you to refer.

The argument type 'Null' can't be assigned to the parameter type
'Key'.

starting code of CreateProfile.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

  @override
  _CreateProfileState createState() => _CreateProfileState();
}

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),


问:
Why my Loader is not working when I am giving all correct code
My loader and form is not showing when I am using pressing button.My loader is outside form still it is not working. Please help me I tried it to solve many time but I couldn't .I am adding here my signup.jsp and Register.java  code details here. I have added Threadsleep(3000) to hold loader for 3 seconds still it is not working</p>
```<code>package com.user;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class Register extends HttpServlet {

   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       try (PrintWriter out = response.getWriter()) {
           /* TODO output your page here. You may use following sample code. */
           /*out.println("<!DOCTYPE html>");
           out.println("<html>");
           out.println("<head>");
           out.println("<title>Servlet Register</title>");
           out.println("</head>");
           out.println("<body>");*/
           //Getting all the details from incoming from request
           String name=request.getParameter("user_name");
           String email=request.getParameter("user_email");
           String password=request.getParameter("user_password");
           //out.println(name);
           //out.println(email);
           //out.println(password);
           //connection
            try{
                Thread.sleep(3000);
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/youtube1","root","Vandana");

                //query
                String q="insert into user(name,email,password) value(?, ?, ?)";
                PreparedStatement pstmpt= con.prepareStatement(q);
                pstmpt.setString(1, name);
                pstmpt.setString(2, password);
                pstmpt.setString(3, email);

                pstmpt.executeUpdate();

                out.println("Done");
            }

            catch (Exception e){
               e.printStackTrace() ;
               out.println("Error");
            }

           //......
           //out.println("</body>");
           //out.println("</html>");
       }
   }

   // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
   /**
    * Handles the HTTP <code>GET</code> method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       processRequest(request, response);
   }

   /**
    * Handles the HTTP <code>POST</code> method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       processRequest(request, response);
   }

   /**
    * Returns a short description of the servlet.
    *
    * @return a String containing servlet description
    */
   @Override
   public String getServletInfo() {
       return "Short description";
   }// </editor-fold>

}

**signup.jsp**

<%--
   Document   : signup
   Created on : 01-Feb-2022, 2:13:08 PM
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       <title>JSP Page</title>
       <!-- Compiled and minified CSS -->
       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

       <!-- Compiled and minified JavaScript -->
       <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

   </head>
   <body style="background-image: url(images/bg.jpg); background-size: cover;background-attachment: fixed;">
       <div class="container">
           <div class="row">
               <div class="col m6 offset-m3">

                   <div class="card">
                        <div class="card-content">
                            <div class="form center-align">
                                <h3 style="margin-top: 10px;"class="center-align">Register Here !!</h3>
                                <h5 id="msg" class="center-align"</h5>
                               <div class="form">
                               <!-- creating form -->
                               <form action="Register" method="post" id="myform">
                                   <input type="text" name="user_name" placeholder="Enter user_name"\>
                                   <input type="password" name="user_password" placeholder="Enter password"\>
                                   <input type="email" name="user_email" placeholder="Enter your email"\>

                                   <button type="submit" name="btn" style="background-color:#b3e5fc;">Submit</button>

                               </form>
                               <div class="loader center-align" style="margin-top: 10px; display: none;" >
                                       <div class="preloader-wrapper big active">
                                           <div class="spinner-layer spinner-blue-only">
                                             <div class="circle-clipper left">
                                               <div class="circle"></div>
                                             </div><div class="gap-patch">
                                               <div class="circle"></div>
                                             </div><div class="circle-clipper right">
                                               <div class="circle"></div>
                                             </div>
                                           </div>

                                   <h5>Please Wait....</h5>
                               </div>

                           </div>
                   </div>
               </div>
           </div>
       </div>
     </div>
   </div>
       <script
           src="https://code.jquery.com/jquery-3.6.0.min.js"
           integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
           crossorigin="anonymous">

       </script>
       <script>
               $(document).ready(function(){
               console.log("Page is ready...... ") ;
               $("#myform").on('submit',function(event){
               event.preventDefault();
               var f = $(this).serialize();
               console.log(f);
               $(".loader").show();
               $(".form").hide();

                   $.ajax({
                      url:"Register",
                      data:f,
                      type:'POST',
                      success:function(data,textStatus,jqXHR){
                          console.log(data);
                          console.log("Success......");
                          $(".loader").hide();
                          $(".form").show();
                          if(data.trim()==="Done"){
                              $("#msg").html("Succesfully Registered !!!");
                              $("#msg").addClass("green-text");
                          }else{
                              $("#msg").html("Something went wrong !!!");
                              $("#msg").addClass("red-text");
                          }

                      },
                      error:function(jqXHR,textStatus,errorThrown){
                          console.log(data);
                          console.log("error");
                          $(".loader").hide();
                          $(".form").show();
                          $("#msg").html("Something went wrong !!!");
                          $("#msg").addClass("red-text");
                      }
                  });
               });
               });

       </script>
   </body>
</html>```

please help

</code>```

答:
No, it is not outside.
you have used form class at two places.
Loader is outside of form, not outside from form class. please check image

Edit:

```<code>error:function(jqXHR,textStatus,errorThrown){
                          console.log(data);
                          console.log("error");
                          $(".loader").hide();
                          $(".form").show();
                          $("#msg").html("Something went wrong !!!");
                          $("#msg").addClass("red-text");
                      }
</code>```

Remove console.log(data); from your error function.
Still not working then check the console for any error

Body:
My loader and form is not showing when I am using pressing button.My loader is outside form still it is not working. Please help me I tried it to solve many time but I couldn't .I am adding here my signup.jsp and Register.java  code details here. I have added Threadsleep(3000) to hold loader for 3 seconds still it is not working

package com.user;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class Register extends HttpServlet {

   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       try (PrintWriter out = response.getWriter()) {
           /* TODO output your page here. You may use following sample code. */
           /*out.println("<!DOCTYPE html>");
           out.println("");
           out.println("");
           out.println("<title>Servlet Register</title>");
           out.println("");
           out.println("");*/
           //Getting all the details from incoming from request
           String name=request.getParameter("user_name");
           String email=request.getParameter("user_email");
           String password=request.getParameter("user_password");
           //out.println(name);
           //out.println(email);
           //out.println(password);
           //connection
            try{
                Thread.sleep(3000);
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/youtube1","root","Vandana");

                //query
                String q="insert into user(name,email,password) value(?, ?, ?)";
                PreparedStatement pstmpt= con.prepareStatement(q);
                pstmpt.setString(1, name);
                pstmpt.setString(2, password);
                pstmpt.setString(3, email);

                pstmpt.executeUpdate();

                out.println("Done");
            }

            catch (Exception e){
               e.printStackTrace() ;
               out.println("Error");
            }

           //......
           //out.println("");
           //out.println("");
       }
   }

   // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
   /**
    * Handles the HTTP GET method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       processRequest(request, response);
   }

   /**
    * Handles the HTTP POST method.
    *
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       processRequest(request, response);
   }

   /**
    * Returns a short description of the servlet.
    *
    * @return a String containing servlet description
    */
   @Override
   public String getServletInfo() {
       return "Short description";
   }// </editor-fold>

}

**signup.jsp**

<%--
   Document   : signup
   Created on : 01-Feb-2022, 2:13:08 PM
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       <title>JSP Page</title>

       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

Register Here !!

                                <h5 id="msg" class="center-align"

                               <form action="Register" method="post" id="myform">
                                   <input type="text" name="user_name" placeholder="Enter user_name"\>
                                   <input type="password" name="user_password" placeholder="Enter password"\>
                                   <input type="email" name="user_email" placeholder="Enter your email"\>

                                   <button type="submit" name="btn" style="background-color:#b3e5fc;">Submit</button>

                               </form>

Please Wait....

```

please help

Body:
No, it is not outside.
you have used form class at two places.
Loader is outside of form, not outside from form class. please check image

Edit:

error:function(jqXHR,textStatus,errorThrown){
                          console.log(data);
                          console.log("error");
                          $(".loader").hide();
                          $(".form").show();
                          $("#msg").html("Something went wrong !!!");
                          $("#msg").addClass("red-text");
                      }

Remove console.log(data); from your error function.
Still not working then check the console for any error


问:
Can boost Pointer Container Library be used as thread safe container collection?
Can we use boost Pointer Container Library to keep an array of strings winth thread safe push and pop and all such operations?</p>

答: No is the answer. And now I have to make the answer last 30 characters when two would suffice.</p>


问:
What is the difference between using list and tuple in `.loc` operator of a single-indexed pandas dataframe?
I checked the documentation for:

Indexing

10 minutes to pandas

pandas.DataFrame.loc

I couldn't find the differences in those pages or in any SO posts (that I could easily search for).

I'm aware that the API reference page for pandas.DataFrame.loc mentions the following as one of the allowed inputs:

A list or array of labels, e.g. ['a', 'b', 'c'].

I've seen parts of the documentation where tuples are used only in the case of a MultiIndex dataframe. There's no mention of tuple being used in the case of non-MultiIndex / single-indexed dataframe.

My confusion is because I can still use a tuple and list almost interchangeably. For example:

data = [
    [ 2, 26, 55, 52],
    [82, 18, 63, 12],
    [36, 24, 78, 55],
    [83,  9, 68, 93],
    [95, 46, 29, 76],
]
df = pandas.DataFrame(data, columns=['col_a', 'col_b', 'col_c', 'col_d'])
```
<p>The following code works as if I'd used list instead:</p>
<pre class="lang-py prettyprint-override"><code>df.loc[:, ('col_a', 'col_b')]

df.loc[:, ('col_a', 'col_b')] = None
</code>```

I've seen errors in some cases. For instance, using df[('col_a', 'col_b')] instead of df[['col_a', 'col_b']] raises a KeyError. That's understandable.

Questions:

But why does it work for .loc operator (specifically, the column part)?

What are the caveats of using tuple in this way instead of the prescribed list approach?

Is there a documentation / post / blog that talks about this behavior extensively?

答:
I think because bug,
df.loc[:, ('col_a', 'col_b')] should raise error like df[('col_a', 'col_b')]

There is many another ways for select in Index and MultiIndex and some ways need discussion, why raise or not error.

 BUG: Index and MultiIndex KeyError cases and discussion #39775 .

Simple Index

Since the introduction of KeyError for missing keys in an index there have been quite a few use cases from different issues. I will try and link some of the issues if I see them.

My view is that KeyErrors for Index is fine, but MultiIndexes should be treated differently: you cannot always raise a KeyError for a single keys in a MultiIndex slice since a MultiIndex cannot always be reindexed.

MultiIndex

MultiIndexing is different. You cannot always reindex for one of two reasons:

The number of possible combinations of the index level values exceeds ram and is computationally slow.
If you are to add in a value or set of values to a MultiIndex level the process is ambiguous and expanding all combinations will lead to above problems.

For example, consider the MultiIndex levels: (a,b), (x,y,z). There are a maximum of 6 index tuples but practically one will work with indexes of much less than the maximum combinations (Since the combinations scale exponentially with the number of levels). Your MultiIndex is thus [(a,x), (a,z), (b,x), (b,y)].

I think you need to be able to index MultiIndexes with keys that are missing. As a rule I would suggest that slices which are an iterable do not yield KeyErrors. Here is a summary of some of the observances below for current behaviour:

```<code>[a, y] : KeyError
[a, [y]] : KeyError but should return empty (a in level0)
[[a], y] : KeyError but should return empty (y in level1)
[[a], [y]] : KeyError but should return empty
[a, !] : KeyError
[a, [!]] : returns empty
[[a], !] : KeyError (maybe OK since ! not in level1)
[[!], x] : returns empty (x in level1)
[[!], [!]] : returns empty
[!, !] : KeyError
</code>```

Body:
I checked the documentation for:

Indexing

10 minutes to pandas

pandas.DataFrame.loc

I couldn't find the differences in those pages or in any SO posts (that I could easily search for).

I'm aware that the API reference page for pandas.DataFrame.loc mentions the following as one of the allowed inputs:

A list or array of labels, e.g. ['a', 'b', 'c'].

I've seen parts of the documentation where tuples are used only in the case of a MultiIndex dataframe. There's no mention of tuple being used in the case of non-MultiIndex / single-indexed dataframe.

My confusion is because I can still use a tuple and list almost interchangeably. For example:

data = [
    [ 2, 26, 55, 52],
    [82, 18, 63, 12],
    [36, 24, 78, 55],
    [83,  9, 68, 93],
    [95, 46, 29, 76],
]
df = pandas.DataFrame(data, columns=['col_a', 'col_b', 'col_c', 'col_d'])

The following code works as if I'd used list instead:

df.loc[:, ('col_a', 'col_b')]

df.loc[:, ('col_a', 'col_b')] = None

I've seen errors in some cases. For instance, using df[('col_a', 'col_b')] instead of df[['col_a', 'col_b']] raises a KeyError. That's understandable.

Questions:

But why does it work for .loc operator (specifically, the column part)?

What are the caveats of using tuple in this way instead of the prescribed list approach?

Is there a documentation / post / blog that talks about this behavior extensively?

Body:
I think because bug,
df.loc[:, ('col_a', 'col_b')] should raise error like df[('col_a', 'col_b')]

There is many another ways for select in Index and MultiIndex and some ways need discussion, why raise or not error.

 BUG: Index and MultiIndex KeyError cases and discussion #39775 .

Simple Index

Since the introduction of KeyError for missing keys in an index there have been quite a few use cases from different issues. I will try and link some of the issues if I see them.

My view is that KeyErrors for Index is fine, but MultiIndexes should be treated differently: you cannot always raise a KeyError for a single keys in a MultiIndex slice since a MultiIndex cannot always be reindexed.

MultiIndex

MultiIndexing is different. You cannot always reindex for one of two reasons:

The number of possible combinations of the index level values exceeds ram and is computationally slow.
If you are to add in a value or set of values to a MultiIndex level the process is ambiguous and expanding all combinations will lead to above problems.

For example, consider the MultiIndex levels: (a,b), (x,y,z). There are a maximum of 6 index tuples but practically one will work with indexes of much less than the maximum combinations (Since the combinations scale exponentially with the number of levels). Your MultiIndex is thus [(a,x), (a,z), (b,x), (b,y)].

I think you need to be able to index MultiIndexes with keys that are missing. As a rule I would suggest that slices which are an iterable do not yield KeyErrors. Here is a summary of some of the observances below for current behaviour:

[a, y] : KeyError
[a, [y]] : KeyError but should return empty (a in level0)
[[a], y] : KeyError but should return empty (y in level1)
[[a], [y]] : KeyError but should return empty
[a, !] : KeyError
[a, [!]] : returns empty
[[a], !] : KeyError (maybe OK since ! not in level1)
[[!], x] : returns empty (x in level1)
[[!], [!]] : returns empty
[!, !] : KeyError


问:
Force HTTP calls go over WIFI network on Xamarin iOS
I have an app, developed in Xamarin Forms, which connects programmatically to a WIFI (with no internet access) exposed by an IoT device.

This is the code I use to connect to the wifi network:

```<code>NEHotspotConfiguration configuration = new NEHotspotConfiguration("ssid");
Device.BeginInvokeOnMainThread(() =>
{
    NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(configuration, (NSError error) =>
    {
        if (error != null)
        {
            if (error.LocalizedDescription == "already associated.")
            {
                // connected!
                CommunicateConnected();
            }
            else
            {
                // not connected
                CommunicateNotConnected();
            }
        }
        else
        {
            // connected!
            CommunicateNotConnected();
        }
    });
});
</code>```

Once the connection is successfully established the app performs some HTTP calls to the IP of the IoT device.

Sometimes it happens that the HTTP calls go over the cellular data connection instead of WIFI connection (because the joined network has no internet connection?) and they fail. (Simply, I see that the 4G icon is still visible instead of the one representing the WIFI connection). The switch between mobile connection and WIFI connection, in these cases, happen after some minutes.

Is there a way to force the HTTP calls to go over the just joined network?

答:
You can set cellular data use for apps and services.

Go to Settings  > Cellular, then turn Cellular Data on or off for any app (such as Maps) or service (such as Wi-Fi Assist) that can use cellular data.

If a setting is off, iPhone uses only Wi-Fi for that service.

Note:

Wi-Fi Assist is on by default. If Wi-Fi connectivity is poor, Wi-Fi Assist automatically switches to cellular data to boost the signal. Because you stay connected to the internet over cellular when you have a poor Wi-Fi connection, you might use more cellular data, which may incur additional charges depending on your data plan. See the Apple Support article About Wi-Fi Assist.

Body:
I have an app, developed in Xamarin Forms, which connects programmatically to a WIFI (with no internet access) exposed by an IoT device.

This is the code I use to connect to the wifi network:

NEHotspotConfiguration configuration = new NEHotspotConfiguration("ssid");
Device.BeginInvokeOnMainThread(() =>
{
    NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(configuration, (NSError error) =>
    {
        if (error != null)
        {
            if (error.LocalizedDescription == "already associated.")
            {
                // connected!
                CommunicateConnected();
            }
            else
            {
                // not connected
                CommunicateNotConnected();
            }
        }
        else
        {
            // connected!
            CommunicateNotConnected();
        }
    });
});

Once the connection is successfully established the app performs some HTTP calls to the IP of the IoT device.

Sometimes it happens that the HTTP calls go over the cellular data connection instead of WIFI connection (because the joined network has no internet connection?) and they fail. (Simply, I see that the 4G icon is still visible instead of the one representing the WIFI connection). The switch between mobile connection and WIFI connection, in these cases, happen after some minutes.

Is there a way to force the HTTP calls to go over the just joined network?


问:
Time complexity with a logarithmic recursive function
Could someone please explain the time complexity of the following bit of code:

def fn(n):
    if n==0:
       linear_time_fn(n) #some function that does work in O(n) time
    else:
       linear_time_fn(n)
       fn(n//5)
```

I was under the impression that the complexity of the code is O(nlogn) while the actual complexity is be O(n). How is this function different from one like merge sort which has an O(nlogn) complexity? Thanks.

答:
You are correct that this is O(n).  The difference between this and merge sort is that this makes one recursive call, while merge sort makes two.

So for this code, you have

One problem of size n

One problem of size n\2

One problem of size n\4

...

With merge sort, you have

One problem of size n

which yields two problems of size n/2

which yields four problems of size n/4

...

which yields n problems of size 1.

In the first case, you have n + n/2 + n/4 + ... = 1.

In the second case you have 1 + 1 + 1 + .... 1, but after log2(n) steps, you reach the end.

Body:
Could someone please explain the time complexity of the following bit of code:

def fn(n):
    if n==0:
       linear_time_fn(n) #some function that does work in O(n) time
    else:
       linear_time_fn(n)
       fn(n//5)

I was under the impression that the complexity of the code is O(nlogn) while the actual complexity is be O(n). How is this function different from one like merge sort which has an O(nlogn) complexity? Thanks.


问:
How to create a dual action (normal + switch) preference in Android?
Is there any way to achieve this dual-action preference item?  Preferably via a third party library but via a simple implementation if necessary.

The 'wireless debugging' preference in Android's developer mode is a dual preference. It's the only one I've seen and I have no idea what this preference is called or if any Jetpack or other libraries expose such a thing.

Tapping the left part (1) opens a new screen, while tapping the right toggle (2) simply toggles the preference without changing screens. There's also a little divider between them to indicate that they have separate actions.

答:
Well There is an element in AndroidStudio Call Switch which is similar to this use that in XML file</p>
```<code><Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

Body:
Well There is an element in AndroidStudio Call Switch which is similar to this use that in XML file

<Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />