问:
Odoo - Give a warning when editing some field with empty value
I want to add an entry to the suppliers table if one creates a new or edits a product. Each product must have a supplier.
If a supplier is not selected, system must give a warning “You should fill in the supplier details, at least one.”

Here is my code:

```<code>class warning_supplier(models.Model):
_inherit = 'product.template'

@api.multi
def write(self, vals):
    res = super(warning_supplier, self).write(vals)
    supplier_id = self.env['res.partner'].search([('name','=','No Supplier')])
    for this in self:
        seller_ids = this.seller_ids
        if len(seller_ids)==0:
            raise Warning('You should fill in the supplier details, at least one.')
    return res
</code>```

When I create products, the code runs correctly.

But when I edit a product & remove the selected supplier, it does not work any more.

Can someone pinpoint the error to me? Thanks!

Edit: Fixed by using constraints.

答:
You can add python constraint, that will execute when given field has been modified.

```<code>class product_template(models.Model):
    _inherit = 'product.template'

    @api.multi
    @api.constrains('seller_ids')
    def onchange_seller(self):
        for record in self :
            if not record.seller_ids :
                raise ValidationError("You should fill in the supplier details, at least one.")
        return
</code>```

For more information about constrains : click here

Body:
I want to add an entry to the suppliers table if one creates a new or edits a product. Each product must have a supplier.
If a supplier is not selected, system must give a warning “You should fill in the supplier details, at least one.”

Here is my code:

class warning_supplier(models.Model):
_inherit = 'product.template'

@api.multi
def write(self, vals):
    res = super(warning_supplier, self).write(vals)
    supplier_id = self.env['res.partner'].search([('name','=','No Supplier')])
    for this in self:
        seller_ids = this.seller_ids
        if len(seller_ids)==0:
            raise Warning('You should fill in the supplier details, at least one.')
    return res

When I create products, the code runs correctly.

But when I edit a product & remove the selected supplier, it does not work any more.

Can someone pinpoint the error to me? Thanks!

Edit: Fixed by using constraints.

Body:
You can add python constraint, that will execute when given field has been modified.

class product_template(models.Model):
    _inherit = 'product.template'

    @api.multi
    @api.constrains('seller_ids')
    def onchange_seller(self):
        for record in self :
            if not record.seller_ids :
                raise ValidationError("You should fill in the supplier details, at least one.")
        return

For more information about constrains : click here


来源: stackexchange

问:
Extract the names of the files in folders
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

```<code>string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }
</code>```

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

答:
you'll need to include option to show all sub directories within your directory:</p>

```<code>var zipFiles = System.IO.Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip", System.IO.SearchOption.AllDirectories);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

Body:
you'll need to include option to show all sub directories within your directory:

var zipFiles = System.IO.Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip", System.IO.SearchOption.AllDirectories);


问:
Widgets are overlapping in the activity in Android app
I am a self learner of android and I am trying to make an app that displays message as Toast.I made the app on Android Studio and it seems okay but when I run it on my phone which runs on Android 5.0 ,all the widgets are overlapped while in studio all of it looks fine.Please Help.
This is how it looks on phone:

This is how it looks on Android

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

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rahulranjan.toast1.MainToast">

<Button
    android:id="@+id/test1"
    android:layout_width="368dp"
    android:layout_height="wrap_content"
    android:onClick="btnClick"
    android:text="Click Me"
    android:textColor="#00C957"
    tools:layout_editor_absoluteY="130dp"
    tools:layout_editor_absoluteX="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Click Below to see Toast :"
    tools:layout_editor_absoluteY="40dp"
    tools:layout_editor_absoluteX="112dp"
    android:textColor="#E3CF57"
    />
</code>```

And yeah I have used ConstrainLayout,I don't know why its not displaying here on this site.
Thanks

答:
Edit:

You're using a constraint layout. You're not giving these constraints. Add constraints to these or else they default pop to the top left:

```<code><TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Click Below to see Toast :"
tools:layout_editor_absoluteY="40dp"
tools:layout_editor_absoluteX="112dp"
android:textColor="#E3CF57"
app:layout_constraintLeft_toRightOf="@id/test1"
/>
</code>```

Body:
I am a self learner of android and I am trying to make an app that displays message as Toast.I made the app on Android Studio and it seems okay but when I run it on my phone which runs on Android 5.0 ,all the widgets are overlapped while in studio all of it looks fine.Please Help.
This is how it looks on phone:

This is how it looks on Android

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

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rahulranjan.toast1.MainToast">

<Button
    android:id="@+id/test1"
    android:layout_width="368dp"
    android:layout_height="wrap_content"
    android:onClick="btnClick"
    android:text="Click Me"
    android:textColor="#00C957"
    tools:layout_editor_absoluteY="130dp"
    tools:layout_editor_absoluteX="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Click Below to see Toast :"
    tools:layout_editor_absoluteY="40dp"
    tools:layout_editor_absoluteX="112dp"
    android:textColor="#E3CF57"
    />

And yeah I have used ConstrainLayout,I don't know why its not displaying here on this site.
Thanks

Body:
Edit:

You're using a constraint layout. You're not giving these constraints. Add constraints to these or else they default pop to the top left:

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Click Below to see Toast :"
tools:layout_editor_absoluteY="40dp"
tools:layout_editor_absoluteX="112dp"
android:textColor="#E3CF57"
app:layout_constraintLeft_toRightOf="@id/test1"
/>


问:
Vlookup property not working in vba
I am searching a variable selrow which holds string values in a sheet. Sometimes it shows error

unable to get vlookup property of worksheet function class

I have also put the error handling code but still error occurs.

Code

this where error occurs

```<code>for i=1 to last_row
    'code
    selrow= range("D"&i)
    opening_inventory_today = 0
    On Error Resume Next
    opening_inventory_today = Application.WorksheetFunction.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)
</code>```

答:
Using On Error Resume Next is not handling the error, you need to trap the cases that VLookup was unable to find selrow, and then raise an error message (or whatever you want).

Try the code below:

```<code>If Not IsError(Application.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)) Then
    opening_inventory_today = Application.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)
    ' rest of your code here

Else
    MsgBox "VLookup was unable to find " & selrow, vbInformation
End If
</code>```

Title: Vlookup property not working in vba

Body:
I am searching a variable selrow which holds string values in a sheet. Sometimes it shows error

unable to get vlookup property of worksheet function class

I have also put the error handling code but still error occurs.

Code

this where error occurs

for i=1 to last_row
    'code
    selrow= range("D"&i)
    opening_inventory_today = 0
    On Error Resume Next
    opening_inventory_today = Application.WorksheetFunction.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)

Body:
Using On Error Resume Next is not handling the error, you need to trap the cases that VLookup was unable to find selrow, and then raise an error message (or whatever you want).

Try the code below:

If Not IsError(Application.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)) Then
    opening_inventory_today = Application.VLookup(selrow, ActiveSheet.Range("A4:B" & lr), 2, False)
    ' rest of your code here

Else
    MsgBox "VLookup was unable to find " & selrow, vbInformation
End If


问:
Add phone number on top of menu and should be responsive view in mobile
The wordpress theme I'm using is this one:
https://wordpress.org/themes/total/

My website is http://www.kalimataxiservice.com/

I just want to add two phone numbers on the right side of this theme like this:

Desktop:

Mobile:

I used this html but not work:

 +91-9996320362

+91-8708558959

I used this css:
    .contact-phone {
    display:block;
    text-align: right;
    font-size: 24px;
    line-height: 1.6;
    font-weight: 400;
    font-family: 'Oswald', sans-serif;
       }

答:
Ok let's do it

First, open your style.css and replace CSS with below code

