问:
How to separate html from js?
I wrote the program based on the tutorial and now I want to separate the html code from js but it doesn't work. Some lines of js code have a connection to the database sent as paramentr and after separating the html codes from js it doesn't work ... anyone have any idea? Here I put the entire index.php file with js code below. In this version it works, however, when I separate it into a separate js file it doesn't work anymore. At the top of the code are the function declarations in php which are then used in the js code</p>

```<code><?php
//index.php

session_start();

if (!isset($_SESSION['zalogowany']))
{
    header('Location: index.php');
    exit();
}

$connect = new PDO("mysql:host=localhost;dbname=bukowski2", "root", "");

//Utworzenie tablicy walut

 $userArray = array();
 $query = "SELECT * FROM currencies";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $i=0;
 foreach($result as $row)
 {
  $userArray[$i]=$row["currency"];
  $i=$i+1;
 }

function fill_unit_select_box0($connect)
{
 $output = '';
 $query = "SELECT * FROM item_name";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["item_name"].'">'.$row["item_name"].'</option>';
 }

 return $output;
}

function fill_unit_select_box1($connect)
{
 $output = '';
 $query = "SELECT * FROM sizes";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["sizes"].'">'.$row["sizes"].'</option>';
 }

 return $output;
}

function fill_unit_select_box2($connect)
{
 $output = '';
 $query = "SELECT * FROM users";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["user"].'">'.$row["user"].'</option>';
 }

 return $output;
}

function fill_unit_select_box3($connect)
{
 $output = '';
 $query = "SELECT * FROM currencies";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["currency"].'">'.$row["currency"].'</option>';
 }

 return $output;
}

function create_currencies_table($connect){
     $userArray = array();
     $query = "SELECT * FROM currencies";
     $statement = $connect->prepare($query);
     $statement->execute();
     $result = $statement->fetchAll();
     $i=0;
     foreach($result as $row)
     {
      $userArray[$i]=$row["currency"];
      $i=$i+1;
     }
     return json_encode($userArray);
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Formularz sprzedaży</title>
  <script src="jquery-3.5.0.min.js" defer></script>
  <link rel="stylesheet" href="bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />
  <script src="jquery-3.5.0.min.js"></script>
  <script src="js.js" defer></script>
 </head>
 <body>
    <?php
    $_SESSION['sales_date']=date('Y-m-d');
    echo '<p class="logged">Zalogowany: '.$_SESSION['user'].' | '.$_SESSION['sales_date'].' |  [ <a href="logout.php">Wyloguj się</a> ]</p>';
    ?>

  <br />
  <div class="container">
   <h3 align="center">Formularz sprzedaży</h3><br />
   <form method="post" id="insert_form">
    <div class="table-repsonsive">
     <span id="error"></span>
    <table class="table table-bordered" id="item_table">
        <thead>
            <tr>
                <th width=70>Lp.</th>
                <th width=300>Nazwa i kolor produktu</th>
                <th width=100>Rozmiar</th>
                <th width=100>Cena PLN</th>
                <th width=100>KARTA</th>
                <th width=200>Inna waluta1</th><!--Inna waluta czyli kolumna w której mamy 2 komórki   -->
                <th width=150>Od</th>
                <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">Dodaj</span></button></th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th colspan="3">SUMA</th>
                <th width=100><input readonly value=0 type="text" class="form-control" id="total_amount_pln"/></th>
                <th width=100><input readonly value=0 type="text" class="form-control" id="total_cart_payment"/></th>
                <th width=200><input readonly value=0 type="text" class="form-control" id="total_amount_oc"/></th><!--Kolumna w której mamy 2 komórki  -->
                <th colspan="2"> </th>
            </tr>
        </tfoot>
    </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Wyślij" />
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>

//deklaracja i definicja funkcji dokonującej zmian w polu inna waluta//
function change_oc(){
    var array1=[],array2=[],array3=[],array4=[],array5=[];
    var x=0,y=0,z=0,m=0,j=0,k=0; //iteratory
    var suma=0;
    var string_suma;

    $('.total_oc1').each(function(){
        array1[x]=$(this).val();
        x++;
        z++;
    });
    $('.total_oc2').each(function(){
        array2[y]=$(this).val();
        y++;
    });
    currency_table.forEach(function(index){
        suma=0;
        for(var i=0;i<z;i++){
            if(array2[i]==index){
                num=array1[i];
                suma+=~~parseInt(num);
            }
        }
        array3[m]=suma;
        m++;
    });
    currency_table.forEach(function(index2){
        if(array3[j]==0){
            array4[j]=0;
        }else{
            array4[j]=array3[j]+index2;
        }
        j++
    });
    array4.forEach(function(index3){
        if(index3!=0){
            array5[k]=index3;
            k++;
        }
    });
    string_suma=array5.join("+");
    $('#total_amount_oc').val((string_suma)||0);
}

//deklaracja i definicja funkcji dokonującej zmian w polu cena PLN//
function total_pln(){
    var suma=0;
    $('.total_pln').each(function(){
        num=($(this).val()||0);
        suma+=parseInt(num);
     });
     if (suma!=0)
        suma=suma+"zł";
    else
        suma=suma;
     $('#total_amount_pln').val((suma)||0);
}

//deklaracja i definicja funkcji dokonującej zmian w polu cena KARTA//
function total_cart_payment(){
    var suma=0;
    $('.cart_payment').each(function(){
        num=($(this).val()||0);
        suma+=parseInt(num);
     });
     if (suma!=0)
        suma=suma+"zł";
    else
        suma=suma;
     $('#total_cart_payment').val((suma)||0);
 }

//deklaracja i definicja funkcji usuwającej wiersz//
function remove_row(){
    $(this).closest('tr').remove();
    var count=0;
    $('.lp').each(function(){
        count=count+1;
        $(this).text(count);
        change_oc();
    });
}
//deklaracja i definicja funkcji wysyłającej dane//

function submit (event){
    event.preventDefault();
    var error = '';
    var count_item_name_color=1;
    var count_item_price=1;

    var form_data = $(this).serialize();
    if(error == ''){
        $.ajax({
            url:"insert.php",
            method:"POST",
            data:form_data,
            success:function(data){
                if(data == 'ok'){
                    $('#item_table').find("tr:gt(0)").remove();
                    $('#error').html('<div class="alert alert-success">Dane zostały wysłane</div>');
                }
            }
        });
    }
    else{
        $('#error').html('<div class="alert alert-danger">'+error+'</div>');
    }
}

//deklaracja i definicja funkcji dodającej wiersz do tableli//
function add_row(){
    var html = '';
    html += '<tr>';
    html += '<td class="lp"></td>';
    html += '<td><select required name="item_name_color[]" class="form-control item_name_color"><option value=""><?php echo fill_unit_select_box0($connect); ?></option></select></td>';
    html += '<td><select required name="size_id[]" class="form-control size_id"><option value=""><?php echo fill_unit_select_box1($connect); ?></option></select></td>';
    html += '<td><input required type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value=0  autocomplete="off" name="total_pln[]" class="form-control total_pln" /></td>';
    html += '<td><input required type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value=0  autocomplete="off" name="total_cart_payment[]" class="form-control cart_payment" /></td>';
    html += '<td><input style="width:45%; display: inline-block; margin-right:5px;" required type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value=0  autocomplete="off" name="total_oc1[]" class="form-control total_oc1" /><select srequired style=" display: inline-block; width:45%;" name="total_oc2[]" class="form-control total_oc2"><option value=""><?php echo fill_unit_select_box3($connect); ?></option></select></td>';
    html += '<td><select srequired name="item_from[]" class="form-control item_from"><option value=""><?php echo fill_unit_select_box2($connect); ?></option></select></td>';
    html += '<td><button type="button" name="remove" class="remove btn btn-danger btn-sm "><span>Usuń</span></button></td></tr>';

    $('#item_table').append(html);
    var count=0;
    $('.lp').each(function(){
    count=count+1;
    $(this).text(count);
    });
}

$(document).ready(function(){

//dodawanie wiersza do tableli//
$(document).on('click', '.add', add_row);

//Dokananie obliczenia po wprowadzeniu zmian w polu cana PLN//
$(document).on('keyup','.total_pln',total_pln);

//Dokananie obliczenia po wprowadzeniu zmian w polu cana PLN//
 $(document).on('keyup','.cart_payment',total_cart_payment);

//Utworzenie tablicy walut która będzie użyta dla funkcji change_oc//
currency_table = <?php echo json_encode($userArray); ?>;

//Dokananie obliczenia po wprowadzeniu zmian w polach inna waluta//
$(document).on('keyup click','.total_oc1,.total_oc2',change_oc);

//Usunięcie wiersza//
$(document).on('click','.remove',remove_row);

//Wysłanie danych//
$('#insert_form').on('submit',submit);

});
</script>
</code>```

答:
Just in case you're not yet aware, PHP runs on the server, before the server sends HTML, CSS and JavaScript to the browser. The PHP and the JavaScript never interact! So with that said, I'm gonna guess that this line is giving you trouble:

currency_table = < ?php echo json_encode($userArray); ? >;

because it looks as though it's in your JavaScript! It will work if this PHP/JavaScript thing is left in your HTML, between script tags. Looks to me like the rest of the JavaScript can be separated. Give it a try!

Title: How to separate html from js?

Body:
I wrote the program based on the tutorial and now I want to separate the html code from js but it doesn't work. Some lines of js code have a connection to the database sent as paramentr and after separating the html codes from js it doesn't work ... anyone have any idea? Here I put the entire index.php file with js code below. In this version it works, however, when I separate it into a separate js file it doesn't work anymore. At the top of the code are the function declarations in php which are then used in the js code

<?php
//index.php

