问:
in react native want to get Home Page data according with respect to logged in email
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```<code>```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```
</code>```

答:
On Your Login Screen,
pass the email in the navigation statement.

Like:

```<code> this.props.navigation.navigate('Home',{email: "You Email Id using"});
</code>```

And on your Home screen, use it like:

```<code>fetch("http://test.com:70/api/productForClient",{
  method:"POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type':'application/json'
  },
 body:JSON.stringify({
   "email":props.navigation.state.params.email,
  })
})
</code>```

There is one more alternative, set the email in the AsyncStorage on login, and access it from AsyncStorage whenever you want to use it.

One more alternative is use redux, and save email in your redux store, and access it wherever you want to use it.

Body:
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```

Body:
On Your Login Screen,
pass the email in the navigation statement.

Like:

 this.props.navigation.navigate('Home',{email: "You Email Id using"});

And on your Home screen, use it like:

fetch("http://test.com:70/api/productForClient",{
  method:"POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type':'application/json'
  },
 body:JSON.stringify({
   "email":props.navigation.state.params.email,
  })
})

There is one more alternative, set the email in the AsyncStorage on login, and access it from AsyncStorage whenever you want to use it.

One more alternative is use redux, and save email in your redux store, and access it wherever you want to use it.


来源: stackexchange

问:
PowerShell ConvertTo-HTML is translating < and > symbols to < and > - how do I stop this?
I have an interesting problem.  I'm trying to embed HTML tags inside string variables in a PowerShell script, so that as it finds servers in a "down" state, it will display a graphic instead of a number when output to an HTML report page.  However, when I open the report, instead of the graphic, I see the HTML code for the graphic.  This of course will not do.

My code snippet is as follows:

```<code>$working | foreach-object {

{ # Triage is less than 5 days
 $graphic = 'greystate\0-5.png'
 $triage = '5-15 Days'
}
add-member -InputObject $_ -MemberType NoteProperty -Name TriageInd -Value "`<img href=""$graphic"" alt=""$triage""`>"

}

$working  | Select-Object * -exclude Triage | convertTo-HTML -as Table -Title "Grey State Report - $surveydate" -body "<H4>The Following systems are currently not reporting to SCOM as of $surveydate :</H4></P>" -post "</p> This report generated by PowerShell, run on $runfrom by $runby." > $resultsHTML
</code>```

This is supposed to add an image tag with a filename stored in $graphic and alt text stored in $triage (the code actually goes thru an If..Elseif..Else function to change the specifics, but you get the idea)

However, the output is like this:

OFFLINESERVER.FQDN MG3 4/17/2014 4:56:03 AM TimedOut OFFLINESERVER 0

The source of the HTML page looks like this:

```<code>....
<td>OFFLINESERVER.FQDN</td><td>MG3</td><td>4/17/2014 4:56:03 AM</td><td>TimedOut</td><td>OFFLINESERVER</td><td>0</td><td><img href="greystate\0-5.png" alt="5-15 Days"></td><td></td><td></td></tr>
....
</code>```

Note the section above:

How do I get ConvertTo-HTML to leave my tag punctuation alone so that it will render properly in the browser?

答:
Use these two line in your script to resolve this error

Add-Type -AssemblyName System.Web

[System.Web.HttpUtility]::HtmlDecode($Results ) | Out-File .\Result.html

ContentLicense: CC BY-SA 3.0

Body:
I have an interesting problem.  I'm trying to embed HTML tags inside string variables in a PowerShell script, so that as it finds servers in a "down" state, it will display a graphic instead of a number when output to an HTML report page.  However, when I open the report, instead of the graphic, I see the HTML code for the graphic.  This of course will not do.

My code snippet is as follows:

$working | foreach-object {

{ # Triage is less than 5 days
 $graphic = 'greystate\0-5.png'
 $triage = '5-15 Days'
}
add-member -InputObject $_ -MemberType NoteProperty -Name TriageInd -Value "`<img href=""$graphic"" alt=""$triage""`>"

}

$working  | Select-Object * -exclude Triage | convertTo-HTML -as Table -Title "Grey State Report - $surveydate" -body "
The Following systems are currently not reporting to SCOM as of $surveydate :

" -post "
 This report generated by PowerShell, run on $runfrom by $runby." > $resultsHTML

This is supposed to add an image tag with a filename stored in $graphic and alt text stored in $triage (the code actually goes thru an If..Elseif..Else function to change the specifics, but you get the idea)

However, the output is like this:

OFFLINESERVER.FQDN MG3 4/17/2014 4:56:03 AM TimedOut OFFLINESERVER 0

The source of the HTML page looks like this:

....
OFFLINESERVER.FQDN	MG3	4/17/2014 4:56:03 AM	TimedOut	OFFLINESERVER	0	&lt;img href="greystate\0-5.png" alt="5-15 Days"&gt;

....

Note the section above:

How do I get ConvertTo-HTML to leave my tag punctuation alone so that it will render properly in the browser?

ContentLicense: CC BY-SA 4.0


问:
Why doesn't PHP auto html decode my POST?
I'm using Zend Framework for a project. Why when I make POST request and get the params in my controller by $this->_request->getParams() it shows undecoded values? For example a string like Speakers & keyboards in my HTML form is retrieved as Speakers & keyboards from getParams() within PHP.

Doesn't PHP autodecode every posted value?

答:
Because there is no reason to do so.

Data is encoded for transport, and then decoded again. HTML isn't an encoding used for transport.

The only reason to expect to receive HTML is if HTML was sent, and if HTML is sent then (presumably) HTML is desired. Converting to text wouldn't often be a desired thing to happen next.


问:
Using xlwings to open excel sheet. Need to search a string and print full line
I'm using xlwings to open excel sheet. Need to search a string in a specific column and print full line of the string without search item and until new line(\n). Output should be in new column of same sheet.

Input:

search string: [game]
Output:

答:
```<code>import xlwings as xw
</code>```

open excel file using xlwings

```<code>filename = r'input.xlsx'
book = xw.Book(filename)
sheet = book.sheets[0]
</code>```

find the last row of the sheet on a specific range in this case from column 'A'

```<code>lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
</code>```

declare a separate variable for the string that you will search and the column where your output will be located.

```<code>search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2
</code>```

now loop through that range to see if your search_string is in that range

```<code>for i in range(1, lrow + 1):
    if search_string in str(sheet.range('A{}'.format(i)).value):
        temp = str(sheet.range('A{}'.format(i)).value)
        temp = temp.split(search_string)[1]
        if '[' in temp:
            temp = temp.split('[')[0]
        sheet.range('B{}'.format(output_index)).value = temp
        output_index += 1

book.save()
book.close()
</code>```

Below is the full code >>

```<code>import xlwings as xw
filename = r'input.xlsx'

book = xw.Book(filename)
sheet = book.sheets[0]
lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2

for i in range(1, lrow + 1):
    if search_string in str(sheet.range('A{}'.format(i)).value):
        temp = str(sheet.range('A{}'.format(i)).value)
        temp = temp.split(search_string)[1]
        if '[' in temp:
            temp = temp.split('[')[0]
        sheet.range('B{}'.format(output_index)).value = temp
        output_index += 1

book.save()
book.close()
</code>```

Body:
import xlwings as xw

open excel file using xlwings

filename = r'input.xlsx'
book = xw.Book(filename)
sheet = book.sheets[0]

find the last row of the sheet on a specific range in this case from column 'A'

lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row

declare a separate variable for the string that you will search and the column where your output will be located.

search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2

now loop through that range to see if your search_string is in that range

for i in range(1, lrow + 1):
    if search_string in str(sheet.range('A{}'.format(i)).value):
        temp = str(sheet.range('A{}'.format(i)).value)
        temp = temp.split(search_string)[1]
        if '[' in temp:
            temp = temp.split('[')[0]
        sheet.range('B{}'.format(output_index)).value = temp
        output_index += 1

book.save()
book.close()

Below is the full code >>

import xlwings as xw
filename = r'input.xlsx'

book = xw.Book(filename)
sheet = book.sheets[0]
lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2

for i in range(1, lrow + 1):
    if search_string in str(sheet.range('A{}'.format(i)).value):
        temp = str(sheet.range('A{}'.format(i)).value)
        temp = temp.split(search_string)[1]
        if '[' in temp:
            temp = temp.split('[')[0]
        sheet.range('B{}'.format(output_index)).value = temp
        output_index += 1

book.save()
book.close()


问:
Plus and minus button (Javascript)
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!--  This is for adult tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div>
<div class="input-group" style="width: 150px;margin: 20px;">
  <span class="input-group-btn"> <!-- This is for child tickets -->
  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
  </span>
  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">
  <span class="input-group-btn">
  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">
    <span class="glyphicon glyphicon-plus"></span>
  </button>
  </span>
</div></code>```

答:
Please refer below code.