```<code>#ht-site-navigation {
  float: left;
  padding: 27px 0;
  transition: padding 0.3s ease 0s;
  width: 47%;
}
.contact-phone {
    display:block;
    text-align: right;
    font-size: 24px;
    line-height: 1.6;
    font-weight: 400;
    font-family: 'Oswald', sans-serif;
    float: right;
       }
</code>```

open your functions.php and find the code below

```<code>function total_widgets_init() {
</code>```

after this code add the new widget like this

```<code>register_sidebar( array(
        'name'          => esc_html__( 'Header Phone', 'total' ),
        'id'            => 'total-head-mobile',
        'description'   => __( 'Add widgets here to appear in Phone not on header.', 'total' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
</code>```

Now turn to call widget into your header.php open it and find the code
below it call your widget

```<code>          <div class="contact-phone">
                        <?php if(is_active_sidebar('total-head-mobile')):
                            dynamic_sidebar('total-head-mobile');
                        endif;
                        ?>
                    </div>
</code>```

open your widget from the back and you will see there a widget with the name Header Phone drag a text box in it  and add your phone no code

```<code> <i class="fa fa-phone" aria-hidden="true"></i> <a href="tel:+91-9996320362">+91-9996320362</a><br>
<a href="tel:+91-8708558959">+91-8708558959</a>
</code>```

init. check the screenshot http://prntscr.com/fgf24h
and it will appear frontend like this: http://prntscr.com/fgf2km

OK for mobile please add this css to your style.css or if there any responsive directory file add there

```<code>@media only screen  and (min-width: 320px)  and (max-width: 767px) {
#ht-site-navigation {
  padding: 0;
}
.contact-phone {
  position: relative;
  z-index: 999;
}
#ht-site-branding {
  float: left;
  width: 100%;
}

}
</code>```

if any you will face any problem adding the comment below.

Thanks

Body:
Ok let's do it

First, open your style.css and replace CSS with below code

#ht-site-navigation {
  float: left;
  padding: 27px 0;
  transition: padding 0.3s ease 0s;
  width: 47%;
}
.contact-phone {
    display:block;
    text-align: right;
    font-size: 24px;
    line-height: 1.6;
    font-weight: 400;
    font-family: 'Oswald', sans-serif;
    float: right;
       }

open your functions.php and find the code below

