问:
ErrorException (E_ERROR) Creating default object from empty value (View: D:\
I am Newbie. I'm trying to return a view when i go to (for instance with selected id) /home/1 but i get this following error:

ErrorException (E_ERROR)
  Creating default object from empty value (View: D:\Michael..\resources\views\home.blade.php)

this is my route

```<code>Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home/{team_id}', 'HomeController@materialID');
</code>```

This is my controller

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $code = \App\Team::where('team_name',"Coding")->get();
        $design = \App\Team::where('team_name',"Design")->get();
        $qa = \App\Team::where('team_name',"Quality Assurance")->get();
        $ana = \App\Team::where('team_name',"Analytics")->get();
        return view('home',compact('code','design','qa','ana'));
    }

    public function materialID($team_id)
    {
        $material = Team::find($team_id);
        return view('material', compact('material'));
    }
}
</code>```

This is how i call it in my blade

```<code><a href="{{ url('home',$material->team_id = '1')}}">
     <h3>{{$code[0]->team_name}}</h3>
     <p style="padding-right: 35px">{{$code[0]->team_description}}</p>
</a>
</code>```

i dont know how to fix it.

答:
Pass the team id as a param to the url:</p>

```<code><a href="{{ url('home',['team_id'=>$material->team_id])}}">
</a>
</code>```

Body:
I am Newbie. I'm trying to return a view when i go to (for instance with selected id) /home/1 but i get this following error:

ErrorException (E_ERROR)
  Creating default object from empty value (View: D:\Michael..\resources\views\home.blade.php)

this is my route

Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/home/{team_id}', 'HomeController@materialID');

This is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Team;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $code = \App\Team::where('team_name',"Coding")->get();
        $design = \App\Team::where('team_name',"Design")->get();
        $qa = \App\Team::where('team_name',"Quality Assurance")->get();
        $ana = \App\Team::where('team_name',"Analytics")->get();
        return view('home',compact('code','design','qa','ana'));
    }

    public function materialID($team_id)
    {
        $material = Team::find($team_id);
        return view('material', compact('material'));
    }
}

This is how i call it in my blade

team_id = '1')}}">

{{$code[0]->team_name}}

{{$code[0]->team_description}}

i dont know how to fix it.

Body:
Pass the team id as a param to the url:

<a href="{{ url('home',['team_id'=>$material->team_id])}}">
</a>


来源: stackexchange

问:
English numbers are shown Persian in asp website
Hi I have a multi language website (English and Persian). I used font face for display different fonts for different languages. If I add a persian font to my font face all numbers including English numbers in english pages shown as persian numbers and if I just use english font-face all numbers are shown in english.
What should I do?</p>

```<code>@font-face {
font-family: 'myNazanin';
    src:
    local('B Nazanin'),
    url('../fonts/BNazanin.eot') format('eot'),  /* IE6–8 */
    url('../fonts/BNazanin.woff') format('woff'),  /* FF3.6+, IE9, Chrome6+,
    Saf5.1+*/
    url('../fonts/BNazanin.ttf') format('truetype');
 }
 @font-face {
   font-family: 'my New Roman';
     src:
    local('Times New Roman'),

 }
 body{

   font-family:myNazanin,'my New Roman';
 }
</code>```

答: It solved! My Persian font wasn't standard font for web! I changed it to an standard font and now everything is working just fine!</p>

ContentLicense: CC BY-SA 3.0

Body:
Hi I have a multi language website (English and Persian). I used font face for display different fonts for different languages. If I add a persian font to my font face all numbers including English numbers in english pages shown as persian numbers and if I just use english font-face all numbers are shown in english.
What should I do?

@font-face {
font-family: 'myNazanin';
    src:
    local('B Nazanin'),
    url('../fonts/BNazanin.eot') format('eot'),  /* IE6–8 */
    url('../fonts/BNazanin.woff') format('woff'),  /* FF3.6+, IE9, Chrome6+,
    Saf5.1+*/
    url('../fonts/BNazanin.ttf') format('truetype');
 }
 @font-face {
   font-family: 'my New Roman';
     src:
    local('Times New Roman'),

 }
 body{

   font-family:myNazanin,'my New Roman';
 }


问:
How to make JTextField appear after a button click and only accept the same length of characters as another string -Java GUI
I had posted a similar question before but it got deleted by accident.

My JTextField is supposed to appear after clicking a button which it does but only after minimizing the window. Another problem with it is that it accepts single characters when it's supposed to accept a phrase of only a certain length.

Here's a bit of the code since it's so long:

```<code> static String answer = "MY PUZZLE", puzzle = "M- -U----";

  //inside constructor
  guess = new JTextField("Write in Caps");
  guess.setVisible(false);
  guess.addActionListener(this);
  board.add(guess);

  //actionperformed
  guess.setVisible(true);
  gueStr = guess.getText();

  if (gueStr.length() != answer.length()) //if it is not the same length
  {
    gueStr = "";
  }
</code>```

the String "puzzle" is changed if a letter button (code not shown here) that is a character from the "answer" String is pressed or if the user's guess is the same phrase as the answer String

```<code>  if ( gueStr.equals(answer)) //if the guess is the answer
  {
    puzzle = answer;
  }

    for(int x=0; x < answer.length(); x++) //go through answer
    {
        if(letter == answer.charAt(x)) //if the letter pressed matches a character in answer
        {
          puzzle = puzzle.substring(0,x) + letter + puzzle.substring(x+1); //substitute in letter
        }

    }
</code>```

If more code is needed for understanding, I can post it. I'd be happy for a few pointers :D

Edit:

Thanks for all help guys, but I haven't been successful in understanding the second part yet.

Right now, I can get the textfield to show, but the problem lies with accepting a certain character length.  It has to be the exact same length as another string, no more, no less.

I have tried implementing it with the links you guys gave but only ended up getting confused (sorry). Can someone please offer a specific example?

Edit:

Resolved after using validate() and adding guess.setActionCommand("1").

答:
frame.validate()

The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.

This should work instead of minimizing the window.

Also for the second part, the API provides an example on how to custumize text fields: https://docs.oracle.com/javase/8/docs/api/javax/swing/JTextField.html

Do something similar to how they only accepts uppercase characters, but instead check the length with string.length().

Body:
I had posted a similar question before but it got deleted by accident.

My JTextField is supposed to appear after clicking a button which it does but only after minimizing the window. Another problem with it is that it accepts single characters when it's supposed to accept a phrase of only a certain length.

Here's a bit of the code since it's so long:

 static String answer = "MY PUZZLE", puzzle = "M- -U----";

  //inside constructor
  guess = new JTextField("Write in Caps");
  guess.setVisible(false);
  guess.addActionListener(this);
  board.add(guess);

  //actionperformed
  guess.setVisible(true);
  gueStr = guess.getText();

  if (gueStr.length() != answer.length()) //if it is not the same length
  {
    gueStr = "";
  }

the String "puzzle" is changed if a letter button (code not shown here) that is a character from the "answer" String is pressed or if the user's guess is the same phrase as the answer String

  if ( gueStr.equals(answer)) //if the guess is the answer
  {
    puzzle = answer;
  }

    for(int x=0; x < answer.length(); x++) //go through answer
    {
        if(letter == answer.charAt(x)) //if the letter pressed matches a character in answer
        {
          puzzle = puzzle.substring(0,x) + letter + puzzle.substring(x+1); //substitute in letter
        }

    }

If more code is needed for understanding, I can post it. I'd be happy for a few pointers :D

Edit:

Thanks for all help guys, but I haven't been successful in understanding the second part yet.

Right now, I can get the textfield to show, but the problem lies with accepting a certain character length.  It has to be the exact same length as another string, no more, no less.

I have tried implementing it with the links you guys gave but only ended up getting confused (sorry). Can someone please offer a specific example?

Edit:

Resolved after using validate() and adding guess.setActionCommand("1").


问:
How to increase the counter value when clicking the button in java script
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo">
      <span id="box1" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;"></span>
      <span id="box2" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box3" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box4" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box5" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box6" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box7" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box8" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box9" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box10"style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

答:
I have passed an extra parameter for the operation that you want to perform. Based on its value you can execute the code as you want.

Update 1 :-

Removed the static spans from div "divInfo".

We are adding span dynamically when user clicks on plus button.

We are removing last child from div "divInfo" when user click on minus button.

var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv,operation) {
            var containerElement =  document.getElementById("container");
            if(operation == "increment"){
            if(counter >= numBoxes){
              document.getElementById("demo").innerHTML = "Limit Is Over";
              return;
            }
            else{
              document.getElementById("demo").innerHTML = "";
            }
              counter++;
              var spn = document.createElement("span");
            spn.id = "box"+counter;
            spn.style = "border: 1px solid black; background: #CCCCCC; padding: 2px;height:90px;width:10px;float:left;";
           containerElement.appendChild(spn);
            }
            else if(operation == "decrement"){
            document.getElementById("demo").innerHTML = "";
              if(counter == 0){
                return;
              }
              containerElement.removeChild(containerElement.lastChild);
              counter--;
            }

            var inputBox = document.getElementById("value");
            inputBox.value = counter;

           /*
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {

           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });

           }*/
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo" id="container">

     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="myFun('box','increment');">
      <input id="decBtn" type="button" value="-" onclick="myFun('box','decrement');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

Body:
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }

      <input type="text" id="value" value="0">

      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">

Body:
I have passed an extra parameter for the operation that you want to perform. Based on its value you can execute the code as you want.

Update 1 :-

Removed the static spans from div "divInfo".

We are adding span dynamically when user clicks on plus button.

We are removing last child from div "divInfo" when user click on minus button.

var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv,operation) {
            var containerElement =  document.getElementById("container");
            if(operation == "increment"){
            if(counter >= numBoxes){
              document.getElementById("demo").innerHTML = "Limit Is Over";
              return;
            }
            else{
              document.getElementById("demo").innerHTML = "";
            }
              counter++;
              var spn = document.createElement("span");
            spn.id = "box"+counter;
            spn.style = "border: 1px solid black; background: #CCCCCC; padding: 2px;height:90px;width:10px;float:left;";
           containerElement.appendChild(spn);
            }
            else if(operation == "decrement"){
            document.getElementById("demo").innerHTML = "";
              if(counter == 0){
                return;
              }
              containerElement.removeChild(containerElement.lastChild);
              counter--;
            }

            var inputBox = document.getElementById("value");
            inputBox.value = counter;

           /*
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {

           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });

           }*/
    }

<div class="divInfo" id="container">

     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="myFun('box','increment');">
      <input id="decBtn" type="button" value="-" onclick="myFun('box','decrement');">
     </div>
     <div>
      <p id="demo"></p>
     </div>


问:
How to get the options inside ng-select in angular2 or typescript
i have installed angular2-select and have defined that in module.ts as well. But when i click on select button, there are 2 contents but the contents are not visible, can anyone help me to solve this.

HTML:

```<code><div class="form-group">
<label >Category Type</label>
<ng-select [options]="category" [(ngModel)]="category.name" name="category" class='filterDropDown' placeholder="Category" notFoundMsg="No Category Found">
 </ng-select>
 </div>