$("#adultMinus").click(function() {
  $("#child").val(0);
  if (parseInt($("#adult").val()) != 0) {
    let result = parseInt($("#adult").val()) - 1;
    $("#adult").val(result);
    let maxLimit = 10 - parseInt($("#adult").val());
    $("#child").attr({
      "max": maxLimit,
    });
  }
})
$("#adultPlus").click(function() {
  $("#child").val(0);
  let result = parseInt($("#adult").val()) + 1;
  $("#adult").val(result);
  let maxLimit = 10 - parseInt($("#adult").val());
  $("#child").attr({
    "max": maxLimit,
  });
})
$("#childMinus").click(function() {
  if (parseInt($("#child").val()) != 0) {
    let result = parseInt($("#child").val()) - 1;
    $("#child").val(result);
  }
})
$("#childPlus").click(function(event) {
  var maxLength = parseInt($("#child").attr("max"));
  let result = parseInt($("#child").val()) + 1;
  if (result > maxLength) {
    alert("Max child limit is: "+maxLength);
    event.preventDefault();
    return false;
  } else {
    $("#child").val(result);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="container">
  <lable>Adult Ticket Count: </lable>
  <button id="adultMinus" class="btn btn-danger">-</button>
  <input type="number" name="quant1" id="adult" value="0" min="0">
  <button id="adultPlus" class="btn btn-success">+</button>

</div><br/><br/>
<div class="container">
  <lable>Child Ticket Count: </lable>
  <button id="childMinus" class="btn btn-danger">-</button>
  <input type="number" style="min-width:160px" name="quant1" id="child" value="0" min="0">
  <button id="childPlus" class="btn btn-success">+</button>

</div></code>```

Title: Plus and minus button (Javascript)

Body:
I have tried out the add and minus button.

The thing i am trying to do is if i have selected 10 bus tickets, then how do i write a javascript function to limit the maximum of the input. For instance, if adult is increment by 1, then the maximum input for the child will be changed into 9.

Here is my code

function myFunction() {
  var adult = document.getElementByID("adult").value;
  var child = document.getElementByID("child").value;
  var maxAdult = document.getElementByID("adult").max;
  var maxChild = document.getElementByID("child").max;
  if (adult + 1) {
    maxChild = -1;
  }
  if (adult + 1) {
    maxAdult = -1;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>

  <button type="button" class="btn btn-default btn-number"  data-type="minus" data-field="quant1">

  </button>

  <input type="text" name="quant1" id="adult" class="form-control input-number" value="0" min="0" max="<?php echo 10 ?>" onchange="myFunction()">

  <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant1">

  </button>

Body:
Please refer below code.

$("#adultMinus").click(function() {
  $("#child").val(0);
  if (parseInt($("#adult").val()) != 0) {
    let result = parseInt($("#adult").val()) - 1;
    $("#adult").val(result);
    let maxLimit = 10 - parseInt($("#adult").val());
    $("#child").attr({
      "max": maxLimit,
    });
  }
})
$("#adultPlus").click(function() {
  $("#child").val(0);
  let result = parseInt($("#adult").val()) + 1;
  $("#adult").val(result);
  let maxLimit = 10 - parseInt($("#adult").val());
  $("#child").attr({
    "max": maxLimit,
  });
})
$("#childMinus").click(function() {
  if (parseInt($("#child").val()) != 0) {
    let result = parseInt($("#child").val()) - 1;
    $("#child").val(result);
  }
})
$("#childPlus").click(function(event) {
  var maxLength = parseInt($("#child").attr("max"));
  let result = parseInt($("#child").val()) + 1;
  if (result > maxLength) {
    alert("Max child limit is: "+maxLength);
    event.preventDefault();
    return false;
  } else {
    $("#child").val(result);
  }
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="container">
  <lable>Adult Ticket Count: </lable>
  <button id="adultMinus" class="btn btn-danger">-</button>
  <input type="number" name="quant1" id="adult" value="0" min="0">
  <button id="adultPlus" class="btn btn-success">+</button>

</div><br/><br/>
<div class="container">
  <lable>Child Ticket Count: </lable>
  <button id="childMinus" class="btn btn-danger">-</button>
  <input type="number" style="min-width:160px" name="quant1" id="child" value="0" min="0">
  <button id="childPlus" class="btn btn-success">+</button>

</div>


问:
database error: A PHP Error was encountered in codeigniter 3
My model:

```<code>class Admin_model extends CI_Model{
    function add_blog($data){
        $this->db->insert('blog',$data);
        return true;
    }
}
</code>```

My controller function:

```<code>function add_blog(){

    $this->form_validation->set_rules('heading','Heading', 'trim|required');
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('error',"Please check the required field");
        redirect('admin/dashboard/add');
    }else{
        //for upload file
        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'pdf|doc|docx|txt|jpeg|png|ppt';
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
        }
        else
        {
            $image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
            $data['picture']  = $image_path;
            $data_image = array('upload_data' => $this->upload->data());
        }
        //Upload file end
        $data['picture'] = $data_image['upload_data']['file_name'];
        $data['heading'] = ucwords($this->input->post('heading'));
        $data['description'] = ucfirst($this->input->post('description'));
        $data['type_id'] = ucwords($this->input->post('type_id'));
        $data['price'] = $this->input->post('price');

        $insert_data = $this->admin_model->add_blog($data);
        if($insert_data){
            echo '<script>alert("Note added sucessfully.");</script>';
            redirect('admin/dashboard');
        }else{
            $this->session->set_flashdata('message',"There is problem in inserting data, please retry once");
            echo "error at last ";
            redirect('admin/dashboard/add');
        }
    }
}
</code>```

My view:

<form role="form" name="myForm"  method="post" enctype="multipart/form-data" action="<?php echo site_url('admin/dashboard/add_blog');?>">
    Category
    <select name="type_id" id="" class="form-control" >
        <?php
            if(count($product_list )>0 ){
                foreach ($product_list as $key => $value) {
                ?>
                <option value="<?php echo $value['type_id'];?>"><?php echo $value['type'];?></option>
                <?php
                }}?>
    </select>

     Heading
    <input type="text" name="heading"class="form-control">
    Price
    <input type="number" name="price" class="form-control">
    Description
    <textarea name="description" id="" cols="30" rows="5" class="form-control"></textarea>

    Upload pic

            <?php echo form_upload(['name'=>'userfile']); ?>

    <?php if(isset($upload_error)){echo $upload_error;}?>

    <button type="submit" class="btn btn-primary">Submit</button>

</form>

```

A PHP Error was encountered

Severity: Notice
  Message: Undefined variable: data_image
  Filename: admin/Dashboard.php
  Line Number: 64

Backtrace:

File:
  /opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
  Line: 64 Function: _error_handler

File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
  require_once

A PHP Error was encountered

Severity: Notice
  Message: Trying to access array offset on value of type null
  Filename: admin/Dashboard.php
  Line Number: 64

Backtrace:

File:
  /opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
  Line: 64 Function: _error_handler

File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
  require_once

A Database Error Occurred

Error Number: 1048
  Column 'picture' cannot be null

INSERT INTO blog (picture, heading, description, type_id,
  price) VALUES (NULL, 'Djjdjdj', 'Jjdjdj', '1', '')

Filename: models/Admin_model.php
  Line Number: 5

答:
Let's analyze the error message first.

Message: Undefined variable: data_image

Which means, somewhere in the code you're calling a variable named "data_image" which is undefined. Now, please notice that this is a NOTICE, so there might be cases that your code would work well BUT it's a bad practice and might cause troubles. (As in your case for instance).

Looking at your code, the following "block":

```<code>    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());
    }
    else
    {
        $image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
        $data['picture']  = $image_path;
        $data_image = array('upload_data' => $this->upload->data());
    }
        //Upload file end
    $data['picture'] = $data_image['upload_data']['file_name'];
</code>```

The $data_image variable is defined only under the "else" statement.
So if the condition returns true, the $data_image variable is truly undefined.
In that case, the following command:

```<code>$data['picture'] = $data_image['upload_data']['file_name'];
</code>```

which is based on the $data_image variable, would return another problem:

Message: Trying to access array offset on value of type null

so $data['picture'] now is NULL, which cause your last problem:

Column 'picture' cannot be null

The solution?

Make sure you have a value for $data_image even in the case that the condition returns true. Or, if this condition returns true - handle the things differently. Please also notice that there might be a logical problem with the function in the condition that returns an unexpected result.

(The condition:     if ( ! $this->upload->do_upload()))

Body:
My model:

class Admin_model extends CI_Model{
    function add_blog($data){
        $this->db->insert('blog',$data);
        return true;
    }
}

My controller function:

function add_blog(){

    $this->form_validation->set_rules('heading','Heading', 'trim|required');
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('error',"Please check the required field");
        redirect('admin/dashboard/add');
    }else{
        //for upload file
        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'pdf|doc|docx|txt|jpeg|png|ppt';
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
        }
        else
        {
            $image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
            $data['picture']  = $image_path;
            $data_image = array('upload_data' => $this->upload->data());
        }
        //Upload file end
        $data['picture'] = $data_image['upload_data']['file_name'];
        $data['heading'] = ucwords($this->input->post('heading'));
        $data['description'] = ucfirst($this->input->post('description'));
        $data['type_id'] = ucwords($this->input->post('type_id'));
        $data['price'] = $this->input->post('price');

        $insert_data = $this->admin_model->add_blog($data);
        if($insert_data){
            echo '';
            redirect('admin/dashboard');
        }else{
            $this->session->set_flashdata('message',"There is problem in inserting data, please retry once");
            echo "error at last ";
            redirect('admin/dashboard/add');
        }
    }
}