function total_widgets_init() {

after this code add the new widget like this

register_sidebar( array(
        'name'          => esc_html__( 'Header Phone', 'total' ),
        'id'            => 'total-head-mobile',
        'description'   => __( 'Add widgets here to appear in Phone not on header.', 'total' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );

Now turn to call widget into your header.php open it and find the code
below it call your widget

          <div class="contact-phone">
                        <?php if(is_active_sidebar('total-head-mobile')):
                            dynamic_sidebar('total-head-mobile');
                        endif;
                        ?>
                    </div>

open your widget from the back and you will see there a widget with the name Header Phone drag a text box in it  and add your phone no code

 <i class="fa fa-phone" aria-hidden="true"></i> <a href="tel:+91-9996320362">+91-9996320362</a><br>
<a href="tel:+91-8708558959">+91-8708558959</a>

init. check the screenshot http://prntscr.com/fgf24h
and it will appear frontend like this: http://prntscr.com/fgf2km

OK for mobile please add this css to your style.css or if there any responsive directory file add there

@media only screen  and (min-width: 320px)  and (max-width: 767px) {
#ht-site-navigation {
  padding: 0;
}
.contact-phone {
  position: relative;
  z-index: 999;
}
#ht-site-branding {
  float: left;
  width: 100%;
}

}

if any you will face any problem adding the comment below.

Thanks


问:
Having issues with if, else statements python
I am learning python and was doing an exercise for myself and I get a few problems.

If I type "yes" will that return invalid answer since it's looking for "Yes"?

Also, I feel like I am doing something wrong with my if statement even if I type "Yes" Correctly I still get "Invalid Answer" Printed.

Any thoughts on how I can improve?

```<code>attribute = {
    "G": "Greatest",
    "O": "Of",
    "A": "All",
    "T": "Time"
    }

answer = str(raw_input("Will You Make Me Food?:"))

for answer in range(2):
    if answer == "Yes":
        print attribute
    elif answer == "No":
        print "Your the Worst"
    else:
        print "Invalid Answer"
</code>```

答:
Your code makes a case-sensitive search. You can modify it so it says:

```<code>for answer in range(2):
    if answer == "Yes" or answer == "yes":
        print attribute
    elif answer == "No" or answer == "no":
        print "Your the Worst"
    else:
        print "Invalid Answer"
</code>```

Or you can make the input read into lower or upper and search in the same case you are converting it into.

```<code>answer = str(raw_input("Will You Make Me Food?:")).lower()   # or .upper()
for answer in range(2):
    if answer == "yes":
        print attribute
    elif answer == "no":
        print "Your the Worst"
    else:
        print "Invalid Answer"
</code>```

Body:
I am learning python and was doing an exercise for myself and I get a few problems.

If I type "yes" will that return invalid answer since it's looking for "Yes"?

Also, I feel like I am doing something wrong with my if statement even if I type "Yes" Correctly I still get "Invalid Answer" Printed.

Any thoughts on how I can improve?

attribute = {
    "G": "Greatest",
    "O": "Of",
    "A": "All",
    "T": "Time"
    }

answer = str(raw_input("Will You Make Me Food?:"))

for answer in range(2):
    if answer == "Yes":
        print attribute
    elif answer == "No":
        print "Your the Worst"
    else:
        print "Invalid Answer"

Body:
Your code makes a case-sensitive search. You can modify it so it says:

for answer in range(2):
    if answer == "Yes" or answer == "yes":
        print attribute
    elif answer == "No" or answer == "no":
        print "Your the Worst"
    else:
        print "Invalid Answer"

Or you can make the input read into lower or upper and search in the same case you are converting it into.

answer = str(raw_input("Will You Make Me Food?:")).lower()   # or .upper()
for answer in range(2):
    if answer == "yes":
        print attribute
    elif answer == "no":
        print "Your the Worst"
    else:
        print "Invalid Answer"


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
A slight edit to Anton's code:

```<code>function fact(x) {
   if(x>0)
       return x* fact(x-1);
   if(x===0)
       return 1;
   return null;

}
</code>```

(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)

ContentLicense: CC BY-SA 2.5

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>

Body:
A slight edit to Anton's code:

function fact(x) {
   if(x>0)
       return x* fact(x-1);
   if(x===0)
       return 1;
   return null;

}

(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)


问:
alasql sheetname with special characters
How can I export an excel files with multiple sheets with special characters in sheet name?
For example, I tried this but the file cannot be opened:</p>

```<code>window.saveFile = function saveFile () {
        var data1 = [{a:1,b:10},{a:2,b:20}];
    var data2 = [{a:100,b:10},{a:200,b:20}];
    var opts = [{sheetid:'Good1&2',header:true},{sheetid:'Two',header:false}];
    var res = alasql('SELECT INTO XLSX("MyAwesomeData.xlsx",?) FROM ?',[opts,[data1,data2]]);
}
</code>```

答:
Finally I found the solution, I need to escape the sheetid in xml since it's generated in xml format to the excel.

Here is the source: http://jsfiddle.net/ry8fq0dL/125/

```<code> window.saveFile = function saveFile () {
var data1 = [{a:1,b:10},{a:2,b:20}];
    var data2 = [{a:100,b:10},{a:200,b:20}];
    var opts = [{sheetid:"One1&2",header:true},{sheetname:'Two',header:false}];
    var res = alasql('SELECT INTO XLSX("restest344b.xlsx",?) FROM ?',
                     [opts,[data1,data2]]);
}
</code>```

Body:
How can I export an excel files with multiple sheets with special characters in sheet name?
For example, I tried this but the file cannot be opened:

window.saveFile = function saveFile () {
        var data1 = [{a:1,b:10},{a:2,b:20}];
    var data2 = [{a:100,b:10},{a:200,b:20}];
    var opts = [{sheetid:'Good1&2',header:true},{sheetid:'Two',header:false}];
    var res = alasql('SELECT INTO XLSX("MyAwesomeData.xlsx",?) FROM ?',[opts,[data1,data2]]);
}

Body:
Finally I found the solution, I need to escape the sheetid in xml since it's generated in xml format to the excel.

Here is the source: http://jsfiddle.net/ry8fq0dL/125/

 window.saveFile = function saveFile () {
var data1 = [{a:1,b:10},{a:2,b:20}];
    var data2 = [{a:100,b:10},{a:200,b:20}];
    var opts = [{sheetid:"One1&amp;2",header:true},{sheetname:'Two',header:false}];
    var res = alasql('SELECT INTO XLSX("restest344b.xlsx",?) FROM ?',
                     [opts,[data1,data2]]);
}


问:
Unknown column 'submittedby' in 'field list'
I am pretty new to PHP and MySQL and I just can't figure this one out. I
have searched all around the forum but haven't found an answer I can make sense of.

I get the following error: Unknown column 'submittedby' in 'field list', the problem is with this line of the code -

```<code>$update="update users set enrol_Date='".$enrol_Date."', username='".$username."', firstname='".$firstname."', lastname='".$lastname."', identificationCard='".$identificationCard."', email='".$email."',contact='".$contact."', submittedby='".$submittedby."' where id='".$id."'";
</code>```

The whole code is:

```<code><?php
  require('db.php');
  include("auth.php");
  $id=$_REQUEST['id'];
  $query = "SELECT * from users where id='".$id."'";
  $result = mysqli_query($con, $query) or die ( mysqli_error());
  $row = mysqli_fetch_assoc($result);
?>

<?php
  $status = "";
  if(isset($_POST['new']) && $_POST['new']==1)
  {
    $id=$_REQUEST['id'];
    $enrol_Date = date("Y-m-d H:i:s");
    $username =$_REQUEST['username'];
    $firstname =$_REQUEST['firstname'];
    $lastname =$_REQUEST['lastname'];
    $identificationCard =$_REQUEST['identificationCard'];
    $email =$_REQUEST['email'];
    $contact =$_REQUEST['contact'];
    $submittedby = $_SESSION["username"];
    $update="update users set enrol_Date='".$enrol_Date."', username='".$username."', firstname='".$firstname."', lastname='".$lastname."', identificationCard='".$identificationCard."', email='".$email."',contact='".$contact."', submittedby='".$submittedby."' where id='".$id."'";
    mysqli_query($con, $update) or die(mysqli_error($con));
    $status = "Profile Updated Successfully. </br></br>
    <a href='view.php'>View Updated Record</a>";
    echo '<p style="color:#FF0000;">'.$status.'</p>';
  }else {
?>
</code>```

Here is my form code:

```<code><form name="form" method="post" action="">
  <input type="hidden" name="new" value="1" />
  <input name="id" type="hidden" value="<?php echo $row['id'];?>" />
  <label for="username"> Username : </label>
  <p><input type="text" name="username" placeholder="Username"
  required value="<?php echo $row['username'];?>" /></p>
  <label for="firstname"> Firstname : </label>
  <p><input type="text" name="firstname" placeholder="Firstname"
  required value="<?php echo $row['firstname'];?>" /></p>
  <label for="lastname"> Lastname : </label>
  <p><input type="text" name="lastname" placeholder="Lastname"
  required value="<?php echo $row['lastname'];?>" /></p>
  <label for="i/cno"> I/C No : </label>
  <p><input type="text" name="identificationCard" placeholder="I/C"
  required value="<?php echo $row['identificationCard'];?>" /></p>
  <label for="email"> Email : </label>
  <p><input type="text" name="email" placeholder="Email"
  required value="<?php echo $row['email'];?>" /></p>
  <label for="contact"> Contact : </label>
  <p><input type="text" name="contact" placeholder="Contact"
  required value="<?php echo $row['contact'];?>" /></p>
  <p><input name="submit" type="submit" value="Submit" /></p>
</form>
</code>```

Thanks.

答: It means your "users" table does not contain "submittedby" column. You will need to add this column to your table for this script to work.</p>

Body:
I am pretty new to PHP and MySQL and I just can't figure this one out. I
have searched all around the forum but haven't found an answer I can make sense of.

I get the following error: Unknown column 'submittedby' in 'field list', the problem is with this line of the code -

$update="update users set enrol_Date='".$enrol_Date."', username='".$username."', firstname='".$firstname."', lastname='".$lastname."', identificationCard='".$identificationCard."', email='".$email."',contact='".$contact."', submittedby='".$submittedby."' where id='".$id."'";

The whole code is:

<?php
  require('db.php');
  include("auth.php");
  $id=$_REQUEST['id'];
  $query = "SELECT * from users where id='".$id."'";
  $result = mysqli_query($con, $query) or die ( mysqli_error());
  $row = mysqli_fetch_assoc($result);
?>

<?php
  $status = "";
  if(isset($_POST['new']) && $_POST['new']==1)
  {
    $id=$_REQUEST['id'];
    $enrol_Date = date("Y-m-d H:i:s");
    $username =$_REQUEST['username'];
    $firstname =$_REQUEST['firstname'];
    $lastname =$_REQUEST['lastname'];
    $identificationCard =$_REQUEST['identificationCard'];
    $email =$_REQUEST['email'];
    $contact =$_REQUEST['contact'];
    $submittedby = $_SESSION["username"];
    $update="update users set enrol_Date='".$enrol_Date."', username='".$username."', firstname='".$firstname."', lastname='".$lastname."', identificationCard='".$identificationCard."', email='".$email."',contact='".$contact."', submittedby='".$submittedby."' where id='".$id."'";
    mysqli_query($con, $update) or die(mysqli_error($con));
    $status = "Profile Updated Successfully.

    View Updated Record";
    echo '
'.$status.'
';
  }else {
?>

Here is my form code:

<form name="form" method="post" action="">
  <input type="hidden" name="new" value="1" />
  <input name="id" type="hidden" value="<?php echo $row['id'];?>" />
   Username :

<input type="text" name="username" placeholder="Username"
  required value="<?php echo $row['username'];?>" />

   Firstname :

<input type="text" name="firstname" placeholder="Firstname"
  required value="<?php echo $row['firstname'];?>" />

   Lastname :

<input type="text" name="lastname" placeholder="Lastname"
  required value="<?php echo $row['lastname'];?>" />

   I/C No :

<input type="text" name="identificationCard" placeholder="I/C"
  required value="<?php echo $row['identificationCard'];?>" />

   Email :

<input type="text" name="email" placeholder="Email"
  required value="<?php echo $row['email'];?>" />

   Contact :

<input type="text" name="contact" placeholder="Contact"
  required value="<?php echo $row['contact'];?>" />

<input name="submit" type="submit" value="Submit" />

</form>

Thanks.


问:
Google spreadsheet color sheet tab
I am using google script in a spreadsheet and I would like to color the sheet tab. Do you have any idea how to do ?

Thank you for your answer

答:
You can use the setTabColor().

From the Google documentation you use it like this:

```<code>// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setTabColor("ff0000"); // Set the color to red.
first.setTabColor(null); // Unset the color.
</code>```

Title: Google spreadsheet color sheet tab

Body:
You can use the setTabColor().

From the Google documentation you use it like this:

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setTabColor("ff0000"); // Set the color to red.
first.setTabColor(null); // Unset the color.


问:
GCC: how to fix or suppress the warning: unknown escape sequence: '\#'
The OpenGL ES shader code is defined as a C string. To make writing the shader code more intuitively, I define a macro named SHADER_STRING(code) like below. But I encounter a GCC warning unknown escape sequence: '\#' and don't know how to suppress it or fix it.

A example code is below

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

int main(void)
{
#define _SHADER_STRING(code) #code
#define SHADER_STRING(code) _SHADER_STRING(code)
    // OpenGL ES Shader codes
    char vShaderStr[] = SHADER_STRING(
        \#version 300 es \n

        void main()
        {
            // ... some OpenGL ES codes.
        });
    printf("%s\n", vShaderStr);
    return 0;
}
</code>```

Because the #version is a preprocessor supported by OpenGL ES 3.0, then it's invalid to replace the \# with \\#, otherwise the codes will become

```<code>\#version 300 es
void main() { }
</code>```

The OpenGL shader compiler will complained knowing nothing about the \#version .

答:
According to this answer, the following code should work:</p>

```<code>#define GLSL(version, shader)  "#version " #version "\n" #shader

const GLchar* vShaderStr_30 = GLSL(300,
    void main() {
        …
    }
);
</code>```

Body:
The OpenGL ES shader code is defined as a C string. To make writing the shader code more intuitively, I define a macro named SHADER_STRING(code) like below. But I encounter a GCC warning unknown escape sequence: '\#' and don't know how to suppress it or fix it.

A example code is below

#include <stdio.h>

int main(void)
{
#define _SHADER_STRING(code) #code
#define SHADER_STRING(code) _SHADER_STRING(code)
    // OpenGL ES Shader codes
    char vShaderStr[] = SHADER_STRING(
        \#version 300 es \n

        void main()
        {
            // ... some OpenGL ES codes.
        });
    printf("%s\n", vShaderStr);
    return 0;
}

Because the #version is a preprocessor supported by OpenGL ES 3.0, then it's invalid to replace the \# with \\#, otherwise the codes will become

\#version 300 es
void main() { }

The OpenGL shader compiler will complained knowing nothing about the \#version .

Body:
According to this answer, the following code should work:

#define GLSL(version, shader)  "#version " #version "\n" #shader

const GLchar* vShaderStr_30 = GLSL(300,
    void main() {
        …
    }
);


问:
Model weights not changing Keras
I am trying to create neural nets with random weights in keras. I am using set_weights() function of models, to assign random weights. However, model.predict() gives the same output on a certain input regardless of weights. The output differs every time I run the program, but it's same while a program is running. Here is the code:

ConnectFourAI.py:

```<code>from keras.models import Sequential
from keras.layers import Dense
from minimax2 import ConnectFour
import numpy as np
from time import sleep
import itertools
import random
import time

def get_model():

    model = Sequential()
    model.add(Dense(630, input_dim=84, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(630,kernel_initializer='normal', activation='relu'))
    model.add(Dense(7, kernel_initializer='normal', activation='relu'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

map = {
    'x':[1,0],
    ' ':[0,0],
    'o':[0,1]
}

model = get_model()

def get_AI_move(grid):
    global model
    inp = np.array(list(itertools.chain.from_iterable([map[t] for t in np.array(grid).reshape(42)]))).reshape(1,84)
    nnout = model.predict(inp)
    # print(list(nnout[0]))
    out = np.argmax(nnout)
    while grid[0][out] != " ":
        out = np.random.randint(7)
    print("out = %d"%out)
    return out

shapes = [(w.shape) for w in model.get_weights()]

print(list(model.get_weights()[0][0][0:5]))
def score_func(x, win):
        if win == "x":
            return 10000
        elif win == " ":
            return 2000
        else:
            return x**2

if __name__=="__main__":

    for i in range(100):
        weights = [np.random.randn(*s) for s in shapes]
        # print(list(weights[0][0][0:5]))
        model.set_weights(weights)
        print(list(model.get_weights()[0][0][0:5]))
        game = ConnectFour()
        game.start_new()
        rounds = game._round
        win = game._winner
        score = score_func(rounds, win)
        print("%dth game scored %.3f"%(i+1,score))

        seed = int(time.time()* 10**6)%(2**32)+1
        np.random.seed(seed)
</code>```

To recreate this error, you need an extra file. Everything is OK in this file, but the only call to random always gives the same value. Here is the file.

答: I don't know what exactly was going wrong, but I came up with a work around. Apparently there was some problem in random module due to which this behaviour took place when random module is called from 2 different files. So I used one file instead of two, and got the results I expected.</p>

Title: Model weights not changing Keras

Body:
I am trying to create neural nets with random weights in keras. I am using set_weights() function of models, to assign random weights. However, model.predict() gives the same output on a certain input regardless of weights. The output differs every time I run the program, but it's same while a program is running. Here is the code:

ConnectFourAI.py:

from keras.models import Sequential
from keras.layers import Dense
from minimax2 import ConnectFour
import numpy as np
from time import sleep
import itertools
import random
import time

def get_model():

    model = Sequential()
    model.add(Dense(630, input_dim=84, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(630,kernel_initializer='normal', activation='relu'))
    model.add(Dense(7, kernel_initializer='normal', activation='relu'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

map = {
    'x':[1,0],
    ' ':[0,0],
    'o':[0,1]
}

model = get_model()

def get_AI_move(grid):
    global model
    inp = np.array(list(itertools.chain.from_iterable([map[t] for t in np.array(grid).reshape(42)]))).reshape(1,84)
    nnout = model.predict(inp)
    # print(list(nnout[0]))
    out = np.argmax(nnout)
    while grid[0][out] != " ":
        out = np.random.randint(7)
    print("out = %d"%out)
    return out

shapes = [(w.shape) for w in model.get_weights()]

print(list(model.get_weights()[0][0][0:5]))
def score_func(x, win):
        if win == "x":
            return 10000
        elif win == " ":
            return 2000
        else:
            return x**2

if __name__=="__main__":

    for i in range(100):
        weights = [np.random.randn(*s) for s in shapes]
        # print(list(weights[0][0][0:5]))
        model.set_weights(weights)
        print(list(model.get_weights()[0][0][0:5]))
        game = ConnectFour()
        game.start_new()
        rounds = game._round
        win = game._winner
        score = score_func(rounds, win)
        print("%dth game scored %.3f"%(i+1,score))

        seed = int(time.time()* 10**6)%(2**32)+1
        np.random.seed(seed)

To recreate this error, you need an extra file. Everything is OK in this file, but the only call to random always gives the same value. Here is the file.


问:
how to summarise only numerical columns in R
I want to have summary of only numerical columns of R dataframe. I am doing following

```<code>numeric_var <- names(df)[which(sapply(df, is.numeric))]

summary(df[,.SD, .SDcols = numeric_var])
</code>```

But, I get following error

```<code>Error in `[.data.frame`(df, , .SD, .SDcols = numeric_var) :
unused argument (.SDcols = numeric_var)
</code>```

How can I do it in R?

答:
UPDATED - June 29/2021

With the new version of tidyverse (dplyr - version 1.0.6), we can modify the _if or _all suffix with

```<code>library(dplyr)
df %>%
    select(where(is.numeric))
   col2      col3
1: -0.5458808 0.6048889
2:  0.5365853 0.3707349
3:  0.4196231 0.6716903
4: -0.5836272 0.6729823
5:  0.8474600 0.3204306
</code>```

With summarise, use

```<code>df %>%
   summarise(across(where(is.numeric), ~ list(summary(.))))
</code>```

We can use tidyverse

```<code>df %>%
   select_if(is.numeric)
#         col2      col3
#1: -0.5458808 0.6048889
#2:  0.5365853 0.3707349
#3:  0.4196231 0.6716903
#4: -0.5836272 0.6729823
#5:  0.8474600 0.3204306
</code>```

If we need to apply summary on the tidyverse

```<code>df %>%
    select_if(is.numeric) %>%
    summarise_all(funs(list(summary(.))))
</code>```

Or get the output in wide format

```<code>df %>%
      select_if(is.numeric) %>%
       do(data.frame(lapply(., function(x) as.list(summary(x)))))
#    col2.Min. col2.1st.Qu. col2.Median col2.Mean col2.3rd.Qu. col2.Max. col3.Min. col3.1st.Qu. col3.Median col3.Mean col3.3rd.Qu. col3.Max.
#1 -0.5836272   -0.5458808   0.4196231 0.1348321    0.5365853   0.84746 0.3204306    0.3707349   0.6048889 0.5281454    0.6716903 0.6729823
</code>```

Or using data.table

```<code>library(data.table)
i1 <- which(unlist(lapply(df, is.numeric)))
</code>```

The summary function can be applied separately on each column.  It is not clear about how the output should look like

```<code>setDT(df)[,  unlist(lapply(.SD, summary), recursive = FALSE) , .SDcols = i1]
#   col2.Min. col2.1st Qu.  col2.Median    col2.Mean col2.3rd Qu.    col2.Max.    col3.Min. col3.1st Qu.  col3.Median    col3.Mean col3.3rd Qu.    col3.Max.
#  -0.5836272   -0.5458808    0.4196231    0.1348321    0.5365853    0.8474600    0.3204306    0.3707349    0.6048889    0.5281454    0.6716903    0.6729823
</code>```

data

```<code>set.seed(24)
df <- data.table(col1 = letters[1:5], col2 = rnorm(5), col3 = runif(5))
</code>```

Body:
I want to have summary of only numerical columns of R dataframe. I am doing following

numeric_var <- names(df)[which(sapply(df, is.numeric))]

summary(df[,.SD, .SDcols = numeric_var])

But, I get following error

Error in `[.data.frame`(df, , .SD, .SDcols = numeric_var) :
unused argument (.SDcols = numeric_var)

How can I do it in R?

Body:
UPDATED - June 29/2021

With the new version of tidyverse (dplyr - version 1.0.6), we can modify the _if or _all suffix with

library(dplyr)
df %>%
    select(where(is.numeric))
   col2      col3
1: -0.5458808 0.6048889
2:  0.5365853 0.3707349
3:  0.4196231 0.6716903
4: -0.5836272 0.6729823
5:  0.8474600 0.3204306

With summarise, use

df %>%
   summarise(across(where(is.numeric), ~ list(summary(.))))

We can use tidyverse

df %>%
   select_if(is.numeric)
#         col2      col3
#1: -0.5458808 0.6048889
#2:  0.5365853 0.3707349
#3:  0.4196231 0.6716903
#4: -0.5836272 0.6729823
#5:  0.8474600 0.3204306

If we need to apply summary on the tidyverse

df %>%
    select_if(is.numeric) %>%
    summarise_all(funs(list(summary(.))))

Or get the output in wide format

df %>%
      select_if(is.numeric) %>%
       do(data.frame(lapply(., function(x) as.list(summary(x)))))
#    col2.Min. col2.1st.Qu. col2.Median col2.Mean col2.3rd.Qu. col2.Max. col3.Min. col3.1st.Qu. col3.Median col3.Mean col3.3rd.Qu. col3.Max.
#1 -0.5836272   -0.5458808   0.4196231 0.1348321    0.5365853   0.84746 0.3204306    0.3707349   0.6048889 0.5281454    0.6716903 0.6729823

Or using data.table

library(data.table)
i1 <- which(unlist(lapply(df, is.numeric)))

The summary function can be applied separately on each column.  It is not clear about how the output should look like

setDT(df)[,  unlist(lapply(.SD, summary), recursive = FALSE) , .SDcols = i1]
#   col2.Min. col2.1st Qu.  col2.Median    col2.Mean col2.3rd Qu.    col2.Max.    col3.Min. col3.1st Qu.  col3.Median    col3.Mean col3.3rd Qu.    col3.Max.
#  -0.5836272   -0.5458808    0.4196231    0.1348321    0.5365853    0.8474600    0.3204306    0.3707349    0.6048889    0.5281454    0.6716903    0.6729823

data

set.seed(24)
df <- data.table(col1 = letters[1:5], col2 = rnorm(5), col3 = runif(5))

ContentLicense: CC BY-SA 4.0


问:
Don't append newline when redirection program's output to a file
I have a program which list files of a directory, when there is not a file, it output is empty, but if program > output.txt, there is a newline in this file, so can not use test -s output.txt to judge if the directory is empty. how to resolve this problem, there is not wc command at my system, but sed, sort, grep are OK, thanks!

答:
Since you mentioned you cannot use wc. You can use the following command to print the number of non-empty lines.

```<code>grep -c . inputfile
</code>```

To print the number of empty lines:

```<code>grep -vc . inputfile
</code>```

Body:
Since you mentioned you cannot use wc. You can use the following command to print the number of non-empty lines.

grep -c . inputfile

To print the number of empty lines:

grep -vc . inputfile


问:
UILabel get Frame width or height
```<code>`lblAddress.frame.width`
`lblAddress.frame.size.width`
</code>```

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

答: They are almost the same; however, fram.width is a get only value, but frame.size.width can be used to set or to get the value

Title: UILabel get Frame width or height

Body:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.


问:
Python - Selenium - select an element from a dropdown menu
I need to select an element from a dropdown menu.

For example:

```<code>    <div class="col-sm-4 col-lg-2">
       <label for="rangeFilter" class="sr-only">Date Range</label>
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>
     </div>
</code>```

but i have always some kind of error.

My code is so easy:

```<code>driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')
</code>```

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

```<code>Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated
</code>```

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

答:
The dropdown you are trying to select from is actually not the element with rangeFilter id. Its in the sibling
.

Since you can't use Select class on any tag either than <select> you need to first click on the dropdown to make it open the options and then click on the option

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")

drop_down = driver.find_element_by_css_selector('[data-id="rangeFilter"]')
ActionChains(driver).move_to_element(drop_down).perform()
drop_down.click()

option = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//span[contains(., "All time")]')))
option.click()
</code>```

Body:
I need to select an element from a dropdown menu.

For example:

       Date Range
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>

but i have always some kind of error.

My code is so easy:

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"

Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

Body:
The dropdown you are trying to select from is actually not the element with rangeFilter id. Its in the sibling <div>.

Since you can't use Select class on any tag either than <select> you need to first click on the dropdown to make it open the options and then click on the option

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")

drop_down = driver.find_element_by_css_selector('[data-id="rangeFilter"]')
ActionChains(driver).move_to_element(drop_down).perform()
drop_down.click()

option = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//span[contains(., "All time")]')))
option.click()


问:
Incompatible types. Required: GoogleApiClient Found: GoogleApiClient.Builder
I am trying to get the last known location using Google API client, but I have an issue with it being incompatible. Can anyone point out what did I miss?</p>

```<code>import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, OnConnectionFailedListener,
        ConnectionCallbacks{

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // getting incompatible issue in below line
        mGoogleApiClient = new GoogleApiClient.Builder(this);

        // Obtain the SupportMapFragment and get notified when the map is ready           to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
</code>```

答:
Try this.</p>

```<code>        mGoogleApiClient = new GoogleApiClient.Builder(this).build();
</code>```

Body:
I am trying to get the last known location using Google API client, but I have an issue with it being incompatible. Can anyone point out what did I miss?

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, OnConnectionFailedListener,
        ConnectionCallbacks{

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // getting incompatible issue in below line
        mGoogleApiClient = new GoogleApiClient.Builder(this);

        // Obtain the SupportMapFragment and get notified when the map is ready           to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

Body:
Try this.

        mGoogleApiClient = new GoogleApiClient.Builder(this).build();


问:
Setting model attributes for every action within each controller
I would like to set three common attributes on my model for each @RequestMapping within the many controllers in a Spring Boot application. I have read about @ModelAttribute but it needs to be placed within each Controller. I have more than 20 controllers in my application and each having more than 10 @RequestMapping.

Is there a way to set such model attributes in one place which gets initialized at the start of the application?

答:
I provide another method by SpringMVC,using the HandlerInterceptor,when you implements it,it provides 3 methods,each of them contains HttpServletRequest,you can set attribute using request.setAttribute("xx","yy"),below are the code:

```<code>public class RequestInterceptor implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
      //you can set attributes here like request.setAttribute("xx","yy")
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        //you can set attributes here like request.setAttribute("xx","yy")
        return false;
    }

}
</code>```

then,you need to add the custom interceptor to your spring mvc application like below:

```<code><bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
   <property name="interceptors">
    <list>
      <!--class of your custom interceptor-->
      <bean class="com.xx.RequestInterceptor"/>
    </list>
   </property>
</bean>
</code>```

Body:
I provide another method by SpringMVC,using the HandlerInterceptor,when you implements it,it provides 3 methods,each of them contains HttpServletRequest,you can set attribute using request.setAttribute("xx","yy"),below are the code:

public class RequestInterceptor implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
      //you can set attributes here like request.setAttribute("xx","yy")
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        //you can set attributes here like request.setAttribute("xx","yy")
        return false;
    }

}

then,you need to add the custom interceptor to your spring mvc application like below:

<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
   <property name="interceptors">
    <list>
      <!--class of your custom interceptor-->
      <bean class="com.xx.RequestInterceptor"/>
    </list>
   </property>
</bean>


问:
Position animated icons and remove overlapping using CSS
I am trying to position the icons to the right and the tags to the center.
My website is using BootStrap and Font-Awesome. Below is the HTML:

```<code><div class="row">
  <div class="col-lg-12" style="text-align: center">
    <a href="#" style="text-decoration: none;">
      <span style="background-color: #171717; color: #FFF; padding: 2px">Health</span>
    </a>
    <span> </span>
    <a href="#" style="text-decoration: none;">
      <span style="background-color: #171717; color: #FFF; padding: 2px">Fitness</span>
    </a>
    <span> </span>
    <a href="#" style="text-decoration: none;">
      <span style="background-color: #171717; color: #FFF; padding: 2px">Safety</span>
    </a>
    <span> </span>
    <i class="fa fa-heart faa-pulse animated" style="float:right;"></i>
    <i class="fa fa-star faa-pulse animated" style="float:right;"></i>
    <i class="fa fa-smile-o faa-pulse animated" style="float:right;"></i>
  </div>
</div>
<div class="row">
  <div class="col-lg-12">
    <h1 class="post-header" style="text-align: center">This is the header</h1>
  </div>
</div>
</code>```

CSS:

```<code>@keyframes pulse {
  0% {
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
  }

  50% {
    -webkit-transform: scale(0.8);
    -ms-transform: scale(0.8);
    transform: scale(0.8);
  }

  100% {
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
  }
}

.faa-pulse.animated,
.faa-pulse.animated-hover:hover,
.faa-parent.animated-hover:hover > .faa-pulse {
  -webkit-animation: pulse 2s linear infinite !important;
  animation: pulse 2s linear infinite !important;
  font-size:1.8em;
}
.fa-heart {
    color: red !important;
}
.fa-star {
    color: gold !important;
}
.fa-smile-o {
  color: deeppink !important;
}
</code>```

The problem is my icons are overlapping with each other during animation and the tags are not aligned to the center. Also,there is very little space between the icons. How can I solve this problem?

Here is the demo

答:
Try Adding margin to the font Awesome Icons

```<code>i.fa
{
  margin:4px;
}
</code>```

Hope this helps.. :D

Body:
I am trying to position the icons to the right and the tags to the center.
My website is using BootStrap and Font-Awesome. Below is the HTML:

      Health

      Fitness

      Safety

This is the header

CSS:

@keyframes pulse {
  0% {
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
  }

  50% {
    -webkit-transform: scale(0.8);
    -ms-transform: scale(0.8);
    transform: scale(0.8);
  }

  100% {
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
  }
}

.faa-pulse.animated,
.faa-pulse.animated-hover:hover,
.faa-parent.animated-hover:hover > .faa-pulse {
  -webkit-animation: pulse 2s linear infinite !important;
  animation: pulse 2s linear infinite !important;
  font-size:1.8em;
}
.fa-heart {
    color: red !important;
}
.fa-star {
    color: gold !important;
}
.fa-smile-o {
  color: deeppink !important;
}

The problem is my icons are overlapping with each other during animation and the tags are not aligned to the center. Also,there is very little space between the icons. How can I solve this problem?

Here is the demo

Body:
Try Adding margin to the font Awesome Icons

i.fa
{
  margin:4px;
}

Hope this helps.. :D


问:
Count level within group_by hierarchy in dplyr
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

```<code>d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))
</code>```

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

```<code>  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2
</code>```

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?

答:
We can use data.table

```<code>library(data.table)
setDT(d)[, numbers := as.numeric(factor(case, levels = unique(case))), group]
</code>```

Body:
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?

Body:
We can use data.table

library(data.table)
setDT(d)[, numbers := as.numeric(factor(case, levels = unique(case))), group]


问:
Post two statements into database
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

```<code>$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));
</code>```

答:
Try this ==>

```<code>$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->bind_param("ss",$firstname, $lastname);
$stmt1->execute();

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->bind_param("ss",$firstname, $lastname);
$stmt2->execute();
</code>```

check more about PHP Prepared Statements here

Title: Post two statements into database

Body:
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));

Body:
Try this ==>

$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->bind_param("ss",$firstname, $lastname);
$stmt1->execute();

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->bind_param("ss",$firstname, $lastname);
$stmt2->execute();

check more about PHP Prepared Statements here


问:
SPARQL construct/insert query and blank nodes
I'm trying to create a SPARQL query to construct or insert graphs, following the BIBFRAME 2.0 Model, using a personal database with a lot of datas. I want to get a result like this:

```<code>Subject a bf:Topic, madsrdf:ComplexSubject ;
rdfs:label "Subject" ;
madsrdf:componentList [ a madsrdf:Topic ;
            madsrdf:authoritativeLabel "FirstSubject" ] ;
</code>```

But I do not know how to do it in SPARQL. I tryed with this query, but I always get a lot of blank nodes (as much as registers with empty "?Subject" fields I have in my database):

```<code>PREFIX bf: <http://id.loc.gov/ontologies/bibframe/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix madsrdf: <http://www.loc.gov/mads/rdf/v1#>

CONSTRUCT{

    ?subject a bf:Topic, madsrdf:ComplexSubject ;
        rdfs:label ?subject;
        madsrdf:componentList [ a madsrdf:Topic ;
                madsrdf:authoritativeLabel ?firstsubject ];

} where{ service <http://localhost:.......> {
        ?registerRow a <urn:Row> ;
        OPTIONAL{?registerRow <urn:col:Subject> ?subject ;}
        OPTIONAL{?registerRow <urn:col:FirstSubject> ?firstsubject ;}
                     }
}
</code>```

答:
@Wences, AKSW answered you, please read more carefully.
You don't use ?registerRow in the CONSTRUCT part, that's why it is executed once for each row.

Body:
I'm trying to create a SPARQL query to construct or insert graphs, following the BIBFRAME 2.0 Model, using a personal database with a lot of datas. I want to get a result like this:

Subject a bf:Topic, madsrdf:ComplexSubject ;
rdfs:label "Subject" ;
madsrdf:componentList [ a madsrdf:Topic ;
            madsrdf:authoritativeLabel "FirstSubject" ] ;

But I do not know how to do it in SPARQL. I tryed with this query, but I always get a lot of blank nodes (as much as registers with empty "?Subject" fields I have in my database):

PREFIX bf: <http://id.loc.gov/ontologies/bibframe/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix madsrdf: <http://www.loc.gov/mads/rdf/v1#>

CONSTRUCT{

    ?subject a bf:Topic, madsrdf:ComplexSubject ;
        rdfs:label ?subject;
        madsrdf:componentList [ a madsrdf:Topic ;
                madsrdf:authoritativeLabel ?firstsubject ];

} where{ service <http://localhost:.......> {
        ?registerRow a <urn:Row> ;
        OPTIONAL{?registerRow <urn:col:Subject> ?subject ;}
        OPTIONAL{?registerRow <urn:col:FirstSubject> ?firstsubject ;}
                     }
}


问:
How can you add a substring inside an if statement?
There is 3 category type (New Permit, Permit to Operate and Renewal) they have a reference number like 'R-662017-01' if the first letter is R its RENEWAL while for New permit its P and N for permit to operate.

how can you substring or do that in an if statement? please help :(

答:
you can use like this as well:</p>

```<code>string input = 'R-662017-01';
if (input.StartsWith("R"))
{
//do RENEWAL code
}
else if(input.StartsWith("P"))
{
//do New permit code
}
else if(input.StartsWith("N"))
{
//do Permit to Operate code
}
</code>```

Body:
you can use like this as well:

string input = 'R-662017-01';
if (input.StartsWith("R"))
{
//do RENEWAL code
}
else if(input.StartsWith("P"))
{
//do New permit code
}
else if(input.StartsWith("N"))
{
//do Permit to Operate code
}


问:
Finding Android SDK on Mac and adding to PATH
I have installed Android Studio on my MacBook Air (OS Version 10.11 El Capitan) and have successfully written a small "hello, world" app and installed on device (Nexus 7) and ran on AVD.  All I want to do now is be able to build the app and install it on device from the command line as opposed to Android Studio.  I'm following the directions here:

http://developer.android.com/training/basics/firstapp/running-app.html

and the relevant line is:

Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute:

The problem is I can't find the Android SDK on my machine!  I assume it's there because otherwise the program wouldn't compile and run through Android Studio?  Perhaps that's a bad assumption?  I'm new to Macs (I'm used to Windows) so I don't know the best way to search for the Android SDK.  So my questions:

How do I find Android SDK on my machine? Or prove to myself it's not there?

If it's not there how do I install it?

How do I change PATH to include Android SDK?

答:
The default path of Android SDK is /Users/<username>/Library/Android/sdk, you can refer to this post.

add this to your .bash_profile to add the environment variable

```<code>export PATH="/Users/<username>/Library/Android/sdk/tools:/Users/<username>/Library/Android/sdk/build-tools:${PATH}"
</code>```

Then save the file.

load it

```<code>source ./.bash_profile
</code>```

Body:
The default path of Android SDK is /Users/<username>/Library/Android/sdk, you can refer to this post.

add this to your .bash_profile to add the environment variable

export PATH="/Users/<username>/Library/Android/sdk/tools:/Users/<username>/Library/Android/sdk/build-tools:${PATH}"

Then save the file.

load it

source ./.bash_profile


问:
Remove space of checkbox if it does not exist
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

```<code>Checkbox - Date of creation - Title
</code>```

if Homework is 0, my row of the listview is like this :

```<code>         - Date of creation - Title
</code>```

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

```<code>-Date of creation - Title
</code>```

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

```<code>`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`
</code>```

my list_row.xml:

```<code>`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

`

答:
if you set the visibility of a view to inivisible it becomes invisible but occupy the space where it is used so set visibility ot Gone to free the space occupied by the view.Use below line of code in getview method of your adapter

```<code>  if(devor==1){
     if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }
     }else{
cbdevoir.setVisibility(View.GONE);
}
</code>```

Body:
I have a listView populated with the help of a CustomAdapter.

I make a test while retrieving the values from my db.

One of the rows if 'Homework'. If homework = 1, then I show a CheckBox in the beginning of the line of my listView. But if it's 0 , I dont show anything. But I'd like to move all the text after the checkbox to the left. in my list_row.xml I declared a checkbox, so if homework is 0, i just setVisibility to INVISIBLE on my checkbox.

I can't post images, so I'll give an example :

if homework is 1 , my listView is like this :

Checkbox - Date of creation - Title

if Homework is 0, my row of the listview is like this :

         - Date of creation - Title

So you can see that there will have an empty space if Homework is 0. How can I change that so it stays like this:

-Date of creation - Title

Thank you !And tell me if you need the code my CustomAdapter please

@UPDATE-my customadapter

`public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    int importance = cursor.getInt(5);
    int fait = cursor.getInt(10);
    final CheckBox cbdevoir = (CheckBox) view.findViewById(R.id.CBDevoir);
    final TextView couleur = (TextView)view.findViewById(R.id.TVCouleurImportance);

    if(importance==0)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff8080"));
    }
    if(importance==1)
    {
        couleur.setBackgroundColor(Color.parseColor("#ff0000"));
    }
    if(importance==2)
    {
        couleur.setBackgroundColor(Color.parseColor("#4d0000"));
    }

    if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }

    cbdevoir.setVisibility(devoir ==1? View.VISIBLE: View.GONE);`

my list_row.xml:

`<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="@+id/item_root"
android:weightSum="1">

