问:
How to Pass Selected text from a list to controller to do some operation in AngularJS
I have just started learning Angular JS and trying bto write a simple calc program which can select the operation from a selection box and do the operation on two numbers.

I am able to do this using buttons but not able to do this using a selection box.

Please suggest on below lines of code:

```<code><!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

  <link rel="stylesheet" href="style.css" />
  <script src="Jscript.js"></script>
</head>

<body ng-app="myApp">
  <h1>Hello Angular</h1>
  <div ng-controller="MainCtrl">
  1st Number : <input type="text" ng-model="num1"><br/>
  2nd Number : <input type="text" ng-model="num2">

        <p><select ng-model="operator">
            <option>+</option>
            <option>*</option>
            <option>-</option>
            <option>/</option>
         </select></p>

  <input type="button" ng-click="add(num1,num2)" value="ADD">        <input type="button" ng-click="multiply(num1,num2)" value="Multiply">

  <input type="button" ng-click="subtract(num1,num2)" value="Subtract">
  <input type="button" ng-click="divide(num1,num2)" value="Divide"><br/> <br/> <br/>

  Sum : {{result}}
  <div>
</body>

</html>
</code>```

and the corresponding JS File:

```<code>var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope)
{
    $scope.add = function (num1, num2)
    {
        $scope.result = parseInt(num1) + parseInt(num2);
    }

    $scope.multiply = function (num1, num2) {
        $scope.result = parseInt(num1) * parseInt(num2);
    }

    $scope.subtract = function (num1, num2) {
        $scope.result = parseInt(num1) - parseInt(num2);
    }

    $scope.divide = function (num1, num2) {
        $scope.result = parseInt(num1) / parseInt(num2);
    }

});
</code>```

Now instead of button I want to do the operation on selection of dropdown list.

答:
Use ng-change a.e.: <select ng-model="operator" ng-change="onChange()">and:

```<code>$scope.onChange = function(){

      switch ($scope.operator) {
        case '+':
          $scope.result = parseInt($scope.num1) + parseInt($scope.num2);
          break;
        case '-':
          $scope.result = parseInt($scope.num1) - parseInt($scope.num2);
          break;
      case '/':
           $scope.result = parseInt($scope.num1) / parseInt($scope.num2);
          break;
      case '*':
           $scope.result = parseInt($scope.num1) * parseInt($scope.num2);
          break;

        default:
          // code
      }

    }
</code>```

Plunker

Body:
I have just started learning Angular JS and trying bto write a simple calc program which can select the operation from a selection box and do the operation on two numbers.

I am able to do this using buttons but not able to do this using a selection box.

Please suggest on below lines of code:

<!DOCTYPE html>

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

Hello Angular

  1st Number : <input type="text" ng-model="num1">

  2nd Number : <input type="text" ng-model="num2">

<select ng-model="operator">
            <option>+</option>
            <option>*</option>
            <option>-</option>
            <option>/</option>
         </select>

  <input type="button" ng-click="add(num1,num2)" value="ADD">        <input type="button" ng-click="multiply(num1,num2)" value="Multiply">

  <input type="button" ng-click="subtract(num1,num2)" value="Subtract">
  <input type="button" ng-click="divide(num1,num2)" value="Divide">

  Sum : {{result}}

and the corresponding JS File:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope)
{
    $scope.add = function (num1, num2)
    {
        $scope.result = parseInt(num1) + parseInt(num2);
    }

    $scope.multiply = function (num1, num2) {
        $scope.result = parseInt(num1) * parseInt(num2);
    }

    $scope.subtract = function (num1, num2) {
        $scope.result = parseInt(num1) - parseInt(num2);
    }

    $scope.divide = function (num1, num2) {
        $scope.result = parseInt(num1) / parseInt(num2);
    }

});

Now instead of button I want to do the operation on selection of dropdown list.

Body:
Use ng-change a.e.: <select ng-model="operator" ng-change="onChange()">and:

$scope.onChange = function(){

      switch ($scope.operator) {
        case '+':
          $scope.result = parseInt($scope.num1) + parseInt($scope.num2);
          break;
        case '-':
          $scope.result = parseInt($scope.num1) - parseInt($scope.num2);
          break;
      case '/':
           $scope.result = parseInt($scope.num1) / parseInt($scope.num2);
          break;
      case '*':
           $scope.result = parseInt($scope.num1) * parseInt($scope.num2);
          break;

        default:
          // code
      }

    }

Plunker


来源: stackexchange

问:
"Uncaught SyntaxError: Unexpected token :" JSONP response
I make a JSONP request to server, from which I get application/json response.

My function:

```<code>  function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/json',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }
</code>```

In Chrome console I get the following error message, and there's no output in console:

Uncaught SyntaxError: Unexpected token :

I have validated my json response manually, and it's ok.

What could be the problem then?

答:
Try:</p>

```<code>function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/javascript',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I make a JSONP request to server, from which I get application/json response.

My function:

  function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/json',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }

In Chrome console I get the following error message, and there's no output in console:

Uncaught SyntaxError: Unexpected token :

I have validated my json response manually, and it's ok.

What could be the problem then?

Body:
Try:

function testJSONP(url) {
    $.ajax({
      url: url,
      jsonp: "callback",
      contentType: 'application/javascript',
      dataType: "jsonp",
      success: function (response) {
        console.log(response);
      }
    });
  }

ContentLicense: CC BY-SA 3.0


问:
NumericUpDown background colour change for disabled element
On my winform application I'm trying to do colour-coding on the required fields. On user editing, when a required input is filled in, the background becomes light green, if required field is empty, it's background is red.
Some fields are enabled and disabled depending on the input in other fields, so sometimes I have required field that is disabled, and that should be completely disabled (disabled colour background).
This is what I have for the background change:

```<code>public static void UpdateBackgroundColor(this NumericUpDown control)
{
    if (!control.Enabled)
    {
        control.BackColor = SystemColors.InactiveBorder;
        return;
    }

    var inputValue = control.Value;

    if (inputValue == 0)
    {
        control.BackColor = Color.Red;
        return;
    }
    control.BackColor = Color.LightGreen;
}
</code>```

Similar function works on TextBox and works fine with no glitches.
But NumericUpDown is misbehaving.
This is what I see when the field is required and empty:

But when this field becomes disabled, it keeps a red border around it:

The same story happens when background is green and becomes disabled.

So why does this happen and how to fix it?

UPD: As per Han's answer, I quickly updated my code, but that still does not work.

```<code>    private static void SetBackgroundColor(this Control control, Color color)
    {
        control.BackColor = color;
        foreach (Control childControl in control.Controls)
        {
            SetBackgroundColor(childControl, color);
        }
    }
</code>```

And I'm roughly using it like this:

```<code>numericUpDown1.Enabled = true;
numericUpDown1.SetBackgroundColor(Color.Red);
numericUpDown1.Enabled = false;
numericUpDown1.SetBackgroundColor(SystemColors.InactiveBorder);
</code>```

And still get that frame around the text box, despite the fact that I go through all the child controls of NUD and change the back colours there. Any other ideas?

Cheers!!

答:
Sorry to bump a question that is nearly 5 years old.  IMHO this is a bug in the NUD control.  I am currently porting an older Windows CE application to Windows 10.  We had no problem with the NUD controls in CE, but now they all are exhibiting the exact same problem trailmax had.

I can add a little bit of observation.  The frame of the child control is not being refreshed when the control is disabled. The backcolor has no impact.   Whatever is previously displayed on the screen shows on the inside frame of the NUD control.  In our application we use several TabPages.  Depending on the previously displayed screen we get broken and sometimes colorful frames.

The only work-around I have now is to enable and disable the control after it is displayed on the screen.  As I said, our controls are on TabPages, so I am using the tab selected event.  Since we have many tabs and many NUD controls, 5 to 20, I loop through all the NUD controls and execute these two lines:

```<code>   nudControl.enabled =  !nudControl.enabled
   nudControl.enabled =  !nudControl.enabled