</code>```

ts:
category:any = [{name:'school'},{name:'college'}];

答:
```<code><ng-select [**items**]="category" [(ngModel)]="category.name" name="category" class='filterDropDown' placeholder="Category" notFoundMsg="No Category Found">
</code>```

It is items not options

Body:
i have installed angular2-select and have defined that in module.ts as well. But when i click on select button, there are 2 contents but the contents are not visible, can anyone help me to solve this.

HTML:

Category Type
<ng-select [options]="category" [(ngModel)]="category.name" name="category" class='filterDropDown' placeholder="Category" notFoundMsg="No Category Found">
 </ng-select>

ts:
category:any = [{name:'school'},{name:'college'}];

Body:
<ng-select [**items**]="category" [(ngModel)]="category.name" name="category" class='filterDropDown' placeholder="Category" notFoundMsg="No Category Found">

It is items not options


问:
ControlToValidate fires on all clicks: I only want it to fire when I click the "Submit" button
I have a textbox that is validated to make sure there is text content, for a file upload page.

My problem is that when the page has first loaded and you click anyway where on the page, the ControlToValidate fires immediately, this is an issue because I only want the page to validate the text box when you click the upload button.

You end up being trapped on the Upload File page until you type some random text into the textbox, even if you click a link to get somewhere else in the site (i.e the logo to get back to the mainpage).

Here is my relevant code snippet:

```<code> <asp:Label runat="server">Name</asp:Label>:
<br />
<asp:TextBox runat="server" ID="txtName"></asp:TextBox><asp:RequiredFieldValidator
    runat="server" ID="txtNameRequired" Display="Dynamic" ControlToValidate="txtName"
    Text="Name is required." CssClass="errorText" /><br />

<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" />
</asp:Panel>
</code>```

So I have a couple ideas but was not sure how to implement them :

1) find some property that will link the ControlToValidate solely to the clicking of the upload button.

or

2) Set up ControlToValidate so that it is only called on PostBacks

I am just not sure where to start and haven't been able to find any properties that specifically do this!

Thank you very much for your time !

答:
Set CausesValidation to false for the other posting controls.

```<code><asp:Button CausesValidation="false" Text="Cancel" Name="CancelButton" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a textbox that is validated to make sure there is text content, for a file upload page.

My problem is that when the page has first loaded and you click anyway where on the page, the ControlToValidate fires immediately, this is an issue because I only want the page to validate the text box when you click the upload button.

You end up being trapped on the Upload File page until you type some random text into the textbox, even if you click a link to get somewhere else in the site (i.e the logo to get back to the mainpage).

Here is my relevant code snippet:

 <asp:Label runat="server">Name</asp:Label>:

<asp:TextBox runat="server" ID="txtName"></asp:TextBox><asp:RequiredFieldValidator
    runat="server" ID="txtNameRequired" Display="Dynamic" ControlToValidate="txtName"
    Text="Name is required." CssClass="errorText" />

<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" />
</asp:Panel>

So I have a couple ideas but was not sure how to implement them :

1) find some property that will link the ControlToValidate solely to the clicking of the upload button.

or

2) Set up ControlToValidate so that it is only called on PostBacks

I am just not sure where to start and haven't been able to find any properties that specifically do this!

Thank you very much for your time !

Body:
Set CausesValidation to false for the other posting controls.

<asp:Button CausesValidation="false" Text="Cancel" Name="CancelButton" />


问:
How to make search bar shrinking effect like default mailbox
How make animation like ios  default mail. I need the same effect like search bar is hide at initial and when i drag table view download the it shows the search bar.

like in the screenshot

update to the question.- Right now i am using a searchBar above tableview in the view controller.

```<code>var resultSearchController = UISearchController()
self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        workActivityTableView.tableHeaderView = controller.searchBar
        workActivityTableView.contentOffset = CGPoint(x: 0, y: controller.searchBar.frame.height)
        navigationController?.extendedLayoutIncludesOpaqueBars = true

        return controller
    })()
</code>```

答:
Drag search bar in to your tableview in your storyboard as it should be the first subview of your tableview!

Tableview will consider it as a header.

Your view hierarchy will be look like,

And the default size of search bar will be 44.

Now in your viewDidload set content offset of your table view like,

```<code>_tblView.contentOffset = CGPointMake(0, 44);
</code>```

or in swift you can say,

```<code>tblView.contentOffset = CGPoint(x: 0, y: 44)
</code>```

and you're done!

bellows are screenshot of results,

Initially

After scroll

This will not work if prefersLargeTitles set to true then initially you will get search bar!

Body:
How make animation like ios  default mail. I need the same effect like search bar is hide at initial and when i drag table view download the it shows the search bar.

like in the screenshot

update to the question.- Right now i am using a searchBar above tableview in the view controller.

var resultSearchController = UISearchController()
self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        workActivityTableView.tableHeaderView = controller.searchBar
        workActivityTableView.contentOffset = CGPoint(x: 0, y: controller.searchBar.frame.height)
        navigationController?.extendedLayoutIncludesOpaqueBars = true

        return controller
    })()

Body:
Drag search bar in to your tableview in your storyboard as it should be the first subview of your tableview!

Tableview will consider it as a header.

Your view hierarchy will be look like,

And the default size of search bar will be 44.

Now in your viewDidload set content offset of your table view like,

_tblView.contentOffset = CGPointMake(0, 44);

or in swift you can say,

tblView.contentOffset = CGPoint(x: 0, y: 44)

and you're done!

bellows are screenshot of results,

Initially

After scroll

This will not work if prefersLargeTitles set to true then initially you will get search bar!


问:
SQL How do you SUM the fields retrieved by COUNT?
This is what I tried, but it didnt work.</p>

```<code>Select customer_id, sum(count (contact_id), count (call_id))
from contacts
limit 10
</code>```

答:
```<code>Select customer_id, count (contact_id) + count (call_id)
from contacts
limit 10
</code>```

you may need a GROUP BY clause unless your db adds one for you (mysql in certain configurations)

Body:
This is what I tried, but it didnt work.

Select customer_id, sum(count (contact_id), count (call_id))
from contacts
limit 10

Body:
Select customer_id, count (contact_id) + count (call_id)
from contacts
limit 10

you may need a GROUP BY clause unless your db adds one for you (mysql in certain configurations)


问:
Update a struct in Arduino
I have one structure like below in Arduino, I want to update it

```<code>struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;
</code>```

If bookId 101 is sold then how can I update qtyInStock? So, qtyInStock for bookId 101 should be 9 now.

Thanks

答:
You can use an array of type record to store multiple books. Sold being your inbuilt function, you can try this:</p>

```<code>struct record
{
   int bookId;
   int qtyInStock;

};
typedef struct record Record;
void sold(int id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
      records[i].qtyInStock--;
    }
  }
}
void updateId(int id, int new_id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].bookid = new_id;
    }
  }
}
void updateQty(int id, int new_qty, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].qtyInStock = new_qty;
    }
  }
}
void main() {
  Record records[3];
  records[0].bookId = 100;
  records[0].qtyInStock = 12;
  records[1].bookId = 101;
  records[1].qtyInStock = 10;
  records[2].bookId = 102;
  records[2].qtyInStock = 100;
  int i;
  sold(101, records);
  updateId(100, 99, records);
  updateQty(102, 15, records);
  for(i=0;i<3;i++) {
    printf("%d\n", records[i].bookId);
    printf("%d\n\n", records[i].qtyInStock);
  }
}
</code>```

Title: Update a struct in Arduino

Body:
I have one structure like below in Arduino, I want to update it

struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;

If bookId 101 is sold then how can I update qtyInStock? So, qtyInStock for bookId 101 should be 9 now.

Thanks

Body:
You can use an array of type record to store multiple books. Sold being your inbuilt function, you can try this:

struct record
{
   int bookId;
   int qtyInStock;

};
typedef struct record Record;
void sold(int id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
      records[i].qtyInStock--;
    }
  }
}
void updateId(int id, int new_id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].bookid = new_id;
    }
  }
}
void updateQty(int id, int new_qty, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].qtyInStock = new_qty;
    }
  }
}
void main() {
  Record records[3];
  records[0].bookId = 100;
  records[0].qtyInStock = 12;
  records[1].bookId = 101;
  records[1].qtyInStock = 10;
  records[2].bookId = 102;
  records[2].qtyInStock = 100;
  int i;
  sold(101, records);
  updateId(100, 99, records);
  updateQty(102, 15, records);
  for(i=0;i<3;i++) {
    printf("%d\n", records[i].bookId);
    printf("%d\n\n", records[i].qtyInStock);
  }
}


问:
how to addMarker from google sheet to google app script
i have two column in google sheet , that contain latitude and longitude,
i use below foramt:

```<code>var map=Maps.newStaticMap().setLanguage('en')
      .beginPath()
      .addMarker(lat, long)
      .addMarker(lat1, long1)
      .addMarker(lat2, long2)
      .addMarker(lat3, long3)
      .endPath().getAs('image/jpeg');
</code>```

i want to add multi addmarker from reading google sheet,

i used this code in google script:

```<code>var app=SpreadsheetApp
var ss= app.openById("1dNw5loVnxpBysrYC9t49vc5LRkOytSP23Blo-ny_oM");
var sheet2=ss.getSheetByName('Sheet2');
var lastRow2= sheet2.getLastRow();
var numRow=lastRow2-7;
var marker= "";
for (var i=8;i<=lastRow2;i++){
marker=marker+".addMarker("+sheet2.getRange(i,1).getValue()+","+ sheet2.getRange(i,2).getValue()+")";
}
marker=marker+".";

var map=Maps.newStaticMap().setLanguage('en').beginPath()+marker+endPath().getAs('image/jpeg');
</code>```

marker output is this:

```<code>.addMarker(32.645814,51.669745).addMarker(32.646284,51.66835).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.647468,51.665443).addMarker(32.650087,51.665625).addMarker(32.652779,51.665893).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653493,51.66599).addMarker(32.653899,51.664413).addMarker(32.654812,51.665571).addMarker(32.656347,51.665582).addMarker(32.656808,51.66202).addMarker(32.656916,51.660207).addMarker(32.660204,51.660572).addMarker(32.663049,51.661119).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).
</code>```

it work when i copy past marker output manuly in map variable:

```<code>var map=Maps.newStaticMap().setLanguage('en').setMarkerStyle(Maps.StaticMap.MarkerSize.TINY, Maps.StaticMap.Color.RED , '1').beginPath().addMarker(32.645814,51.669745).addMarker(32.646284,51.66835).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.647468,51.665443).addMarker(32.650087,51.665625).addMarker(32.652779,51.665893).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653493,51.66599).addMarker(32.653899,51.664413).addMarker(32.654812,51.665571).addMarker(32.656347,51.665582).addMarker(32.656808,51.66202).addMarker(32.656916,51.660207).addMarker(32.660204,51.660572).addMarker(32.663049,51.661119).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).endPath().getAs('image/jpeg');
</code>```

bu it dont work when i use this form:

```<code>var map=Maps.newStaticMap().setLanguage('en').beginPath()+marker+endPath().getAs('image/jpeg');
</code>```

image of my google sheet

答:
You need quotes around +marker+. Here is a test you can run. Check the
  log result.

thank you ,Ed Nelson
but it return , only string
and dont return image of google map.

Body:
i have two column in google sheet , that contain latitude and longitude,
i use below foramt:

var map=Maps.newStaticMap().setLanguage('en')
      .beginPath()
      .addMarker(lat, long)
      .addMarker(lat1, long1)
      .addMarker(lat2, long2)
      .addMarker(lat3, long3)
      .endPath().getAs('image/jpeg');

i want to add multi addmarker from reading google sheet,

i used this code in google script:

var app=SpreadsheetApp
var ss= app.openById("1dNw5loVnxpBysrYC9t49vc5LRkOytSP23Blo-ny_oM");
var sheet2=ss.getSheetByName('Sheet2');
var lastRow2= sheet2.getLastRow();
var numRow=lastRow2-7;
var marker= "";
for (var i=8;i<=lastRow2;i++){
marker=marker+".addMarker("+sheet2.getRange(i,1).getValue()+","+ sheet2.getRange(i,2).getValue()+")";
}
marker=marker+".";

var map=Maps.newStaticMap().setLanguage('en').beginPath()+marker+endPath().getAs('image/jpeg');

marker output is this:

.addMarker(32.645814,51.669745).addMarker(32.646284,51.66835).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.647468,51.665443).addMarker(32.650087,51.665625).addMarker(32.652779,51.665893).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653493,51.66599).addMarker(32.653899,51.664413).addMarker(32.654812,51.665571).addMarker(32.656347,51.665582).addMarker(32.656808,51.66202).addMarker(32.656916,51.660207).addMarker(32.660204,51.660572).addMarker(32.663049,51.661119).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).

it work when i copy past marker output manuly in map variable:

var map=Maps.newStaticMap().setLanguage('en').setMarkerStyle(Maps.StaticMap.MarkerSize.TINY, Maps.StaticMap.Color.RED , '1').beginPath().addMarker(32.645814,51.669745).addMarker(32.646284,51.66835).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.645769,51.665775).addMarker(32.647468,51.665443).addMarker(32.650087,51.665625).addMarker(32.652779,51.665893).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653032,51.665389).addMarker(32.653493,51.66599).addMarker(32.653899,51.664413).addMarker(32.654812,51.665571).addMarker(32.656347,51.665582).addMarker(32.656808,51.66202).addMarker(32.656916,51.660207).addMarker(32.660204,51.660572).addMarker(32.663049,51.661119).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).addMarker(32.663302,51.661666).endPath().getAs('image/jpeg');

bu it dont work when i use this form:

var map=Maps.newStaticMap().setLanguage('en').beginPath()+marker+endPath().getAs('image/jpeg');

image of my google sheet


问:
How do I get Composer to download the latest commit in the master branch from GitHub for a package?
I am trying to get Composer do download the latest commit for the Behat/MinkSelenium2Driver package. That particular repo only has a master branch. I have tried every method I can think of, including deleting the files and letting it pull them back in, to get it to work but it doesn't.

How would I get it to pull in latest committed files or at least those from the commit I list below?

Specifically I want to get this commit:
https://github.com/Behat/MinkSelenium2Driver/commit/2e73d8134ec8526b6e742f05c146fec2d5e1b8d6

Thanks,
Patrick

答:
Simply specify the master branch:

```<code>composer require --dev behat/mink-selenium2-driver:dev-master
</code>```

PS: the --dev is just to specify it's a test/development requirement, that's probably what you want.

Body:
Simply specify the master branch:

composer require --dev behat/mink-selenium2-driver:dev-master

PS: the --dev is just to specify it's a test/development requirement, that's probably what you want.


问:
Javascript html: Constructing a Quoted Google search String
I would like to construct a quoted google search string, and put this string in a link. The user would click on the link and be taken to the quoted search result. (Using JQuery)

```<code>$(".abstract_text",this).append('<div><a href="http://google.com/search?btnI=1&q="'+art_title.make_search()+'"> Search For Fulltext</a></div>');
</code>```

The above code gives this output:

```<code>http://google.com/search?btnI=1&q=The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin
</code>```

I would like to find a way to produce this output:

```<code>http://google.com/search?btnI=1&q="The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin"
</code>```

My question seems to be related to this question but I'm not exactly sure how to apply the answer that was accepted there: Nesting Quotes in JavaScript/HTML

*Please Note that though the search results are the same regardless of the output in this case, they will be different in general.

Solution:Use the encode URI function

```<code>$(".abstract_text",this).append('<div><a href="http://google.com/search?btnI=1&q='+encodeURI('"'+art_title.make_search()+'"')+'"> Search For Fulltext</a></div>');
</code>```

Output:

```<code>http://www.google.com/search?btnI=1&q=%22Early+treatment+of+traumatic+tattoo+by+erbium+YAG+laser%22
</code>```

答:
I don't know about JQuery but I guess what you want to do is encode your URL's special chars.
You can use the native Javascript function encodeURI() (function reference)

The default encoding for double quotes " is %22.

Body:
I would like to construct a quoted google search string, and put this string in a link. The user would click on the link and be taken to the quoted search result. (Using JQuery)