<CheckBox
    android:id="@+id/CBDevoir"
    android:layout_width="30dp"
    android:layout_height="20dp"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="-1dp"
    android:checked="false"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_branche_cours"
    android:layout_width="75dp"
    android:layout_height="16dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="2dp"
    android:text="English"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_trait"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=" - "
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="-1dp"
    android:layout_marginLeft="106dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<TextView
    android:id="@+id/text_designation"
    android:layout_width="150dp"
    android:layout_height="18dp"
    android:layout_marginLeft="122dp"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:text="Reading"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TVCouleurImportance"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="281dp"
    android:layout_marginTop="-1dp"
    android:layout_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

`

Body:
if you set the visibility of a view to inivisible it becomes invisible but occupy the space where it is used so set visibility ot Gone to free the space occupied by the view.Use below line of code in getview method of your adapter

  if(devor==1){
     if (fait == 1) {
        cbdevoir.setChecked(true);
    } else {
        cbdevoir.setChecked(false);
    }
     }else{
cbdevoir.setVisibility(View.GONE);
}


问:
In query variables replacement error
I am using SQL variable replacements, and I am getting the following errors:

```<code> at com.ibm.as400.access.JDError.throwSQLException(JDError.java:408)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setValue(AS400JDBCPreparedStatement.java:3532)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setString(AS400JDBCPreparedStatement.java:3211)
        at queries.RunQueryDB2.runNameAccount(RunQueryDB2.java:237)