session_start();

if (!isset($_SESSION['zalogowany']))
{
    header('Location: index.php');
    exit();
}

$connect = new PDO("mysql:host=localhost;dbname=bukowski2", "root", "");

//Utworzenie tablicy walut

 $userArray = array();
 $query = "SELECT * FROM currencies";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $i=0;
 foreach($result as $row)
 {
  $userArray[$i]=$row["currency"];
  $i=$i+1;
 }

function fill_unit_select_box0($connect)
{
 $output = '';
 $query = "SELECT * FROM item_name";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["item_name"].'">'.$row["item_name"].'</option>';
 }

 return $output;
}

function fill_unit_select_box1($connect)
{
 $output = '';
 $query = "SELECT * FROM sizes";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["sizes"].'">'.$row["sizes"].'</option>';
 }

 return $output;
}

function fill_unit_select_box2($connect)
{
 $output = '';
 $query = "SELECT * FROM users";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["user"].'">'.$row["user"].'</option>';
 }

 return $output;
}

function fill_unit_select_box3($connect)
{
 $output = '';
 $query = "SELECT * FROM currencies";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option  value="'.$row["currency"].'">'.$row["currency"].'</option>';
 }

 return $output;
}

function create_currencies_table($connect){
     $userArray = array();
     $query = "SELECT * FROM currencies";
     $statement = $connect->prepare($query);
     $statement->execute();
     $result = $statement->fetchAll();
     $i=0;
     foreach($result as $row)
     {
      $userArray[$i]=$row["currency"];
      $i=$i+1;
     }
     return json_encode($userArray);
}

?>
<!DOCTYPE html>

  <title>Formularz sprzedaży</title>

  <link rel="stylesheet" href="bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />

    <?php
    $_SESSION['sales_date']=date('Y-m-d');
    echo '
Zalogowany: '.$_SESSION['user'].' | '.$_SESSION['sales_date'].' |  [ Wyloguj się ]
';
    ?>

Formularz sprzedaży

   <form method="post" id="insert_form">

                Lp.
                Nazwa i kolor produktu
                Rozmiar
                Cena PLN
                KARTA
                Inna waluta1
                Od
                <button type="button" name="add" class="btn btn-success btn-sm add">Dodaj</button>

                SUMA
                <input readonly value=0 type="text" class="form-control" id="total_amount_pln"/>
                <input readonly value=0 type="text" class="form-control" id="total_cart_payment"/>
                <input readonly value=0 type="text" class="form-control" id="total_amount_oc"/>

      <input type="submit" name="submit" class="btn btn-info" value="Wyślij" />

   </form>


来源: stackexchange

问:
Angular - convert to lowercase in an input field
i have an email input, i want when i write in the input uppercase letters it converts them into lowercase letters

i tried this method but it shows me an errer

ERROR RangeError: Maximum call stack size exceeded

```<code><input type="text" formControlName="mail" (ngModelChange)="toLowerCase($event)">

private toLowerCase(event): void {
    this.cmOrganizationForm.get('mail').setValue(event.toLowerCase());
}
</code>```

答:
this function in angular 6 for underscore and lowercase: </p>

```<code> underscore(selectkpi){
    this.selectedUnderKpi = selectkpi.replace(' ', '_').toLowerCase();
    var a = this.selectedUnderKpi
    console.log("ini = ",a);
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have an email input, i want when i write in the input uppercase letters it converts them into lowercase letters

i tried this method but it shows me an errer

ERROR RangeError: Maximum call stack size exceeded

<input type="text" formControlName="mail" (ngModelChange)="toLowerCase($event)">

private toLowerCase(event): void {
    this.cmOrganizationForm.get('mail').setValue(event.toLowerCase());
}

Body:
this function in angular 6 for underscore and lowercase:

 underscore(selectkpi){
    this.selectedUnderKpi = selectkpi.replace(' ', '_').toLowerCase();
    var a = this.selectedUnderKpi
    console.log("ini = ",a);
  }


问:
assign an existing id value to same record and new id to new record
I'm trying to see if I can assign an id to a name every time that same record comes in. For instance, if I assign an ID E001 to John Doe, I want to be able to assign that same value to John every time I see a record of John. And if a new person comes into the picture, I want to pick the next ID from a list I created (table ID) and assign it to that person and so on. I'm open to suggestions or ideas or better ways on how to go about doing it either SQL (preferably) or some ETL approach. Thanks

Month 1 file (or another table in oracle)

```<code>Name       Addr      Location
------------------------------
John Doe  123 Main   NA
John Doe  123 Main   NA
Bob Lava  456 Tel    US
</code>```

ORACLE_TABLE in month 1

```<code>ID    Name       Addr       Location
-------------------------------------
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US
</code>```

Month 2 files (or oracle table)

```<code>Name       Addr       Location
-------------------------------
Denny Fry 456 str    AB
John Doe  123 Main   NA
John Doe  123 Main   NA
Bob Lava  456 Tel    US
</code>```

ORACLE TABLE in month 2 (simply append month 2 files to existing data but using previously assigned ID for existing records and a new id for a new record)

```<code>ID    Name       Add       Location
------------------------------------
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US
E003   Denny Fry 456 str    AB
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US
</code>```

ID table list (used to assign IDs to records)

```<code>E001
E002
E003
E004
B001
</code>```

答:
I can suggest a SQL solution in which first do union all and then you can use dense_rank() as following

```<code>select
  Name,
  Addr,
  Location,
  'E00' || dense_rank() over (order by Name) as EmpId
from
(
  select
    Name,
    Addr,
    Location
  from monthOne

  union all

  select
    Name,
    Addr,
    Location
  from monthTwo
) val
order by
 EmpId
</code>```

output:

```<code>*-----------------------------------*
| NAME       ADDR   LOCATION  EMPID |
*-----------------------------------*
|Bob Lava   456 Tel    US     E001  |
|Bob Lava   456 Tel    US     E001  |
|Denny Fry  456 str    AB     E002  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
*-----------------------------------*
</code>```

Body:
I'm trying to see if I can assign an id to a name every time that same record comes in. For instance, if I assign an ID E001 to John Doe, I want to be able to assign that same value to John every time I see a record of John. And if a new person comes into the picture, I want to pick the next ID from a list I created (table ID) and assign it to that person and so on. I'm open to suggestions or ideas or better ways on how to go about doing it either SQL (preferably) or some ETL approach. Thanks

Month 1 file (or another table in oracle)

Name       Addr      Location
------------------------------
John Doe  123 Main   NA
John Doe  123 Main   NA
Bob Lava  456 Tel    US

ORACLE_TABLE in month 1

ID    Name       Addr       Location
-------------------------------------
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US

Month 2 files (or oracle table)

Name       Addr       Location
-------------------------------
Denny Fry 456 str    AB
John Doe  123 Main   NA
John Doe  123 Main   NA
Bob Lava  456 Tel    US

ORACLE TABLE in month 2 (simply append month 2 files to existing data but using previously assigned ID for existing records and a new id for a new record)

ID    Name       Add       Location
------------------------------------
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US
E003   Denny Fry 456 str    AB
E001   John Doe  123 Main   NA
E001   John Doe  123 Main   NA
E002   Bob Lava  456 Tel    US

ID table list (used to assign IDs to records)

E001
E002
E003
E004
B001

Body:
I can suggest a SQL solution in which first do union all and then you can use dense_rank() as following

select
  Name,
  Addr,
  Location,
  'E00' || dense_rank() over (order by Name) as EmpId
from
(
  select
    Name,
    Addr,
    Location
  from monthOne

  union all

  select
    Name,
    Addr,
    Location
  from monthTwo
) val
order by
 EmpId

output:

*-----------------------------------*
| NAME       ADDR   LOCATION  EMPID |
*-----------------------------------*
|Bob Lava   456 Tel    US     E001  |
|Bob Lava   456 Tel    US     E001  |
|Denny Fry  456 str    AB     E002  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
|John Doe   123 Main   NA     E003  |
*-----------------------------------*


问:
C Programming : Need to get output of the number of letters in a string. (Newbie)
I am trying to complete an assignment, part of the assignment is to print the output of the number of letters in a string.

I was trying to reverse engineer the code that the instructor gave us, but his code is not even working. Or am I doing something wrong or missing something?

```<code>#include <stdio.h>
#include <string.h>

int main() {
    char str1[13] = "Hello";
    char str2[13] = "World";

    /* concatenates str1 and str2 */
    strcat(str1, str2);
    printf("strcat(str1, str2): %s\n", str1);

    /* total lenghth of str1 after concatenation */
    len = strlen(str1);
    printf("strlen(str1) : %d\n", len);
    return 0;
}
</code>```

The errors I am getting is:

test2.c:13:5: error: use of undeclared identifier 'len'
    len = strlen(str1);
    ^
test2.c:14:35: error: use of undeclared identifier 'len'
    printf("strlen(str1) : %d\n", len);

If I am not using the right identifier, how do I know which identifier covers the specific commands?

I will also be incorporating the following code in my assignment, any suggestions are greatly appreciated.

```<code>char first[10] = "first";
char last[10] = "last";
char  full[20] = " ";