</code>```

I needn’t check if the control is enabled or not, I simply toggle it to the opposite value, and then toggle it back.  In our application this executes very quickly and I do not see any visual flashing on the screen.   Again, we have less than 20 NUD’s on any given TabPage.

P.S.  I get all the children NUD controls using code from this StackOverflow post:  How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Body:
On my winform application I'm trying to do colour-coding on the required fields. On user editing, when a required input is filled in, the background becomes light green, if required field is empty, it's background is red.
Some fields are enabled and disabled depending on the input in other fields, so sometimes I have required field that is disabled, and that should be completely disabled (disabled colour background).
This is what I have for the background change:

public static void UpdateBackgroundColor(this NumericUpDown control)
{
    if (!control.Enabled)
    {
        control.BackColor = SystemColors.InactiveBorder;
        return;
    }

    var inputValue = control.Value;

    if (inputValue == 0)
    {
        control.BackColor = Color.Red;
        return;
    }
    control.BackColor = Color.LightGreen;
}

Similar function works on TextBox and works fine with no glitches.
But NumericUpDown is misbehaving.
This is what I see when the field is required and empty:

But when this field becomes disabled, it keeps a red border around it:

The same story happens when background is green and becomes disabled.

So why does this happen and how to fix it?

UPD: As per Han's answer, I quickly updated my code, but that still does not work.

    private static void SetBackgroundColor(this Control control, Color color)
    {
        control.BackColor = color;
        foreach (Control childControl in control.Controls)
        {
            SetBackgroundColor(childControl, color);
        }
    }

And I'm roughly using it like this:

numericUpDown1.Enabled = true;
numericUpDown1.SetBackgroundColor(Color.Red);
numericUpDown1.Enabled = false;
numericUpDown1.SetBackgroundColor(SystemColors.InactiveBorder);

And still get that frame around the text box, despite the fact that I go through all the child controls of NUD and change the back colours there. Any other ideas?

Cheers!!

Body:
Sorry to bump a question that is nearly 5 years old.  IMHO this is a bug in the NUD control.  I am currently porting an older Windows CE application to Windows 10.  We had no problem with the NUD controls in CE, but now they all are exhibiting the exact same problem trailmax had.

I can add a little bit of observation.  The frame of the child control is not being refreshed when the control is disabled. The backcolor has no impact.   Whatever is previously displayed on the screen shows on the inside frame of the NUD control.  In our application we use several TabPages.  Depending on the previously displayed screen we get broken and sometimes colorful frames.

The only work-around I have now is to enable and disable the control after it is displayed on the screen.  As I said, our controls are on TabPages, so I am using the tab selected event.  Since we have many tabs and many NUD controls, 5 to 20, I loop through all the NUD controls and execute these two lines:

   nudControl.enabled =  !nudControl.enabled
   nudControl.enabled =  !nudControl.enabled

I needn’t check if the control is enabled or not, I simply toggle it to the opposite value, and then toggle it back.  In our application this executes very quickly and I do not see any visual flashing on the screen.   Again, we have less than 20 NUD’s on any given TabPage.

P.S.  I get all the children NUD controls using code from this StackOverflow post:  How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?


问:
How to include opencv source files as a cmake dependency without installing it?
I have opencv installed in my system but I do not want to use the installed version. The installed version (from distro repository) was compiled with gcc 7.

I want to compile a C++ project with opencv and dlib as dependency using older gcc compiler installed in a separate path. I have downloaded the opencv sources and extracted it into a seperate folder. What is the proper way to include it cmake so that it is compiled and included as a dependency during compilation?

This is my project structure.

```<code>projects/
  |--> project1/
  |      |--> main.cpp
  |      |--> CMakeLists.txt
  |
  |--> dlib/
  |
  |--> opencv-3.3.1/
</code>```

My CMakeLists.txt looks like this.

```<code>cmake_minimum_required(VERSION 2.8.12)

project(project1)
add_subdirectory(../dlib/dlib dlib_build)
add_subdirectory(../opencv-3.3.1/dlib opencv_build)

add_executable(project1 main.cpp)
target_link_libraries(project1 dlib::dlib opencv)
</code>```

答:
To specify a different compiler, pass in the -DCMAKE_CXX_COMPILER -DCMAKE_CC_COMPILER  parameters in to cmake, each referencing the appropriate path and command.

When you are adding sources within the add_library function, tell it exactly where the sources are.
so...

```<code>list(${CUSTOM_OPENCV} APPEND
"/custom/path/source1.cpp"
"/custom/path/source2.cpp"
)

add_library(my_app ${CUSTOM_OPENCV})
</code>```

That might be how I would do it.  You might even want to pass in the custom path through a cmake parameter to make your project a little more robust for future uses.

Body:
I have opencv installed in my system but I do not want to use the installed version. The installed version (from distro repository) was compiled with gcc 7.

I want to compile a C++ project with opencv and dlib as dependency using older gcc compiler installed in a separate path. I have downloaded the opencv sources and extracted it into a seperate folder. What is the proper way to include it cmake so that it is compiled and included as a dependency during compilation?

This is my project structure.

projects/
  |--> project1/
  |      |--> main.cpp
  |      |--> CMakeLists.txt
  |
  |--> dlib/
  |
  |--> opencv-3.3.1/

My CMakeLists.txt looks like this.

cmake_minimum_required(VERSION 2.8.12)

project(project1)
add_subdirectory(../dlib/dlib dlib_build)
add_subdirectory(../opencv-3.3.1/dlib opencv_build)

add_executable(project1 main.cpp)
target_link_libraries(project1 dlib::dlib opencv)

Body:
To specify a different compiler, pass in the -DCMAKE_CXX_COMPILER -DCMAKE_CC_COMPILER  parameters in to cmake, each referencing the appropriate path and command.

When you are adding sources within the add_library function, tell it exactly where the sources are.
so...

list(${CUSTOM_OPENCV} APPEND
"/custom/path/source1.cpp"
"/custom/path/source2.cpp"
)

add_library(my_app ${CUSTOM_OPENCV})

That might be how I would do it.  You might even want to pass in the custom path through a cmake parameter to make your project a little more robust for future uses.


问:
Select where date falls within range
Codeigniter/PHP:

This is my current db query:

```<code>$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->get();
$pass_check = $pass_check->result_array();
</code>```

There are two other fields: 'exp_date', and 'start_date'. These represent when the coupon should be available and when it should not.

How can I only select codes/coupons that fall within the applicable date range in the db?

Does that make sense?

答:
Here you go:
$today = today's date.</p>

```<code>$today = date();
$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->$this->db->where("$date BETWEEN start_date and exp_date")->get();
$pass_check = $pass_check->result_array();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Select where date falls within range

Body:
Codeigniter/PHP:

This is my current db query:

$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->get();
$pass_check = $pass_check->result_array();

There are two other fields: 'exp_date', and 'start_date'. These represent when the coupon should be available and when it should not.

How can I only select codes/coupons that fall within the applicable date range in the db?

Does that make sense?

Body:
Here you go:
$today = today's date.

$today = date();
$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->$this->db->where("$date BETWEEN start_date and exp_date")->get();
$pass_check = $pass_check->result_array();


问:
onblur event is not firing
I need to fire onblur event when I click outside "aside panel", in order to make the panel close if user clicks outside navigation panel.

Though I'm using React JS - but for simplicity I've written example in pure JavaScript.
Lately I've written something similar and everything works fine, but in this case it's not working, may be because of position fixed.

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}</code>```

This example

<button type="button" onClick="myFunction2()">
☰
</button>

      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>

      Main

```

答:
To have Onblur on an element it should receive focus first, Div elements don't receive focus by default. You can add tabindex="0" </p>

```<code><div tabindex="0" ....
</code>```

<p>Thanks to Emil, for react you can use </p>

```<code>tabIndex={0}
</code>```

Title: onblur event is not firing

Body:
I need to fire onblur event when I click outside "aside panel", in order to make the panel close if user clicks outside navigation panel.

Though I'm using React JS - but for simplicity I've written example in pure JavaScript.
Lately I've written something similar and everything works fine, but in this case it's not working, may be because of position fixed.

var d = document.getElementById("fname");

d.addEventListener("blur", myFunction);

function myFunction() {
  alert("Input field lost focus.");
}
var state = true;

function myFunction2() {
  state = !state;
  if (state) {
    d.className = "header__aside";
  } else {
    d.className += " header__aside--open";
  }

}

.main {
  background-color: violet;
  padding: 50px;
}

.header__aside {
  background-color: #cfcfcf;
  box-shadow: 0 19px 38px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.22);
  font-size: 1.2rem;
  height: 100%;
  opacity: 0.9;
  position: fixed;
  right: -30%;
  top: 0;
  transition: right 0.5s ease-out;
  width: 30%;
  z-index: 10;
}

.header__aside--open {
  right: 0;
}

This example

<button type="button" onClick="myFunction2()">
☰
</button>

      <button type="button" class="aside-nav__header-button" onClick="myFunction2()">x</button>

      Main

Body:
To have Onblur on an element it should receive focus first, Div elements don't receive focus by default. You can add tabindex="0"

<div tabindex="0" ....

Thanks to Emil, for react you can use

tabIndex={0}


问:
Difference between different git search commands
A question from a beginner: there are several ways to search in git history.
To me, it is not clear what, the difference between the commands really is:

git log, e.g. git log -S 'for what you search' --all to search for a string in all branches and
git log -G 'search for regexpr' --all to search for regexpr. See for example here

git log --grep 'pattern'

git rev-list, e.g. git rev-list --grep='string' --all

git grep, e.g. git grep "string or regexpr" $(git rev-list --all) from here

gitk, e.g. gitk file.txt a gui interface

git log --all --full-history -- **/thefile.* to search for a filename in history from here.

git diff --word-diff-regex=. > changes.txt combined with grep -oP '\+[^\+]+\+' changes.txt | tr -d '\+' to display changes on a character basis. From here. This even works if changes are not commited yet.