My view:

<form role="form" name="myForm"  method="post" enctype="multipart/form-data" action="<?php echo site_url('admin/dashboard/add_blog');?>">
    Category
    <select name="type_id" id="" class="form-control" >
        <?php
            if(count($product_list )>0 ){
                foreach ($product_list as $key => $value) {
                ?>
                <option value="<?php echo $value['type_id'];?>"><?php echo $value['type'];?></option>
                <?php
                }}?>
    </select>

     Heading
    <input type="text" name="heading"class="form-control">
    Price
    <input type="number" name="price" class="form-control">
    Description
    <textarea name="description" id="" cols="30" rows="5" class="form-control"></textarea>

    Upload pic

            <?php echo form_upload(['name'=>'userfile']); ?>

    <?php if(isset($upload_error)){echo $upload_error;}?>

    <button type="submit" class="btn btn-primary">Submit</button>

</form>

A PHP Error was encountered

Severity: Notice
  Message: Undefined variable: data_image
  Filename: admin/Dashboard.php
  Line Number: 64

Backtrace:

File:
  /opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
  Line: 64 Function: _error_handler

File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
  require_once

A PHP Error was encountered

Severity: Notice
  Message: Trying to access array offset on value of type null
  Filename: admin/Dashboard.php
  Line Number: 64

Backtrace:

File:
  /opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
  Line: 64 Function: _error_handler

File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
  require_once

A Database Error Occurred

Error Number: 1048
  Column 'picture' cannot be null

INSERT INTO blog (picture, heading, description, type_id,
  price) VALUES (NULL, 'Djjdjdj', 'Jjdjdj', '1', '')

Filename: models/Admin_model.php
  Line Number: 5

Body:
Let's analyze the error message first.

Message: Undefined variable: data_image

Which means, somewhere in the code you're calling a variable named "data_image" which is undefined. Now, please notice that this is a NOTICE, so there might be cases that your code would work well BUT it's a bad practice and might cause troubles. (As in your case for instance).

Looking at your code, the following "block":

    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());
    }
    else
    {
        $image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
        $data['picture']  = $image_path;
        $data_image = array('upload_data' => $this->upload->data());
    }
        //Upload file end
    $data['picture'] = $data_image['upload_data']['file_name'];

The $data_image variable is defined only under the "else" statement.
So if the condition returns true, the $data_image variable is truly undefined.
In that case, the following command:

$data['picture'] = $data_image['upload_data']['file_name'];

which is based on the $data_image variable, would return another problem:

Message: Trying to access array offset on value of type null

so $data['picture'] now is NULL, which cause your last problem:

Column 'picture' cannot be null

The solution?

Make sure you have a value for $data_image even in the case that the condition returns true. Or, if this condition returns true - handle the things differently. Please also notice that there might be a logical problem with the function in the condition that returns an unexpected result.

(The condition:     if ( ! $this->upload->do_upload()))


问:
Remove decimals fom pandas column(String type)
I would like to remove decimal points from a pandas column Which is of string type

Df

```<code>Net Sales
123.45
34.89
65.00
</code>```

I am trying to remove decimals from that column

```<code>Net Sales
123
34
65
</code>```

df['Net Sales'] is already a string type.

I tried as below:

df['Net Sales'] = df['Net Sales'].astype(str).replace('\.0', '', regex=True)

But I get teh error as below:

ValueError: invalid literal for int() with base 10: '1567.55'

Thanks.

答:
If values are strings first convert to floats and then to integers:

```<code>df['Net Sales'] = df['Net Sales'].astype(float).astype(int)
</code>```

If values are floats use:

```<code>df['Net Sales'] = df['Net Sales'].astype(int)
</code>```

Your solution should be changed with \d+ for match digits after .:

```<code>df['Net Sales'] = df['Net Sales'].astype(str).replace('\.\d+', '', regex=True).astype(int)
print (df)
   Net Sales
0        123
1         34
2         65
</code>```

Or youcan use split by dot and select first list by indexing:

```<code>df['Net Sales'] = df['Net Sales'].astype(str).str.split('.').str[0].astype(int)
</code>```

Body:
I would like to remove decimal points from a pandas column Which is of string type

Df

Net Sales
123.45
34.89
65.00

I am trying to remove decimals from that column

Net Sales
123
34
65

df['Net Sales'] is already a string type.

I tried as below:

df['Net Sales'] = df['Net Sales'].astype(str).replace('\.0', '', regex=True)

But I get teh error as below:

ValueError: invalid literal for int() with base 10: '1567.55'

Thanks.

Body:
If values are strings first convert to floats and then to integers:

df['Net Sales'] = df['Net Sales'].astype(float).astype(int)

If values are floats use:

df['Net Sales'] = df['Net Sales'].astype(int)

Your solution should be changed with \d+ for match digits after .:

df['Net Sales'] = df['Net Sales'].astype(str).replace('\.\d+', '', regex=True).astype(int)
print (df)
   Net Sales
0        123
1         34
2         65

Or youcan use split by dot and select first list by indexing:

df['Net Sales'] = df['Net Sales'].astype(str).str.split('.').str[0].astype(int)


问:
Ignore everything in a directory except one subfolder
I have a directory ~/x7/music/sfx.

There are some files and folders in the root of ~/x7/music.

I need to sync only the sfx folder and ignore anything else in music.

I've tried many variants, but all of them was wrong.