strcat(full, first);
strcat(full, " ");
strcat(full, last);
</code>```

Ultimately I need to print the name (first, last, and full name), and then print the number of characters of each.

Thank you for your assistance.

答:
regarding:

```<code>len = strlen(str1);
printf("strlen(str1) : %d\n", len);
</code>```

the function: strlen() returns a size_t not a int and you need to declare the 'type' for every variable:

therefore:

```<code>size_t len = strlen(str1);
printf("strlen(str1) : %d\n", len);
</code>```

But the proper way to output a size_t is with the format specifier %zu  not: %d

Therefore:

```<code>size_t len = strlen(str1);
printf("strlen(str1) : %zu\n", len);
</code>```

regarding:

```<code>char  full[20] = " ";
strcat(full, first);
</code>```

The array full[] is being set to contain a space in the first byte.  Using strcat() will keep that space, which you probably don't want.  Suggest:

```<code>char  full[20] = {'\0'};
strcat(full, first);
strcat(full, " ");
strcat(full, last);
</code>```

or, not so good, because it results in a waste of a string containing nothing but a space and a NUL byte

```<code>char  full[20] = " ";
strcpy(full, first);
strcat(full, " ");
strcat(full, last);
</code>```

Body:
I am trying to complete an assignment, part of the assignment is to print the output of the number of letters in a string.

I was trying to reverse engineer the code that the instructor gave us, but his code is not even working. Or am I doing something wrong or missing something?

#include <stdio.h>
#include <string.h>

int main() {
    char str1[13] = "Hello";
    char str2[13] = "World";

    /* concatenates str1 and str2 */
    strcat(str1, str2);
    printf("strcat(str1, str2): %s\n", str1);

    /* total lenghth of str1 after concatenation */
    len = strlen(str1);
    printf("strlen(str1) : %d\n", len);
    return 0;
}

The errors I am getting is:

test2.c:13:5: error: use of undeclared identifier 'len'
    len = strlen(str1);
    ^
test2.c:14:35: error: use of undeclared identifier 'len'
    printf("strlen(str1) : %d\n", len);

If I am not using the right identifier, how do I know which identifier covers the specific commands?

I will also be incorporating the following code in my assignment, any suggestions are greatly appreciated.

char first[10] = "first";
char last[10] = "last";
char  full[20] = " ";

strcat(full, first);
strcat(full, " ");
strcat(full, last);

Ultimately I need to print the name (first, last, and full name), and then print the number of characters of each.

Thank you for your assistance.

Body:
regarding:

len = strlen(str1);
printf("strlen(str1) : %d\n", len);

the function: strlen() returns a size_t not a int and you need to declare the 'type' for every variable:

therefore:

size_t len = strlen(str1);
printf("strlen(str1) : %d\n", len);

But the proper way to output a size_t is with the format specifier %zu  not: %d

Therefore:

size_t len = strlen(str1);
printf("strlen(str1) : %zu\n", len);

regarding:

char  full[20] = " ";
strcat(full, first);

The array full[] is being set to contain a space in the first byte.  Using strcat() will keep that space, which you probably don't want.  Suggest:

char  full[20] = {'\0'};
strcat(full, first);
strcat(full, " ");
strcat(full, last);

or, not so good, because it results in a waste of a string containing nothing but a space and a NUL byte

char  full[20] = " ";
strcpy(full, first);
strcat(full, " ");
strcat(full, last);


问:
What word is abbreviated by "N" in names of destructive Lisp functions?
What word is abbreviated by "N" in names of destructive Lisp functions?</p>

答:
Here is a direct answer from Linearity's link:

The N stands for non-consing, meaning it doesn't need to allocate any new cons cells.

Instead of allocating new cells, the old cells are reused resulting
in destructive/impure modifications.

Signalling destructive behavior is critical, but it's also nice to know that the non-consing variants are typically faster as they don't copy objects and leave garbage lying around.

The specific section containing this information is titled: "Destructive" Operations

ContentLicense: CC BY-SA 2.5


问:
i'm getting error in php code. trying to access input value in php on wamp server. it gives error as undefined variable but my code is correct

<form  action="add.php" method="post"  >
<input type="text" name="user" />
<input  type="number" name="age" />
<input type="submit" />
</form>

======================================================================================================
//php code

<?php
$n=$_post['user'];
$a=$_post['age'];
echo "Hello $n your age is $a";
?>```

i am getting the error message that the variable is not found but my code is correct how to resolve this issue

答:
The official superglobal's variable name is $_POST. You cannot replace it with $_post as it is case-sensitive.

Shoutout to @Barmar in the comments.

Body:
<form  action="add.php" method="post"  >
<input type="text" name="user" />
<input  type="number" name="age" />
<input type="submit" />
</form>

======================================================================================================
//php code

<?php
$n=$_post['user'];
$a=$_post['age'];
echo "Hello $n your age is $a";
?>

i am getting the error message that the variable is not found but my code is correct how to resolve this issue


问:
Push list of elements to component in React
I want to build a sidebar component similar to the one in this image:
Instead of passing the child components as Objects with text values through the props, I'd like to create a separate component for each key-value pair in each element in the list. For example: if the list has 3 elements, there should be 3 components for each element in the list.

Here is my code so far:

sidebarcomponents.js:

```<code>import React from 'react'

function SidebarComponents({ name, title, selected, onSelect }) {
  const style = {
    cursor: 'pointer'
  }

  return (
    <div
      name={name}
      title={title}
      style={style}
      onClick={() => {
        if (onSelect) onSelect(name)
      }}
    >

    </div>
  )
}

export default SidebarComponents

</code>```

sidebar.js:

```<code>
import React, { useEffect, useState } from 'react'
import SidebarComponents from '../../components/Sidebar1/Sidebar'

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: 'Overview', title: 'Overview' },
      { name: 'SPO2', title: 'SPO2' }
    ]
  })

  return (
    <div>
      {selectedComponent.componentsName.map(componentsName => {
        return (
          <SidebarComponents
            name={componentsName.name}
            title={componentsName.title}
          />
        )
      })}
    </div>
  )
}

export default Sidebar
</code>```

How can I change my code to map a list child components rather than a list of objects that represent them?

I hope that my question is clear.

答:
You need to render the name within the DIV inside the component and not pass it on as a prop to div like

```<code>function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    return (
        <div
            title = {title}
            style={style}
            onClick={() => {if (onSelect) onSelect(name)}}
        >
           {name}
        </div>
    )

}
</code>```

Also pass on the onSelect and selected prop to the SidebarComponents when you are rendering it after mapping

Body:
I want to build a sidebar component similar to the one in this image:
Instead of passing the child components as Objects with text values through the props, I'd like to create a separate component for each key-value pair in each element in the list. For example: if the list has 3 elements, there should be 3 components for each element in the list.

Here is my code so far:

sidebarcomponents.js:

import React from 'react'

function SidebarComponents({ name, title, selected, onSelect }) {
  const style = {
    cursor: 'pointer'
  }

  return (

 {
        if (onSelect) onSelect(name)
      }}
    >

  )
}

export default SidebarComponents

sidebar.js:

import React, { useEffect, useState } from 'react'
import SidebarComponents from '../../components/Sidebar1/Sidebar'

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: 'Overview', title: 'Overview' },
      { name: 'SPO2', title: 'SPO2' }
    ]
  })

  return (

      {selectedComponent.componentsName.map(componentsName => {
        return (
          <SidebarComponents
            name={componentsName.name}
            title={componentsName.title}
          />
        )
      })}

  )
}

export default Sidebar

How can I change my code to map a list child components rather than a list of objects that represent them?

I hope that my question is clear.

Body:
You need to render the name within the DIV inside the component and not pass it on as a prop to div like

function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    return (
        <div
            title = {title}
            style={style}
            onClick={() => {if (onSelect) onSelect(name)}}
        >
           {name}
        </div>
    )

}

Also pass on the onSelect and selected prop to the SidebarComponents when you are rendering it after mapping


问:
How to update data on a webpage using Flask?
I am trying to call a class method which then returns a list such as ['Station: 0', 'Place1: 2', 'Extension12: 4'] and then display this list in flask webpage. My problem is, When the list is updated by the call_agent.Main_Agent() method, to something like this ['Station: 0', 'Place2: 2', 'Extension12: 4'] the webpage does not update the records. I was wondering what could be the problem

Here is my code below:

```<code>file_path = '../SAPS_Forecast/Dockets.txt'

app = Flask(__name__)

call_agent = UtilityAgent(file_path)

path_sequence = call_agent.Main_Agent()

@app.route('/forecast.html')
def My_Forecast():
    return render_template('./forecast.html', post=path_sequence)
</code>```

答: Even I used to get the same error. What I did was saved the data in an external database like sqlite or MySql and in the route function, I retrieve the data directly from the database. And then after reloading, the web-page updates.</p>

Body:
I am trying to call a class method which then returns a list such as ['Station: 0', 'Place1: 2', 'Extension12: 4'] and then display this list in flask webpage. My problem is, When the list is updated by the call_agent.Main_Agent() method, to something like this ['Station: 0', 'Place2: 2', 'Extension12: 4'] the webpage does not update the records. I was wondering what could be the problem

Here is my code below:

file_path = '../SAPS_Forecast/Dockets.txt'

app = Flask(__name__)

call_agent = UtilityAgent(file_path)

path_sequence = call_agent.Main_Agent()

@app.route('/forecast.html')
def My_Forecast():
    return render_template('./forecast.html', post=path_sequence)


问:
C++ The loop in my switch format isn't allowing me to display menu options or accept input?
I'm needing to write a loan program for a course and I have this bit of code thus far:

```<code>    /*
    Project: Course Project - Loan Calculator
    Program Description: To calculate customer's loan
 information including interest rate, monthly
 payment and number of months payments will be
 required for.
 Developer: ___________
 Last Update Date: June 1st, 2020
 */

#include <iostream>
#include <string>

//variables listed here
double loanAmt = 0, intRate = 0, loanLength = 0;
std::string CustName[0];
int choice; //menu choice identifier

using namespace std;
int main()
{
    //Welcome User
    cout << "Thank you for using our calculator." << endl;
    cout << endl;
    cout << "Please enter the number of your preferred calculator and press 'Enter': " << endl;
    cout << endl;
    cin >> choice;

    {
        while (choice !=4);
        switch (choice)
        {
            case 1:
                cout << "Monthly Payment Calculator:";
                cout << endl;
                break;
            case 2:
                cout << "Interest Rate Calculator:";
                cout << endl;
                break;
            case 3:
                cout << "Payment Term (In Months):";
                cout << endl;
            case 4:
                cout << "Exit Calculator:";

            default: //all other choices
                cout << "Please Select A Valid Option.";
                break;

        }
    }
}
</code>```