My poor understanding is that

git log searches in the commit messages? It seems to be based on rev-list? From the docs:

Shows the commit logs. The command takes options applicable to the git
  rev-list command to control what is shown and how, and options
  applicable to the git diff-* commands to control how the changes each
  commit introduces are shown.

git-rev-list seems to be a more basic command as it operates on the commit object (or tree object?). From the docs:

git-rev-list - Lists commit objects in reverse chronological order

git grep seems to search everywhere: in files, blobs, trees and commit objects? From the docs:

git-grep - Print lines matching a pattern. Look for specified patterns
  in the tracked files in the work tree, blobs registered in the index
  file, or blobs in given tree objects. Patterns are lists of one or
  more search expressions separated by newline characters. An empty
  string as search expression matches all lines.

I used the Git book as reference.

答:
git log searches in the commit messages?

Yes. Options -S/-G search for commits that change the number of occurence (i.e., add or remove) mentioned text. --grep searches through entire commit messages.

git grep seems to search everywhere: in files, blobs, trees and commit objects?

No, only in files (that is, blobs).


问:
keep checkbox state after changing page
I am using the following code which is keeping the checkbox state when the page refreshes but as soon as I move to another page I am losing the state of the check boxes.</p>

```<code>$(document).ready(function () {

if (sessionStorage.getItem('checked-checkboxes') && $.parseJSON(sessionStorage.getItem('checked-checkboxes')).length !== 0)
{
    var arrCheckedCheckboxes = $.parseJSON(sessionStorage.getItem('checked-checkboxes'));
    //Convert checked checkboxes array to comma seprated id
    $(arrCheckedCheckboxes.toString()).prop('checked', true);
}
$("#checkboxes input").change(function () {
    var arrCheckedCheckboxes = [];
    // Get all checked checkboxes
    $.each($("#checkboxes input:checked"), function () {
        arrCheckedCheckboxes.push("#" + $(this).attr('id'));
    });

    // Convert checked checkboxes array to JSON ans store it in session storage
    sessionStorage.setItem('checked-checkboxes', JSON.stringify(arrCheckedCheckboxes));
});
});
</code>```

答:
sessionStorage will not persist its data when you navigate away from the page. To do that, you need to use localStorage. They both have a similar interface, so you should just be able to swap sessionStorage for localStorage in your code.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Title: keep checkbox state after changing page

Body:
I am using the following code which is keeping the checkbox state when the page refreshes but as soon as I move to another page I am losing the state of the check boxes.

$(document).ready(function () {

if (sessionStorage.getItem('checked-checkboxes') && $.parseJSON(sessionStorage.getItem('checked-checkboxes')).length !== 0)
{
    var arrCheckedCheckboxes = $.parseJSON(sessionStorage.getItem('checked-checkboxes'));
    //Convert checked checkboxes array to comma seprated id
    $(arrCheckedCheckboxes.toString()).prop('checked', true);
}
$("#checkboxes input").change(function () {
    var arrCheckedCheckboxes = [];
    // Get all checked checkboxes
    $.each($("#checkboxes input:checked"), function () {
        arrCheckedCheckboxes.push("#" + $(this).attr('id'));
    });

    // Convert checked checkboxes array to JSON ans store it in session storage
    sessionStorage.setItem('checked-checkboxes', JSON.stringify(arrCheckedCheckboxes));
});
});


问:
Write function with two different ways of passing input in Matlab
I'm wondering how to write a function in Matlab with two different ways of passing the same input.

One example of this is the built-in function lsqcurvefit. You can either pass the input like this:

x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)

where the first 4 arguments are required and the last 3 are optional, OR you can call it like this:

x = lsqcurvefit(problem)

where problem is a struct containing the same inputs. In this case there is only one required input.

My question is: how do I write a function that can take the same input in two different ways?

I looked at documentation and can't seem to find it because I just don't know what words or terminology to search for... Can someone point me to this? I'm sure it's very simple. Maybe it's trivial and I'm just missing it?

Ben

EDIT: It seems what I may have been looking for is 'function overloading' and 'function signature'.

答:
I am not sure on how to write code on matlab but I believe that the concept  is the same for all programming languages so " just do method overriding where by one method will passes 4 parameters and other pass 2.
 e.g</p>

```<code>//assume that the  following method are defined within the class

public void FirstFunction( int x, int y,int c,int f){
    System.out.print(x + y + c + f);
}

public void SecondFunction( int m,int s){
    System.out.print(m - s);
}

//within the main method on java you call these method
//so it will depend on the number of parameters you have passed the it will call.
</code>```

Body:
I am not sure on how to write code on matlab but I believe that the concept  is the same for all programming languages so " just do method overriding where by one method will passes 4 parameters and other pass 2.
 e.g

//assume that the  following method are defined within the class

public void FirstFunction( int x, int y,int c,int f){
    System.out.print(x + y + c + f);
}

public void SecondFunction( int m,int s){
    System.out.print(m - s);
}

//within the main method on java you call these method
//so it will depend on the number of parameters you have passed the it will call.


问:
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q'] (which is used in Drupal)?

答:
Given this example url:

http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

$_SERVER['REQUEST_URI'] will give you:

/some-dir/yourpage.php?q=bogus&n=10

Whereas $_GET['q'] will give you:

bogus

In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.


问:
Does LSApplicationWorkspace not work on iOS 11?
I have an app in private which need to scan all applications and schemes and get it by using private API LSApplicationWorkspace defaultWorkspace with others functional method, such as privateURLSchemes allInstalledApplications. This app works good and I can get all I need from the private API before iOS 11, but in this version I only got some warning and an empty array. It seems Apple limits private API that developer can't use in private in iOS 11.

So my question is what alternative ways can achieve my need in iOS 11?

答:
UPDATE: This method does not work on iOS 12 - entitlement required

There is a way to find if a specific application is installed, its not a list of all apps like allInstalledApplications returned but its useful to query for a specific bundle id

Here is an example, the method receives bundle id and return true if it's installed on the device:

```<code>- (BOOL)checkIfAppInstalled: (NSString*)bundleID {
    dlopen("/System/Library/PrivateFrameworks/MobileContainerManager.framework/MobileContainerManager",RTLD_NOW);
    Class MBAppManager = NSClassFromString(@"MCMAppDataContainer");
    NSError  * error ;
    id contentApp = [MBAppManager performSelector:@selector(containerWithIdentifier:error:) withObject:bundleID withObject:error];
    return contentApp != nil;
}
</code>```

Body:
UPDATE: This method does not work on iOS 12 - entitlement required

There is a way to find if a specific application is installed, its not a list of all apps like allInstalledApplications returned but its useful to query for a specific bundle id

Here is an example, the method receives bundle id and return true if it's installed on the device:

- (BOOL)checkIfAppInstalled: (NSString*)bundleID {
    dlopen("/System/Library/PrivateFrameworks/MobileContainerManager.framework/MobileContainerManager",RTLD_NOW);
    Class MBAppManager = NSClassFromString(@"MCMAppDataContainer");
    NSError  * error ;
    id contentApp = [MBAppManager performSelector:@selector(containerWithIdentifier:error:) withObject:bundleID withObject:error];
    return contentApp != nil;
}


问:
Assembly Call Stack - Terminology Questions
I'm completely new to Assembly and looking to confirm where, in the following statements, I have a misunderstanding and need to be corrected.

The stack pointer (ESP) refers to the top (lowest memory address) of the stack.

The base Pointer (EBP) is used for temporarily storing various memory addresses when building a stack frame. It normally holds the highest memory address of the current stack frame.

The instruction pointer (EIP) refers to the memory address of a line of code in the text (code) segment of memory

Once something has been pushed to the stack, it can't be changed in-place. ie. If we PUSH EBP to the stack, we are pushing the current value of EBP, not some kind of reference or pointer to it. We can't then change that value in-place.

Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. [ESP-12].

When a function is called (using CALL), the following occurs:

The return address is added to the stack (the memory of the address immediately following the current EIP so we know where to return to after the called function has completed

The saved frame pointer is added to the stack, which is normally the stack pointer of the stack frame of the calling function

We would then move into the prologue of the called function

Thanks. I'm trying to get my head around this stuff.

答:
Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. [ESP-12].

Often arguments are pushed on the stack, before the call.

```<code>push paramA  ; ( some 32bit value, register, whatever )
push paramB
call myFunct
</code>```

This leads to the following stack content:

```<code>---------------
|    paramA   |
---------------
|    paramB   |
---------------
| return addr |   <-- ESP
---------------
</code>```

Since the return address (pushed by the call ) is 4 bytes, the parameters for the function are at [ESP+4] and [ESP+8].

If your function adds a stack frame, usually you do

```<code>myFunct:  push EBP
          mov EBP, ESP
</code>```

Now the stack looks like this:

```<code>---------------
|    paramA   |
---------------
|    paramB   |
---------------
| return addr |
---------------
|   saved EBP |   <-- EBP, ESP
---------------
</code>```

and the parameters are at [EBP+8] and [EBP+12], even if you push more values (or add some place for local variables) since EBP is not changing anymore:

```<code>myFunct:  push EBP
          mov EBP, ESP
          sub ESP, 12      ; make room for 3 32bit local variables

          mov eax, [EBP+8] ; access one of the parameters
          mov [EBP-4], eax ; save it in local variable #1

rel |  rel |
to  |  to  |
ESP |  EBP |
----|------|--------------
+24 | +12  |    paramA   |
    |      |--------------
+20 | +8   |    paramB   |
    |      |--------------
+16 | +4   | return addr |
    |      |--------------
+12 |      |   saved EBP |  <-- EBP   (is fixed here for now)
    |      |---------------
+8  | -4   |    local#1  |
    |      |---------------
+4  | -8   |    local#2  |
    |      | ---------------
0   | -12  |    local#3  |  <--- ESP  (keeps growing, by pushing, calling etc)
           ---------------
</code>```

The local variables are at [EBP-4], [EBP-8], [EBP-12] etc.

The return Address is at [EBP+4]

Note: As you can see, it is possible

to access by ESP (then you do not need a frame-pointer, but then you need to keep track of how much data you pushed, to "find" the parameters and variables )

or by EBP (which ofc adds some overhead). In many functions, the frame pointer is not needed at all, and optimized away by compilers.

Body:
Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. [ESP-12].

Often arguments are pushed on the stack, before the call.

push paramA  ; ( some 32bit value, register, whatever )
push paramB
call myFunct

This leads to the following stack content:

---------------
|    paramA   |
---------------
|    paramB   |
---------------
| return addr |   <-- ESP
---------------

Since the return address (pushed by the call ) is 4 bytes, the parameters for the function are at [ESP+4] and [ESP+8].

If your function adds a stack frame, usually you do

myFunct:  push EBP
          mov EBP, ESP

Now the stack looks like this:

---------------
|    paramA   |
---------------
|    paramB   |
---------------
| return addr |
---------------
|   saved EBP |   <-- EBP, ESP
---------------

and the parameters are at [EBP+8] and [EBP+12], even if you push more values (or add some place for local variables) since EBP is not changing anymore:

myFunct:  push EBP
          mov EBP, ESP
          sub ESP, 12      ; make room for 3 32bit local variables

          mov eax, [EBP+8] ; access one of the parameters
          mov [EBP-4], eax ; save it in local variable #1

rel |  rel |
to  |  to  |
ESP |  EBP |
----|------|--------------
+24 | +12  |    paramA   |
    |      |--------------
+20 | +8   |    paramB   |
    |      |--------------
+16 | +4   | return addr |
    |      |--------------
+12 |      |   saved EBP |  <-- EBP   (is fixed here for now)
    |      |---------------
+8  | -4   |    local#1  |
    |      |---------------
+4  | -8   |    local#2  |
    |      | ---------------
0   | -12  |    local#3  |  <--- ESP  (keeps growing, by pushing, calling etc)
           ---------------

The local variables are at [EBP-4], [EBP-8], [EBP-12] etc.

The return Address is at [EBP+4]

Note: As you can see, it is possible

to access by ESP (then you do not need a frame-pointer, but then you need to keep track of how much data you pushed, to "find" the parameters and variables )

or by EBP (which ofc adds some overhead). In many functions, the frame pointer is not needed at all, and optimized away by compilers.


问:
equals() method comparison for two different list implementations
Below is the program to compare two different list implementations. When I run this, getting true as a result.

I want to understand the behaviour of this equals() method in this case.

```<code>package com.tests;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListsTest {
    public static void main(String[] args) {
        List listA = new ArrayList<>();
        List listB = new LinkedList<>();
        Object object = new Object();
        Integer integer = new Integer(4);
        listA.add(object);
        listB.add(object);
        System.out.println(listA.equals(listB));
    }
}
</code>```

答:
The behaviour of .equals() method here will be governed by the class implementing the List interface (in your case the ArrayList class)

Following is a snippet from the Oracle JDK 1.8 implementation of ArrayList:

```<code>public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List))
        return false;

    ListIterator<E> e1 = listIterator();
    ListIterator<?> e2 = ((List<?>) o).listIterator();
    while (e1.hasNext() && e2.hasNext()) {
        E o1 = e1.next();
        Object o2 = e2.next();
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }
    return !(e1.hasNext() || e2.hasNext());
}
</code>```

As is evident from here, the method will return true for any object implementing the List interface where the contents of the list are same as the current object or if both are pointing to the same object. It will return false if the passed object is not an implementation of List

Body:
Below is the program to compare two different list implementations. When I run this, getting true as a result.

I want to understand the behaviour of this equals() method in this case.

package com.tests;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListsTest {
    public static void main(String[] args) {
        List listA = new ArrayList<>();
        List listB = new LinkedList<>();
        Object object = new Object();
        Integer integer = new Integer(4);
        listA.add(object);
        listB.add(object);
        System.out.println(listA.equals(listB));
    }
}

Body:
The behaviour of .equals() method here will be governed by the class implementing the List interface (in your case the ArrayList class)

Following is a snippet from the Oracle JDK 1.8 implementation of ArrayList:

public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List))
        return false;

    ListIterator<E> e1 = listIterator();
    ListIterator<?> e2 = ((List<?>) o).listIterator();
    while (e1.hasNext() && e2.hasNext()) {
        E o1 = e1.next();
        Object o2 = e2.next();
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }
    return !(e1.hasNext() || e2.hasNext());
}

As is evident from here, the method will return true for any object implementing the List interface where the contents of the list are same as the current object or if both are pointing to the same object. It will return false if the passed object is not an implementation of List


问:
Threads(PThreads) stopping execution and going into wait state
I have been having this problem wherein my threads stop execution and go into a wait state(reason : unknown). Pseudo code is posted below followed by some explanation

```<code>int arr[1000];
T1
{
tmp = arr[i];
}
T2
{
tmp=arr[i];
}
T3
{
arr[i] = value;
}
Main()
{
spawns of threads and waits for them to finish;
}
</code>```

So the only thing that is shared across these threads is the array, T3 writes into this array and T1,T2 read from it and use it for some purpose.
When I execute the program all three threads work fine and do what is required of them but when I try to run it for longer periods, after a while they stop execution and go into a wait state. The threads are still in the process mix but in less idle state. I do not know why this is happening and would greatly appreciate if someone can provide any useful pointers as to how I can find a resolution to this problem.

答: There was problem with the way I was using one of the calls to an external library that caused me to go into self-deadlock mode. Thanks to everyone who tried to help me.</p>

Body:
I have been having this problem wherein my threads stop execution and go into a wait state(reason : unknown). Pseudo code is posted below followed by some explanation

int arr[1000];
T1
{
tmp = arr[i];
}
T2
{
tmp=arr[i];
}
T3
{
arr[i] = value;
}
Main()
{
spawns of threads and waits for them to finish;
}

So the only thing that is shared across these threads is the array, T3 writes into this array and T1,T2 read from it and use it for some purpose.
When I execute the program all three threads work fine and do what is required of them but when I try to run it for longer periods, after a while they stop execution and go into a wait state. The threads are still in the process mix but in less idle state. I do not know why this is happening and would greatly appreciate if someone can provide any useful pointers as to how I can find a resolution to this problem.


问:
NSURLSession Request returns 404 but works fine on Postman
```<code>NSString *URLString = @"http://api.sandbox.africastalking.com/version1/airtime/send";
NSString *encodedString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:encodedString];

NSDictionary *body = @{
                       ...
                       };
// convert the dictionary into json data
NSError *error;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

// Create a post request with the json as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPBody = JSONData;

// create the task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
        NSLog(@"Response: %@", response);

        NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response Text: %@", responseText);

    } else {
        NSLog(@"Error: %@", error.localizedDescription);
    }
}];
[task resume];
</code>```

<p>The code returns "The requested resource could not be found" 404 as response but when I try this request in my REST client (Postman) it works fine. </p>

答:
Try a url with the URLWithString method</p>

```<code>NSURL *url = [NSURL URLWithString:@"http://api.sandbox.africastalking.com/version1/airtime/send"];
</code>```

Body:
NSString *URLString = @"http://api.sandbox.africastalking.com/version1/airtime/send";
NSString *encodedString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:encodedString];

NSDictionary *body = @{
                       ...
                       };
// convert the dictionary into json data
NSError *error;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

// Create a post request with the json as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPBody = JSONData;

// create the task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
        NSLog(@"Response: %@", response);

        NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response Text: %@", responseText);

    } else {
        NSLog(@"Error: %@", error.localizedDescription);
    }
}];
[task resume];

The code returns "The requested resource could not be found" 404 as response but when I try this request in my REST client (Postman) it works fine.

Body:
Try a url with the URLWithString method