ignore = Name music/*
ignorenot = Regex music/sfx/.* (OR just *)
```

<p>does not work.</p>

<p>I was expecting to use something like</p>

<pre class="lang-sh prettyprint-override"><code>ignore = Name music/*^/
</code>```

答:
On 2.48.3, this should work:</p>

```<code>ignore = Path /root/path/to/music/*
ignorenot = Path /root/path/to/music/sfx
</code>```

Body:
I have a directory ~/x7/music/sfx.

There are some files and folders in the root of ~/x7/music.

I need to sync only the sfx folder and ignore anything else in music.

I've tried many variants, but all of them was wrong.

ignore = Name music/*
ignorenot = Regex music/sfx/.* (OR just *)

does not work.

I was expecting to use something like

ignore = Name music/*^/

Body:
On 2.48.3, this should work:

ignore = Path /root/path/to/music/*
ignorenot = Path /root/path/to/music/sfx


问:
Trouble incrementing and decrementing a malloced array of multiple data types in C
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later. I have tried using a modified version of this method to store various datatypes in these incremented elements.

Here is an example of how such an array is created:

```<code>int *array;
array = malloc(sizeof(int) + sizeof(double) + (n * sizeof(int)))
*(array) = n;
array++;
(double*)array++;
return array;
</code>```

In this example, the sizeof(int) and sizeof(double) in the malloc statement are the elements that will store things, such as the size of the array in the int element, and in the double element we can store something like the average of all the numbers in the array (excluding these two elements of course)

(n * sizeof(int)) is for creating the rest of the elements in the array, where n is the number of elements, and sizeof(int) is the desired data type for these elements, and in theory this should work for an array of any data type.

Now, here is the trouble I am having:

I have created another function to retrieve the size of the array, but I am having trouble decrementing and incrementing the array. Here is my code:

```<code>getArraySize(void* array){
(double*)array--;//Decrement past the double element
(int*)array--;//Decrement past the int element

int size = *((int*)array);//Acquire size of the array

(int*)array++;//Increment past int element
(double*)array++;//Increment past the double element

return size;}
</code>```

This function fails to get the size of the array, and I have realized it is because the compiler first increments the array then type casts it. However, when i try to fix such increment/decrement statements as follows:

```<code>((int*)array)++;
</code>```

I get an error that says lvalue required as increment operand. I do not know how to fix this notation in such a way that it will increment and decrement correctly. Any suggestions would be much appreciated.

答:
What you can do to reach your goal and is (to my opinion) more readable anyway:

```<code>array -= sizeof(double);  // get to position where double starts
array -= sizeof(int);     // get to position where int starts
</code>```

NOTE
This only works on some compilers and within getArraySize since you casted the array pointer to void*. So this is also not advisable at all

But I really think that this is NOT the way to go and I also recommend to use a struct instead as @Lundin points out.

If you call your getArraySize function with any other pointer or with a pointer of the expected array but not at the right position, it will most likely end up in segmentation faults

Body:
In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later. I have tried using a modified version of this method to store various datatypes in these incremented elements.

Here is an example of how such an array is created:

int *array;
array = malloc(sizeof(int) + sizeof(double) + (n * sizeof(int)))
*(array) = n;
array++;
(double*)array++;
return array;

In this example, the sizeof(int) and sizeof(double) in the malloc statement are the elements that will store things, such as the size of the array in the int element, and in the double element we can store something like the average of all the numbers in the array (excluding these two elements of course)

(n * sizeof(int)) is for creating the rest of the elements in the array, where n is the number of elements, and sizeof(int) is the desired data type for these elements, and in theory this should work for an array of any data type.

Now, here is the trouble I am having:

I have created another function to retrieve the size of the array, but I am having trouble decrementing and incrementing the array. Here is my code:

getArraySize(void* array){
(double*)array--;//Decrement past the double element
(int*)array--;//Decrement past the int element

int size = *((int*)array);//Acquire size of the array

(int*)array++;//Increment past int element
(double*)array++;//Increment past the double element

return size;}

This function fails to get the size of the array, and I have realized it is because the compiler first increments the array then type casts it. However, when i try to fix such increment/decrement statements as follows:

((int*)array)++;

I get an error that says lvalue required as increment operand. I do not know how to fix this notation in such a way that it will increment and decrement correctly. Any suggestions would be much appreciated.

Body:
What you can do to reach your goal and is (to my opinion) more readable anyway:

array -= sizeof(double);  // get to position where double starts
array -= sizeof(int);     // get to position where int starts

NOTE
This only works on some compilers and within getArraySize since you casted the array pointer to void*. So this is also not advisable at all

But I really think that this is NOT the way to go and I also recommend to use a struct instead as @Lundin points out.

If you call your getArraySize function with any other pointer or with a pointer of the expected array but not at the right position, it will most likely end up in segmentation faults


答:
You can coerce the datatype to int, Just a note in case you have nans in your data, the conversion to int doesn't work as they have float data type, so regex solution might be better.

```<code>df['Net Sales'] = df['Net Sales'].astype('int')
</code>```

or in case of regex:

```<code>df['Net Sales'] = df['Net Sales'].astype('str').replace(r'\.\d+$', '', regex=True).astype('int')
</code>```

Example:

```<code>import pandas as pd

df = pd.DataFrame({"Net Sales" : [1.5, 2.5]})

df['Net Sales'] = df['Net Sales'].astype('int')

df['Net Sales'] = df['Net Sales'].astype('str').replace(r'\.\d+$', '', regex=True).astype('int')
</code>```

Output:

```<code>#   Net Sales
#0  1
#1  2
</code>```

Title: Remove decimals fom pandas column(String type)

Body:
You can coerce the datatype to int, Just a note in case you have nans in your data, the conversion to int doesn't work as they have float data type, so regex solution might be better.

df['Net Sales'] = df['Net Sales'].astype('int')

or in case of regex:

df['Net Sales'] = df['Net Sales'].astype('str').replace(r'\.\d+$', '', regex=True).astype('int')

Example:

import pandas as pd

df = pd.DataFrame({"Net Sales" : [1.5, 2.5]})

df['Net Sales'] = df['Net Sales'].astype('int')

df['Net Sales'] = df['Net Sales'].astype('str').replace(r'\.\d+$', '', regex=True).astype('int')

Output:

#   Net Sales
#0  1
#1  2


问:
How to merge two intersecting arrays via es6
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

```<code>export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});
</code>```

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.

答:
```<code>playerStat.forEach((initItem) => {
  let result = auctionStat.filter((item) => (
    initItem.displayName === item.displayName
  ))
  // let me suppose the same displayName only has one
  result.length && Object.assign(initItem, result[0])
})

</code>```

Body:
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.


问:
Keeping track of mutated rows in BigQuery?
I have a large table whose rows get updated/inserted/merged periodically from a few different queries. I need a scheduled process to run (via API) to periodically check for which rows in that table were updated since the last check. So here are my issues...

When I run the merge query, I don't see a way for it to return which records were updated... otherwise, I could be copying those updated rows to a special updated_records table.

There are no triggers so I can't keep track of mutations that way.

I could add a last_updated timestamp column to keep track that way, but then repeatedly querying the entire table all day for that would be a huge amount of data billed (expensive).

I'm wondering if I'm overlooking something obvious or if maybe there's some kind of special BQ metadata that could help?

The reason I'm attempting this is that I'm wanting to extract and synchronize a smaller subset of this table into my PostgreSQL instance because the latency for querying BQ is just too much for smaller queries.

Any ideas? Thanks!

答:
One way is to periodically save intermediate state of the table using the time travel feature. Or store only the diffs. I just want to leave this option here:

FOR SYSTEM_TIME AS OF references the historical versions of the table definition and rows that were current at timestamp_expression.

The value of timestamp_expression has to be within last 7 days.

The following query returns a historical version of the table from one hour ago.

```<code>SELECT * FROM table
  FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);
</code>```

The following query returns a historical version of the table at an absolute point in time.

```<code>SELECT * FROM table
  FOR SYSTEM_TIME AS OF '2017-01-01 10:00:00-07:00';
</code>```

Body:
One way is to periodically save intermediate state of the table using the time travel feature. Or store only the diffs. I just want to leave this option here:

FOR SYSTEM_TIME AS OF references the historical versions of the table definition and rows that were current at timestamp_expression.

The value of timestamp_expression has to be within last 7 days.

The following query returns a historical version of the table from one hour ago.

SELECT * FROM table
  FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);

The following query returns a historical version of the table at an absolute point in time.

SELECT * FROM table
  FOR SYSTEM_TIME AS OF '2017-01-01 10:00:00-07:00';


问:
Delete images and pdf when the session is over
I want to develop a healthcare app in android. the doctor will be authenticate for a specific time to access patient's medical reports and download them to the application (reports will be in a block-chain or a db). when the session is over all of those downloaded data (reports) should be permanently deleted from the doctors mobile. what is the best approach to delete these data?

答: Well, the best approach would be to create a cache directory with some unique name that distinguishes all the patients' records and caching all the downloadable items into that directory and deleting that directory upon completion of the session.</p>


问:
How to include only once tag on the page
I have implemented some component. I used jsp custom tags. But I've implemented 2 tags which make hard to use this in the future by others programmers. How can I improve my code to use only one tag. My tags are .tag files.

Below is what I need:

```<code><c:foreach...
   <u:myTag1/>

<u:myTag2/>
</code>```

I want to display repeatable myTag1 and only once myTag2

It would be nice to have such things (without myTag2):

```<code><c:foreach....
   <u:myTag1>
</code>```

答:
If you want to use only one tag then you're in the realms of creating a new tag in the TLD and implementing another Tag.  Hopefully you should be able to refactor Tag1 and Tag2 to put common functionality somewhere e.g. Helper class or abstract class, so the duplication between Tag1, Tag2 and Tag1AndTag2 is minimal.

Alternatively you may want to look at JSP fragments or some other templating system, so pages can include the common JSP in.  However, the tag solution sounds better - if you're sure that offering a third flavour of tag (combing two of them) is the way to go.  You may make the decision to stay with just Tag1 and Tag2.

I'm assuming you're using just standard JSP tags here.  If you were using JSF 2 you could look at composite components or something, which may save some pain.

Body:
I have implemented some component. I used jsp custom tags. But I've implemented 2 tags which make hard to use this in the future by others programmers. How can I improve my code to use only one tag. My tags are .tag files.

Below is what I need:

<c:foreach...

I want to display repeatable myTag1 and only once myTag2

It would be nice to have such things (without myTag2):

<c:foreach....


问:
How to select all checkboxes, while clicking the main checkbox in android?
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

```<code> selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

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

答:
Checkout the logic with this demo kotlin code...</p>

```<code>        checkBox1.setOnClickListener {
            if (checkBox2.isChecked) {
                selectAllCheckbox.isChecked = true
            }

            if (!checkBox2.isChecked || !checkBox1.isChecked) {
                selectAllCheckbox.isChecked = false
            }
        }
        checkBox2.setOnClickListener {
            if (checkBox1.isChecked) {
                selectAllCheckbox.isChecked = true
            }
            if (!checkBox1.isChecked || !checkBox2.isChecked) {
                selectAllCheckbox.isChecked = false
            }
        }
        selectAllCheckbox.setOnClickListener {
            if (selectAllCheckbox.isChecked) {
                checkBox1.isChecked = true
                checkBox2.isChecked = true
            }
            if (!selectAllCheckbox.isChecked) {
                checkBox1.isChecked = false
                checkBox2.isChecked = false
            }
        }
</code>```

Body:
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

 selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

                    }
                }
            }
        });

Body:
Checkout the logic with this demo kotlin code...

        checkBox1.setOnClickListener {
            if (checkBox2.isChecked) {
                selectAllCheckbox.isChecked = true
            }

            if (!checkBox2.isChecked || !checkBox1.isChecked) {
                selectAllCheckbox.isChecked = false
            }
        }
        checkBox2.setOnClickListener {
            if (checkBox1.isChecked) {
                selectAllCheckbox.isChecked = true
            }
            if (!checkBox1.isChecked || !checkBox2.isChecked) {
                selectAllCheckbox.isChecked = false
            }
        }
        selectAllCheckbox.setOnClickListener {
            if (selectAllCheckbox.isChecked) {
                checkBox1.isChecked = true
                checkBox2.isChecked = true
            }
            if (!selectAllCheckbox.isChecked) {
                checkBox1.isChecked = false
                checkBox2.isChecked = false
            }
        }


问:
#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'
Hopefully someone can help me, for I have queried the web with no success or concrete answer to this error.  I’m using Windows and Xampp.  Here is the error I am getting after I have recently imported the database into phpmyadmin…

```<code>#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'
</code>```

After I import the database, everything is fine in phpmyadmin until I log out and then log back in, this is where the problem lies.  When I click on any of the tables from the imported database, I get the following errors…

```<code>SELECT 'prefs'
FROM 'phpmyadmin'.'pma_table_uiprefs'
WEHRE 'username' = 'root'
AND 'db_name' = 'afdb'
AND 'table_name' = 'role'

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'
</code>```

Thank you again for taking time to read my post and hopefully someone can help me with this error.

答:
You use this command in phpMyAdmin SQL Part: </p>

```<code>GRANT SELECT , INSERT , UPDATE , DELETE ON phpmyadmin.* TO  `pma`@`localhost` IDENTIFIED BY  ''
</code>```

Body:
Hopefully someone can help me, for I have queried the web with no success or concrete answer to this error.  I’m using Windows and Xampp.  Here is the error I am getting after I have recently imported the database into phpmyadmin…

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

After I import the database, everything is fine in phpmyadmin until I log out and then log back in, this is where the problem lies.  When I click on any of the tables from the imported database, I get the following errors…

SELECT 'prefs'
FROM 'phpmyadmin'.'pma_table_uiprefs'
WEHRE 'username' = 'root'
AND 'db_name' = 'afdb'
AND 'table_name' = 'role'

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Thank you again for taking time to read my post and hopefully someone can help me with this error.

Body:
You use this command in phpMyAdmin SQL Part:

GRANT SELECT , INSERT , UPDATE , DELETE ON phpmyadmin.* TO  `pma`@`localhost` IDENTIFIED BY  ''


问:
How do I place a m*n array within a M*N array?
I'm trying to stitch together 30px*30px images into a 3000px*3000px image. If there is a better way than what I'm describing could you please let me know.

I've created BigArr = np.zeros((3000,3000)). And I have my image arrays (which have dimensions 30px*30px). I want to place the first image so that it occupies all the space between BigArr[0][0] and BigArr[29][29].

Is there an easy way to do this? Is there an even easier way to do what I'm trying to do overall?

Edit: The second image should occupy [0][30] -> [59][29], etc.

答:
Assuming you have exactly as many images as needed to completely fill your BigArr and your images can be stored in some list, you can create a nested list with the desired grid and use np.block to generate such an image:

from matplotlib import pyplot as plt
import numpy as np

# Image sizes (width x height)
img_w, img_h = (40, 30)
f_img_w, f_img_h = (200, 300)

# Number of rows / columns in final image
r = np.int32(f_img_h / img_h)
c = np.int32(f_img_w / img_w)

# Generate some images (stored in N-dimensional array)
imgs = np.ones((img_h, img_w, r * c), np.uint8) * 5 * (np.arange(r * c) + 1)

# Assumed starting point of procedure: All images stored in list
imgs_list = [imgs[:, :, i] for i in np.arange(imgs.shape[2])]

# Generate nested list with desired grid
imgs_nested_list = [[imgs_list[y * c + x] for x in np.arange(c)] for y in np.arange(r)]

# Generate desired image
big_arr = np.block(imgs_nested_list)

plt.figure(1)
plt.imshow(big_arr, vmin=0, vmax=255)
plt.show()
```

<p>The output from the example then would look like this:</p>

<p><img src="https://i.stack.imgur.com/LGZnq.png" alt="Output"></p>

<p>Hope that helps!</p>

<pre class="lang-none prettyprint-override"><code>----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Matplotlib:  3.2.0rc3
NumPy:       1.18.1
----------------------------------------
</code>```

Body:
Assuming you have exactly as many images as needed to completely fill your BigArr and your images can be stored in some list, you can create a nested list with the desired grid and use np.block to generate such an image:

from matplotlib import pyplot as plt
import numpy as np

# Image sizes (width x height)
img_w, img_h = (40, 30)
f_img_w, f_img_h = (200, 300)

# Number of rows / columns in final image
r = np.int32(f_img_h / img_h)
c = np.int32(f_img_w / img_w)

# Generate some images (stored in N-dimensional array)
imgs = np.ones((img_h, img_w, r * c), np.uint8) * 5 * (np.arange(r * c) + 1)

# Assumed starting point of procedure: All images stored in list
imgs_list = [imgs[:, :, i] for i in np.arange(imgs.shape[2])]

# Generate nested list with desired grid
imgs_nested_list = [[imgs_list[y * c + x] for x in np.arange(c)] for y in np.arange(r)]

# Generate desired image
big_arr = np.block(imgs_nested_list)

plt.figure(1)
plt.imshow(big_arr, vmin=0, vmax=255)
plt.show()

The output from the example then would look like this:

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Matplotlib:  3.2.0rc3
NumPy:       1.18.1
----------------------------------------


问:
Flyway does not seem to recognize java/scala migrations
I am using Flyway version 5.2.4 in a scala project and have all my migration scripts are under src/main/resources/db/migrations with the following folder structure

```<code>main

-resources

--db

---migrations

----V1__example1.sql

----V2__example2.sql

----V3__scala_migration.scala
</code>```

locations is set to db.migrations (Without any prefix. Flyway documentation says if no prefix is used then sql/java migrations are supported)

V1 and V2 seem to get picked up without issues. But V3 is being ignored. I tried adding a V3__java_migration.java as well and it made no difference. Did anyone have any kind luck adding non-sql migrations?

Here is the scala code in the migration

```<code>package db.migration

import org.flywaydb.core.api.migration.{ BaseJavaMigration, Context }

class V3__scala_migration extends BaseJavaMigration {

  override def migrate(context: Context): Unit = {

    val conn = context.getConnection

    conn.createStatement().executeUpdate(
      """
        |DROP TABLE IF EXISTS `users`;

        |CREATE TABLE IF NOT EXISTS `users`

        |`name` varchar(100) NOT NULL,

        |`email` varchar(100) NOT NULL,

        |PRIMARY KEY (`email`)

        |)ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        |INSERT INTO `users` (`name`, `email`) ('john','john@example.com');

      """.stripMargin)
  }

}
</code>```

答:
You must move your Scala or Java migration scripts to the according directories.

For Scala this would be src/main/scala/db/migration

See here the documentation: https://flywaydb.org/documentation/migrations#discovery-1

Body:
I am using Flyway version 5.2.4 in a scala project and have all my migration scripts are under src/main/resources/db/migrations with the following folder structure

main

-resources

--db

---migrations

----V1__example1.sql

----V2__example2.sql

----V3__scala_migration.scala

locations is set to db.migrations (Without any prefix. Flyway documentation says if no prefix is used then sql/java migrations are supported)

V1 and V2 seem to get picked up without issues. But V3 is being ignored. I tried adding a V3__java_migration.java as well and it made no difference. Did anyone have any kind luck adding non-sql migrations?

Here is the scala code in the migration

package db.migration

import org.flywaydb.core.api.migration.{ BaseJavaMigration, Context }

class V3__scala_migration extends BaseJavaMigration {

  override def migrate(context: Context): Unit = {

    val conn = context.getConnection

    conn.createStatement().executeUpdate(
      """
        |DROP TABLE IF EXISTS `users`;

        |CREATE TABLE IF NOT EXISTS `users`

        |`name` varchar(100) NOT NULL,

        |`email` varchar(100) NOT NULL,

        |PRIMARY KEY (`email`)

        |)ENGINE=InnoDB  DEFAULT CHARSET=utf8;

        |INSERT INTO `users` (`name`, `email`) ('john','john@example.com');

      """.stripMargin)
  }

}


问:
get spawned process environment
In my node application I would like to spawn the vcvars32.bat then use the environment set by it to spawn the cl.exe.

There is a way to get the new "Environment key-value pairs" from ended child process?

Many thanks.

答:
After some trials, I developed this solution that looks a trick to me:

```<code>const cp = require("child_process");
const process = require("process")
const fs = require("fs")

fs.writeFileSync("testCL.bat",
    "call \"c:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat\"\r\nset\r\n")

var env1 = {};
function onData(str) {
    //console.log(str.toString())
    /** @type{String[]} */
    var str = str.toString().split(/[\r\n]{1,2}/);
    for(let i=0;i<str.length-1;++i) {
        var m = str[i].match(/([^=]+)=(.*)$/);
        if(m) {
            env1[ m[1].toUpperCase() ] = m[2];
        }
    }
}