</code>```

The trace brings me to this code section,

```<code>stmt.setString( 1, name[0]);
stmt.setString( 2, name[1]);
stmt.setString( 3, name[2]);
</code>```

which references this SQL variable replacement:

```<code>nameToAcctQuery="SELECT DISTINCT a.Acnum"
                    + "FROM table c, table p, table a "
                    + "WHERE c.First= '?.toUpperCase()' "
                    + "AND c.Mid= '?.toUpperCase()' "
                    + "AND c.Last= '?.toUpperCase()' "
                    + "AND p.Pol= a.pol"
                    + "AND p.name= c.name";
</code>```

I use this format in many other queries, and I can not, for the life of me, figure out why I am getting an error in my variable replacement. Any ideas why?

答:
Modify your code like this:

```<code>stmt.setString( 1, name[0].toUpperCase());
stmt.setString( 2, name[1].toUpperCase());
stmt.setString( 3, name[2].toUpperCase());
</code>```

And your query like this (DB2 doesn't know the toUpperCase function):

```<code>nameToAcctQuery="SELECT DISTINCT a.Acnum"
                + "FROM table c, table p, table a "
                + "WHERE c.First= ? "
                + "AND c.Mid= ? "
                + "AND c.Last= ? "
                + "AND p.Pol= a.pol"
                + "AND p.name= c.name";