NSURL *url = [NSURL URLWithString:@"http://api.sandbox.africastalking.com/version1/airtime/send"];


问:
Replace multiple fragments at the same time
I have an Activity with a navigation drawer. I have used fragments for this and when I'm moving to different menus in the drawer I add them to the backstack with addToBackStack() method. Basically, Activity starts with Fragment A then if I go to Fragment B or Fragment C I can press back and go back to Fragment A.

But now I have a notification which should open the Activity with Fragment B open and when I press back it should take me back to Fragment A. Is there a way to handle this like in startActivities.

Here is the code for the Activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, new FragmentA()).commit();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.buttonA:
            getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

            break;

        case R.id.buttonB:
            transactFragment(new FragmentB());

            break;
        ...
     }
 }

private void transactFragment(Fragment fragment) {
    getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, fragment).addToBackStack(fragment.getClass().getName()).commit();
}
</code>```

答:
Why not just define the fragments with tags and call them as you need to?

Here's a sample of how I work with my fragments:

Start your fragments in the Activity's  onCreate() method, like so:

```<code>/** Load screen1 */
    Instructions screen1 = new Instructions();
    screen1.setArguments(getIntent().getExtras());

    getFragmentManager().beginTransaction().
            add(com.example.tool.R.id.
                    instructions_container, screen1, "screen1").
            addToBackStack(null).
            commit();
</code>```

Then you can grab them and show/hide them as much as you like:

```<code>/** screen 1 */
public void showInstructions()
{
    // show screen 1
    getFragmentManager().findFragmentByTag("screen1").
            getView().setVisibility(View.VISIBLE);
}
</code>```

In my project, we use a global enum to check which fragment is currently up, so we don't have to rely on the stack, which has more than once proven itself to be unreliable.

onBack calls a switch, which checks this enum and acts accordingly. For your use-case, you can just track when this notification has been called, so it will go from Fragment B, to Fragment A.

Body:
I have an Activity with a navigation drawer. I have used fragments for this and when I'm moving to different menus in the drawer I add them to the backstack with addToBackStack() method. Basically, Activity starts with Fragment A then if I go to Fragment B or Fragment C I can press back and go back to Fragment A.

But now I have a notification which should open the Activity with Fragment B open and when I press back it should take me back to Fragment A. Is there a way to handle this like in startActivities.

Here is the code for the Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, new FragmentA()).commit();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.buttonA:
            getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

            break;

        case R.id.buttonB:
            transactFragment(new FragmentB());

            break;
        ...
     }
 }

private void transactFragment(Fragment fragment) {
    getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, fragment).addToBackStack(fragment.getClass().getName()).commit();
}

Body:
Why not just define the fragments with tags and call them as you need to?

Here's a sample of how I work with my fragments:

Start your fragments in the Activity's  onCreate() method, like so:

/** Load screen1 */
    Instructions screen1 = new Instructions();
    screen1.setArguments(getIntent().getExtras());

    getFragmentManager().beginTransaction().
            add(com.example.tool.R.id.
                    instructions_container, screen1, "screen1").
            addToBackStack(null).
            commit();

Then you can grab them and show/hide them as much as you like:

/** screen 1 */
public void showInstructions()
{
    // show screen 1
    getFragmentManager().findFragmentByTag("screen1").
            getView().setVisibility(View.VISIBLE);
}

In my project, we use a global enum to check which fragment is currently up, so we don't have to rely on the stack, which has more than once proven itself to be unreliable.

onBack calls a switch, which checks this enum and acts accordingly. For your use-case, you can just track when this notification has been called, so it will go from Fragment B, to Fragment A.


问:
How to filter all rows that belong to groups with more than 1 member?
I have a similar question as this one.

I have a dataframe like this:

```<code>import pandas as pd

df = pd.DataFrame({'A': list(range(7)),
                   'B': ['a', 'b', 'a', 'c', 'c', 'b', 'b'],
                   'C': ['x', 'x', 'x', 'z', 'z', 'y', 'x']}
                  )

   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
5  5  b  y
6  6  b  x
</code>```

I want to groupby columns B and C and then select all rows from df that have a group size greater than 1.

My desired outcome would be

```<code>   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x
</code>```

So I can do

```<code>gs_bool = df.groupby(['B', 'C']).size() > 1
</code>```

which gives

```<code>B  C
a  x     True
b  x     True
   y    False
c  z     True
dtype: bool
</code>```

How do I now feed this back to df?

答:
You are really close - need GroupBy.transform:

```<code>gs_bool = df.groupby(['B', 'C'])['B'].transform('size') > 1
print (gs_bool)
0     True
1     True
2     True
3     True
4     True
5    False
6     True
Name: B, dtype: bool
</code>```

```<code>df = df[gs_bool]
print (df)
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x
</code>```

Body:
I have a similar question as this one.

I have a dataframe like this:

import pandas as pd

df = pd.DataFrame({'A': list(range(7)),
                   'B': ['a', 'b', 'a', 'c', 'c', 'b', 'b'],
                   'C': ['x', 'x', 'x', 'z', 'z', 'y', 'x']}
                  )

   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
5  5  b  y
6  6  b  x

I want to groupby columns B and C and then select all rows from df that have a group size greater than 1.

My desired outcome would be

   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x

So I can do

gs_bool = df.groupby(['B', 'C']).size() > 1

which gives

B  C
a  x     True
b  x     True
   y    False
c  z     True
dtype: bool

How do I now feed this back to df?

Body:
You are really close - need GroupBy.transform:

gs_bool = df.groupby(['B', 'C'])['B'].transform('size') > 1
print (gs_bool)
0     True
1     True
2     True
3     True
4     True
5    False
6     True
Name: B, dtype: bool

df = df[gs_bool]
print (df)
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x


问:
Generating 'customers also bought' from table
I've got a 'cart' table as follows:

```<code>+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+
</code>```

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

```<code>SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC
</code>```

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

答:
Use could make use off a IN filter like this.</p>

```<code>   SELECT
     productID
    FROM
     cart
    WHERE
       orderID IN(
         SELECT
          orderId
         FROM
          cart
         WHERE
            productID = 333
          AND
            status = 'complete'
       )
     AND
       productID <> 333
     AND
       status = 'complete'
</code>```

Body:
I've got a 'cart' table as follows:

+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

Body:
Use could make use off a IN filter like this.

   SELECT
     productID
    FROM
     cart
    WHERE
       orderID IN(
         SELECT
          orderId
         FROM
          cart
         WHERE
            productID = 333
          AND
            status = 'complete'
       )
     AND
       productID <> 333
     AND
       status = 'complete'


问:
django rest framework write only field usage
I just want to know usage of write_only that is option password1,2 fields below

I checked view returns fileds information without password, so i could understand roughly but cannot find what exactly write_onlyoptions usage is.

please somebody explain or leave reference document link..

```<code>class SignupSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)
    token = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'username',
            'password1',
            'password2',
        )
</code>```

this is view

```<code>class Signup(APIView):
    def post(self, request):
        serializer = SignupSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors,
    status=status.HTTP_400_BAD_REQUEST)
</code>```

答:
write_only is exactly what it says.

When you use the enclosing serializer class in an APIView of ViewSet for 'GET' methods, DRF won't include the field when serializing the representation.

Here is the api documentation for write_only

Body:
I just want to know usage of write_only that is option password1,2 fields below

I checked view returns fileds information without password, so i could understand roughly but cannot find what exactly write_onlyoptions usage is.

please somebody explain or leave reference document link..

class SignupSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)
    token = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'username',
            'password1',
            'password2',
        )

this is view

class Signup(APIView):
    def post(self, request):
        serializer = SignupSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors,
    status=status.HTTP_400_BAD_REQUEST)


问:
How to make dynamic main page content in WPF

I want to make change main panel content when I choice action in menu button.
Like main content page, setting page, content page on Main panel (in code used grid x:Name="main_~~~)
It for use just can make 3 and control visibility??
or Can use include like xml at Android and change include target??
( ex > includelayout="@layout/app_bar_main")

Mainwindow.xaml

```<code><Window x:Class="M_C.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow"
        Width="1024" Height="768"
        WindowStyle="None"
        WindowState="Maximized"
        WindowStartupLocation="CenterScreen">
    <Grid x:Name="wide_Out" Background="#000000">
        <Viewbox Stretch="Uniform">
            <Grid Width="1024" Height="768" VerticalAlignment="Top">
                <DockPanel x:Name="L_black" HorizontalAlignment="Left"
Height="768" LastChildFill="False" VerticalAlignment="Top" Width="62"
Background="#FF242424">
                    <Button Margin="15,8,0,0" Height="40"
VerticalAlignment="Top" Width="30"/>
                </DockPanel>
                <DockPanel x:Name="T_blue" HorizontalAlignment="Left"
Height="84" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
Width="968" Background="#FF248BC7">
                    <TextBlock Margin="200,5,200,0" Height="70"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
                </DockPanel>
                <DockPanel x:Name="L_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="62,83,0,0"
VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
                <DockPanel x:Name="R_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="940,83,0,0"
Background="#FF248BC7" Width="84"/>
                <DockPanel x:Name="B_blue" HorizontalAlignment="Left"
Height="90" LastChildFill="False" Margin="143,678,0,0"
VerticalAlignment="Top" Width="799" Background="#FF248BC7">
                    <Image Margin="250,15,250,15" Height="70"
VerticalAlignment="Top" Width="290" />
                </DockPanel>
                <!--<DockPanel x:Name="main_content_panel"
HorizontalAlignment="Left" Height="594" LastChildFill="False"
Margin="144,84,0,0" VerticalAlignment="Top" Width="790">-->
                <Grid x:Name="main_con_body" Margin="143,82,84,88"
Width="798" Height="594" Background="#ffffff">
                </Grid>
            <!--</DockPanel>-->
         </Grid>
     </Viewbox>
   </Grid>
</Window>
</code>```

答:
You can Define Frame inside Your Window and navigate between as many page you want:

```<code><Frame Name="FrameWithinGrid" >
</Frame>
</code>```

and on button Click you can simply navigate:

```<code>private void button1_Click(object sender, RoutedEventArgs e)
{
   FrameWithinGrid.Navigate(new System.Uri("Page1.xaml",
         UriKind.RelativeOrAbsolute));
}
</code>```

to know more See here

Body:
I want to make change main panel content when I choice action in menu button.
Like main content page, setting page, content page on Main panel (in code used grid x:Name="main_~~~)
It for use just can make 3 and control visibility??
or Can use include like xml at Android and change include target??
( ex > includelayout="@layout/app_bar_main")

Mainwindow.xaml

<Window x:Class="M_C.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow"
        Width="1024" Height="768"
        WindowStyle="None"
        WindowState="Maximized"
        WindowStartupLocation="CenterScreen">
    <Grid x:Name="wide_Out" Background="#000000">
        <Viewbox Stretch="Uniform">
            <Grid Width="1024" Height="768" VerticalAlignment="Top">
                <DockPanel x:Name="L_black" HorizontalAlignment="Left"
Height="768" LastChildFill="False" VerticalAlignment="Top" Width="62"
Background="#FF242424">
                    <Button Margin="15,8,0,0" Height="40"
VerticalAlignment="Top" Width="30"/>
                </DockPanel>
                <DockPanel x:Name="T_blue" HorizontalAlignment="Left"
Height="84" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
Width="968" Background="#FF248BC7">
                    <TextBlock Margin="200,5,200,0" Height="70"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
                </DockPanel>
                <DockPanel x:Name="L_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="62,83,0,0"
VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
                <DockPanel x:Name="R_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="940,83,0,0"
Background="#FF248BC7" Width="84"/>
                <DockPanel x:Name="B_blue" HorizontalAlignment="Left"
Height="90" LastChildFill="False" Margin="143,678,0,0"
VerticalAlignment="Top" Width="799" Background="#FF248BC7">
                    <Image Margin="250,15,250,15" Height="70"
VerticalAlignment="Top" Width="290" />
                </DockPanel>

                <Grid x:Name="main_con_body" Margin="143,82,84,88"
Width="798" Height="594" Background="#ffffff">
                </Grid>

         </Grid>
     </Viewbox>
   </Grid>
</Window>

Body:
You can Define Frame inside Your Window and navigate between as many page you want:

<Frame Name="FrameWithinGrid" >
</Frame>

and on button Click you can simply navigate:

private void button1_Click(object sender, RoutedEventArgs e)
{
   FrameWithinGrid.Navigate(new System.Uri("Page1.xaml",
         UriKind.RelativeOrAbsolute));
}

to know more See here


问:
DIV won't bottom?
My blog has popup divs and the divs should bottom but they don't :( The bottom will bottom but the content will stay up so the div just stretches.</p>

答:
Not sure if this is relevant, but I am getting this error in Chrome Developer Tools:

```<code>Uncaught ReferenceError: _popupControl is not defined  http://roseannebarr.tumblr.com/:730
</code>```

The relevant line is:

```<code><script type="text/javascript">_popupControl();</script>
</code>```

(which is calling a function that is indeed undefined)

Title: DIV won't bottom?

Body:
Not sure if this is relevant, but I am getting this error in Chrome Developer Tools:

Uncaught ReferenceError: _popupControl is not defined  http://roseannebarr.tumblr.com/:730

The relevant line is:

<script type="text/javascript">_popupControl();</script>

(which is calling a function that is indeed undefined)


答:
If you want the products in the same order then you can query by orderID, e.g.:

```<code>SELECT *
FROM cart
WHERE orderID = 3443
AND productID <> 333;
</code>```

This will give you all the other products that were included in the same order.

Title: Generating 'customers also bought' from table

Body:
If you want the products in the same order then you can query by orderID, e.g.:

SELECT *
FROM cart
WHERE orderID = 3443
AND productID <> 333;

This will give you all the other products that were included in the same order.


问:
No click events working when switching between 2 fragments with listview's in android xamarin
My problem happens when switching between fragments. If I switch from a fragment without a listview to either of these, it works fine. Once I switch from fragment A to fragment B, no touch/click events work on fragment b. But, if I go from fragment B to fragment A, fragment A still works fine.

Anyone have any idea what would be causing this?

First fragment xml (Fragment A)

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:fab="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="fill_parent">
    <ListView
        android:id="@+id/tmp_lv_er_List"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:fastScrollEnabled="true" />
</RelativeLayout>
</code>```

Second xml fragment (Fragment B)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:fastScrollEnabled="true" />
</LinearLayout>
</code>```

Here is the main view xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true">
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
      <android.support.v7.widget.Toolbar
          android:id="@+id/toolbar2"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:minHeight="?attr/actionBarSize"
          android:background="?attr/colorPrimary"
          android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
          app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </LinearLayout>
    <ScrollView
    android:id="@+id/user_profile_scrollView"
    android:layout_gravity="start|bottom"
    android:fillViewport="true"
    android:layout_width="fill_parent"
    android:layout_height="match_parent">
      <FrameLayout
              android:id="@+id/fragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />
    </ScrollView>
  </LinearLayout>
  <android.support.design.widget.NavigationView
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_gravity="start"
      android:background="@android:color/white"
      android:id="@+id/nav_view"
      app:menu="@menu/navmenu"
      app:headerLayout="@layout/header" />
</android.support.v4.widget.DrawerLayout>
</code>```

Here is my show fragment code in C#

```<code>    private Android.Support.V4.App.Fragment mCurrentFragment;
    private Stack<Android.Support.V4.App.Fragment> mStackFragments;

    //Fragments
    private WorkorderFragment woFragment;
    private ProfileFragment pFragment;
    private ClockInOutFragment cioFragment;
    private ExpenseReportFragment erFragment;
    private SettingsFragment sFragment;

    public FragmentController(MainActivity activity)
    {
        this.activity = activity;
        InitializeFragments();
        LoadFragments();
        mCurrentFragment = woFragment;//Set current fragment
    }

    private void InitializeFragments()
    {
        //Initialization
        woFragment = new WorkorderFragment();
        pFragment = new ProfileFragment();
        cioFragment = new ClockInOutFragment();
        erFragment = new ExpenseReportFragment();
        sFragment = new SettingsFragment();
        mStackFragments = new Stack<Android.Support.V4.App.Fragment>();
    }

private void LoadFragments()
    {
        //Fragment init
        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.Add(Resource.Id.fragmentContainer, woFragment, "WorkorderFragment");
        //trans.Hide(woFragment);

        trans.Add(Resource.Id.fragmentContainer, cioFragment, "ClockInOutFragment");
        trans.Hide(cioFragment);

        trans.Add(Resource.Id.fragmentContainer, erFragment, "ExpenseReportFragment");
        trans.Hide(erFragment);

        trans.Add(Resource.Id.fragmentContainer, pFragment, "ProfileFragment");
        trans.Hide(pFragment);

        trans.Add(Resource.Id.fragmentContainer, sFragment, "SettingsFragment");
        trans.Hide(sFragment);

        trans.Commit();
    }

private void ShowFragment(Android.Support.V4.App.Fragment fragment)
    {
        if (fragment.IsVisible)
            return;

        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.SetCustomAnimations(Resource.Animation.abc_slide_in_bottom, Resource.Animation.abc_slide_out_top, Resource.Animation.abc_slide_in_top, Resource.Animation.abc_slide_out_bottom);

        fragment.View.BringToFront();
        mCurrentFragment.View.BringToFront();

        trans.Hide(mCurrentFragment);
        trans.Show(fragment);

        trans.AddToBackStack(null);
        mStackFragments.Push(mCurrentFragment);

        trans.Commit();
        mCurrentFragment = fragment;
    }
</code>```

答:
For some reason, changing the order of the ExpenseReport fragment in the LoadFragments() method fixed the problem. Really strange.</p>