var p1 = cp.spawn( "testCL.bat",{env:process.env})
p1.stdout.on('data', onData);
p1.on("exit", (c) => {
    fs.unlink("testCL.bat", ()=>{});
    var p2 = cp.spawn( "cl.exe",[], { "env":env1 })
    p2.stdout.on('data', d=>console.log(d.toString()));
});
</code>```

So i create a batch file with the call to vcvars and the command set, then parse the set's output to create the environment variable.

Title: get spawned process environment

Body:
After some trials, I developed this solution that looks a trick to me:

const cp = require("child_process");
const process = require("process")
const fs = require("fs")

fs.writeFileSync("testCL.bat",
    "call \"c:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat\"\r\nset\r\n")

var env1 = {};
function onData(str) {
    //console.log(str.toString())
    /** @type{String[]} */
    var str = str.toString().split(/[\r\n]{1,2}/);
    for(let i=0;i<str.length-1;++i) {
        var m = str[i].match(/([^=]+)=(.*)$/);
        if(m) {
            env1[ m[1].toUpperCase() ] = m[2];
        }
    }
}

var p1 = cp.spawn( "testCL.bat",{env:process.env})
p1.stdout.on('data', onData);
p1.on("exit", (c) => {
    fs.unlink("testCL.bat", ()=>{});
    var p2 = cp.spawn( "cl.exe",[], { "env":env1 })
    p2.stdout.on('data', d=>console.log(d.toString()));
});

So i create a batch file with the call to vcvars and the command set, then parse the set's output to create the environment variable.


问:
Selenium Webscraper Click doesn't work on Morningstar
I want to access a Morningstar link such as "https://www.morningstar.com/stocks/xnas/aapl/quote" using Selenium Webscraper, but on Firefox, an ad pops up and I want the webscraper to click the "Continue to Site" button so then I can access the financial data.

I've tried using

```<code>exchange = "xnas"
ticker = "aapl"
url = 'https://www.morningstar.com/stocks/' + exchange + '/' + ticker + '/quote'
driver.get(url)
driver.find_element_by_css_selector('.mdc-button.mds-button.mds-button--flat').click()
</code>```

but then I get the error that

```<code>Message: Element <button class="mdc-button mds-button default-layout__nav-toggle mds-button--icon-only mds-button--flat mds-button--flat-icon-m" type="button"> is not clickable at point (31,34) because another element <div class="mdc-masthead__inner mds-masthead__inner"> obscures it
</code>```

I've also tried using Actions or execute_script and neither of those throw errors, but Firefox doesn't continue onto the site and the ad is still present.

Please help,
Thank you in advance.

答:
Try using webdriver manager. Then your code works fine for me:

```<code>from webdriver_manager.firefox import GeckoDriverManager