$(".abstract_text",this).append('
 Search For Fulltext
');

The above code gives this output:

http://google.com/search?btnI=1&q=The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin

I would like to find a way to produce this output:

http://google.com/search?btnI=1&q="The+Q+switched+ND+YAG+laser+effectively+treats+tattoos+in+darkly+pigmented+skin"

My question seems to be related to this question but I'm not exactly sure how to apply the answer that was accepted there: Nesting Quotes in JavaScript/HTML

*Please Note that though the search results are the same regardless of the output in this case, they will be different in general.

Solution:Use the encode URI function

$(".abstract_text",this).append('
 Search For Fulltext
');

Output:

http://www.google.com/search?btnI=1&q=%22Early+treatment+of+traumatic+tattoo+by+erbium+YAG+laser%22


问:
Does Flutter support cascading grids?
Does Flutter support cascading grid style layouts such as:

答:
You can create 4 Expanded in a Row and add Column of Containers in each Expanded:

Below is the code I ran and gives exact result you wish:

```<code>new Row(
                children: <Widget>[
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 24.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 150.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 140.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 90.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 58.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 20.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 220.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 150.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 100.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                ],
            )
</code>```

It gives the below result:

Title: Does Flutter support cascading grids?

Body:
You can create 4 Expanded in a Row and add Column of Containers in each Expanded:

Below is the code I ran and gives exact result you wish:

new Row(
                children: <Widget>[
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 24.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 150.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 140.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 90.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 58.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 20.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 220.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                    new Expanded(
                        child: new Column(
                            children: <Widget>[
                                new Container(
                                    height: 50.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 150.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                                new Container(
                                    height: 100.0,
                                    color: Colors.grey,
                                    margin: new EdgeInsets.all(10.0),
                                ),
                            ],
                        ),
                    ),
                ],
            )

It gives the below result:


问:
Getting "Server unexpectedly closed network connection" after executing a remote command with Plink
I am using Plink to execute remote command:

When using remote command (text file) error occurs:

FATAL ERROR: Server unexpectedly closed network connection

test.bat

```<code>"C:\Program Files (x86)\PuTTY\plink.exe"  XX.XX.XX.XX -l userID -pw password   -m "D:\FindingLog\test.txt"
</code>```

test.txt

```<code>cd log
</code>```

When I remove -m "D:\FindingLog\test.txt" in batch file, it works (successful login)

What's the problem?

答:
The SSH session closes (and Plink with it) as soon as the command finishes. Normally the "command" is shell. As you have overridden this default "command" and yet you seem to want to run the shell nevertheless, you have to explicitly execute the shell yourself:

```<code>cd log
/bin/bash
</code>```

Also as use of -m switch implies a non-interactive terminal, you probably want to force an interactive terminal back using -t switch.

See also How to prevent PuTTY shell from auto-exit after executing command from batch file in Windows?

Body:
I am using Plink to execute remote command:

When using remote command (text file) error occurs:

FATAL ERROR: Server unexpectedly closed network connection

test.bat

"C:\Program Files (x86)\PuTTY\plink.exe"  XX.XX.XX.XX -l userID -pw password   -m "D:\FindingLog\test.txt"

test.txt

cd log

When I remove -m "D:\FindingLog\test.txt" in batch file, it works (successful login)

What's the problem?

Body:
The SSH session closes (and Plink with it) as soon as the command finishes. Normally the "command" is shell. As you have overridden this default "command" and yet you seem to want to run the shell nevertheless, you have to explicitly execute the shell yourself:

cd log
/bin/bash

Also as use of -m switch implies a non-interactive terminal, you probably want to force an interactive terminal back using -t switch.

See also How to prevent PuTTY shell from auto-exit after executing command from batch file in Windows?


问:
How can I send trade offer
Actually I am working on Steam trade offer functionality, in which I am getting a problem.  I have downloaded the Steam class library and implement it in Codeigniter. I am following the setup guide from https://github.com/halipso/php-steam-tradeoffers#setupsessionid-cookies this. Actually I don't know about session id and cookie:

```<code>$steam->setup('sessionID', 'cookies');
</code>```

What will be sessionID and cookies?

I have read about it but did not get any solution. How can I get and implement it in my code?

答:
The session ID is the UUID of Steam which corresponds to our Steam profile.
The cookies are there to keep you authenticate.

Here's an example how you can get the sessionID and the cookies :
https://github.com/SzymonLisowiec/php-steamlogin (not my repo, credit to SzymonLisowiec)

Title: How can I send trade offer

Body:
Actually I am working on Steam trade offer functionality, in which I am getting a problem.  I have downloaded the Steam class library and implement it in Codeigniter. I am following the setup guide from https://github.com/halipso/php-steam-tradeoffers#setupsessionid-cookies this. Actually I don't know about session id and cookie:

$steam->setup('sessionID', 'cookies');

What will be sessionID and cookies?

I have read about it but did not get any solution. How can I get and implement it in my code?


问:
Setting Prime face dialog properties from java script
I don't have deep knowledge about JS or jQuery. What I am trying to achieve is I have few dialogues to show and I wanna give them common look and feel. so I am calling a js function to show each of them. I know I can set the properties at the

 tag. But I don't want that approach as I want a modular approach to set the properties to deal with all dialogue in my application.

Function Definition:

```<code>function editPartner(dialog){
      dialog.cfg.height = '500px';
      dialog.cfg.width = '600px';
      dialog.cfg.minHeight = '500px';
      dialog.cfg.minWidth = '600px';
      dialog.show();
}
</code>```

And calling it from

```<code> <p:commandButton id="editButton" oncomplete="editPartner(PF('DialogEditPartner'))" />
</code>```

but the width and height setting is not reflecting in the dialog.

Just a Reference, from the Prime-face component.js I can see the height and
 weight are set from cfg object.

```<code>PrimeFaces.widget.Dialog = PrimeFaces.widget.BaseWidget.extend({
init: function(a) {
    this._super(a);
    this.content = this.jq.children(".ui-dialog-content");
    this.titlebar = this.jq.children(".ui-dialog-titlebar");
    this.footer = this.jq.find(".ui-dialog-footer");
    this.icons = this.titlebar.children(".ui-dialog-titlebar-icon");
    this.closeIcon = this.titlebar.children(".ui-dialog-titlebar-close");
    this.minimizeIcon = this.titlebar.children(".ui-dialog-titlebar-minimize");
    this.maximizeIcon = this.titlebar.children(".ui-dialog-titlebar-maximize");
    this.blockEvents = "focus." + this.id + " mousedown." + this.id + " mouseup." + this.id;
    this.resizeNS = "resize." + this.id;
    this.cfg.absolutePositioned = this.jq.hasClass("ui-dialog-absolute");
    this.cfg.width = this.cfg.width || "auto";
    this.cfg.height = this.cfg.height || "auto";
    this.cfg.draggable = this.cfg.draggable === false ? false : true;
    this.cfg.resizable = this.cfg.resizable === false ? false : true;
    this.cfg.minWidth = this.cfg.minWidth || 150;
    this.cfg.minHeight = this.cfg.minHeight || this.titlebar.outerHeight();
    this.cfg.position = this.cfg.position || "center";
</code>```

答:
Based on the comments I edit my answer ans show my complete code:
complete code:

```<code><script type="text/javascript">
function editPartner(dialog){
     alert(dialog);

      dialog.show();

      var myDialog =  document.getElementById(dialog.id);
      myDialog.style.height = '500px';
      myDialog.style.width = "600px";
      myDialog.style.minHeight = '500px';
      myDialog.style.minWidth = '600px';

}
</script>
</h:head>
<h:body>
    <h1>Hello Raaj, this is for you</h1>

    <div style="height: 500px">

<p:growl id="grwl" showDetail="true" />
<p:commandButton id="editButton" value="stackoverflow problem" oncomplete="editPartner(PF('dialogForRaajVar'))" />

    <p:dialog   widgetVar="dialogForRaajVar" draggable="true" id="dialogForRaaj"
                 modal="true" showEffect="fade" showHeader="true"
                hideEffect="fade" resizable="false">
                <p:commandButton value="Close"
                    actionListener="#{dashboardView.addDiklat(actionevent)}"
                    update=":mainForm,grwl" oncomplete="PF('frmDiklat').hide()">
                     </p:commandButton>

                </p:dialog>
</code>```

Body:
I don't have deep knowledge about JS or jQuery. What I am trying to achieve is I have few dialogues to show and I wanna give them common look and feel. so I am calling a js function to show each of them. I know I can set the properties at the

 tag. But I don't want that approach as I want a modular approach to set the properties to deal with all dialogue in my application.

Function Definition:

function editPartner(dialog){
      dialog.cfg.height = '500px';
      dialog.cfg.width = '600px';
      dialog.cfg.minHeight = '500px';
      dialog.cfg.minWidth = '600px';
      dialog.show();
}

And calling it from

but the width and height setting is not reflecting in the dialog.

Just a Reference, from the Prime-face component.js I can see the height and
 weight are set from cfg object.

PrimeFaces.widget.Dialog = PrimeFaces.widget.BaseWidget.extend({
init: function(a) {
    this._super(a);
    this.content = this.jq.children(".ui-dialog-content");
    this.titlebar = this.jq.children(".ui-dialog-titlebar");
    this.footer = this.jq.find(".ui-dialog-footer");
    this.icons = this.titlebar.children(".ui-dialog-titlebar-icon");
    this.closeIcon = this.titlebar.children(".ui-dialog-titlebar-close");
    this.minimizeIcon = this.titlebar.children(".ui-dialog-titlebar-minimize");
    this.maximizeIcon = this.titlebar.children(".ui-dialog-titlebar-maximize");
    this.blockEvents = "focus." + this.id + " mousedown." + this.id + " mouseup." + this.id;
    this.resizeNS = "resize." + this.id;
    this.cfg.absolutePositioned = this.jq.hasClass("ui-dialog-absolute");
    this.cfg.width = this.cfg.width || "auto";
    this.cfg.height = this.cfg.height || "auto";
    this.cfg.draggable = this.cfg.draggable === false ? false : true;
    this.cfg.resizable = this.cfg.resizable === false ? false : true;
    this.cfg.minWidth = this.cfg.minWidth || 150;
    this.cfg.minHeight = this.cfg.minHeight || this.titlebar.outerHeight();
    this.cfg.position = this.cfg.position || "center";

Body:
Based on the comments I edit my answer ans show my complete code:
complete code:

<script type="text/javascript">
function editPartner(dialog){
     alert(dialog);

      dialog.show();

      var myDialog =  document.getElementById(dialog.id);
      myDialog.style.height = '500px';
      myDialog.style.width = "600px";
      myDialog.style.minHeight = '500px';
      myDialog.style.minWidth = '600px';

}
</script>
</h:head>
<h:body>
    <h1>Hello Raaj, this is for you</h1>

    <div style="height: 500px">

<p:growl id="grwl" showDetail="true" />
<p:commandButton id="editButton" value="stackoverflow problem" oncomplete="editPartner(PF('dialogForRaajVar'))" />

    <p:dialog   widgetVar="dialogForRaajVar" draggable="true" id="dialogForRaaj"
                 modal="true" showEffect="fade" showHeader="true"
                hideEffect="fade" resizable="false">
                <p:commandButton value="Close"
                    actionListener="#{dashboardView.addDiklat(actionevent)}"
                    update=":mainForm,grwl" oncomplete="PF('frmDiklat').hide()">
                     </p:commandButton>

                </p:dialog>


问:
three.js: rotate tetrahedron on correct axis
I have to display a rotating tetrahedron in an animated HTML5 graphic, using three.js.

When i create the object, it's upside down, but it should be on the ground with one surface, like on this screenshot: http://www10.pic-upload.de/08.10.12/v3nnz25zo65q.png

This is the code for rotating the object, at the moment. Stored in render() function. But the axis is incorrect and the object is rotating wrong.

```<code>object.useQuaternion = true;
var rotateQuaternion_ = new THREE.Quaternion();
rotateQuaternion_.setFromAxisAngle(new THREE.Vector3(0, 1, 1), 0.2 * (Math.PI / 180));
object.quaternion.multiplySelf(rotateQuaternion_);
object.quaternion.normalize();
</code>```

(copied from Three.JS - how to set rotation axis)

This is the result at the moment: http://jsfiddle.net/DkhT3/

How can i access the correct axis to move/rotate the tetrahedron on the ground?

Thanks for suggestions!

答:
```<code>Download three.js from [http://www.html5canvastutorials.com/libraries/Three.js] library and put in the below HTML code.
You will get good output.

<!Doctype html>
<html lang="eng">
<head>
    <title>I like shapes</title>
    <meta charset="UTF-8">
     <style>
     canvas{
     width: 100%;
     height: 100%
     }
    body{
    background: url(mathematics.jpg);
    width: 800px;
    height: 500px;
    }
     </style>
</head>
<body>

    <script src="three.js"></script>

    <script>
    // creating a Scene
    var scene = new THREE.Scene();

    // Adding Perspective Camera
    // NOTE: There are 3 cameras: Orthographic, Perspective and Combined.
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    //create WebGL renderer
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //Drawing a Tetrahedron.
    var pyramidgeometry = new THREE.CylinderGeometry(0, 0.8, 4, 4, false);

    //Change colour of Pyramid using Wireframe
    var pyramidmaterial = new THREE.MeshBasicMaterial({wireframe: true, color: 0x0ff000});
    var pyramid = new THREE.Mesh(pyramidgeometry, pyramidmaterial); //This creates the cone
    pyramid.position.set(3.1,0,0);
    scene.add(pyramid);

    //moving camera outward of centre to Z-axis, because Cube is being created at the centre
    camera.position.z = 5;

    //we have a scene, a camera, a cube and a renderer.

    /*A render loop essentially makes the renderer draw the scene 60 times per second.
    I have used requestAnimationFrame() function.*/
    var render = function() {
    requestAnimationFrame(render);

    /*cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    cube.rotation.z += 0.01;*/

    pyramid.rotation.y += 0.01;
    pyramid.rotation.x += 0.01;
    pyramid.rotation.z += 0.01;

    renderer.render(scene, camera);
    };
    // calling the function
    render();

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

Body:
I have to display a rotating tetrahedron in an animated HTML5 graphic, using three.js.

When i create the object, it's upside down, but it should be on the ground with one surface, like on this screenshot: http://www10.pic-upload.de/08.10.12/v3nnz25zo65q.png

This is the code for rotating the object, at the moment. Stored in render() function. But the axis is incorrect and the object is rotating wrong.

object.useQuaternion = true;
var rotateQuaternion_ = new THREE.Quaternion();
rotateQuaternion_.setFromAxisAngle(new THREE.Vector3(0, 1, 1), 0.2 * (Math.PI / 180));
object.quaternion.multiplySelf(rotateQuaternion_);
object.quaternion.normalize();

(copied from Three.JS - how to set rotation axis)

This is the result at the moment: http://jsfiddle.net/DkhT3/

How can i access the correct axis to move/rotate the tetrahedron on the ground?

Thanks for suggestions!


问:
M2Crypto bad performance to decrypt and verify big email
The input : big multipart signed and encrypted email (~10MB) done with openssl.

Decrypting the file seems to be fast enough.

Getting the decrypted information to verify them is MORE than long. It seems there is some problem in M2Crypto library. If you replace the smime_load_pkcs7_bio call by a file writing the p7s + reading it with smime_load_pkcs7 call it is MUCH faster. But I want to avoid a write/read on disk (as it is my bottleneck by now).

Question :
Does anyone have some workaround or solution to this performance problem ?

The python 2.7 code :

```<code>from M2Crypto import SMIME, X509, BIO, m2

# read signed and encrypted file
with open("toto.p7m", "r") as p7mFile:
  p7mBio = BIO.File(p7mFile)
  p7m = SMIME.PKCS7(m2.pkcs7_read_bio_der(p7mBio._ptr()), 1)

s = SMIME.SMIME()
# Decrypt
s.load_key('cnt.key', 'cnt.crt', callback = lambda x : 'cnt_password.info')
p7s = s.decrypt(p7m)
print("Decryption ok (and fast).")
# Verify
p7s_bio = BIO.MemoryBuffer(p7s)
p7, data = SMIME.smime_load_pkcs7_bio(p7s_bio)
# MUCH FASTER !!!
#p7, data = SMIME.smime_load_pkcs7('toto.p7s')
print("Wow this long to load something that is in memory!")
sk =  p7.get0_signers(X509.X509_Stack())
if 0 == len(sk) :
  print("ERROR : No signers.")

s.set_x509_stack(sk)

st = X509.X509_Store()
st.load_info('ca.crt')
s.set_x509_store(st)

v = s.verify(p7, data)
if v:
  print("Client signature verified.")
else:
  print("ERROR : Signature verification FAILED.")
</code>```

Generate keys/certs

```<code># generate control authority (key+cert)
openssl genrsa -out ca.key 2048 -passout file:ca_password.info
openssl req -x509 -new -nodes -key ca.key -passin file:ca_password.info -days 7300 -sha256 -extensions v3_ca -out ca.crt -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=XXX Xxxx XX"
openssl x509 -noout -text -in ca.crt

# generate client key + cert for CNT
openssl genrsa -out cnt.key 2048 -passout file:cnt_password.info
openssl req -new -key cnt.key -out cnt.csr -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=CNT xxxx"

echo "authorityKeyIdentifier = keyid,issuer" > cnt.ext
echo "basicConstraints = CA:FALSE" >> cnt.ext
echo "keyUsage = digitalSignature, keyEncipherment" >> cnt.ext
echo "subjectKeyIdentifier = hash" >> cnt.ext

openssl x509 -req -in cnt.csr -passin file:cnt_password.info -CA ca.crt -CAkey ca.key -CAcreateserial -out cnt.crt -days 1024 -extfile cnt.ext
openssl x509 -noout -text -in cnt.crt

# generate client key + cert for ET
openssl genrsa -out et.key 2048 -passout file:et_password.info
openssl req -new -key et.key -out et.csr -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=ET xxxx"

echo "authorityKeyIdentifier = keyid,issuer" > et.ext
echo "basicConstraints = CA:FALSE" >> et.ext
echo "keyUsage = digitalSignature, keyEncipherment" >> et.ext
echo "subjectKeyIdentifier = hash" >> et.ext

openssl x509 -req -in et.csr -passin file:et_password.info -CA ca.crt -CAkey ca.key -CAcreateserial -out et.crt -days 1024 -extfile et.ext
openssl x509 -noout -text -in et.crt
</code>```

Generate test data to go into the email

```<code>dd if=/dev/urandom of=sample1.jpg bs=1K count=743
dd if=/dev/urandom of=sample2.jpg bs=1K count=3009
dd if=/dev/urandom of=sample3.xml bs=1K count=5
dd if=/dev/urandom of=sample4.mp4 bs=1K count=2864
</code>```

Generate the email

The email is generated by some PHP code with the Mail/mime.php library.

```<code><?php
date_default_timezone_set('Europe/Paris');
require_once 'Mail/mime.php';

function add_fichier_2_mail(&$mime, $filename) {
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime_type=finfo_file($finfo,$filename);
  finfo_close($finfo);
  $mime->addAttachment($filename, $mime_type);
}
$crlf = "\n";
$mime_mif = new Mail_mime($crlf);
add_fichier_2_mail($mime_mif, "sample1.jpg");
add_fichier_2_mail($mime_mif, "sample2.jpg");
add_fichier_2_mail($mime_mif, "sample3.xml");
add_fichier_2_mail($mime_mif, "sample4.mp4");
$body = $mime_mif->get();
$hdrs=array();
$entete = $mime_mif->headers($hdrs);
unset($mime_mif);
$msg='';
foreach ($entete as $key=>$value) {
  $msg.=$key.': '.$value.$crlf;
}
$msg.=$crlf.$crlf.$body;
file_put_contents("email_clear.eml",$msg);
?>
</code>```

Sign / Encrypt the email

The email is signed by ET private key and then encrypted by CNT public certificate. This gives the following commands :

```<code>openssl smime -sign -binary -nodetach -certfile et.crt -signer et.crt -inkey et.key -in email_clear.eml -out email_signed.p7s
openssl smime -encrypt -outform DER -binary -des3 -in email_signed.p7s -out email_crypted_signed.p7m cnt.crt
</code>```

答:
I was able to confirm this on my machine, but not able to figure out why it's happening. The problem seems to be in the BIO.MemoryBuffer class...

As I commented, the workaround that immediately jumped out to me was to create a RAM disk and use smime_load_pkcs7 against that.

Creating a ram disk on Linux

```<code>mkdir -p /mnt/tmpfs
mount -o size=16G -t tmpfs none /mnt/tmpfs
</code>```

This has two benefits: (1) you avoid the faulty code in M2Crypto and (2) you can avoid having to write to or read from the disk.

Body:
The input : big multipart signed and encrypted email (~10MB) done with openssl.

Decrypting the file seems to be fast enough.

Getting the decrypted information to verify them is MORE than long. It seems there is some problem in M2Crypto library. If you replace the smime_load_pkcs7_bio call by a file writing the p7s + reading it with smime_load_pkcs7 call it is MUCH faster. But I want to avoid a write/read on disk (as it is my bottleneck by now).

Question :
Does anyone have some workaround or solution to this performance problem ?

The python 2.7 code :

from M2Crypto import SMIME, X509, BIO, m2

# read signed and encrypted file
with open("toto.p7m", "r") as p7mFile:
  p7mBio = BIO.File(p7mFile)
  p7m = SMIME.PKCS7(m2.pkcs7_read_bio_der(p7mBio._ptr()), 1)

s = SMIME.SMIME()
# Decrypt
s.load_key('cnt.key', 'cnt.crt', callback = lambda x : 'cnt_password.info')
p7s = s.decrypt(p7m)
print("Decryption ok (and fast).")
# Verify
p7s_bio = BIO.MemoryBuffer(p7s)
p7, data = SMIME.smime_load_pkcs7_bio(p7s_bio)
# MUCH FASTER !!!
#p7, data = SMIME.smime_load_pkcs7('toto.p7s')
print("Wow this long to load something that is in memory!")
sk =  p7.get0_signers(X509.X509_Stack())
if 0 == len(sk) :
  print("ERROR : No signers.")

s.set_x509_stack(sk)

st = X509.X509_Store()
st.load_info('ca.crt')
s.set_x509_store(st)

v = s.verify(p7, data)
if v:
  print("Client signature verified.")
else:
  print("ERROR : Signature verification FAILED.")

Generate keys/certs

# generate control authority (key+cert)
openssl genrsa -out ca.key 2048 -passout file:ca_password.info
openssl req -x509 -new -nodes -key ca.key -passin file:ca_password.info -days 7300 -sha256 -extensions v3_ca -out ca.crt -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=XXX Xxxx XX"
openssl x509 -noout -text -in ca.crt

# generate client key + cert for CNT
openssl genrsa -out cnt.key 2048 -passout file:cnt_password.info
openssl req -new -key cnt.key -out cnt.csr -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=CNT xxxx"

echo "authorityKeyIdentifier = keyid,issuer" > cnt.ext
echo "basicConstraints = CA:FALSE" >> cnt.ext
echo "keyUsage = digitalSignature, keyEncipherment" >> cnt.ext
echo "subjectKeyIdentifier = hash" >> cnt.ext

openssl x509 -req -in cnt.csr -passin file:cnt_password.info -CA ca.crt -CAkey ca.key -CAcreateserial -out cnt.crt -days 1024 -extfile cnt.ext
openssl x509 -noout -text -in cnt.crt

# generate client key + cert for ET
openssl genrsa -out et.key 2048 -passout file:et_password.info
openssl req -new -key et.key -out et.csr -subj "/C=XX/ST=Xxxxxx/L=XXXX/O=XXXXX/OU=XXXX/CN=ET xxxx"

echo "authorityKeyIdentifier = keyid,issuer" > et.ext
echo "basicConstraints = CA:FALSE" >> et.ext
echo "keyUsage = digitalSignature, keyEncipherment" >> et.ext
echo "subjectKeyIdentifier = hash" >> et.ext

openssl x509 -req -in et.csr -passin file:et_password.info -CA ca.crt -CAkey ca.key -CAcreateserial -out et.crt -days 1024 -extfile et.ext
openssl x509 -noout -text -in et.crt

Generate test data to go into the email

dd if=/dev/urandom of=sample1.jpg bs=1K count=743
dd if=/dev/urandom of=sample2.jpg bs=1K count=3009
dd if=/dev/urandom of=sample3.xml bs=1K count=5
dd if=/dev/urandom of=sample4.mp4 bs=1K count=2864

Generate the email

The email is generated by some PHP code with the Mail/mime.php library.

<?php
date_default_timezone_set('Europe/Paris');
require_once 'Mail/mime.php';

function add_fichier_2_mail(&$mime, $filename) {
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime_type=finfo_file($finfo,$filename);
  finfo_close($finfo);
  $mime->addAttachment($filename, $mime_type);
}
$crlf = "\n";
$mime_mif = new Mail_mime($crlf);
add_fichier_2_mail($mime_mif, "sample1.jpg");
add_fichier_2_mail($mime_mif, "sample2.jpg");
add_fichier_2_mail($mime_mif, "sample3.xml");
add_fichier_2_mail($mime_mif, "sample4.mp4");
$body = $mime_mif->get();
$hdrs=array();
$entete = $mime_mif->headers($hdrs);
unset($mime_mif);
$msg='';
foreach ($entete as $key=>$value) {
  $msg.=$key.': '.$value.$crlf;
}
$msg.=$crlf.$crlf.$body;
file_put_contents("email_clear.eml",$msg);
?>

Sign / Encrypt the email

The email is signed by ET private key and then encrypted by CNT public certificate. This gives the following commands :

openssl smime -sign -binary -nodetach -certfile et.crt -signer et.crt -inkey et.key -in email_clear.eml -out email_signed.p7s
openssl smime -encrypt -outform DER -binary -des3 -in email_signed.p7s -out email_crypted_signed.p7m cnt.crt

Body:
I was able to confirm this on my machine, but not able to figure out why it's happening. The problem seems to be in the BIO.MemoryBuffer class...

As I commented, the workaround that immediately jumped out to me was to create a RAM disk and use smime_load_pkcs7 against that.

Creating a ram disk on Linux

mkdir -p /mnt/tmpfs
mount -o size=16G -t tmpfs none /mnt/tmpfs

This has two benefits: (1) you avoid the faulty code in M2Crypto and (2) you can avoid having to write to or read from the disk.


问:
During activating Tensorflow program, Error 'NoneType' object has no attribute 'group'. How can I solve this?
When I was using Tensorflow to follow the tutorial of Simple Audio Recognition on TensorFlow page, I got a problem in downloading audio data for train.

I have entered the following command:

```<code>C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py
</code>```

and got an error message,

```<code> Downloading speech_commands_v0.01.tar.gz 100.0%
INFO:tensorflow:Successfully downloaded speech_commands_v0.01.tar.gz (1488293908 bytes)
Traceback (most recent call last):
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 427, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\user\AppData\Local\conda\conda\envs\my_root\lib\site-packages\tensorflow\python\platform\app.py", line 133, in run
    _sys.exit(main(argv))
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 104, in main
    FLAGS.testing_percentage, model_settings)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 161, in __init__
    testing_percentage)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 243, in prepare_data_index
    word = re.search('.*/([^/]+)/.*.wav', wav_path).group(1).lower()
AttributeError: 'NoneType' object has no attribute 'group'
</code>```

Should I fix the code on file input_data.py? If it is possible, how can I fix it? It will be helpful if anyone gives me some advice on this problem.

答:
I think it'a python error instead of a tensorflow error.

There's no match for your regexp in re.search()

Body:
When I was using Tensorflow to follow the tutorial of Simple Audio Recognition on TensorFlow page, I got a problem in downloading audio data for train.

I have entered the following command:

C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py

and got an error message,

 Downloading speech_commands_v0.01.tar.gz 100.0%
INFO:tensorflow:Successfully downloaded speech_commands_v0.01.tar.gz (1488293908 bytes)
Traceback (most recent call last):
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 427, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\user\AppData\Local\conda\conda\envs\my_root\lib\site-packages\tensorflow\python\platform\app.py", line 133, in run
    _sys.exit(main(argv))
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 104, in main
    FLAGS.testing_percentage, model_settings)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 161, in __init__
    testing_percentage)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 243, in prepare_data_index
    word = re.search('.*/([^/]+)/.*.wav', wav_path).group(1).lower()
AttributeError: 'NoneType' object has no attribute 'group'

Should I fix the code on file input_data.py? If it is possible, how can I fix it? It will be helpful if anyone gives me some advice on this problem.


问:
How to set the log level for an imported module?
Write your code with a nice logger

```<code>import logging

def init_logging():
     logFormatter = logging.Formatter("[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s")
     rootLogger = logging.getLogger()
     LOG_DIR = os.getcwd() + '/' + 'logs'
     if not os.path.exists(LOG_DIR):
          os.makedirs(LOG_DIR)
     fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
     fileHandler.setFormatter(logFormatter)
     rootLogger.addHandler(fileHandler)
     rootLogger.setLevel(logging.DEBUG)
     consoleHandler = logging.StreamHandler()
     consoleHandler.setFormatter(logFormatter)
     rootLogger.addHandler(consoleHandler)
     return rootLogger

logger = init_logging()
</code>```

works as expected. Logging using logger.debug("Hello! :)") logs to file and console.

In a second step you want to import an external module which is also logging using logging module:

Install it using pip3 install pymisp (or any other external module)

Import it using from pymisp import PyMISP (or any other external module)

Create an object of it using self.pymisp = PyMISP(self.ds_model.api_url, self.ds_model.api_key, False, 'json') (or any other...)

What now happens is, that every debug log output from the imported module is getting logged to the log file and the console. The question now is, how to set a different (higher) log level for the imported module.

答:
A colleague of mine helped with this question:

Get a named logger yourLogger = logging.getLogger('your_logger')

Add a filter to each handler prevents them to print/save other logs than yours

```<code>for handler in logging.root.handlers:
    handler.addFilter(logging.Filter('your_logger'))
</code>```

Body:
Write your code with a nice logger

import logging

def init_logging():
     logFormatter = logging.Formatter("[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s")
     rootLogger = logging.getLogger()
     LOG_DIR = os.getcwd() + '/' + 'logs'
     if not os.path.exists(LOG_DIR):
          os.makedirs(LOG_DIR)
     fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
     fileHandler.setFormatter(logFormatter)
     rootLogger.addHandler(fileHandler)
     rootLogger.setLevel(logging.DEBUG)
     consoleHandler = logging.StreamHandler()
     consoleHandler.setFormatter(logFormatter)
     rootLogger.addHandler(consoleHandler)
     return rootLogger

logger = init_logging()

works as expected. Logging using logger.debug("Hello! :)") logs to file and console.

In a second step you want to import an external module which is also logging using logging module:

Install it using pip3 install pymisp (or any other external module)

Import it using from pymisp import PyMISP (or any other external module)

Create an object of it using self.pymisp = PyMISP(self.ds_model.api_url, self.ds_model.api_key, False, 'json') (or any other...)

What now happens is, that every debug log output from the imported module is getting logged to the log file and the console. The question now is, how to set a different (higher) log level for the imported module.

Body:
A colleague of mine helped with this question:

Get a named logger yourLogger = logging.getLogger('your_logger')

Add a filter to each handler prevents them to print/save other logs than yours

for handler in logging.root.handlers:
    handler.addFilter(logging.Filter('your_logger'))


问:
Jquery DataTable Searching behaves incorrectly if string has double quotes " in middle
I am using jquery.datatable.js and using default smart search of datatable

```<code>    var dataTable=$('#task_table').DataTable( {
        deferRender:true,
        destroy:true,
        scrollCollapse: true,
        select:'multi',
        rowId:'_id',
        scroller:true,
        scrollY:"0px",
        bInfo:false,
        bLengthChange:false,
        columns:self.getColumns(),
        fnDrawCallback:function(){
        }
    } );
    $('#Search').on( 'keyup', function(){
        dataTable.search(this.value).draw();
    });
</code>```

I am using above code to search
Below are examples of Strings i have in search

Using  dataTable.search(this.value).draw(); this not searching both the string i have mentioned

After using

```<code>dataTable.search('"'+ this.value +'"').draw();
</code>```

=calc|a!z'ss"s:s: working fine

!"abc'aa"ads#$%k"as'": not Searching after !"abc'aa" this part of string

can anyone help to search any string in datatable

答:
You can escape the special characters in your variable prior to searching</p>

```<code>.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1') + "']"
</code>```

Body:
I am using jquery.datatable.js and using default smart search of datatable

    var dataTable=$('#task_table').DataTable( {
        deferRender:true,
        destroy:true,
        scrollCollapse: true,
        select:'multi',
        rowId:'_id',
        scroller:true,
        scrollY:"0px",
        bInfo:false,
        bLengthChange:false,
        columns:self.getColumns(),
        fnDrawCallback:function(){
        }
    } );
    $('#Search').on( 'keyup', function(){
        dataTable.search(this.value).draw();
    });

I am using above code to search
Below are examples of Strings i have in search

Using  dataTable.search(this.value).draw(); this not searching both the string i have mentioned

After using

dataTable.search('"'+ this.value +'"').draw();

=calc|a!z'ss"s:s: working fine

!"abc'aa"ads#$%k"as'": not Searching after !"abc'aa" this part of string

can anyone help to search any string in datatable

Body:
You can escape the special characters in your variable prior to searching

.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1') + "']"


问:
Does Tensorflow's tf.while_loop automatically capture dependencies when executing in parallel?
I am interested in implementing a Recursive Neural Network in Tensorflow, like what has been done in How can I implement a recursive neural network in TensorFlow?.

However, in his implementation, the parallel_iterations of the tf.while_loop statement was fixed to be 1. I fear that this might be too slow. Since the tree I am going to feed into tensorflow have parts that are not dependent on each other, I would hope that I could set parallel_iterations to a higher value. However, it is inevitable that there are some dependencies required in the tree I feed in as input to tensorflow, and I am afraid that setting it to higher value may break the dependency property.

So my question is, had Tensorflow's tf.while_loop automatically captured dependencies already, in order to only use paralleism on placed that are not dependent on each other?

The tensorflow documentation says the following:

For correct programs, while_loop should return the same result for any
  parallel_iterations > 0.

But I am not sure what they mean by "correct programs".

答:
You can.

according to this issue, ops will run in parallel once all their inputs nodes are computed:

while_loop implements non-strict semantics. An iteration can start as soon as one of the ops for this iteration is ready (i.e., all its inputs are available.) for execution. So a while_loop can easily have multiple iterations running in parallel. For example, for scan, even if the accumulated value is not available in a step, the step can still start and execute any ops that don't depend on the accumulated value.

so you shouldn't encounter any issues.


问:
How do I convert a Win32 lParam to a C struct?
Say I have some windows method and a struct:

```<code>struct SomeStruct{
int foo;
int bar;
int baz;
int bat;
}

SomeMethod(int a,int wParam, int lParam)
{
   SomeStruct s;

   // get lParam into SomeStruct
}
</code>```

How to I get the lParam into a SomeStruct variable? I'm thinking that I need something like this (but feel free to point out my ignorance):

```<code>SomeMethod(int a, int wParam, int lParam)
{
  SomeStruct *s; //declare struct variable
  s = lParam;    //assign integer value as pointer to struct
  printf("the value of s.foo is %d", s.foo);  //print result
}
</code>```

答:
Please use the correct types, or your code will fail on Win64.

```<code>SomeMethod(int a, WPARAM wParam, LPARAM lParam)
{
  SomeStruct *s = (SomeStruct *) lParam;
  printf("the value of s.foo is %d", s.foo);  //print result
}
</code>```

Body:
Say I have some windows method and a struct:

struct SomeStruct{
int foo;
int bar;
int baz;
int bat;
}

SomeMethod(int a,int wParam, int lParam)
{
   SomeStruct s;

   // get lParam into SomeStruct
}

How to I get the lParam into a SomeStruct variable? I'm thinking that I need something like this (but feel free to point out my ignorance):

SomeMethod(int a, int wParam, int lParam)
{
  SomeStruct *s; //declare struct variable
  s = lParam;    //assign integer value as pointer to struct
  printf("the value of s.foo is %d", s.foo);  //print result
}

Body:
Please use the correct types, or your code will fail on Win64.

SomeMethod(int a, WPARAM wParam, LPARAM lParam)
{
  SomeStruct *s = (SomeStruct *) lParam;
  printf("the value of s.foo is %d", s.foo);  //print result
}

OwnerDisplayName: MSalters


问:
How can I log a hyperlink click?
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</code>```

to the Site.Master file.

And

```<code>public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}
</code>```

to the HomeController.cs file

And

```<code><p>
    <a id="lnkTestPost" href="/home/about">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething");
        });
    </script>
</p>
</code>```

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

答:
Alternatively, you could do what Google Reader does, and put a "from url" in each link:

```<code><script>
$("a:href").each(function(){
    this.attr("href", this.attr("href") + "?from=" + encodeURIComponent(window.location));
    // (note: this exact code won't handle links which already have GET vars…)
});
</script>
</code>```

Then use some middleware to log the "from" in inbound requests.

This has the disadvantage that it won't be able to log clicks going to another domain… But that might be alright.

Title: How can I log a hyperlink click?

Body:
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

to the Site.Master file.

And

public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}

to the HomeController.cs file

And

    Test Post

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

Body:
Alternatively, you could do what Google Reader does, and put a "from url" in each link:

<script>
$("a:href").each(function(){
    this.attr("href", this.attr("href") + "?from=" + encodeURIComponent(window.location));
    // (note: this exact code won't handle links which already have GET vars…)
});
</script>

Then use some middleware to log the "from" in inbound requests.

This has the disadvantage that it won't be able to log clicks going to another domain… But that might be alright.


问:
Upload image to S3 using AWS SDK.
So I'm trying to upload an image up to S3 using the AWS-SDK. The upload is working but sometimes I run into a warning/ error and I haven't been able to figure out why this is happening.

If anyone has any ideas greatly appreciated.

Here's the source code:

```<code>      const s3 = new AWS.S3();
      const ext = uri.substr(uri.lastIndexOf('.') + 1);
      const type = `image/${ext}`;
      const filePath = `uploads/cache/${randomString({ length: 32 })}/${randomString(10)}.${ext}`;

      s3.putObject({
        Bucket: Config.S3_BUCKET,
        Key: filePath,
        ContentType: type,
        Body: new Buffer(data, 'base64'),
        ACL: 'public-read',
      }
</code>```

Error or Warning

```<code>Promise Rejection (id: 0):
Error: C++ exception in 'nativeFlushQueueImmediate'

Malformed calls from JS: field sizes are different.

[[58,58,58,58,58,58,15,27],[4,4,4,4,4,4,1,0],[[1],[1],[1],[1],[1],[1],[136,100,1510545939677,false]],5224]
nativeFlushQueueImmediate@[native code]
</code>```

答:
There's actually nothing wrong with the code. Sorry, it was a problem being caused with my async calls.

But at least its good to know uploading to S3 with aws-sdk is working nicely :D

Title: Upload image to S3 using AWS SDK.

Body:
So I'm trying to upload an image up to S3 using the AWS-SDK. The upload is working but sometimes I run into a warning/ error and I haven't been able to figure out why this is happening.

If anyone has any ideas greatly appreciated.

Here's the source code:

      const s3 = new AWS.S3();
      const ext = uri.substr(uri.lastIndexOf('.') + 1);
      const type = `image/${ext}`;
      const filePath = `uploads/cache/${randomString({ length: 32 })}/${randomString(10)}.${ext}`;

      s3.putObject({
        Bucket: Config.S3_BUCKET,
        Key: filePath,
        ContentType: type,
        Body: new Buffer(data, 'base64'),
        ACL: 'public-read',
      }

Error or Warning

Promise Rejection (id: 0):
Error: C++ exception in 'nativeFlushQueueImmediate'

Malformed calls from JS: field sizes are different.

[[58,58,58,58,58,58,15,27],[4,4,4,4,4,4,1,0],[[1],[1],[1],[1],[1],[1],[136,100,1510545939677,false]],5224]
nativeFlushQueueImmediate@[native code]


问:
IE11 Angular 2 error "Expected identifier, string or number"
Well, I have created site using Angular 2. When I run "ng-serve" command and trying to test my site using "http://localhost:4200" in Google Chrome and IE11 it works perfectly, but, if I build project using "ng-build --prod", host it on IIS. Site still works on Chrome, but IE11 shows the following errors:

I googled it and found that it was maybe reserved words in my identifiers key:value pairs. So I added Apostrophes(') arround my keys.
For example I had the following object:

```<code>user:UserViewModel={
    Username:"",
    Age:0
};
and changed this to:
user:UserViewModel={
    'Username':"",
    'Age':0
};
</code>```

Also deleted last commas in key:value pairs and imported core.js in polyfills.ts

答:
The main problem is IE has Compatibility Mode enabled by default. And IE 11 has some compatibility mode issues.
As per the followings question answer Angular 2 / 4 not working in IE11

When I tried to disable the compatibility mode off It works fine.

But ingeneral user will not off the compatibility mode. So I want a good solution for that.

Then I found following solution form Force IE compatibility mode off using tags

```<code>      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</code>```

Body:
Well, I have created site using Angular 2. When I run "ng-serve" command and trying to test my site using "http://localhost:4200" in Google Chrome and IE11 it works perfectly, but, if I build project using "ng-build --prod", host it on IIS. Site still works on Chrome, but IE11 shows the following errors:

I googled it and found that it was maybe reserved words in my identifiers key:value pairs. So I added Apostrophes(') arround my keys.
For example I had the following object:

user:UserViewModel={
    Username:"",
    Age:0
};
and changed this to:
user:UserViewModel={
    'Username':"",
    'Age':0
};

Also deleted last commas in key:value pairs and imported core.js in polyfills.ts

Body:
The main problem is IE has Compatibility Mode enabled by default. And IE 11 has some compatibility mode issues.
As per the followings question answer Angular 2 / 4 not working in IE11

When I tried to disable the compatibility mode off It works fine.

But ingeneral user will not off the compatibility mode. So I want a good solution for that.

Then I found following solution form Force IE compatibility mode off using tags

      <meta http-equiv="X-UA-Compatible" content="IE=edge" />


问:
Autoreleasepool in background queue for Realm
In the example project of RealmCocoa:

```<code>// Multi-threading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    RLMRealm *otherRealm = [RLMRealm defaultRealm];
    RLMResults *otherResults = [Dog objectsInRealm:otherRealm where:@"name contains 'Rex'"];
    NSLog(@"Number of dogs: %li", (unsigned long)otherResults.count);
});
</code>```

In the website docs:

```<code>dispatch_async(dispatch_queue_create("background", 0), ^{
    @autoreleasepool {
        Dog *theDog = [[Dog objectsWhere:@"age == 1"] firstObject];
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        theDog.age = 3;
        [realm commitWriteTransaction];
    }
});
</code>```

Why doesn't the example project have autoreleasepool?

Should the example project's code also include an autoreleasepool?

Which one of these usage is more appropriate?

答:
Why doesn't the example project have autoreleasepool?

It’s an oversight.

Should the example project's code also include an autoreleasepool?

Yes.

Which one of these usage is more appropriate?

The latter. As Realm’s documentation on threading states, all use of Realm from background threads should be contained within explicit autorelease pools.

Body:
In the example project of RealmCocoa:

// Multi-threading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    RLMRealm *otherRealm = [RLMRealm defaultRealm];
    RLMResults *otherResults = [Dog objectsInRealm:otherRealm where:@"name contains 'Rex'"];
    NSLog(@"Number of dogs: %li", (unsigned long)otherResults.count);
});

In the website docs:

dispatch_async(dispatch_queue_create("background", 0), ^{
    @autoreleasepool {
        Dog *theDog = [[Dog objectsWhere:@"age == 1"] firstObject];
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        theDog.age = 3;
        [realm commitWriteTransaction];
    }
});

Why doesn't the example project have autoreleasepool?

Should the example project's code also include an autoreleasepool?

Which one of these usage is more appropriate?


问:
How do I print the success message
How do I print the success message in this JSON code using PHP

```<code>{
    "status": 0,

     " result":{
           "status":"success"
               }

}
</code>```

答:
Convert this json to PHP Array using json_decode()

Check the ['result']['status']

if its equals to 'success'

Then print some message

Title: How do I print the success message

Body:
How do I print the success message in this JSON code using PHP

{
    "status": 0,

     " result":{
           "status":"success"
               }

}


问:
Change order of containers in mobile
I am using w3.css, want to change order of containers when on mobile ( check screenshot below). Is there any class in w3.css which help changing order of blocks? I don't want to use standard css flex, just wanted to use w3.css

答:
Since you have the flexbox tag I'm giving you the Flexbox solution:

body {
  color: #fff;
}

.parent {
  display: flex; /* displays the children inline */
}

.child {
  flex: 1; /* children take as much horizontal space as they can */
  height: 100px;
}

.A {
  background: blue;
}

.B {
  background: red;
}

@media screen and (max-width: 568px) { /* adjust to your needs */
  .parent {
    flex-direction: column; /* stacks the children vertically */
  }
  .A {
    order: 2; /* changes the order, i.e. displays the .A below the .B */
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child A">A</div>
  <div class="child B">B</div>
</div></code>```

You can also do it with the Grid:

body {
  color: #fff;
}

.parent {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* could also use: 1fr 1fr or 50% 50% without the repeat() */
  grid-template-rows: repeat(2, minmax(100px, auto)); /* minimum height 100px, maximum height unlimited, adjust to your needs, you can also remove it, not mandatory */
}

.A {
  background: blue;
}

.B {
  background: red;
}

@media screen and (max-width: 568px) {
  .parent {
    grid-template-columns: 1fr; /* could also use: 100% */
  }
  .A {
    order: 2;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="A">A</div>
  <div class="B">B</div>
</div></code>```

Title: Change order of containers in mobile

Body:
Since you have the flexbox tag I'm giving you the Flexbox solution:

body {
  color: #fff;
}

.parent {
  display: flex; /* displays the children inline */
}

.child {
  flex: 1; /* children take as much horizontal space as they can */
  height: 100px;
}

.A {
  background: blue;
}

.B {
  background: red;
}

@media screen and (max-width: 568px) { /* adjust to your needs */
  .parent {
    flex-direction: column; /* stacks the children vertically */
  }
  .A {
    order: 2; /* changes the order, i.e. displays the .A below the .B */
  }
}

<div class="parent">
  <div class="child A">A</div>
  <div class="child B">B</div>
</div>

You can also do it with the Grid:

body {
  color: #fff;
}

.parent {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* could also use: 1fr 1fr or 50% 50% without the repeat() */
  grid-template-rows: repeat(2, minmax(100px, auto)); /* minimum height 100px, maximum height unlimited, adjust to your needs, you can also remove it, not mandatory */
}

.A {
  background: blue;
}

.B {
  background: red;
}

@media screen and (max-width: 568px) {
  .parent {
    grid-template-columns: 1fr; /* could also use: 100% */
  }
  .A {
    order: 2;
  }
}

<div class="parent">
  <div class="A">A</div>
  <div class="B">B</div>
</div>

ContentLicense: CC BY-SA 4.0