```<code>    private void LoadFragments()
    {
        //Fragment init
        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.Add(Resource.Id.fragmentContainer, woFragment, "WorkorderFragment");
        //trans.Hide(woFragment);

        trans.Add(Resource.Id.fragmentContainer, erFragment, "ExpenseReportFragment");
        trans.Hide(erFragment);

        trans.Add(Resource.Id.fragmentContainer, cioFragment, "ClockInOutFragment");
        trans.Hide(cioFragment);

        trans.Add(Resource.Id.fragmentContainer, pFragment, "ProfileFragment");
        trans.Hide(pFragment);

        trans.Add(Resource.Id.fragmentContainer, sFragment, "SettingsFragment");
        trans.Hide(sFragment);

        trans.Commit();
    }
</code>```

Body:
My problem happens when switching between fragments. If I switch from a fragment without a listview to either of these, it works fine. Once I switch from fragment A to fragment B, no touch/click events work on fragment b. But, if I go from fragment B to fragment A, fragment A still works fine.

Anyone have any idea what would be causing this?

First fragment xml (Fragment A)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:fab="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="fill_parent">
    <ListView
        android:id="@+id/tmp_lv_er_List"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:fastScrollEnabled="true" />
</RelativeLayout>

Second xml fragment (Fragment B)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:fastScrollEnabled="true" />
</LinearLayout>

Here is the main view xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true">
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
      <android.support.v7.widget.Toolbar
          android:id="@+id/toolbar2"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:minHeight="?attr/actionBarSize"
          android:background="?attr/colorPrimary"
          android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
          app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </LinearLayout>
    <ScrollView
    android:id="@+id/user_profile_scrollView"
    android:layout_gravity="start|bottom"
    android:fillViewport="true"
    android:layout_width="fill_parent"
    android:layout_height="match_parent">
      <FrameLayout
              android:id="@+id/fragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />
    </ScrollView>
  </LinearLayout>
  <android.support.design.widget.NavigationView
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_gravity="start"
      android:background="@android:color/white"
      android:id="@+id/nav_view"
      app:menu="@menu/navmenu"
      app:headerLayout="@layout/header" />
</android.support.v4.widget.DrawerLayout>

Here is my show fragment code in C#

    private Android.Support.V4.App.Fragment mCurrentFragment;
    private Stack<Android.Support.V4.App.Fragment> mStackFragments;

    //Fragments
    private WorkorderFragment woFragment;
    private ProfileFragment pFragment;
    private ClockInOutFragment cioFragment;
    private ExpenseReportFragment erFragment;
    private SettingsFragment sFragment;

    public FragmentController(MainActivity activity)
    {
        this.activity = activity;
        InitializeFragments();
        LoadFragments();
        mCurrentFragment = woFragment;//Set current fragment
    }

    private void InitializeFragments()
    {
        //Initialization
        woFragment = new WorkorderFragment();
        pFragment = new ProfileFragment();
        cioFragment = new ClockInOutFragment();
        erFragment = new ExpenseReportFragment();
        sFragment = new SettingsFragment();
        mStackFragments = new Stack<Android.Support.V4.App.Fragment>();
    }

private void LoadFragments()
    {
        //Fragment init
        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.Add(Resource.Id.fragmentContainer, woFragment, "WorkorderFragment");
        //trans.Hide(woFragment);

        trans.Add(Resource.Id.fragmentContainer, cioFragment, "ClockInOutFragment");
        trans.Hide(cioFragment);

        trans.Add(Resource.Id.fragmentContainer, erFragment, "ExpenseReportFragment");
        trans.Hide(erFragment);

        trans.Add(Resource.Id.fragmentContainer, pFragment, "ProfileFragment");
        trans.Hide(pFragment);

        trans.Add(Resource.Id.fragmentContainer, sFragment, "SettingsFragment");
        trans.Hide(sFragment);

        trans.Commit();
    }

private void ShowFragment(Android.Support.V4.App.Fragment fragment)
    {
        if (fragment.IsVisible)
            return;

        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.SetCustomAnimations(Resource.Animation.abc_slide_in_bottom, Resource.Animation.abc_slide_out_top, Resource.Animation.abc_slide_in_top, Resource.Animation.abc_slide_out_bottom);

        fragment.View.BringToFront();
        mCurrentFragment.View.BringToFront();

        trans.Hide(mCurrentFragment);
        trans.Show(fragment);

        trans.AddToBackStack(null);
        mStackFragments.Push(mCurrentFragment);

        trans.Commit();
        mCurrentFragment = fragment;
    }

Body:
For some reason, changing the order of the ExpenseReport fragment in the LoadFragments() method fixed the problem. Really strange.

    private void LoadFragments()
    {
        //Fragment init
        var trans = activity.SupportFragmentManager.BeginTransaction();

        trans.Add(Resource.Id.fragmentContainer, woFragment, "WorkorderFragment");
        //trans.Hide(woFragment);

        trans.Add(Resource.Id.fragmentContainer, erFragment, "ExpenseReportFragment");
        trans.Hide(erFragment);

        trans.Add(Resource.Id.fragmentContainer, cioFragment, "ClockInOutFragment");
        trans.Hide(cioFragment);

        trans.Add(Resource.Id.fragmentContainer, pFragment, "ProfileFragment");
        trans.Hide(pFragment);

        trans.Add(Resource.Id.fragmentContainer, sFragment, "SettingsFragment");
        trans.Hide(sFragment);

        trans.Commit();
    }


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答: The behavior is documented in this page about Nullable Types. It doesn't give a real explanation for why, but my interpretation is the following. > and < have no meaning when with regards to null. null is the absence of a value and thus is only equal to another variable that also has no value. Since there is no meaning for > and <, that is carried over to >= and <=.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?


问:
Why is my simple Angular app deployed to openshift origin not being served?
I created a simple Angular (not AngularJS) app using the cli and checked it into our private GitHub repo.  I created a project in Openshift Origin running on my Windows 10 box, pointed to the angular app, and got it deployed to the NodeJS builder image - the pod is up and running.  The build logs show no errors.

Here's the problem.  When i click the link that openshift defines for me to be the external route, I get an "Application is not available" message on the screen (see below).

openshift app not available message

I don't know why the app is not being served.  I'm thinking there must be something special that needs to be done to prepare the Angular app to run on openshift, but I have been unable to tease out enough information from this site or other places to recognize what the solution is - most likely due to the fact that this is my first time trying to deploy an Angular app to a prod-like enviroment.

I am obviously missing something trying to deploy this simple angular app to openshift.  Any help would be greatly appreciated.  Thank you.

答:
I found a solution to my issue.  For now, since it's not intended to be a production-ready solution, it is fine.

In package.json, I modified the "start" script to be:

"start": "ng serve --H 0.0.0.0 --port 8080 --disable-host-check"

Currently, my @angular/cli version is 1.4.2, and I'm using the ^4.2.4 @angular packages.


答:
IIUC:</p>

```<code>In [38]: df.groupby(['B','C']).filter(lambda x: len(x) > 1)
Out[38]:
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x
</code>```

Title: How to filter all rows that belong to groups with more than 1 member?

Body:
IIUC:

In [38]: df.groupby(['B','C']).filter(lambda x: len(x) > 1)
Out[38]:
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x


问:
Android Studio: How to integrate Git from Windows 10 Ubuntu bash?
Yesterday I installed bash on Windows 10 and also installed Git on it. It works perfectly fine. Following that, I changed the path of the Terminal in Android Studio from "cmd.exe" to "bash.exe" so I can have the bash shell instead of the cmd shell. But now Android Studio cannot find Git (because on Windows it expects a Git.exe) and I would like to know if it is possible to integrate the bash git into Android Studio (just as it does with the Windows .exe version).</p>

答:
Try GitWrap
https://github.com/ardevd/gitwrap/releases

This wrapper pipes output from WSL to windows and also works on android studio claimed by the developer


问:
responseCode 4 of Google In-App Billing Library 1.0
I'm programming in-app billing function in my app for ads free version by using google in-app billing library 1.0. And I've gone through all stages of here codelab until now. However, I alway meet this error and returned responseCode is 4 (= ITEM_UNAVAILABLE) at onPurchasesUpdated().

I had already registered my product item at google play console and activated it about 3 hours ago. Isn't it enough time? Or... are there any steps that I missed? Please let me know what is wrong? Thanks. :)

答:
Can you comply with the list?

Signing release apk with release keystore

Uploading the previously signed apk to at least alpha or beta google play

Starting purchase flow with the specific id that is already activated

If you want to make test(no pay) purchases you have to register your phone user and the user should be different from the one of the developer account.


问:
Azure app service: Cannot find the certificate in X509Store(StoreName.My, StoreLocation.CurrentUser)
I have written a program that needs a certificate for signing and some other things.

I have uploaded my pfx file as private certificate in SSL certificates of my app service.