exchange = "xnas"
ticker = "aapl"
url = 'https://www.morningstar.com/stocks/' + exchange + '/' + ticker + '/quote'
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get(url)
button=driver.find_element_by_css_selector('.mdc-button.mds-button.mds-button--flat')
button.click()
</code>```

The side menu bar then opens.

Hope this helps?

Body:
I want to access a Morningstar link such as "https://www.morningstar.com/stocks/xnas/aapl/quote" using Selenium Webscraper, but on Firefox, an ad pops up and I want the webscraper to click the "Continue to Site" button so then I can access the financial data.

I've tried using

exchange = "xnas"
ticker = "aapl"
url = 'https://www.morningstar.com/stocks/' + exchange + '/' + ticker + '/quote'
driver.get(url)
driver.find_element_by_css_selector('.mdc-button.mds-button.mds-button--flat').click()

but then I get the error that

Message: Element <button class="mdc-button mds-button default-layout__nav-toggle mds-button--icon-only mds-button--flat mds-button--flat-icon-m" type="button"> is not clickable at point (31,34) because another element
 obscures it

I've also tried using Actions or execute_script and neither of those throw errors, but Firefox doesn't continue onto the site and the ad is still present.

Please help,
Thank you in advance.

Body:
Try using webdriver manager. Then your code works fine for me:

from webdriver_manager.firefox import GeckoDriverManager

exchange = "xnas"
ticker = "aapl"
url = 'https://www.morningstar.com/stocks/' + exchange + '/' + ticker + '/quote'
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get(url)
button=driver.find_element_by_css_selector('.mdc-button.mds-button.mds-button--flat')
button.click()

The side menu bar then opens.

Hope this helps?


问:
React Data Grid shows bad
I have a problem with ReactDataGrid component. I have already installed react-data-grid. The code is the same as in the reac grid's web:

```<code>const columns = [
  { key: 'id', name: 'ID' },
  { key: 'title', name: 'Title' },
  { key: 'count', name: 'Count' }];

const rows = [{ id: 0, title: 'row1', count: 20 }, { id: 1, title: 'row1', count: 40 }, { id: 2, title: 'row1', count: 60 }];

class App extends React.Component {
  render() {
    return (
      <ReactDataGrid
        columns={columns}
        rowGetter={i => rows[i]}
        rowsCount={3}
        minHeight={150} />
    )
  }
}

export default App;
</code>```

and i get:
Result

Thank you!

答:
You don't really need to downgrade. The issue is that the css is not being imported.
If you can import css from node-modules, it'll work.
Workaround for me was I took the whole css and we are now self-maintaining the css, making changes when needed.</p>

Title: React Data Grid shows bad

Body:
I have a problem with ReactDataGrid component. I have already installed react-data-grid. The code is the same as in the reac grid's web:

const columns = [
  { key: 'id', name: 'ID' },
  { key: 'title', name: 'Title' },
  { key: 'count', name: 'Count' }];

const rows = [{ id: 0, title: 'row1', count: 20 }, { id: 1, title: 'row1', count: 40 }, { id: 2, title: 'row1', count: 60 }];

class App extends React.Component {
  render() {
    return (
      <ReactDataGrid
        columns={columns}
        rowGetter={i => rows[i]}
        rowsCount={3}
        minHeight={150} />
    )
  }
}

export default App;

and i get:
Result

Thank you!


问:
Laravel - How to Approve all the posts of a particular Employee
Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:

Controller

```<code>public function index()
{
    $userEmployee = Auth::user()->employee_id;
    $posts = Post::latest()->where('employee_id', $userEmployee)->get();

    return view('admin.post.index', compact('posts'));
}
</code>```

And it generates this view shown below. The view loads all the unapproved posts for a particular employee:

```<code><table class="table table-bordered table-striped table-hover dataTable js-exportable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Author</th>
      <th><i class="material-icons">visibility</i></th>
      <th>Is Approved</th>
      <th>Status</th>
      <th>Action</th>
   </tr>
  </thead>
  <tbody>
    @foreach($posts as $key=>$post)
     <tr>
       <td>{{ $key + 1 }}</td>
       <td>{{ str_limit($post->title,'10') }}</td>
       <td>{{ $post->user->name }}</td>
       <td>{{ $post->view_count }}</td>
       <td>
         @if($post->is_approved == true)
            <span class="badge bg-blue">Approved</span>
         @else
            <span class="badge bg-pink">Pending</span>
         @endif
       </td>
       <td>
          @if($post->status == true)
             <span class="badge bg-blue">Published</span>
          @else
             <span class="badge bg-pink">Pending</span>
          @endif
        </td>
       </tr>
         @endforeach
  </tbody>
</code>```

```<code><form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')
    <div>
        <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> {{ trans('global.submit') }}</button>
    </div>