I've tried moving the cin << choice; to many different spots, including inside of the while loop written for the switch, but I can only seem to get it to show the prompt for the menu, but not the menu options themselves and it isn't taking input. If it makes a difference, I'm using Xcode for the first time and I need it to run there as I can't run C++ on my version of Visual studio (on Mac). Where may I have gone wrong here and any insight into why my version is wrong is appreciated as I'm still very new to coding overall. Thank you.

答:
You had this:

```<code>while (choice !=4);
</code>```

This makes it so that your code never continues further than this while loop. Unless your compiler removes this line during optimization.

This is the correct way:

```<code>    while (choice !=4) {
        switch (choice)
        {
            case 1:
                cout << "Monthly Payment Calculator:";
                cout << endl;
                break;
            case 2:
                cout << "Interest Rate Calculator:";
                cout << endl;
                break;
            case 3:
                cout << "Payment Term (In Months):";
                cout << endl;
            case 4:
                cout << "Exit Calculator:";

            default: //all other choices
                cout << "Please Select A Valid Option.";
                break;

        }
        cin >> choice; // have it right after the switch
   }
</code>```

Body:
I'm needing to write a loan program for a course and I have this bit of code thus far:

    /*
    Project: Course Project - Loan Calculator
    Program Description: To calculate customer's loan
 information including interest rate, monthly
 payment and number of months payments will be
 required for.
 Developer: ___________
 Last Update Date: June 1st, 2020
 */

#include <iostream>
#include <string>

//variables listed here
double loanAmt = 0, intRate = 0, loanLength = 0;
std::string CustName[0];
int choice; //menu choice identifier

using namespace std;
int main()
{
    //Welcome User
    cout << "Thank you for using our calculator." << endl;
    cout << endl;
    cout << "Please enter the number of your preferred calculator and press 'Enter': " << endl;
    cout << endl;
    cin >> choice;

    {
        while (choice !=4);
        switch (choice)
        {
            case 1:
                cout << "Monthly Payment Calculator:";
                cout << endl;
                break;
            case 2:
                cout << "Interest Rate Calculator:";
                cout << endl;
                break;
            case 3:
                cout << "Payment Term (In Months):";
                cout << endl;
            case 4:
                cout << "Exit Calculator:";

            default: //all other choices
                cout << "Please Select A Valid Option.";
                break;

        }
    }
}

I've tried moving the cin << choice; to many different spots, including inside of the while loop written for the switch, but I can only seem to get it to show the prompt for the menu, but not the menu options themselves and it isn't taking input. If it makes a difference, I'm using Xcode for the first time and I need it to run there as I can't run C++ on my version of Visual studio (on Mac). Where may I have gone wrong here and any insight into why my version is wrong is appreciated as I'm still very new to coding overall. Thank you.

Body:
You had this:

while (choice !=4);

This makes it so that your code never continues further than this while loop. Unless your compiler removes this line during optimization.

This is the correct way:

    while (choice !=4) {
        switch (choice)
        {
            case 1:
                cout << "Monthly Payment Calculator:";
                cout << endl;
                break;
            case 2:
                cout << "Interest Rate Calculator:";
                cout << endl;
                break;
            case 3:
                cout << "Payment Term (In Months):";
                cout << endl;
            case 4:
                cout << "Exit Calculator:";

            default: //all other choices
                cout << "Please Select A Valid Option.";
                break;

        }
        cin >> choice; // have it right after the switch
   }


问:
How to store number with thousand separator in JavaScript Array
I want to store an Array like this

```<code>const price = [ 1.000, 24.500, 3.99, 4.00 ];
</code>```

but when i'm print this with console.log, the 1.000 becomes 1 , the 4.00 become 4.

how to keep the thousand number with dot separator?

答:
Try the following code:

console.log(price.toFixed(3));

edit-1:

prices.forEach((price)=>{ console.log(price.toFixed(3)); })

let truePrice = prices.map( (price)=> price.toFixed(3) )

```

Body:
I want to store an Array like this

const price = [ 1.000, 24.500, 3.99, 4.00 ];

but when i'm print this with console.log, the 1.000 becomes 1 , the 4.00 become 4.

how to keep the thousand number with dot separator?


问:
Parse YAML Files in C++
I want a simple tutorial to show me how to load a yaml file and parse the data. Expat style would be great but any solution that actually shows me the data in some form would be useful.

So far I ran multiple tests in the yaml-0.1.1 source code for C and I either get an error, no output whatsoever, or in the run-emitter.c case. It reads in the yaml file and prints it to STDOUT, it does not produce the text via libyaml functions/structs. In the cases with an error I don't know if it was because the file was bad or my build is incorrect (I didn't modify anything...) The file was copied from yaml.org

Can anyone point me to a tutorial? (I googled for at least 30 minutes reading anything that looked relevant) or a name of a lib that has a good tutorial or example. Maybe you can tell me which libyaml test loads in files and does something with it or why I got errors. This document does not explain how to use the file--only how to load it:

http://pyyaml.org/wiki/LibYAML#Documentation

答:
C example - parsing YAML tree to a glib "N-ary tree":</p>

```<code>#include <yaml.h>
#include <stdio.h>
#include <glib.h>

void process_layer(yaml_parser_t *parser, GNode *data);
gboolean dump(GNode *n, gpointer data);

int main (int argc, char **argv) {
    char *file_path = "test.yaml";
    GNode *cfg = g_node_new(file_path);
    yaml_parser_t parser;

    FILE *source = fopen(file_path, "rb");
    yaml_parser_initialize(&parser);
    yaml_parser_set_input_file(&parser, source);
    process_layer(&parser, cfg); // Recursive parsing
    yaml_parser_delete(&parser);
    fclose(source);

    printf("Results iteration:\n");
    g_node_traverse(cfg, G_PRE_ORDER, G_TRAVERSE_ALL, -1, dump, NULL);
    g_node_destroy(cfg);

    return(0);
}

enum storage_flags { VAR, VAL, SEQ }; // "Store as" switch

void process_layer(yaml_parser_t *parser, GNode *data) {
    GNode *last_leaf = data;
    yaml_event_t event;
    int storage = VAR; // mapping cannot start with VAL definition w/o VAR key

    while (1) {
        yaml_parser_parse(parser, &event);

        // Parse value either as a new leaf in the mapping
        //  or as a leaf value (one of them, in case it's a sequence)
        if (event.type == YAML_SCALAR_EVENT) {
            if (storage) g_node_append_data(last_leaf, g_strdup((gchar*) event.data.scalar.value));
            else last_leaf = g_node_append(data, g_node_new(g_strdup((gchar*) event.data.scalar.value)));
            storage ^= VAL; // Flip VAR/VAL switch for the next event
        }

        // Sequence - all the following scalars will be appended to the last_leaf
        else if (event.type == YAML_SEQUENCE_START_EVENT) storage = SEQ;
        else if (event.type == YAML_SEQUENCE_END_EVENT) storage = VAR;

        // depth += 1
        else if (event.type == YAML_MAPPING_START_EVENT) {
            process_layer(parser, last_leaf);
            storage ^= VAL; // Flip VAR/VAL, w/o touching SEQ
        }

        // depth -= 1
        else if (
            event.type == YAML_MAPPING_END_EVENT
            || event.type == YAML_STREAM_END_EVENT
        ) break;

        yaml_event_delete(&event);
    }
}