</code>```

Title: In query variables replacement error

Body:
I am using SQL variable replacements, and I am getting the following errors:

 at com.ibm.as400.access.JDError.throwSQLException(JDError.java:408)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setValue(AS400JDBCPreparedStatement.java:3532)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setString(AS400JDBCPreparedStatement.java:3211)
        at queries.RunQueryDB2.runNameAccount(RunQueryDB2.java:237)

The trace brings me to this code section,

stmt.setString( 1, name[0]);
stmt.setString( 2, name[1]);
stmt.setString( 3, name[2]);

which references this SQL variable replacement:

nameToAcctQuery="SELECT DISTINCT a.Acnum"
                    + "FROM table c, table p, table a "
                    + "WHERE c.First= '?.toUpperCase()' "
                    + "AND c.Mid= '?.toUpperCase()' "
                    + "AND c.Last= '?.toUpperCase()' "
                    + "AND p.Pol= a.pol"
                    + "AND p.name= c.name";

I use this format in many other queries, and I can not, for the life of me, figure out why I am getting an error in my variable replacement. Any ideas why?

Body:
Modify your code like this:

stmt.setString( 1, name[0].toUpperCase());
stmt.setString( 2, name[1].toUpperCase());
stmt.setString( 3, name[2].toUpperCase());

And your query like this (DB2 doesn't know the toUpperCase function):

nameToAcctQuery="SELECT DISTINCT a.Acnum"
                + "FROM table c, table p, table a "
                + "WHERE c.First= ? "
                + "AND c.Mid= ? "
                + "AND c.Last= ? "
                + "AND p.Pol= a.pol"
                + "AND p.name= c.name";


Title: Efficient search

Body:
I have written the following code

a<-matrix(0,1,nrow = nrow(x))
for(i in 1:nrow(x)){
  for(j in 1:nrow(y)){
   if((y[j,3] > x[i,2]) & (y[j,2] == x[i,1])){
     a[i,]<- y[j,4]
     i<- i+1
   }
  }

x looks something like:

x1  x2
401 4
401 38
401 142...

and y looks like

 y1 y2   y3    y4
  1 401 10  22.152
  2 401 40  167.986
  3 401 70  393.198
  4 401 100 923
  5 401 120 923
  6 401 140 686.712
  7 401 160 865.774...

I want a to be:

22.152
167.986
865.774...

where nrow(y) > nrow(x) is TRUE. Is it possible to make this more efficient?

Body:
With data.table, we join on 'x1', 'y1' from 'x' and 'y', specify the i as y3 > x2, grouped by 'x1' and 'x2', get the first row

library(data.table)
setDT(x)[y, on = .(x1 = y2), allow.cartesian = TRUE][y3 > x2, head(.SD, 1) , .(x1, x2)]
#    x1  x2 y1  y3      y4
#1: 401   4  1  10  22.152
#2: 401  38  2  40 167.986
#3: 401 142  7 160 865.774

data

x <- read.table(text = "
  x1  x2
401 4
401 38
401 142", header = TRUE)

y <- read.table(text = "
y1 y2   y3    y4
1 401 10  22.152
2 401 40  167.986
3 401 70  393.198
4 401 100 923
5 401 120 923
6 401 140 686.712
7 401 160 865.774", header = TRUE)


问:
How do you link Pachyderm with the correct Kubernetes context?
I have more than one Kubernetes context. When I change contexts, I have been using kill -9  to kill the port-forward in order to redo the pachtctl port-forward & command. I wonder if this is the right way of doing it.

In more detail:

I start off being in a Kubernetes context, we'll call it context_x. I then want to change context to my local context, called minikube. I also want to see my repos for this minikube context, but when I use pachctl list-repo, it still shows context_x's Pachyderm repos. When I do pachctl port-forward, I then get an error message about the address being already in use. So I have to ps -a, then kill -9 on those port forward processes, and then do pachctl port-forward command again.

An example of what I've been doing:

```<code>$ kubectl config use-context minikube
$ pachctl list-repo #doesn't show minikube context's repos
$ pachctl port-forward &
...several error messages along the lines of:
Unable to create listener: Error listen tcp4 127.0.0.1:30650: bind: address already in use
$ ps -a | grep forward
33964 ttys002    0:00.51 kubectl port-forward dash-12345678-abcde 38080:8080
33965 ttys002    0:00.51 kubectl port-forward dash-12345679-abcde 38081:8081
37245 ttys002    0:00.12 pachctl port-forward &
37260 ttys002    0:00.20 kubectl port-forward pachd-4212312322-abcde 30650:650
$ kill -9 37260
$ pachctl port-forward & #works as expected now
</code>```

Also, kill -9 on the pachctl port-forward process 37245 doesn't work, it seems like I have to kill -9 on the kubectl port-forward

答:
You can specify the port if you want, as a different one using -p flag as mentioned in docs Is there a reason of not doing it?

Also starting processes in background and then sending it a SIGKILL causes the resources to be unallocated properly so when you try to join again you might see it giving errors since it cannot allocate the same port again. So try running it without & at the end.

So whenever you change the context all you need to do is CTRL + C and start it again, this will release the resources properly and gain thema gain.

Body:
I have more than one Kubernetes context. When I change contexts, I have been using kill -9  to kill the port-forward in order to redo the pachtctl port-forward & command. I wonder if this is the right way of doing it.

In more detail:

I start off being in a Kubernetes context, we'll call it context_x. I then want to change context to my local context, called minikube. I also want to see my repos for this minikube context, but when I use pachctl list-repo, it still shows context_x's Pachyderm repos. When I do pachctl port-forward, I then get an error message about the address being already in use. So I have to ps -a, then kill -9 on those port forward processes, and then do pachctl port-forward command again.

An example of what I've been doing:

$ kubectl config use-context minikube
$ pachctl list-repo #doesn't show minikube context's repos
$ pachctl port-forward &
...several error messages along the lines of:
Unable to create listener: Error listen tcp4 127.0.0.1:30650: bind: address already in use
$ ps -a | grep forward
33964 ttys002    0:00.51 kubectl port-forward dash-12345678-abcde 38080:8080
33965 ttys002    0:00.51 kubectl port-forward dash-12345679-abcde 38081:8081
37245 ttys002    0:00.12 pachctl port-forward &
37260 ttys002    0:00.20 kubectl port-forward pachd-4212312322-abcde 30650:650
$ kill -9 37260
$ pachctl port-forward & #works as expected now

Also, kill -9 on the pachctl port-forward process 37245 doesn't work, it seems like I have to kill -9 on the kubectl port-forward


问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答:
Based on your comment in MindingData's answer, it has nothing to do with your CORS, it's working fine.

Your Controller action is returning the wrong data. HttpCode 415 means, "Unsupported Media type". This happens when you either pass the wrong format to the controller (i.e. XML to a controller which only accepts json) or when you return a wrong type (return Xml in a controller which is declared to only return xml).

For later one check existence of [Produces("...")]attribute on your action

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));