</form>
</code>```

I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.

I have written this function in the same controller, but I see that it will only work for a selected row:

```<code>public function approve($id){

    $post = Post::find($id);
    if ($post->is_approved == false){
        $post->is_approved = true;
        $post->save();
        $post->user->notify(new AuthorPostApprove($post));

        Toastr::success('Post Successfully Approved');
    }else{
        Toastr::info('Post is already Approved');
    }

    return redirect()->back();
}
</code>```

and have this route/web.php

```<code>Route::get('posts/', 'PostController@index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController@approve')->name('post.approve');
</code>```

How do I re-write my Controller, view and route to achieve this?

Thank you.

答:
try this:</p>

```<code>public function approve($id){

 $post = Post::where('employee_id', $id)
      ->where('is_approved', 0)
      ->update(['is_approved' => 1]);

if ($post){
    $post->user->notify(new AuthorPostApprove($post));
    Toastr::success('Post Successfully Approved');
} else {
    Toastr::info('Post is already Approved');
}

return redirect()->back();

}
</code>```

Body:
Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:

Controller

public function index()
{
    $userEmployee = Auth::user()->employee_id;
    $posts = Post::latest()->where('employee_id', $userEmployee)->get();

    return view('admin.post.index', compact('posts'));
}

And it generates this view shown below. The view loads all the unapproved posts for a particular employee:

      ID
      Title
      Author
      visibility
      Is Approved
      Status
      Action

    @foreach($posts as $key=>$post)

       {{ $key + 1 }}
       {{ str_limit($post->title,'10') }}
       {{ $post->user->name }}
       {{ $post->view_count }}

         @if($post->is_approved == true)
            Approved
         @else
            Pending
         @endif

          @if($post->status == true)
             Published
          @else
             Pending
          @endif

         @endforeach

<form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')

        <button type="submit" class="btn btn-primary"> {{ trans('global.submit') }}</button>

</form>

I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.

I have written this function in the same controller, but I see that it will only work for a selected row:

public function approve($id){

    $post = Post::find($id);
    if ($post->is_approved == false){
        $post->is_approved = true;
        $post->save();
        $post->user->notify(new AuthorPostApprove($post));

        Toastr::success('Post Successfully Approved');
    }else{
        Toastr::info('Post is already Approved');
    }

    return redirect()->back();
}

and have this route/web.php

Route::get('posts/', 'PostController@index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController@approve')->name('post.approve');

How do I re-write my Controller, view and route to achieve this?

Thank you.

Body:
try this:

public function approve($id){

 $post = Post::where('employee_id', $id)
      ->where('is_approved', 0)
      ->update(['is_approved' => 1]);

if ($post){
    $post->user->notify(new AuthorPostApprove($post));
    Toastr::success('Post Successfully Approved');
} else {
    Toastr::info('Post is already Approved');
}

return redirect()->back();

}


问:
ALSA async mode doesn't invoke callback function
I wrote a simple C++ wrapper representing an AudioStream based on ALSA API. It seems to me very convenient to use the async mode. Unfortunately, the callback function registered for async mode doesn't get invoked.

The alsa documentation states for snd_async_add_handler():

This function associates the callback function with the given file, and saves this association in a snd_async_handler_t object.
Whenever the SIGIO signal is raised for the file fd, the callback function will be called with its parameter pointing to the async handler object returned by this function.
The ALSA sigaction handler for the SIGIO signal automatically multiplexes the notifications to the registered async callbacks. However, the application is responsible for instructing the device driver to generate the SIGIO signal.
The SIGIO signal may have been replaced with another signal, see snd_async_handler_get_signo.

Especially the bold part is interesting. Does that mean, that the user has to somehow configure the driver to generate those SIGIO's? I guess the SIGIO is just some sort of interrupt, so one has to enable interrupt generation by the driver???
I would expect this to be responsibility of ALSA through the hw_params configuration or so.

The only thing I was able to find was in the following link, where the answer states, that ASYNC is deprecated, however, from the ALSA documentation this doesn't seem to be true.

ALSA - managing async IO

ALSA documentation for reference:
https://www.alsa-project.org/alsa-doc/alsa-lib/group___global.html#gafd936c40505997bb659b74bd368636b8

答:
snd_async_add_pcm_handler() is a wrapper for snd_async_add_handler() and automatically enables the signal.

And you should not specify SND_PCM_ASYNC in the snd_pcm_open() call.

And you must use a device that actually supports generating signals.

And your signal handler must not use any functions except for those in the list of async-signal-safe functions.


问:
request module works but FormRequest doesn't
I am trying to learn Scrapy. I tried to replicate the below post request in Scrapy, but it didn't work. I tried scrapy.Request(method='POST') as well but it too didn't work.

```<code>import requests, json

headers = {
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'content-length': '132',
'content-type': 'application/x-www-form-urlencoded',
'origin': 'https://www.autozone.com',
'referer': 'https://www.autozone.com/miscellaneous-non-automotive/jump-starter',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'x-requested-with': 'XMLHttpRequest'
}

url = 'https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2'

data = {
'arg1': '9801',
'arg2': '',
'arg3': '824997',
'arg4': ''
}

response = requests.post(url, headers=headers, data=data, timeout=5)

info = json.loads(response.text)
print(info['atgResponse'][0]['retailPrice']) # prints 129.99
</code>```

Scrapy Shell:

```<code>> r = scrapy.FormRequest(url, formdata=data, headers=headers)
> fetch(r) # Doesn't work
</code>```

Can anyone point out where I am going wrong

Edit 1:

Here is the stacktrace of scrapy. Hope this helps.

```<code>>>> fetch(r)
2020-02-15 15:00:08 [scrapy.core.engine] INFO: Spider opened
2020-02-15 15:03:08 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <POST https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2> (failed 1 times): User timeout caused connection failure: Getting https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2 took longer than 180.0 seconds..
</code>```

It retries a few times, and then fails.

Thanks.

答: I tried accessing your link but it returned this error Access to the requested resource is not allowed: /autozone/diy/commerce/pricing/PricingServices, so I suspect that you require either an Authorization header or session cookies in your request, which you did not provide nor put a placeholder. The lack of those could have caused the timeout.

Body:
I am trying to learn Scrapy. I tried to replicate the below post request in Scrapy, but it didn't work. I tried scrapy.Request(method='POST') as well but it too didn't work.

import requests, json

headers = {
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'content-length': '132',
'content-type': 'application/x-www-form-urlencoded',
'origin': 'https://www.autozone.com',
'referer': 'https://www.autozone.com/miscellaneous-non-automotive/jump-starter',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'x-requested-with': 'XMLHttpRequest'
}

url = 'https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2'

data = {
'arg1': '9801',
'arg2': '',
'arg3': '824997',
'arg4': ''
}

response = requests.post(url, headers=headers, data=data, timeout=5)

info = json.loads(response.text)
print(info['atgResponse'][0]['retailPrice']) # prints 129.99

Scrapy Shell:

> r = scrapy.FormRequest(url, formdata=data, headers=headers)
> fetch(r) # Doesn't work

Can anyone point out where I am going wrong

Edit 1:

Here is the stacktrace of scrapy. Hope this helps.

>>> fetch(r)
2020-02-15 15:00:08 [scrapy.core.engine] INFO: Spider opened
2020-02-15 15:03:08 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <POST https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2> (failed 1 times): User timeout caused connection failure: Getting https://www.autozone.com/rest/bean/autozone/diy/commerce/pricing/PricingServices/retrievePriceAndAvailability?atg-rest-depth=2 took longer than 180.0 seconds..

It retries a few times, and then fails.

Thanks.


问:
GLSL textureCube and texture2D in same shader
I can't seem to be able to have both texture2D() and textureCube() in one shader. When I do, nothing shows up and there is no error. I tried this both with my own shader loader and the Apple GLSL shader builder and the same thing happens. It happens even if I have textureCube() in the vertex shader and texture2D() in the fragment. They seem to work fine by themselves, but as soon as they're called together, no matter in which order, nothing shows up.

答: You need to bind both textures as uniforms in both shaders and assign two different texture units, each with one of the textures to the sampler uniforms.</p>


问:
Issues using 'info.hoang8f.widget.FButton'
I am unable to see any color change for the button below

Its color as been assigned and all that.The UI view is as in the image

```<code>      <info.hoang8f.widget.FButton
        android:id="@+id/btnSignUp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign Up"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignUp"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />

    <info.hoang8f.widget.FButton
        android:id="@+id/btnSignIn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign In"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignActive"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />
</code>```

答: You should use android:backgroundTint to modify the actual tint of your background, or use android:background to change the whole background

Body:
I am unable to see any color change for the button below

Its color as been assigned and all that.The UI view is as in the image

      <info.hoang8f.widget.FButton
        android:id="@+id/btnSignUp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign Up"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignUp"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />

    <info.hoang8f.widget.FButton
        android:id="@+id/btnSignIn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:text="Sign In"
        android:textColor="@android:color/white"
        app:buttonColor="@color/btnSignActive"
        app:cornerRadius="4dp"
        app:shadowColor="@android:color/black"
        app:shadowEnabled="true"
        app:shadowHeight="5dp" />


问:
Issue with wildcards into arguments of a Bash function
From the following link, I tried to use the following solution to compare a group of source files (here fortran90 = *.f90).

To do this and see the source which are different, I have put into my ~/.bashrc :

```<code>function diffm { for file in "$1"/"$2"; do diff -qs "$file" "$3"/"${file##*/}"; done ;}
</code>```

But unfortunately, if I am in the current directory for argument $1, i.e by execute :

```<code>$ diffm . '*.f90' ../../dir2
</code>```

The result is : impossible to access to './*.f90'. However, the sources *.f90 exist but wildcards are not taken into account.

Surely a problem with double quotes on arguments of my function ($1, $2, $3)?

More generally, this function doesn't work well.

How can I modify this function in order to make it work in all cases, even being in the current directory "." for  the first argument $1 or the third $3?

答:
If i understood what you are trying to do, this should work

```<code>diffm () {
    dir="$1"; shift
    for file in "$@"; do
        filename=$(basename "$file")
        diff -qs "$file" "$dir/$filename"
    done
}
</code>```

Usage

```<code>diffm ../../dir2 ./*.f90
</code>```

Body:
From the following link, I tried to use the following solution to compare a group of source files (here fortran90 = *.f90).

To do this and see the source which are different, I have put into my ~/.bashrc :

function diffm { for file in "$1"/"$2"; do diff -qs "$file" "$3"/"${file##*/}"; done ;}