Then I've tried to see installed certificates on my app service as it has been described in here by using power shell.

But my current user doesn't have any certificates.

I've also checked my local machine, but it wasn't there either.

I cannot also find it using my c# code:

```<code> X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
        if (certCollection.Count == 0)
            throw new Exception("Certificate not found");
</code>```

答:
Oh, I have forgotten to add WEBSITE_LOAD_CERTIFICATES valued * in the app settings :|

Hope it can help the next person

Body:
I have written a program that needs a certificate for signing and some other things.

I have uploaded my pfx file as private certificate in SSL certificates of my app service.

Then I've tried to see installed certificates on my app service as it has been described in here by using power shell.

But my current user doesn't have any certificates.

I've also checked my local machine, but it wasn't there either.

I cannot also find it using my c# code:

 X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
        if (certCollection.Count == 0)
            throw new Exception("Certificate not found");


问:
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q'] (which is used in Drupal)?

答:
The PHP manual explains both quite well:

http://php.net/manual/en/reserved.variables.server.php  # REQUEST_URI

http://php.net/manual/en/reserved.variables.get.php # for the $_GET["q"] variable


问:
SPSS function spssOpenWrite returned error code SPSS_FILE_OERROR
Been using the opensource library from http://spss.codeplex.com/ to create spss files for quit sometime, but now the following error pops up on the creation of a SPSS file.

SPSS function spssOpenWrite returned error code SPSS_FILE_OERROR

```<code> public static void createSpss(Enquete eq)
    {
        if (File.Exists(eq.titel + ".sav"))
        {
            File.Delete(eq.titel + ".sav");
        }
        SpssDataDocument doc = SpssDataDocument.Create(eq.titel + ".sav");
        createMetaData(doc, eq);
        if (doc.Variables.Count != 0)
        {
            createData(doc, eq);
        }
        doc.Close();
    }
</code>```

Anyone got any ideas what could be the problem?

答: You don't have permission to write/update for this location</p>

Body:
Been using the opensource library from http://spss.codeplex.com/ to create spss files for quit sometime, but now the following error pops up on the creation of a SPSS file.

SPSS function spssOpenWrite returned error code SPSS_FILE_OERROR

 public static void createSpss(Enquete eq)
    {
        if (File.Exists(eq.titel + ".sav"))
        {
            File.Delete(eq.titel + ".sav");
        }
        SpssDataDocument doc = SpssDataDocument.Create(eq.titel + ".sav");
        createMetaData(doc, eq);
        if (doc.Variables.Count != 0)
        {
            createData(doc, eq);
        }
        doc.Close();
    }

Anyone got any ideas what could be the problem?


问:
XmlDocument and the Formal Public Identifier
Why is my GetEntity function in my overloaded XmlResolver being passed the Formal Public Identifier when I load an xml file into an XmlDocument?  Is this a bug or am I supposed to deal with this some how?

edit: Here's some code.

Say for example I do this:

```<code>XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.XmlResolver = new MyXmlResolver();
myXmlDoc.Load("myxmlfile.xml");
</code>```

In MyXmlResolver I have the following code:

```<code>public override object GetEntity(Uri absUri, string role, Type typeToRet)
{
  if (typeToRet == null || typeToRet == typeof(Stream))
     return GetStream(absUri);
  else
     throw new XmlException("Unsupported class type: " + typeToRet);
}
</code>```

I get passed "file://path/to/xmldoc/-//W3C//DTD XHTML 1.1//EN", in absUri which doesn't make any sense to me.  Am I just supposed to ignore it?

答:
Do you really need a custom XmlResolver?  What are you doing in your resolver that warrants a custom implementation?

The reason you are being passed a URI like that is because you have told the XmlDocument that you will explicitly resolve all external references in the document (like DTDs).  If you don't need to do that manually then you should use the existing XmlResolver type or just leave it null and let the default behavior occur.

OwnerDisplayName: Sprintstar

Body:
Why is my GetEntity function in my overloaded XmlResolver being passed the Formal Public Identifier when I load an xml file into an XmlDocument?  Is this a bug or am I supposed to deal with this some how?

edit: Here's some code.

Say for example I do this:

XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.XmlResolver = new MyXmlResolver();
myXmlDoc.Load("myxmlfile.xml");

In MyXmlResolver I have the following code:

public override object GetEntity(Uri absUri, string role, Type typeToRet)
{
  if (typeToRet == null || typeToRet == typeof(Stream))
     return GetStream(absUri);
  else
     throw new XmlException("Unsupported class type: " + typeToRet);
}

I get passed "file://path/to/xmldoc/-//W3C//DTD XHTML 1.1//EN", in absUri which doesn't make any sense to me.  Am I just supposed to ignore it?

LastEditorDisplayName: Sprintstar

OwnerDisplayName: Andrew Hare


问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答:
Berkeley DB Java Edition has a Collections API. Within that API, StoredMap in particular, is a drop-in replacement for a ConcurrentHashMap. You'll need to create the Environment and Database before creating the StoredMap, but the Collections tutorial should make that pretty easy.

Per your requirements, Berkeley DB is designed to be easy to use and I think that you'll find that it has exceptional scalability and performance. Berkeley DB is available under an open source license, it's persistent, platform independent and allows you to search for data. The data can certainly be purged/deleted, as needed. Berkeley DB has long list of other features which you may find highly useful to your application, especially as your requirements change and grow with the success of the application.

If you decide to use Berkeley DB Java Edition, please be sure to ask questions on the BDB JE Forum. There's an active developer community that's happy to help answer questions and resolve problems.


问:
How to ignore javascript timezone to send a datetime to server
I am building a web app with c# and angular to store event schedule. The user will input a date time which is in UTC and I want to save that time in db exactly as inputted. And then show exactly same time when a user will view this information. And this should not depend on user's timezone, and I am telling the user that time is in UTC.

But the problem is browser send time information with timezone info when ajax post to server and server saves a different time (by converting its own timezone) in db as the server is in a different timezone.

How to prevent this?

答:
If you are using .Net Web API as backend, you can config the timezone in Web API WebApiconfig.cs like below. It will serialize the time in UTC.</p>

```<code>public static void Register(HttpConfiguration config)
{
    config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
}
</code>```

Body:
If you are using .Net Web API as backend, you can config the timezone in Web API WebApiconfig.cs like below. It will serialize the time in UTC.

public static void Register(HttpConfiguration config)
{
    config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
}


问:
wp_signon() does not save a cookie == cant login
I'was looking for a solution, but i found nothing.

I'm trying to make AJAX login. The scipts are sending correct data and response: bad or correct login data. After succes page is reloading and ... user is still not logged in.
I was trying to force set a cookie, but it didn;t works.

I'm using force ssl admin (if that's important).

```<code>function ajax_login(){
    global $user_ID;
    if (!$user_ID) {
        // First check the nonce, if it fails the function will break
        check_ajax_referer( 'ajax-login-nonce', 'security' );

        // Nonce is checked, get the POST data and sign user on
        $info = array();
        $info['user_login'] = $_POST['username'];
        $info['user_password'] = $_POST['password'];
        $info['remember'] = true;

        $user_signon = wp_signon($info, true);
        if (is_wp_error($user_signon)){
            echo json_encode(array('loggedin'=>false, 'message'=>__('Get lost.')));
        } else {
            wp_set_current_user($user_ID);
            wp_set_auth_cookie($user_ID);
            echo json_encode(array('loggedin'=>true, 'message'=>__('Wait stupid, im redirecting...')));
        }
    }
    die();
}
</code>```

Could You help me please? I don't have an idea what can be wrong. (everything looks fine before that place, data is sending corretly, var_dump($info) also return correct data).

答:
Your wp-config.php file should also have
define('FORCE_SSL_ADMIN', true);.

Body:
I'was looking for a solution, but i found nothing.

I'm trying to make AJAX login. The scipts are sending correct data and response: bad or correct login data. After succes page is reloading and ... user is still not logged in.
I was trying to force set a cookie, but it didn;t works.

I'm using force ssl admin (if that's important).

function ajax_login(){
    global $user_ID;
    if (!$user_ID) {
        // First check the nonce, if it fails the function will break
        check_ajax_referer( 'ajax-login-nonce', 'security' );

        // Nonce is checked, get the POST data and sign user on
        $info = array();
        $info['user_login'] = $_POST['username'];
        $info['user_password'] = $_POST['password'];
        $info['remember'] = true;

        $user_signon = wp_signon($info, true);
        if (is_wp_error($user_signon)){
            echo json_encode(array('loggedin'=>false, 'message'=>__('Get lost.')));
        } else {
            wp_set_current_user($user_ID);
            wp_set_auth_cookie($user_ID);
            echo json_encode(array('loggedin'=>true, 'message'=>__('Wait stupid, im redirecting...')));
        }
    }
    die();
}

Could You help me please? I don't have an idea what can be wrong. (everything looks fine before that place, data is sending corretly, var_dump($info) also return correct data).