gboolean dump(GNode *node, gpointer data) {
    int i = g_node_depth(node);
    while (--i) printf(" ");
    printf("%s\n", (char*) node->data);
    return(FALSE);
}
</code>```

LastEditorDisplayName: zacherates

Title: Parse YAML Files in C++

Body:
C example - parsing YAML tree to a glib "N-ary tree":

#include <yaml.h>
#include <stdio.h>
#include <glib.h>

void process_layer(yaml_parser_t *parser, GNode *data);
gboolean dump(GNode *n, gpointer data);

int main (int argc, char **argv) {
    char *file_path = "test.yaml";
    GNode *cfg = g_node_new(file_path);
    yaml_parser_t parser;

    FILE *source = fopen(file_path, "rb");
    yaml_parser_initialize(&parser);
    yaml_parser_set_input_file(&parser, source);
    process_layer(&parser, cfg); // Recursive parsing
    yaml_parser_delete(&parser);
    fclose(source);

    printf("Results iteration:\n");
    g_node_traverse(cfg, G_PRE_ORDER, G_TRAVERSE_ALL, -1, dump, NULL);
    g_node_destroy(cfg);

    return(0);
}

enum storage_flags { VAR, VAL, SEQ }; // "Store as" switch

void process_layer(yaml_parser_t *parser, GNode *data) {
    GNode *last_leaf = data;
    yaml_event_t event;
    int storage = VAR; // mapping cannot start with VAL definition w/o VAR key

    while (1) {
        yaml_parser_parse(parser, &event);

        // Parse value either as a new leaf in the mapping
        //  or as a leaf value (one of them, in case it's a sequence)
        if (event.type == YAML_SCALAR_EVENT) {
            if (storage) g_node_append_data(last_leaf, g_strdup((gchar*) event.data.scalar.value));
            else last_leaf = g_node_append(data, g_node_new(g_strdup((gchar*) event.data.scalar.value)));
            storage ^= VAL; // Flip VAR/VAL switch for the next event
        }

        // Sequence - all the following scalars will be appended to the last_leaf
        else if (event.type == YAML_SEQUENCE_START_EVENT) storage = SEQ;
        else if (event.type == YAML_SEQUENCE_END_EVENT) storage = VAR;

        // depth += 1
        else if (event.type == YAML_MAPPING_START_EVENT) {
            process_layer(parser, last_leaf);
            storage ^= VAL; // Flip VAR/VAL, w/o touching SEQ
        }

        // depth -= 1
        else if (
            event.type == YAML_MAPPING_END_EVENT
            || event.type == YAML_STREAM_END_EVENT
        ) break;

        yaml_event_delete(&event);
    }
}

gboolean dump(GNode *node, gpointer data) {
    int i = g_node_depth(node);
    while (--i) printf(" ");
    printf("%s\n", (char*) node->data);
    return(FALSE);
}

OwnerDisplayName: FraGGod

LastEditorDisplayName: FraGGod


问:
SQL Server WITH XMLNAMESPACES dynamic declaration
I have the following query:

```<code>;WITH XMLNAMESPACES (
    'Bob' AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')
</code>```

However I'd like the name space definition to be dynamically picked up at runtime from a configuration table. I've tried the following but they don't appear to be valid SQL:

```<code>-- use a sub query
;WITH XMLNAMESPACES (
    (SELECT 'Fred') AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')

-- declare a variable
DECLARE @ns VARCHAR(10) = 'Fred'

;WITH XMLNAMESPACES (
    @ns AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')
</code>```

Is there any way to have the name space definition dynamic?

Thanks,

Tom

答:
You should use dynamic SQL:</p>

```<code>DECLARE @d NVARCHAR(30)='Fred'

;WITH XMLNAMESPACES (
    'UniqueValue' AS b
)
SELECT @ns=(
SELECT  'Test' AS [@b:Test]
FOR XML PATH('root'))

SELECT CAST(REPLACE(@ns, 'UniqueValue',@D) AS XML)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following query:

;WITH XMLNAMESPACES (
    'Bob' AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')

However I'd like the name space definition to be dynamically picked up at runtime from a configuration table. I've tried the following but they don't appear to be valid SQL:

-- use a sub query
;WITH XMLNAMESPACES (
    (SELECT 'Fred') AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')

-- declare a variable
DECLARE @ns VARCHAR(10) = 'Fred'

;WITH XMLNAMESPACES (
    @ns AS b
)
SELECT 'Test' AS [@b:Test]
FOR XML PATH('root')

Is there any way to have the name space definition dynamic?

Thanks,

Tom

Body:
You should use dynamic SQL:

DECLARE @d NVARCHAR(30)='Fred'

;WITH XMLNAMESPACES (
    'UniqueValue' AS b
)
SELECT @ns=(
SELECT  'Test' AS [@b:Test]
FOR XML PATH('root'))

SELECT CAST(REPLACE(@ns, 'UniqueValue',@D) AS XML)


问:
How to get reCAPTCHA data with Ajax
I would like to get "human" or "bot" with Ajax based on reCAPTCHA score, but it doesn't work... Could you give me any advice? You don't need to think about validation at this point.

html

```<code><form id="contact-form" action="/" method="POST">
   <input type="hidden" name="recaptchaResponse" id="recaptchaResponse" />
   <input class="btn-send" type="button" name="send" value="SUBMIT">
</form>
</code>```

script (ajax)

```<code>$(function() {

   $('.btn-send').on('click', function(e){
      e.preventDefault();

      //reCAPTCHA
      grecaptcha.ready(function() {
         grecaptcha.execute('my_key_here', {action: 'homepage'}).then(function(token) {
            var recaptchaResponse = document.getElementById('recaptchaResponse');
            recaptchaResponse.value = token;
         });
      });

      //ajax
      var formData = $('#contact-form');
      $.ajax({
         url: "/",
         type: "POST",
         data: formData.serialize()
      })
      .then(

      function (data) {
         //I want to alert "human" or "bot" here
         alert(data);
      },
      function () {
         alert("fail");
      });
   }
});
</code>```

php

```<code>if (isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])) {
    $secret = 'my_key_here';
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptchaResponse']);
    $reCAPTCHA = json_decode($verifyResponse);
    if ($reCAPTCHA->score >= 0.7) {
         echo 'human';
         exit;
    } else {
         echo 'bot';
         exit;
    }
}
</code>```

答:
If ajax is giving you right data then just check at your ajax side if return value is human or bot depending on that display required alert .

Your function will look like :

```<code>function(data) {
  var values = $.trim(data); //triming value if there is any whitespaces
  if (values == "human") {
    alert("Hello you are human"); //show alert
  } else {
    alert("Hello you are Robot");
  }
}
</code>```

Title: How to get reCAPTCHA data with Ajax

Body:
I would like to get "human" or "bot" with Ajax based on reCAPTCHA score, but it doesn't work... Could you give me any advice? You don't need to think about validation at this point.

html

<form id="contact-form" action="/" method="POST">
   <input type="hidden" name="recaptchaResponse" id="recaptchaResponse" />
   <input class="btn-send" type="button" name="send" value="SUBMIT">
</form>

script (ajax)

$(function() {

   $('.btn-send').on('click', function(e){
      e.preventDefault();

      //reCAPTCHA
      grecaptcha.ready(function() {
         grecaptcha.execute('my_key_here', {action: 'homepage'}).then(function(token) {
            var recaptchaResponse = document.getElementById('recaptchaResponse');
            recaptchaResponse.value = token;
         });
      });

      //ajax
      var formData = $('#contact-form');
      $.ajax({
         url: "/",
         type: "POST",
         data: formData.serialize()
      })
      .then(

      function (data) {
         //I want to alert "human" or "bot" here
         alert(data);
      },
      function () {
         alert("fail");
      });
   }
});

php

if (isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])) {
    $secret = 'my_key_here';
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptchaResponse']);
    $reCAPTCHA = json_decode($verifyResponse);
    if ($reCAPTCHA->score >= 0.7) {
         echo 'human';
         exit;
    } else {
         echo 'bot';
         exit;
    }
}

Body:
If ajax is giving you right data then just check at your ajax side if return value is human or bot depending on that display required alert .

Your function will look like :

function(data) {
  var values = $.trim(data); //triming value if there is any whitespaces
  if (values == "human") {
    alert("Hello you are human"); //show alert
  } else {
    alert("Hello you are Robot");
  }
}


问:
Bottom border is not added to view in StackView (ios)
I am trying to add UIView with the bottom border programatically to stack view.But border is not getting added to UIView().
Code to add UIView to stack view:

```<code>    func addOtpViews()
    {
        var otpLength=Int(otpLen as String)!
        print("otpLength is\(otpLength)")

        var i=0;
        while(i<=otpLength)
        {
             var view=UIView(frame: .zero)
            addBottomBorderTo(view: view)
            otpStackView.addArrangedSubview(view)
            i=i+1

        }
        otpStackView.translatesAutoresizingMaskIntoConstraints=false

      }
</code>```

on the above otpStackView is a stack view which I have already added in StoryBoard.

code to add bottom line:

```<code>    func addBottomBorderTo(view:UIView) {
        print("bottom is added")
         let layer = CALayer()
         layer.backgroundColor = UIColor.gray.cgColor
         layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)
         view.layer.addSublayer(layer)
     }
</code>```

Why bottom line is not added to UIView()?Please help me.Thanks in advance.

答:
have you checked the view frame here

```<code>layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)
</code>```

view.frame could be (0,0),then you will not see the bottom line.

always be careful when you work with view frame.

My suggestions:
1.Adding sub view instead of adding sub layer,then use snapkit to layout.
2.Build a seperate view class called bottomedView,then add sub view there with snapkit.
3.Build a seperate view class called bottomedView,and draw your bottom line in onDraw.

Always be aware view frame may not be determined when view is missing unexpectedly.

Body:
I am trying to add UIView with the bottom border programatically to stack view.But border is not getting added to UIView().
Code to add UIView to stack view:

    func addOtpViews()
    {
        var otpLength=Int(otpLen as String)!
        print("otpLength is\(otpLength)")

        var i=0;
        while(i<=otpLength)
        {
             var view=UIView(frame: .zero)
            addBottomBorderTo(view: view)
            otpStackView.addArrangedSubview(view)
            i=i+1

        }
        otpStackView.translatesAutoresizingMaskIntoConstraints=false

      }

on the above otpStackView is a stack view which I have already added in StoryBoard.

code to add bottom line:

    func addBottomBorderTo(view:UIView) {
        print("bottom is added")
         let layer = CALayer()
         layer.backgroundColor = UIColor.gray.cgColor
         layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)
         view.layer.addSublayer(layer)
     }

Why bottom line is not added to UIView()?Please help me.Thanks in advance.

Body:
have you checked the view frame here

layer.frame = CGRect(x: 0.0, y: view.frame.size.height - 2.0, width: view.frame.size.width, height: 2.0)

view.frame could be (0,0),then you will not see the bottom line.

always be careful when you work with view frame.

My suggestions:
1.Adding sub view instead of adding sub layer,then use snapkit to layout.
2.Build a seperate view class called bottomedView,then add sub view there with snapkit.
3.Build a seperate view class called bottomedView,and draw your bottom line in onDraw.

Always be aware view frame may not be determined when view is missing unexpectedly.


问:
How to use check_password function in django
I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm.
I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?</p>

```<code>def save(request):
    if request.method == 'POST':
       name = request.POST.get('name')
       password = request.POST.get('pass')
       enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
       a = signup(username = name, password = enc_pass)
       a.save()
   return render(request,'save.html')
def login(request):
   if request.method  == 'POST':

       username        = request.POST.get('user')
       password1          = request.POST.get('password1')
       p = check_password(password=password1)
      if signup.objects.filter(username__exact=username).exists() and p is True:
           return HttpResponse("Success")
     else:
           return HttpResponse("Invalid Credentials")
   return render(request, 'login.html')
</code>```

答:
You can do:

```<code>if check_password(password_user_entered, request.user.password):
    # You can authenticate
</code>```

Here, password_user_entered is password that came from the request(or, pw to be checked). And, request.user.password which is the password with which we want to compare.

Body:
I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm.
I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?

def save(request):
    if request.method == 'POST':
       name = request.POST.get('name')
       password = request.POST.get('pass')
       enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
       a = signup(username = name, password = enc_pass)
       a.save()
   return render(request,'save.html')
def login(request):
   if request.method  == 'POST':

       username        = request.POST.get('user')
       password1          = request.POST.get('password1')
       p = check_password(password=password1)
      if signup.objects.filter(username__exact=username).exists() and p is True:
           return HttpResponse("Success")
     else:
           return HttpResponse("Invalid Credentials")
   return render(request, 'login.html')

Body:
You can do:

if check_password(password_user_entered, request.user.password):
    # You can authenticate

Here, password_user_entered is password that came from the request(or, pw to be checked). And, request.user.password which is the password with which we want to compare.


问:
How to convert strings into column names in Google Bigquery?
I have a large data set in Google BigQuery with millions of rows of dirty data (App tracking) that I am trying to clean up. One of my problems is that the same data got sent to different columns for different events triggered in the App. By this I mean that maybe the country was sent to custom dimension 1 for some events, but to custom dimension 147 for other events. I can't post actual data, but a SELECT * FROM table_with_dirty_data would produce something like this:

date | session | eventAction | cd001 | cd002    | cd004    | cd005
-----|---------|-------------|-------|----------|----------|-------
1    | 1       | 'event_1'   | '1'   | 'Pizza'  | null     | '21'
1    | 1       | 'event_2'   | '10'  | '25'     | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | '3.1' | null     | '15'     | 'France'
1    | 2       | 'event_1'   | '6'   | 'Burger' | null     | '21'
1    | 2       | 'event_2'   | '21'  | '25'     | 'Burger' | '12.6'
```
<p>The ultimate goal here is to end up with a clean table that can be analyzed. Something like this:</p>
<pre class="lang-sql prettyprint-override"><code>date | session | eventAction | country  | vendor   | product  | price
-----|---------|-------------|----------|----------|----------|-------
1    | 1       | 'event_1'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_2'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 2       | 'event_1'   | 'Spain'  | '25'     | 'Burger' | '12.6'
1    | 2       | 'event_2'   | 'Spain'  | '25'     | 'Burger' | '12.6'
</code>```

I am aware that some events will need some degree of statistical imputation and data type casting, but for now I am only concerned with getting every variable into its own column. So I've created an auxiliary table (let's call it matrix) that looks like this:

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_2'  | 'cd020'    | 'cd146'    | 'cd056'
'event_3'  | 'cd001'    | 'cd020'    | 'cd035'
```
<p>and so on, where the value in each cell of column <code>variable_#</code> is the column name in the <code>table_with_dirty_data</code> where the information can be found. That is, <code>variable_1</code> can be found in a column called <code>cd020</code> for events with <code>event_name</code> 'event_1' and 'even_2', but in a column called <code>cd001</code> for events with <code>event_name</code> 'event_3'. So basically what <code>matrix</code> does is to map to which custom dimension each variable was sent for each event.</p>
<p>I have hundreds of different events in <code>table_with_dirty_data</code>, and <code>matrix</code> holds all 200 GA custom dimensions, so doing something like</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
  CASE
    WHEN event_name = 'event_1' THEN cd020
    WHEN event_name = 'event_2' THEN cd020
    WHEN event_name = 'event_3' THEN cd001
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN cd035
      WHEN event_name = 'event_2' THEN cd146
      WHEN event_name = 'event_3' THEN cd020
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN cd120
      WHEN event_name = 'event_2' THEN cd056
      WHEN event_name = 'event_3' THEN cd035
  END AS variable_3
FROM table_with_dirty_data
</code>```

would take me a looooong time and is very error-prone. What I am trying to do is to use SELECT statements that return the column name (cd###) from the table_with_dirty_data where the information is stored and the use a WHILE to loop over all different events. So, for example, with event_name = 'event_1' it would be something like this:

SELECT
  CASE
    WHEN event_name = 'event_1'
    THEN (SELECT variable_1 FROM matrix WHERE event_name = 'event_1')
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_2 FROM matrix WHERE event_name = 'event_1')
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_3 FROM matrix WHERE event_name = 'event_1')
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'
```
<p>The goal here is that I can then loop over an array with all the <code>event_name</code>s (something that can be easily achieved). Ultimately I need all events in one table, but I'm ok with having a table for curating each event, as long as it can be done programmatically (something I personally don't know if it's even possible in GBQ...would have to check on that).</p>
<p>The issue is that the <code>SELECT</code> statements I am using get evaluated to a string, so the result of the queries inside the <code>CASE</code> clause are string literals. For example, if I were to run it for event = 'event_1',</p>
<pre class="lang-sql prettyprint-override"><code>SELECT variable_1 FROM matrix WHERE event_name = 'event_1'
</code>```

evaluates to

'cd020'
```
<p>which then cause the outer query to become</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
  CASE
    WHEN event_name = 'event_1' THEN 'cd020'
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN 'cd035'
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN 'cd120'
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'
</code>```

which produces a table like this

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
```

instead of returning the value stored in columns cd020, cd035 or cd120 for each time the event 'event_1' is found.

Does anyone know a way to unquote the result of those inner queries so that when the outer query executes, they are transformed into column names (so 'cd020' becomes cd020)??

PS: I am also open to a totally different strategy if anyone knows one.

答:
Sounds like a case where EXECUTE IMMEDIATE might be helpful.  I'm not sure I fully understand the mapping, but it should allow you to compose a dynamic statement based off your matrix table.

However, it is unclear based on the description how unwieldy the generated query might be, as you mention having hundreds of these kinds of events and you may start running into other problems such as query complexity or length limits.

Body:
I have a large data set in Google BigQuery with millions of rows of dirty data (App tracking) that I am trying to clean up. One of my problems is that the same data got sent to different columns for different events triggered in the App. By this I mean that maybe the country was sent to custom dimension 1 for some events, but to custom dimension 147 for other events. I can't post actual data, but a SELECT * FROM table_with_dirty_data would produce something like this:

date | session | eventAction | cd001 | cd002    | cd004    | cd005
-----|---------|-------------|-------|----------|----------|-------
1    | 1       | 'event_1'   | '1'   | 'Pizza'  | null     | '21'
1    | 1       | 'event_2'   | '10'  | '25'     | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | '3.1' | null     | '15'     | 'France'
1    | 2       | 'event_1'   | '6'   | 'Burger' | null     | '21'
1    | 2       | 'event_2'   | '21'  | '25'     | 'Burger' | '12.6'

The ultimate goal here is to end up with a clean table that can be analyzed. Something like this:

date | session | eventAction | country  | vendor   | product  | price
-----|---------|-------------|----------|----------|----------|-------
1    | 1       | 'event_1'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_2'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 2       | 'event_1'   | 'Spain'  | '25'     | 'Burger' | '12.6'
1    | 2       | 'event_2'   | 'Spain'  | '25'     | 'Burger' | '12.6'

I am aware that some events will need some degree of statistical imputation and data type casting, but for now I am only concerned with getting every variable into its own column. So I've created an auxiliary table (let's call it matrix) that looks like this:

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_2'  | 'cd020'    | 'cd146'    | 'cd056'
'event_3'  | 'cd001'    | 'cd020'    | 'cd035'

and so on, where the value in each cell of column variable_# is the column name in the table_with_dirty_data where the information can be found. That is, variable_1 can be found in a column called cd020 for events with event_name 'event_1' and 'even_2', but in a column called cd001 for events with event_name 'event_3'. So basically what matrix does is to map to which custom dimension each variable was sent for each event.

I have hundreds of different events in table_with_dirty_data, and matrix holds all 200 GA custom dimensions, so doing something like

SELECT
  CASE
    WHEN event_name = 'event_1' THEN cd020
    WHEN event_name = 'event_2' THEN cd020
    WHEN event_name = 'event_3' THEN cd001
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN cd035
      WHEN event_name = 'event_2' THEN cd146
      WHEN event_name = 'event_3' THEN cd020
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN cd120
      WHEN event_name = 'event_2' THEN cd056
      WHEN event_name = 'event_3' THEN cd035
  END AS variable_3
FROM table_with_dirty_data

would take me a looooong time and is very error-prone. What I am trying to do is to use SELECT statements that return the column name (cd###) from the table_with_dirty_data where the information is stored and the use a WHILE to loop over all different events. So, for example, with event_name = 'event_1' it would be something like this:

SELECT
  CASE
    WHEN event_name = 'event_1'
    THEN (SELECT variable_1 FROM matrix WHERE event_name = 'event_1')
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_2 FROM matrix WHERE event_name = 'event_1')
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_3 FROM matrix WHERE event_name = 'event_1')
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'

The goal here is that I can then loop over an array with all the event_names (something that can be easily achieved). Ultimately I need all events in one table, but I'm ok with having a table for curating each event, as long as it can be done programmatically (something I personally don't know if it's even possible in GBQ...would have to check on that).

The issue is that the SELECT statements I am using get evaluated to a string, so the result of the queries inside the CASE clause are string literals. For example, if I were to run it for event = 'event_1',

SELECT variable_1 FROM matrix WHERE event_name = 'event_1'

evaluates to

'cd020'

which then cause the outer query to become

SELECT
  CASE
    WHEN event_name = 'event_1' THEN 'cd020'
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN 'cd035'
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN 'cd120'
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'

which produces a table like this

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'

instead of returning the value stored in columns cd020, cd035 or cd120 for each time the event 'event_1' is found.

Does anyone know a way to unquote the result of those inner queries so that when the outer query executes, they are transformed into column names (so 'cd020' becomes cd020)??

PS: I am also open to a totally different strategy if anyone knows one.


问:
Sqoop Import Error "Could not load db driver class" with Amazon EMR Service

I have created a EMR cluster with hadoop,Sqoop and Spark
  configuration. I am trying Sqoop Import but getting error "Could not
  load db driver class: com.mysql.jdbc.Driver" . My question is which
  location do we put the  Mysql Driver ?

```<code>I have tried putting the Jar at path
1. /etc/sqoop/conf/
2. /etc/sqoop/lib/ (after creating the lib folder)
</code>```

sqoop import --connect jdbc:mysql://--.--.--.--:3306/xyz --table
  sample_submission --target-dir /home/sqoop7 --username x --password y -m 1;

答:
Jars to put for sqoop is under lib dir in SQOOP_HOME

Full path: /usr/lib/sqoop/lib/

Body:
I have created a EMR cluster with hadoop,Sqoop and Spark
  configuration. I am trying Sqoop Import but getting error "Could not
  load db driver class: com.mysql.jdbc.Driver" . My question is which
  location do we put the  Mysql Driver ?

I have tried putting the Jar at path
1. /etc/sqoop/conf/
2. /etc/sqoop/lib/ (after creating the lib folder)

sqoop import --connect jdbc:mysql://--.--.--.--:3306/xyz --table
  sample_submission --target-dir /home/sqoop7 --username x --password y -m 1;


问:
Cannot understand the following code in objective C?
Please refer to the following code:

Filename: myclass.h

```<code>@interface myclass:NSObject
...
@end
@interface NSObject(CategoryName)
....
@end
</code>```

I do not understand how can we declare 2 @interface directives in the same .h file? and like in the implementation file we can only implement one of the above interfaces.eg.

Filename: myclass.m

```<code>@implementation myclass
...
@end
</code>```

in the above code, i cannot write @implementation Categoryname as the name of the .h file is myclass. How do i implement the methods described in the category.

Also can my main interface extend one class and the category that i am defining in the same .h file extend another class?

How can i declare one class into another class (nested class) in objective c?

thank you in advance.

UPDATE

After reading the responses, i have 2 more questions

if i have 2 @interface in my .h file, can i have 2 @implementation in the .m file.

if i have 2 @interface in my .h file and if i import that .h file in another file, can i access the methods under both the @interface directives?

Can i implement the methods declared in the category in the interface of another class?

答:
Add it as another declaration in the same file, like this

```<code>@implementation NSObject (categoryname)

...

@end
</code>```

It's all described in the Categories and extensions section of the Developer docs.

Since you are extending a different class in the same interface - you need to have a separate declaration in the implementation file.

Edited to answer the additions:

Yes - I just said so.

Yes - Interfaces expose public methods.

Somewhere in your compilation tree, you have to have a file that implements the methods that you declared in your category. Most people define categories in their own files with a particular naming convention.For example uliwitness/uikit. For your example it would be in NSObject+CategoryName.h and NSObject+CategoryName.m. Once you have declared and defined a category on a class it is available to all objects of that class. So since you are adding an extension to NSObject, those methods are available to all classes that inherit from NSObject (which is practically all classes) whether or not you import the header file. But, you get a compiler warning if you don't import the header, even though the Objective-C runtime will still allow those methods to be called.

Body:
Please refer to the following code:

Filename: myclass.h

@interface myclass:NSObject
...
@end
@interface NSObject(CategoryName)
....
@end

I do not understand how can we declare 2 @interface directives in the same .h file? and like in the implementation file we can only implement one of the above interfaces.eg.

Filename: myclass.m

@implementation myclass
...
@end

in the above code, i cannot write @implementation Categoryname as the name of the .h file is myclass. How do i implement the methods described in the category.

Also can my main interface extend one class and the category that i am defining in the same .h file extend another class?

How can i declare one class into another class (nested class) in objective c?

thank you in advance.

UPDATE

After reading the responses, i have 2 more questions

if i have 2 @interface in my .h file, can i have 2 @implementation in the .m file.

if i have 2 @interface in my .h file and if i import that .h file in another file, can i access the methods under both the @interface directives?

Can i implement the methods declared in the category in the interface of another class?

Body:
Add it as another declaration in the same file, like this

@implementation NSObject (categoryname)

...

@end

It's all described in the Categories and extensions section of the Developer docs.

Since you are extending a different class in the same interface - you need to have a separate declaration in the implementation file.

Edited to answer the additions:

Yes - I just said so.

Yes - Interfaces expose public methods.

Somewhere in your compilation tree, you have to have a file that implements the methods that you declared in your category. Most people define categories in their own files with a particular naming convention.For example uliwitness/uikit. For your example it would be in NSObject+CategoryName.h and NSObject+CategoryName.m. Once you have declared and defined a category on a class it is available to all objects of that class. So since you are adding an extension to NSObject, those methods are available to all classes that inherit from NSObject (which is practically all classes) whether or not you import the header file. But, you get a compiler warning if you don't import the header, even though the Objective-C runtime will still allow those methods to be called.


问:
Can 3 values (consecutive) of a vector be sorted using this method?
So I'm trying to swap 3 values of a vector of ints by rotating them leftwards , i.e. ABC->BCA
And i want to make this happen by using iterators. Also, i know the iterator referring to C.
So what i did was I made the following function:

```<code>void xsort(vector<int>::iterator& it)
{
    int temp= *(it-2);
    *(it-2)= *(it-1);
    *(it-1)= *(it);
    *(it)=temp;
    return;
}
</code>```

My question is that if this function will correctly do what I wish? And if not , how will I achieve the required?

```<code>funk(vector<int>& vec , vector<int>::iterator i)
{
    ...
    ...
    xsort(i);
    ...
}
</code>```

Second question: If we have a function named funk having the given arguments , and if this function is the one calling xsort() by passing to it, the iterator 'i' (funk is called by the main() ) . Would this still change the values of the vector as desired?
Note: In the arguments of funk(), the vector has the reference operator associated with it while the iterator 'i' doesn't.

答:
U can use std::rotate, as follows

```<code>#include <iostream>
#include <vector>
#include <algorithm>

int main(){
    std::vector vec {'A', 'B', 'C'};
    std::rotate(vec.rbegin(), vec.rend()-1, vec.rend());
    for(auto const &el :vec) std::cout<< el <<" ";
}
So the out is -> B C A
</code>```

If u have two functions and u want to pass a var by reference to one of them, the second will be called by the first and will take the same argument by ref., then the answer is yes if any one of them changes the var, the original one will change.

Body:
So I'm trying to swap 3 values of a vector of ints by rotating them leftwards , i.e. ABC->BCA
And i want to make this happen by using iterators. Also, i know the iterator referring to C.
So what i did was I made the following function:

void xsort(vector<int>::iterator& it)
{
    int temp= *(it-2);
    *(it-2)= *(it-1);
    *(it-1)= *(it);
    *(it)=temp;
    return;
}

My question is that if this function will correctly do what I wish? And if not , how will I achieve the required?

funk(vector<int>& vec , vector<int>::iterator i)
{
    ...
    ...
    xsort(i);
    ...
}

Second question: If we have a function named funk having the given arguments , and if this function is the one calling xsort() by passing to it, the iterator 'i' (funk is called by the main() ) . Would this still change the values of the vector as desired?
Note: In the arguments of funk(), the vector has the reference operator associated with it while the iterator 'i' doesn't.

Body:
U can use std::rotate, as follows

#include <iostream>
#include <vector>
#include <algorithm>

int main(){
    std::vector vec {'A', 'B', 'C'};
    std::rotate(vec.rbegin(), vec.rend()-1, vec.rend());
    for(auto const &el :vec) std::cout<< el <<" ";
}
So the out is -> B C A

If u have two functions and u want to pass a var by reference to one of them, the second will be called by the first and will take the same argument by ref., then the answer is yes if any one of them changes the var, the original one will change.


问:
How to remove models from django?
In Django how do you remove models that you have synced into the database?

For example in Django tutorial page had this following code

```<code>from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
</code>```

Then I used python manage.py sql polls and python manage.py sql choice  to create the tables into the database. But what if I did something wrong and don't want that model any more. What's the syntax to remove it?

答:
Since the Migration command handle Model(database) you can do following steps.

First type

python manage.py makemigrations app_name # it will restructure your model

then type

python manage.py migrate app_name # it will apply to restructure your database.

Example:
I had Posts and PostDetail model,
later on, I wanted to remove PostDetail model and some fields(columns) from Posts model too.

I simply run migrations and migrate commands,checked in Mysql Database. It worked fine.

Hope it will work for you too.

Title: How to remove models from django?

Body:
In Django how do you remove models that you have synced into the database?

For example in Django tutorial page had this following code

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

Then I used python manage.py sql polls and python manage.py sql choice  to create the tables into the database. But what if I did something wrong and don't want that model any more. What's the syntax to remove it?


问:
Rendering  in JSX
I have a stencil component that can accept "draggable" prop, I want to pass the value of this prop to a child img tag when it is applied.

```<code>  render() {
    // this.el = Host Element
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'

    const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : undefined);

    console.log("render -> shouldBeDraggable", shouldBeDraggable); // Logs Correct Value

    return (
      <Host>
        <img
          src={this.loadSrc}
          draggable={shouldBeDraggable}
        />
      </Host>
    );
  }