But unfortunately, if I am in the current directory for argument $1, i.e by execute :

$ diffm . '*.f90' ../../dir2

The result is : impossible to access to './*.f90'. However, the sources *.f90 exist but wildcards are not taken into account.

Surely a problem with double quotes on arguments of my function ($1, $2, $3)?

More generally, this function doesn't work well.

How can I modify this function in order to make it work in all cases, even being in the current directory "." for  the first argument $1 or the third $3?

Body:
If i understood what you are trying to do, this should work

diffm () {
    dir="$1"; shift
    for file in "$@"; do
        filename=$(basename "$file")
        diff -qs "$file" "$dir/$filename"
    done
}

Usage

diffm ../../dir2 ./*.f90


问:
How to use grep function to separate multiple column with common name in R?
For the following data set, I would like to separate columns with beta1 only.

```<code>mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80
</code>```

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

```<code> dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80
</code>```

Any help is appreciated.

答:
In data.table, you can use patterns() withing .SDcols.

```<code>library(data.table)
setDT(mydata)[, .SD, .SDcols = patterns("^beta1_")]
</code>```

Body:
For the following data set, I would like to separate columns with beta1 only.

mydata
         beta1_C1 beta2_C2 beta1_C2 beta2_C1 beta3_C1 beta4_C2 beta4_C1 beta21_C1 beta21_C2 beta10_C1
    [1,]        1        9       17       25       33       41       49        57        65        73
    [2,]        2       10       18       26       34       42       50        58        66        74
    [3,]        3       11       19       27       35       43       51        59        67        75
    [4,]        4       12       20       28       36       44       52        60        68        76
    [5,]        5       13       21       29       37       45       53        61        69        77
    [6,]        6       14       22       30       38       46       54        62        70        78
    [7,]        7       15       23       31       39       47       55        63        71        79
    [8,]        8       16       24       32       40       48       56        64        72        80

I am using the following code but beta10 is showing in the output which I do not want. In my expected data, I should have only beta1_C1 and beta1_C2 columns.

 dat1=mydata[,grep("beta1",colnames(mydata))]
 dat1
         beta1_C1 beta1_C2 beta10_C1
    [1,]        1       17        73
    [2,]        2       18        74
    [3,]        3       19        75
    [4,]        4       20        76
    [5,]        5       21        77
    [6,]        6       22        78
    [7,]        7       23        79
    [8,]        8       24        80

Any help is appreciated.

Body:
In data.table, you can use patterns() withing .SDcols.

library(data.table)
setDT(mydata)[, .SD, .SDcols = patterns("^beta1_")]


问:
Conflict Newtonsoft.Json 6.0.0.0 and 12.0.0.0 in Web Application with Web Api, C#
I have started a new Web Application in Visual Studio 2019. I have added a Web Api. Shortly after or at the same time (can't remember), I startet getting warnings like this:

```<code>Warning     No way to resolve conflict between "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" and "Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed". Choosing "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" arbitrarily.
</code>```

I noticed but did not do anything as I decided to wait until it gave me problems.

And that is now...

I am about to use a JSon object but when writing this:

```<code>JObject jObject = JObject.Parse(result);
</code>```

The compiler gives me this error:

```<code>Error   CS0433  The type 'JObject' exists in both 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
</code>```

I have searched the web and my conclusions are as follows:

It looks like it is Microsoft.AspNet.WebApi.Client that is the only package installed, that has a dependency on Newtonsoft.Json (>= 6.0.4)

I have installed Newtonsoft.Json (12.0.3)

In Solution Explorer. In reference list, I have only 1 reference. And that is the one for 12.0.3.

In Web.Config I have this entry (and only this for Newtonsoft.Json).

<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/></dependentAssembly>

In my .csproj I can see 3 different references in 3 different ItemGroups:

One for v. 12.0.0.0

One for v. 12.0.2

And one for v. 12.0.3

I tried to uninstall package Newtonsoft.Json, but is not allowed as other packages are dependent on this.

I have runned this command: Update-Package Newtonsoft.Json in the Package Manager Console, which told me, that no new updates were available.

And now, I have runned out of ideas. I am stucked. Anyone knows what to do?

****New update****
I found the 6.0.0.0. Please have a look at the picture:

Here in resources I double clicked the Newtonsoft.Json reference and in the object browser I can see both 6.0.0.0 and 12.0.0.0.

As you can see, both 6.0.0.0 and 12.0.0.0 are present. 6.0.0.0 is somewhere on my C:-drive inside a SDK.

I have tried to delete the file. My project got nuts. Then I replaced that file with the 12.0.0.0 from my project. This gave me the error that assemplies did not match.

I finally copied the old .dll back. And is a bit stucked again.

Any ideas?

答:
The issue usually comes from two different projects that use different versions of the same library.

Both of those projects are then referenced to another one and the warning effectively warns you that something like this might happen.

Go to the solution and right click - manage nuget packages.

Go to the consolidate tab. Check that newtonsoft is there. If it is, install the same package to all projects.

If that doesn't work, check your projects for added references that don't come from a nuget and remove those too.

Body:
I have started a new Web Application in Visual Studio 2019. I have added a Web Api. Shortly after or at the same time (can't remember), I startet getting warnings like this:

Warning     No way to resolve conflict between "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" and "Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed". Choosing "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" arbitrarily.

I noticed but did not do anything as I decided to wait until it gave me problems.

And that is now...

I am about to use a JSon object but when writing this:

JObject jObject = JObject.Parse(result);

The compiler gives me this error:

Error   CS0433  The type 'JObject' exists in both 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I have searched the web and my conclusions are as follows:

It looks like it is Microsoft.AspNet.WebApi.Client that is the only package installed, that has a dependency on Newtonsoft.Json (>= 6.0.4)

I have installed Newtonsoft.Json (12.0.3)

In Solution Explorer. In reference list, I have only 1 reference. And that is the one for 12.0.3.

In Web.Config I have this entry (and only this for Newtonsoft.Json).

<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/></dependentAssembly>

In my .csproj I can see 3 different references in 3 different ItemGroups:

One for v. 12.0.0.0

One for v. 12.0.2

And one for v. 12.0.3

I tried to uninstall package Newtonsoft.Json, but is not allowed as other packages are dependent on this.

I have runned this command: Update-Package Newtonsoft.Json in the Package Manager Console, which told me, that no new updates were available.

And now, I have runned out of ideas. I am stucked. Anyone knows what to do?

****New update****
I found the 6.0.0.0. Please have a look at the picture:

Here in resources I double clicked the Newtonsoft.Json reference and in the object browser I can see both 6.0.0.0 and 12.0.0.0.

As you can see, both 6.0.0.0 and 12.0.0.0 are present. 6.0.0.0 is somewhere on my C:-drive inside a SDK.

I have tried to delete the file. My project got nuts. Then I replaced that file with the 12.0.0.0 from my project. This gave me the error that assemplies did not match.

I finally copied the old .dll back. And is a bit stucked again.

Any ideas?


问:
Adding function parameters using a single variable in jQuery
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

```<code>function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);
</code>```

Problem demo

Thanks in advance

答:
Here is another way to do it, I like this better myself because it is somewhat self documenting.  Each of the "parameters" in the options list has a name.

This is a common design pattern in JavaScript libraries for options to a module.

```<code>function Func (c){
 alert(c.a+' | '+c.b);
}
var Parameters = { a : "cool", b: 123 };
var Function = Func;

$('button').click(Parameters );
</code>```

Body:
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);

Problem demo

Thanks in advance

Body:
Here is another way to do it, I like this better myself because it is somewhat self documenting.  Each of the "parameters" in the options list has a name.

This is a common design pattern in JavaScript libraries for options to a module.

function Func (c){
 alert(c.a+' | '+c.b);
}
var Parameters = { a : "cool", b: 123 };
var Function = Func;

$('button').click(Parameters );