</code>```

It only renders draggable="true" when the host prop value is true but it does not render draggable="false" when the host prop value is false.

Another simplified sample;

```<code> render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>
        <img src={this.loadSrc} draggable={false} />
      </Host>
    );
  }
</code>```

Unfortunately, the type of img.draggable attribute is boolean.
(JSX attribute) JSXBase.HTMLAttributes.draggable?: boolean | undefined

Passing as a string;

```<code> render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>
        <img src={this.loadSrc} draggable={"false" as any} />
      </Host>
    );
  }
</code>```

This does render draggable="true" to the img tag Because "false" string becomes true boolean no render.

How can I successfully pass the falsy case of the draggable attribute to a child an img tag?

答:
Replace undefined with false:

```<code>const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : false);
</code>```

But since you want to pass true or false, you can just define:

```<code>const shouldBeDraggable = this.el.hasAttribute('draggable') // true or false
</code>```

Further, set a class and use style:

```<code><img
  src={this.loadSrc}
  draggable={shouldBeDraggable}
  className={shouldBeDraggable ? 'draggable' : 'no-draggable'}
/>

.no-draggable {
  pointer-events: none;
}
</code>```

Or, use style: user-drag:none; user-select:none; whatever suits you.

Title: Rendering <img attribute={false} /> in JSX

Body:
I have a stencil component that can accept "draggable" prop, I want to pass the value of this prop to a child img tag when it is applied.

  render() {
    // this.el = Host Element
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'

    const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : undefined);

    console.log("render -> shouldBeDraggable", shouldBeDraggable); // Logs Correct Value

    return (
      <Host>

      </Host>
    );
  }

It only renders draggable="true" when the host prop value is true but it does not render draggable="false" when the host prop value is false.

Another simplified sample;

 render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>

      </Host>
    );
  }

Unfortunately, the type of img.draggable attribute is boolean.
(JSX attribute) JSXBase.HTMLAttributes.draggable?: boolean | undefined

Passing as a string;

 render() {
    // this.loadSrc = Image URL as String
    // draggable has to be type 'boolean | undefined'
    return (
      <Host>

      </Host>
    );
  }

This does render draggable="true" to the img tag Because "false" string becomes true boolean no render.

How can I successfully pass the falsy case of the draggable attribute to a child an img tag?

Body:
Replace undefined with false:

const shouldBeDraggable = (this.el.hasAttribute('draggable') ? this.el.draggable : false);

But since you want to pass true or false, you can just define:

const shouldBeDraggable = this.el.hasAttribute('draggable') // true or false

Further, set a class and use style:

<img
  src={this.loadSrc}
  draggable={shouldBeDraggable}
  className={shouldBeDraggable ? 'draggable' : 'no-draggable'}
/>

.no-draggable {
  pointer-events: none;
}

Or, use style: user-drag:none; user-select:none; whatever suits you.


问:
Enemies Projectiles Wont Append?
I am trying to make my enemy shoot my player but for some reason the bullets arent showing nor they are shooting at the player I don't even know why, I even draw the bullets on my window

```<code>bulls = []
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False

    for bull in bulls:
        if bull.x < 500 and bull.x > 0:
            bull.x += bull.vel  # Moves the bullet by its vel
        else:
            for enemys in enemying:
                if playerman.x - 100 <= enemys.x <= playerman.x + 100 and playerman.y - 100 <= enemys.y <= playerman.y + 100:
                    bulls.pop(bulls.index(bull))
                    bulls.append(enemybullets(round(enemys.x+enemys.width//2), round(enemys.y + enemys.height//2), 6, (0,0,0), facing))

</code>```

then I called it below

```<code>    for bull in bulls:
        bull.draw(window)
</code>```

my enemy projectile class

```<code># enemys bullets
class enemybullets(object):
    def __init__(self,x,y,radius,color,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.facing = facing
        self.vel = 8 * facing

    def draw(self,win):
        pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)

</code>```

答:
Your code is not ever moving or drawing the bullets.

Another loop over the bull list would do it.  Your code does not include anything about drawing the window, so I've had to make assumptions.

```<code>while runninggame:
    [...]

    for enemys in enemying:
        playerman = math.sqrt(enemys.x**2 + enemys.y**2)
        if distance  >= 250:
            new_bullets = enemybullets(playerman.rect.x, playerman.rect.x, enemys.x/distance, enemys.y/distance, (0,0,0))
            bull.append(new_bullets)

     # Re-paint the screen
     [...]

     # Move and Paint the enemy bullets
     for b in bull:
         b.move()
         b.draw( window )
</code>```

Title: Enemies Projectiles Wont Append?

Body:
I am trying to make my enemy shoot my player but for some reason the bullets arent showing nor they are shooting at the player I don't even know why, I even draw the bullets on my window

bulls = []
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False

    for bull in bulls:
        if bull.x < 500 and bull.x > 0:
            bull.x += bull.vel  # Moves the bullet by its vel
        else:
            for enemys in enemying:
                if playerman.x - 100 <= enemys.x <= playerman.x + 100 and playerman.y - 100 <= enemys.y <= playerman.y + 100:
                    bulls.pop(bulls.index(bull))
                    bulls.append(enemybullets(round(enemys.x+enemys.width//2), round(enemys.y + enemys.height//2), 6, (0,0,0), facing))

then I called it below

    for bull in bulls:
        bull.draw(window)

my enemy projectile class

# enemys bullets
class enemybullets(object):
    def __init__(self,x,y,radius,color,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.facing = facing
        self.vel = 8 * facing

    def draw(self,win):
        pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)

Body:
Your code is not ever moving or drawing the bullets.

Another loop over the bull list would do it.  Your code does not include anything about drawing the window, so I've had to make assumptions.

while runninggame:
    [...]

    for enemys in enemying:
        playerman = math.sqrt(enemys.x**2 + enemys.y**2)
        if distance  >= 250:
            new_bullets = enemybullets(playerman.rect.x, playerman.rect.x, enemys.x/distance, enemys.y/distance, (0,0,0))
            bull.append(new_bullets)

     # Re-paint the screen
     [...]

     # Move and Paint the enemy bullets
     for b in bull:
         b.move()
         b.draw( window )


问:
Custom Installer in .Net showing Form behind installer
```<code>[RunInstaller(true)]
public partial class Installer1 : Installer
{
    public Installer1()
    {
        InitializeComponent();
    }

    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);
    }
    private void Installer1_AfterInstall(object sender, InstallEventArgs e)
    {
        Form1 topmostForm = new Form1();
        topmostForm.BringToFront();
        topmostForm.TopMost = true;
        topmostForm.ShowDialog();
  } }
</code>```

I need to display the topmostForm in front of the default Windows Installer UI. The above is sample code inside my CustomAction that I am using to create a Form. Setting the TopMost property or using ShowDialog is not helping. Is there any other solution to make my form the top most and focussed?

答: although i'm not wuite sure what exactly you're asking for, using WiX for building windows installers is the prefered way to go. There you can build your forms and custom actions and pretty much anything else.</p>

Body:
[RunInstaller(true)]
public partial class Installer1 : Installer
{
    public Installer1()
    {
        InitializeComponent();
    }

    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);
    }
    private void Installer1_AfterInstall(object sender, InstallEventArgs e)
    {
        Form1 topmostForm = new Form1();
        topmostForm.BringToFront();
        topmostForm.TopMost = true;
        topmostForm.ShowDialog();
  } }

I need to display the topmostForm in front of the default Windows Installer UI. The above is sample code inside my CustomAction that I am using to create a Form. Setting the TopMost property or using ShowDialog is not helping. Is there any other solution to make my form the top most and focussed?


问:
Trouble with large numbers while using <iomanip> larger in cpp
While sorting and displaying big numbers you usually end up displaying the large numbers in enotation. I was trying to display the whole number by using the <iomanip> library in cpp and it fails for very large numbers.

```<code> //big sorting
    #include<bits/stdc++.h>
    #include<iomanip>
    using namespace std;
    int main()
    {
        int n;
        cin>>n;
        double arr[n];
        for (int i = 0;i < n; i++)
            cin>>arr[i];

        sort(arr, arr+n);
        cout<<fixed<<setprecision(0);
        for (int i = 0;i < n; i++)
            cout<<arr[i]<<endl;
    }
</code>```

Input:

```<code>31415926535897932384626433832795
1
3
10
3
5
</code>```

Expected output:

```<code>1
3
3
5
10
31415926535897932384626433832795
</code>```

Actual output:

```<code>1
3
3
5
10
31415926535897933290036940242944
</code>```

The last digit is getting messed up.

答: The double type precision is only 15 decimal digits, so very large whole numbers can't be expressed in double type without loss of precison.</p>

Body:
While sorting and displaying big numbers you usually end up displaying the large numbers in enotation. I was trying to display the whole number by using the <iomanip> library in cpp and it fails for very large numbers.

 //big sorting
    #include<bits/stdc++.h>
    #include<iomanip>
    using namespace std;
    int main()
    {
        int n;
        cin>>n;
        double arr[n];
        for (int i = 0;i < n; i++)
            cin>>arr[i];

        sort(arr, arr+n);
        cout<<fixed<<setprecision(0);
        for (int i = 0;i < n; i++)
            cout<<arr[i]<<endl;
    }

Input:

31415926535897932384626433832795
1
3
10
3
5

Expected output:

1
3
3
5
10
31415926535897932384626433832795

Actual output:

1
3
3
5
10
31415926535897933290036940242944

The last digit is getting messed up.