问:
Ranking with PHP on certain condition
I have marks scored by several students in php array.

$firstarray:

```<code>Array (
       [0] => Array (
             [6] => Array ( //I want to skip this student from ranking
                     [ENGLISH] => 45.00
                     [MATHEMATICS] => 5.00
                     [SCIENCE] => 40.00
                    )
                )
      [1] => Array (
             [7] => Array (
                     [ENGLISH] => 41.00
                     [MATHEMATICS] => 40.00
                     [SCIENCE] => 47.00
                     )
                )
      )
      [2] => Array (
             [8] => Array (
                     [ENGLISH] => 42.00
                     [MATHEMATICS] => 44.00
                     [SCIENCE] => 40.00
                     )
                )
      [3] => Array (
             [9] => Array (
                     [ENGLISH] => 42.00
                     [MATHEMATICS] => 25.00
                     [SCIENCE] => 31.00
                     )
                )
      )
</code>```

In another array, I have the total mark scored by each student with the ranking.:

$secondarray:

```<code>Array ( [7] =>
           Array (
             [score] => 128
             [rank] => 1
            )
        [8] =>
           Array (
             [score] => 126
             [rank] => 2
            )
        [9] =>
           Array (
             [score] => 98
             [rank] => 3
            )
       [6] =>
           Array (
             [score] => 90
             [rank] => 4
            )
        )
</code>```

After taking out the students total mark scored in all subjects, I used the following php code to calculate the ranking with ties:

$totalmarkscore:

```<code>   Array (
       [0] => Array (
            [6] => 90
           )
       [1] => Array (
            [7] => 128
           )
       [2] => Array (
            [8] => 126
           )
       [3] => Array (
            [9] => 98
           )
       )

   $rankchu =array();
   foreach($totalmarkscore as $k => $vl){
      if(is_array($vl)){
          foreach($vl as $hlutna =>$ken){
             $rankchu[$hlutna]= $ken;
      }
    }
  }
  $secondarray = setRankings($rankchu);
</code>```

My question is: How do I skip calculating the rank of a student who does not get minimum 15 marks from each subject? But I still want to show the student marks scoring detail, I just want to skip it from the ranking and then maintain the ranking order. In the above example, I want to skip the student with id=6 because he did not get minimum 15 mark (he scored only 5 mark) in Mathematics from ranking calculation, other things remaining the same.
Please help. Thanks.

答:
When you are processing $firstarray, you will need to retain the information whether any of the scores was under 15. Here we add a can_be_scored flag to store that:

```<code> $totalmarkscore = array_reduce(
   $firstarray,
   function($result, $item) {
     $id = key($item);
     $scores = $item[$id];
     $result[$id] = array(
       "score" => array_sum($scores),
       "can_be_scored" => min($scores) >= 15
     );
     return $result;
   },
   array()
 );
</code>```

With this, $totalmarkscore should look something like this:

```<code>Array (
    [7] =>
       Array (
         [score] => 128
         [can_be_scored] => true
        )
    [8] =>
       Array (
         [score] => 126
         [can_be_scored] => true
        )
    [9] =>
       Array (
         [score] => 98
         [can_be_scored] => true
        )
   [6] =>
       Array (
         [score] => 90
         [can_be_scored] => false
        )
    )
</code>```

Then, in setRankings, you can check if $item["can_be_scored"] and exclude the item if it is false.

Title: Ranking with PHP on certain condition

Body:
I have marks scored by several students in php array.

$firstarray:

Array (
       [0] => Array (
             [6] => Array ( //I want to skip this student from ranking
                     [ENGLISH] => 45.00
                     [MATHEMATICS] => 5.00
                     [SCIENCE] => 40.00
                    )
                )
      [1] => Array (
             [7] => Array (
                     [ENGLISH] => 41.00
                     [MATHEMATICS] => 40.00
                     [SCIENCE] => 47.00
                     )
                )
      )
      [2] => Array (
             [8] => Array (
                     [ENGLISH] => 42.00
                     [MATHEMATICS] => 44.00
                     [SCIENCE] => 40.00
                     )
                )
      [3] => Array (
             [9] => Array (
                     [ENGLISH] => 42.00
                     [MATHEMATICS] => 25.00
                     [SCIENCE] => 31.00
                     )
                )
      )

In another array, I have the total mark scored by each student with the ranking.:

$secondarray:

Array ( [7] =>
           Array (
             [score] => 128
             [rank] => 1
            )
        [8] =>
           Array (
             [score] => 126
             [rank] => 2
            )
        [9] =>
           Array (
             [score] => 98
             [rank] => 3
            )
       [6] =>
           Array (
             [score] => 90
             [rank] => 4
            )
        )

After taking out the students total mark scored in all subjects, I used the following php code to calculate the ranking with ties:

$totalmarkscore:

   Array (
       [0] => Array (
            [6] => 90
           )
       [1] => Array (
            [7] => 128
           )
       [2] => Array (
            [8] => 126
           )
       [3] => Array (
            [9] => 98
           )
       )

   $rankchu =array();
   foreach($totalmarkscore as $k => $vl){
      if(is_array($vl)){
          foreach($vl as $hlutna =>$ken){
             $rankchu[$hlutna]= $ken;
      }
    }
  }
  $secondarray = setRankings($rankchu);

My question is: How do I skip calculating the rank of a student who does not get minimum 15 marks from each subject? But I still want to show the student marks scoring detail, I just want to skip it from the ranking and then maintain the ranking order. In the above example, I want to skip the student with id=6 because he did not get minimum 15 mark (he scored only 5 mark) in Mathematics from ranking calculation, other things remaining the same.
Please help. Thanks.

Body:
When you are processing $firstarray, you will need to retain the information whether any of the scores was under 15. Here we add a can_be_scored flag to store that:

 $totalmarkscore = array_reduce(
   $firstarray,
   function($result, $item) {
     $id = key($item);
     $scores = $item[$id];
     $result[$id] = array(
       "score" => array_sum($scores),
       "can_be_scored" => min($scores) >= 15
     );
     return $result;
   },
   array()
 );

With this, $totalmarkscore should look something like this:

Array (
    [7] =>
       Array (
         [score] => 128
         [can_be_scored] => true
        )
    [8] =>
       Array (
         [score] => 126
         [can_be_scored] => true
        )
    [9] =>
       Array (
         [score] => 98
         [can_be_scored] => true
        )
   [6] =>
       Array (
         [score] => 90
         [can_be_scored] => false
        )
    )

Then, in setRankings, you can check if $item["can_be_scored"] and exclude the item if it is false.


来源: stackexchange

问:
Javascript: convert a multidimensional array to object in ajax
I try to send a javascript array to php using ajax he's what I did

```<code>var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}
</code>```

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

```<code>$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});
</code>```

In the network tab i find

```<code>date    "2017-07-08"
</code>```

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php

答:
var myArray = {} is object not a array .Because  Array not have key value pair in js.

var arr=[];
for(var x=0; x<10; x++){
       var myArray = {};//try with object not a array
       myArray['val'] = 10;
       myArray['type'] = 11;
       myArray['id'] = 12;
       arr.push(myArray);
}

console.log(arr)```

ContentLicense: CC BY-SA 3.0

Body:
I try to send a javascript array to php using ajax he's what I did

var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});

In the network tab i find

date    "2017-07-08"

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php


问:
search suggestion functionality with angularjs not working
I am trying to run the below code on my system but not able to get the result. but same code i was running on js fiddler it was running.

this my index.html

```<code><div ng-app="myApp" ng-controller="myCtrl">
<div ng-app>
    <div ng-controller="MyController">
        <input type="search" ng-model="search" placeholder="Search...">
        <ul>
            <li ng-repeat="name in names | filter:search">
                {{ name }}
            </li>
        </ul>
    </div>
</div>
</code>```

script.js

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

app.controller('DefaultCtrl', function($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});
</code>```

Also i want to get exaxct match if i enter 'A' only the words come which is start with the letter 'A' and so on...

答:
As far as I can tell, you named your controller DefaultCtrl, and in HTML
you're calling

So change that to match the controller names, i.e.

Body:
I am trying to run the below code on my system but not able to get the result. but same code i was running on js fiddler it was running.

this my index.html

        <input type="search" ng-model="search" placeholder="Search...">

                {{ name }}

script.js

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

app.controller('DefaultCtrl', function($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

Also i want to get exaxct match if i enter 'A' only the words come which is start with the letter 'A' and so on...

Body:
As far as I can tell, you named your controller DefaultCtrl, and in HTML
you're calling

<div ng-controller="MyController">

So change that to match the controller names, i.e.

<div ng-controller="DefaultCtrl">


问:
MongoDb Connector singleton pattern
I am trying to implement a singleton pattern for connecting to my mongodb database so as to make sure i have only one connection.I have written following code '

public enum MongoConnector {
 CONNECTION;

 private MongoClient client = null;

 /**
  * This function is used to create a single instance of the MongoDb connector
  * Thread Pooling is handled internally by MongoDb
  */
 private MongoConnector() {
  try {
   client = new MongoClient();
  } catch (Exception e) {
   e.printStackTrace();

  }
 }
 public MongoClient getClient() {
  if (client == null) {
   throw new RuntimeException();
  }

  return client;
 }
}```

So i want to know if this is ensuring the singleton pattern.If not please let me know how it should be .Thank you

答: Yes, the MongoConnector is a singleton.  </p>

Title: MongoDb Connector singleton pattern

Body:
I am trying to implement a singleton pattern for connecting to my mongodb database so as to make sure i have only one connection.I have written following code '

public enum MongoConnector {
 CONNECTION;

 private MongoClient client = null;

 /**
  * This function is used to create a single instance of the MongoDb connector
  * Thread Pooling is handled internally by MongoDb
  */
 private MongoConnector() {
  try {
   client = new MongoClient();
  } catch (Exception e) {
   e.printStackTrace();

  }
 }
 public MongoClient getClient() {
  if (client == null) {
   throw new RuntimeException();
  }

  return client;
 }
}

So i want to know if this is ensuring the singleton pattern.If not please let me know how it should be .Thank you

Body: Yes, the MongoConnector is a singleton.


问:
Can I create Background and foreground using Flexbox?
I want to position one div in the background and the other div in the foreground. The foground div should be centered automatically vertically and horizontally according to the size of the div in the background, or the size of the container div.

I wonder if there is an elegant way to do it using Flexbox. Sometimes, before I start arranging the flexbox elements I see the different children overlap. So far I have failed to duplicate this. The advantage is that if we can get the elements to overlap using flexbox, we can center the foreground both vertically and horizontally easily using the margin:auto;.

A different way to do this is to use position relative and absolute. For example:

I'm centered horizontally, but not vertically

```

but then I'll have to add flexbox inside the foreground div to  center the foreground vertically.

答:
I’m not sure if I got you right. But you would just need display: flex; for releasing the magic, align-items: center; for horizontal, and justify-content: center; for vertical aligning nested element(s).

html, body {
  height: 100%;
}

.container {
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: pink;
}

.item {
  padding: 2em;
  color: white;
  background-color: hotpink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item">
    <p>Lorem ipsum dolor sit amet</p>
    <p>Consectetur adipisci velit</p>
  </div>
</div></code>```

Body:
I want to position one div in the background and the other div in the foreground. The foground div should be centered automatically vertically and horizontally according to the size of the div in the background, or the size of the container div.

I wonder if there is an elegant way to do it using Flexbox. Sometimes, before I start arranging the flexbox elements I see the different children overlap. So far I have failed to duplicate this. The advantage is that if we can get the elements to overlap using flexbox, we can center the foreground both vertically and horizontally easily using the margin:auto;.

A different way to do this is to use position relative and absolute. For example:

I'm centered horizontally, but not vertically

but then I'll have to add flexbox inside the foreground div to  center the foreground vertically.

Body:
I’m not sure if I got you right. But you would just need display: flex; for releasing the magic, align-items: center; for horizontal, and justify-content: center; for vertical aligning nested element(s).

html, body {
  height: 100%;
}

.container {
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: pink;
}

.item {
  padding: 2em;
  color: white;
  background-color: hotpink;
}

<div class="container">
  <div class="item">
    <p>Lorem ipsum dolor sit amet</p>
    <p>Consectetur adipisci velit</p>
  </div>
</div>


问:
Vue.js - Passing Parameters to a child route
I have a Vue.js app. This app shows views using the vue-router. When the app starts, I need to retrieve a key from the server. I then want to pass that key to the child views. To demonstrate the problem I've setup this Fiddle. The code related to this question like this:

```<code>var Page1 = { template: '<div><h3>Page 1</h3><p>Number: {{ number }}</p></div>', props: [ 'number' ] };
var Page2 = { template: '<div><h3>Page 2</h3><p>Number: {{ number }}</p></div>', props: [ 'number' ] };

var routes = [
  { path: '/page-1', component: Page1 },
  { path: '/page-2', component: Page2 }
];

var router = new VueRouter({
  routes
});

var app = new Vue({
  router,
  el: '#app',
  data: {
    num: 0
  },
  created: function() {
    var self = this;
    setTimeout(function() {
      self.num = 1;
    }, 100);
  }
});
</code>```

When I run this app, I'm not sure how to "pass" the app.num to the child views (Page1 and Page2) when app.num gets set. I tried using the approach mentioned in the "passing props to route components" docs. However, that approach doesn't seem to work for data that is loaded after creation. What am I missing?

答:
You can bind values from the parent component to the child via the router-view like this:

```<code><router-view :number="num"></router-view>
</code>```

Body:
I have a Vue.js app. This app shows views using the vue-router. When the app starts, I need to retrieve a key from the server. I then want to pass that key to the child views. To demonstrate the problem I've setup this Fiddle. The code related to this question like this:

var Page1 = { template: '

Page 1

Number: {{ number }}

', props: [ 'number' ] };
var Page2 = { template: '

Page 2

Number: {{ number }}

', props: [ 'number' ] };

var routes = [
  { path: '/page-1', component: Page1 },
  { path: '/page-2', component: Page2 }
];

var router = new VueRouter({
  routes
});

var app = new Vue({
  router,
  el: '#app',
  data: {
    num: 0
  },
  created: function() {
    var self = this;
    setTimeout(function() {
      self.num = 1;
    }, 100);
  }
});

When I run this app, I'm not sure how to "pass" the app.num to the child views (Page1 and Page2) when app.num gets set. I tried using the approach mentioned in the "passing props to route components" docs. However, that approach doesn't seem to work for data that is loaded after creation. What am I missing?

Body:
You can bind values from the parent component to the child via the router-view like this:

<router-view :number="num"></router-view>


问:
If we create an object called 'a' from a function constructor, then why is 'a' not an instance of Function?

function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
console.log(myFather instanceof person); //true
console.log(myFather instanceof Object); //true
console.log(myFather instanceof Function); //false```

Hello, in this case, we created an object from the function constructor: 'person'.

Every function in JavaScript is an instance of the Function constructor.
Why is myFather not an instance of Function?

答:
myFather is an object instance of person that is why it is returning true for myFather instanceof Object but false for myFather instanceof Function as it is not a function but an object, you can't call myFather again to instantiate another object. Actually person is an instance of Function. When you call new person a plain object is returned and it is stored in myFather.

function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
console.log(myFather instanceof person); //true
console.log(myFather instanceof Object); //true
console.log(myFather instanceof Function); //false
console.log(person instanceof Function); //true```

Body:
function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
console.log(myFather instanceof person); //true
console.log(myFather instanceof Object); //true
console.log(myFather instanceof Function); //false

Hello, in this case, we created an object from the function constructor: 'person'.

Every function in JavaScript is an instance of the Function constructor.
Why is myFather not an instance of Function?


问:
Checking if part of the elements of a list are repeated
I have a list that I am filling up in the following way:

```<code>complete = []
for (i,j) in list:
    complete.append('%s %s %s'%(i,j,R[i,j]))
</code>```

The list has (as an example) the following elements:

```<code>complete = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']
</code>```

I want to check which letters are repeated, and on that case add the numbers corresponding to them.
On this example, (B A) is repeated with 1 and 7, so one of the outputs would have to be 'B A 8'.

I could also change the way I am appending the elements to complete, but I do not know how other way.

Thanks!

答:
This can be done very simply in two steps:

First, get a list of the unique letter pairs in your list. This will be used to make a dictionary.

Next, iterate over each element in your list and use the current letter pair to index the dictionary. Increment that letter pair's key value pair in the dictionary by cast the last character in the element to a integer.

```<code>>>> lst = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']
>>> keys = set(key[:3] for key in lst)
>>>
>>> new_dict = {key: 0 for key in keys}
>>> for el in lst:
...     new_dict[el[:3]] += int(el[4])
...
>>> new_dict
{'B C': 7, 'H B': 8, 'R P': 9, 'B A': 8, 'B P': 7, 'B M': 9, 'P A': 9, 'A H': 8, 'C S': 7, 'M B': 7, 'M R': 9, 'P B': 8, 'B W': 1}
>>>
</code>```

Body:
I have a list that I am filling up in the following way:

complete = []
for (i,j) in list:
    complete.append('%s %s %s'%(i,j,R[i,j]))

The list has (as an example) the following elements:

complete = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']

I want to check which letters are repeated, and on that case add the numbers corresponding to them.
On this example, (B A) is repeated with 1 and 7, so one of the outputs would have to be 'B A 8'.

I could also change the way I am appending the elements to complete, but I do not know how other way.

Thanks!

Body:
This can be done very simply in two steps:

First, get a list of the unique letter pairs in your list. This will be used to make a dictionary.

Next, iterate over each element in your list and use the current letter pair to index the dictionary. Increment that letter pair's key value pair in the dictionary by cast the last character in the element to a integer.

>>> lst = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']
>>> keys = set(key[:3] for key in lst)
>>>
>>> new_dict = {key: 0 for key in keys}
>>> for el in lst:
...     new_dict[el[:3]] += int(el[4])
...
>>> new_dict
{'B C': 7, 'H B': 8, 'R P': 9, 'B A': 8, 'B P': 7, 'B M': 9, 'P A': 9, 'A H': 8, 'C S': 7, 'M B': 7, 'M R': 9, 'P B': 8, 'B W': 1}
>>>


问:
POST form not working with PHP, working with Postman
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

```<code><?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

<div class="row">
    <div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
        <div class="login-panel panel panel-default">
            <div class="panel-heading"> Admin Log in</div>
            <div class="panel-body">
                <form role="form">
                    <fieldset>
                        <div class="form-group">
                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">
                        </div>
                        <div class="form-group">
                            <input class="form-control" placeholder="Password" name="password" type="password" value="">
                        </div>
                        <div class="checkbox">
                            <label>
                                <input name="remember" type="checkbox" value="Remember Me">Remember Me
                            </label>
                        </div>
                        <a href="" class="btn btn-primary">Login</a>
                    </fieldset>
                </form>
            </div>
        </div>
    </div><!-- /.col-->
</div><!-- /.row -->
</code>```

答:
Your form is a GET form, you need to set method="POST" on your <form> tag.

Other than that, your code is very vulnerable, you should be hashing the passwords in your database, and you should use PDO as it's more secure and you should also use prepared statements and turn off emulated ones with that.

Currently, your code is vulnerable to SQL injection, one of the most basic but the most dangerous security threats for a web application.

Body:
This is login code with session. Iam using bootstrap.The code is not redirecting to index.html, when I test it in Postman it works but it is not working in this bootstrap template. I didnt get the reason? Please Help

<?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    $email=$_POST["email"];
    $password=$_POST["password"];

    $sql = "SELECT * FROM login where email='$email' and password='$password'";

    $result = mysqli_query($conn,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);

    if ($count>0) {

        // output data of each row
        if($row['admin_role']==1) {
            //$_SESSION["email"]=$email;
            //$_SESSION["id"]=$row['user_id'];

            //echo "Login successfull";

            header('Location: index.html');
            exit;
        }
    } else {
        echo "0 results";
    }
}

?>

 Admin Log in

                <form role="form">
                    <fieldset>

                            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus="">

                            <input class="form-control" placeholder="Password" name="password" type="password" value="">

                                <input name="remember" type="checkbox" value="Remember Me">Remember Me

                        Login
                    </fieldset>
                </form>


问:
packages installation for arules in R
I have the same problem with previous post by another user How to upload arules package in R

i am using R version 3.0.2 (32-bit)

The error message is like this:

```<code>> install.packages("arules")
Installing package into ‘C:/Users/HKGGAIT001/Documents/R/win-library/3.0’
(as ‘lib’ is unspecified)
trying URL 'http://cran.ms.unimelb.edu.au/bin/windows/contrib/3.0/arules_1.1-1.zip'
Error in download.file(url, destfile, method, mode = "wb", ...) :
  cannot open URL 'http://cran.ms.unimelb.edu.au/bin/windows/contrib/3.0/arules_1.1-1.zip'
In addition: Warning message:
In download.file(url, destfile, method, mode = "wb", ...) :
  cannot open: HTTP status was '404 Not Found'
Warning in download.packages(pkgs, destdir = tmpd, available = available,  :
  download of package ‘arules’ failed
</code>```

Is that means the packages no longer available? Plus, is there any other packages for market basket analysis?

Many thanks!

答:
If you want to install "arules" package, you may not be able to install it just using the code below.

```<code><<  install.packages("arules")  >>
</code>```

Follow the steps:

Go to the package's address and download it manually. You will find it in the link below:

https://cran.r-project.org/web/packages/arules/index.html

If you are using R-Studio just install that package you have got, by "tools" menu in your IDE (R-studio)

Tools->Install packages->...

Browse the file in your computer and install it.

Go to the command line and using library(arules) function test the package. If there is still an error it could belong to incompatibility of the package with the version of R (Not R-Studio or any other IDE that you are using), just upgrade R and try installation period again.

Title: packages installation for arules in R

Body:
I have the same problem with previous post by another user How to upload arules package in R

i am using R version 3.0.2 (32-bit)

The error message is like this:

> install.packages("arules")
Installing package into ‘C:/Users/HKGGAIT001/Documents/R/win-library/3.0’
(as ‘lib’ is unspecified)
trying URL 'http://cran.ms.unimelb.edu.au/bin/windows/contrib/3.0/arules_1.1-1.zip'
Error in download.file(url, destfile, method, mode = "wb", ...) :
  cannot open URL 'http://cran.ms.unimelb.edu.au/bin/windows/contrib/3.0/arules_1.1-1.zip'
In addition: Warning message:
In download.file(url, destfile, method, mode = "wb", ...) :
  cannot open: HTTP status was '404 Not Found'
Warning in download.packages(pkgs, destdir = tmpd, available = available,  :
  download of package ‘arules’ failed

Is that means the packages no longer available? Plus, is there any other packages for market basket analysis?

Many thanks!

Body:
If you want to install "arules" package, you may not be able to install it just using the code below.

<<  install.packages("arules")  >>

Follow the steps:

Go to the package's address and download it manually. You will find it in the link below:

https://cran.r-project.org/web/packages/arules/index.html

If you are using R-Studio just install that package you have got, by "tools" menu in your IDE (R-studio)

Tools->Install packages->...

Browse the file in your computer and install it.

Go to the command line and using library(arules) function test the package. If there is still an error it could belong to incompatibility of the package with the version of R (Not R-Studio or any other IDE that you are using), just upgrade R and try installation period again.


问:
What are the x.x.x-rc Node.js versions in nodenv?
After installing nodenv and node-build I viewed available Node.js versions nodenv install --list.

However, the list has several versions of the kind 6.11.0-rc.1, 7.0.0-rc.1, 7.0.0-rc.2 etc. along with their non-suffixed counter parts 6.11.0, 7.0.0

I haven't been able to find an explanation of what these rc versions are. Are they releases leading up to the complete Node.js versions or special files?

答:
The acronym rc in the name of the version means Release Candidate. Usually, these versions are the previous version of the final release.

E.g. 7.0.0.-rc.1 is the previous version of the final release 7.0.0. But, if  several mistakes are found in this release, then they make another rc before they make the final version.
For this reason, you can also have 7.0.0-rc.2and finally 7.0.0.

rc is like the step after a beta release.


问:
How to ignore null values for all source members during mapping in Automapper 6?
I've been looking everywhere: stackoverflow, automapper documentation, internets and just couldn't find any info on this one, even tho this seems to be a very common problem.

My mapping:

```<code>CreateMap<StatusLevelDTO, StatusLevel>()
            .ForAllMembers(opt => opt.Condition(src => src != null));
</code>```

This doesn't work because src represents source object (StatusLevelDTO), not a source property (I think).

To be more specific, If I map ObjectA to ObjectB, ObjectA.SomeValue is null and ObjectB.SomeValue is 2, I want the destination object to keep its value (2).

I've seen this question: Automapper skip null values with custom resolver and tried the first two answers but they both seem to be outdated for version 6.

Is there any way to make this happen in Automapper 6? I am using 6.0.2 to be exact.

答:
The solution here works for my project, which is using AutoMapper 6.0.2. In previous projects using AutoMapper 4, I had used IsSourceValueNull to achieve the same behavior.

I made a small change to the original solution. Instead of checking the type of the property to be mapped, I set the filter in ForAllPropertyMaps to check the type of the source object, so that the custom resolver only applies to maps from that source object. But the filter can be set to anything as needed.

```<code>var config = new MapperConfiguration(cfg =>
{
    cfg.ForAllPropertyMaps(
        pm => pm.TypeMap.SourceType == typeof(<class of source object>),
        (pm, c) => c.ResolveUsing<object, object, object, object>(new IgnoreNullResolver(), pm.SourceMember.Name));
});

class IgnoreNullResolver : IMemberValueResolver<object, object, object, object>
{
    public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
    {
        return sourceMember ?? destinationMember;
    }
}
</code>```

Body:
I've been looking everywhere: stackoverflow, automapper documentation, internets and just couldn't find any info on this one, even tho this seems to be a very common problem.

My mapping:

CreateMap<StatusLevelDTO, StatusLevel>()
            .ForAllMembers(opt => opt.Condition(src => src != null));

This doesn't work because src represents source object (StatusLevelDTO), not a source property (I think).

To be more specific, If I map ObjectA to ObjectB, ObjectA.SomeValue is null and ObjectB.SomeValue is 2, I want the destination object to keep its value (2).

I've seen this question: Automapper skip null values with custom resolver and tried the first two answers but they both seem to be outdated for version 6.

Is there any way to make this happen in Automapper 6? I am using 6.0.2 to be exact.

Body:
The solution here works for my project, which is using AutoMapper 6.0.2. In previous projects using AutoMapper 4, I had used IsSourceValueNull to achieve the same behavior.

I made a small change to the original solution. Instead of checking the type of the property to be mapped, I set the filter in ForAllPropertyMaps to check the type of the source object, so that the custom resolver only applies to maps from that source object. But the filter can be set to anything as needed.

var config = new MapperConfiguration(cfg =>
{
    cfg.ForAllPropertyMaps(
        pm => pm.TypeMap.SourceType == typeof(<class of source object>),
        (pm, c) => c.ResolveUsing<object, object, object, object>(new IgnoreNullResolver(), pm.SourceMember.Name));
});

class IgnoreNullResolver : IMemberValueResolver<object, object, object, object>
{
    public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
    {
        return sourceMember ?? destinationMember;
    }
}


问:
Facebook Ads API /adcreatives video error
My team and I have been crawling both the net and Facebook Docs for answers, but for some reason there are no valid answers to our question.

So we desperately hope for help from someone here

We are trying to create a video AD on facebook. Upload is done and we are at the step where we need to create the creative through /adcreatives endpoint.

Below is the body of the POST :
https://graph.facebook.com/v2.8/act_[account_id]/adcreatives

```<code> {
      "access_token": "token_that_is_valid",
      "object_story_spec": {
        "page_id": "valid_numeric_page_id",
        "video_data":{
          "image_url": "link_to_img",
            "video_id": "valid_numeric_video_id",
            "call_to_action" :{
                "type": "LEARN_MORE",
                "value":{
                    "link": "my_link",
                    "link_caption":"my_link_caption",
                    "link_description": "description"
                }
            }
       }

      },
      "name":"jjkkllkjljl"
    }
</code>```

The response from facebook is rather worrying :

```<code>{
    "error": {
        "message": "Invalid parameter",
        "type": "OAuthException",
        "code": 100,
        "error_subcode": 1487390,
        "is_transient": false,
        "error_user_title": "Adcreative Create Failed",
        "error_user_msg": "The Adcreative Create Failed for the following reason: Oops, something went wrong. Please try again later",
        "fbtrace_id": "EVL6GYOOtYi"
    }
}
</code>```

Also as an extra info, creating both non-video / image creatives and herafter ads is not an issue. Posting pre uploaded videos to a page is NOT an issue. All access rights has been given to the Facebook APP.

Thank you for taking the time to look at this.

答: link description is not a valid parameter in the call_to_action value: https://developers.facebook.com/docs/marketing-api/reference/ad-creative-link-data-call-to-action-value/

Body:
My team and I have been crawling both the net and Facebook Docs for answers, but for some reason there are no valid answers to our question.

So we desperately hope for help from someone here

We are trying to create a video AD on facebook. Upload is done and we are at the step where we need to create the creative through /adcreatives endpoint.

Below is the body of the POST :
https://graph.facebook.com/v2.8/act_[account_id]/adcreatives

 {
      "access_token": "token_that_is_valid",
      "object_story_spec": {
        "page_id": "valid_numeric_page_id",
        "video_data":{
          "image_url": "link_to_img",
            "video_id": "valid_numeric_video_id",
            "call_to_action" :{
                "type": "LEARN_MORE",
                "value":{
                    "link": "my_link",
                    "link_caption":"my_link_caption",
                    "link_description": "description"
                }
            }
       }

      },
      "name":"jjkkllkjljl"
    }

The response from facebook is rather worrying :

{
    "error": {
        "message": "Invalid parameter",
        "type": "OAuthException",
        "code": 100,
        "error_subcode": 1487390,
        "is_transient": false,
        "error_user_title": "Adcreative Create Failed",
        "error_user_msg": "The Adcreative Create Failed for the following reason: Oops, something went wrong. Please try again later",
        "fbtrace_id": "EVL6GYOOtYi"
    }
}

Also as an extra info, creating both non-video / image creatives and herafter ads is not an issue. Posting pre uploaded videos to a page is NOT an issue. All access rights has been given to the Facebook APP.

Thank you for taking the time to look at this.


问:
Building PortAudio and PyAudio on Mac running Snow Leopard (arch issues)
I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly!

I've tried installing the stable and svn releases of PortAudio from their website for my Core 2 Duo MacBook Pro running Snow Leopard. The stable release has a sizeof error that can be fixed(?), but the daily svn release installs fine with ./configure && make &&  make install (so this is what I'm using). The tests are compiled properly and I can get the binaries to produce output/can read microphone input.

Ok, so then PyAudio has troubles. Installing from source I get errors about not finding the libraries:

```<code>mwoods 13 pyaudio-0.2.3$ python setup.py build
running build
running build_py
running build_ext
building '_portaudio' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe -DMACOSX=1 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _portaudiomodule.c -o build/temp.macosx-10.6-universal-2.6/_portaudiomodule.o -fno-strict-aliasing
_portaudiomodule.c:35:25: error: pa_mac_core.h: No such file or directory
_portaudiomodule.c:679: error: expected specifier-qualifier-list before ‘PaMacCoreStreamInfo’
_portaudiomodule.c: In function ‘_pyAudio_MacOSX_hostApiSpecificStreamInfo_cleanup’:
_portaudiomodule.c:690: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:691: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:692: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:695: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘channelMap’
_portaudiomodule.c:696: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘channelMap’
_portaudiomodule.c:699: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘flags’

... another 100 lines of this ...

_portaudiomodule.c:2471: error: ‘paMacCoreMinimizeCPUButPlayNice’ undeclared (first use in this function)
_portaudiomodule.c:2473: error: ‘paMacCoreMinimizeCPU’ undeclared (first use in this function)
lipo: can't open input file: /var/folders/Qc/Qcl516fqHAWupTUV9BE9rU+++TI/-Tmp-//cc7BqpBc.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
</code>```

I can install PyAudio from their .dmg installer, but it targets python2.5. If I copy all of the related contents of /Library/Python/2.5/site-packages/ to /Library/Python/2.6/site-packages/ (this includes PyAudio-0.2.3-py2.5.egg-info, _portaudio.so, pyaudio.py, pyaudio.pyc, and pyaudio.pyo) then my python2.6 can recognize it.

```<code>In [1]: import pyaudio
Please build and install the PortAudio Python bindings first.
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "/Library/Python/2.6/site-packages/pyaudio.py", line 103, in <module>
    sys.exit(-1)
SystemExit: -1

Type %exit or %quit to exit IPython (%Exit or %Quit do so unconditionally).

In [2]:
</code>```

So this happens because _portaudio can't be imported. If I try to import that directly:

```<code>In [2]: import _portaudio
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
ImportError: /Library/Python/2.6/site-packages/_portaudio.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode)
</code>```

Ok, so if I export VERSIONER_PYTHON_PREFER_32_BIT=yes and then run python again (well, ipython I suppose), we can see it works but with consequences:

```<code>In [1]: import pyaudio

In [2]: pyaudio
Out[2]: <module 'pyaudio' from '/Library/Python/2.6/site-packages/pyaudio.pyc'>

In [3]: import pylab
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/__init__.py", line 129, in <module>
    from rcsetup import defaultParams, validate_backend, validate_toolbar
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/rcsetup.py", line 19, in <module>
    from matplotlib.colors import is_color_like
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/colors.py", line 52, in <module>
    import numpy as np
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/__init__.py", line 130, in <module>
    import add_newdocs
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/add_newdocs.py", line 9, in <module>
    from lib import add_newdoc
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/lib/__init__.py", line 4, in <module>
    from type_check import *
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/lib/type_check.py", line 8, in <module>
    import numpy.core.numeric as _nx
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py", line 5, in <module>
    import multiarray
ImportError: dlopen(/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/multiarray.so, 2): no suitable image found.  Did find:
    /Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/multiarray.so: mach-o, but wrong architecture
</code>```

We can assume pylab was working before! I spent a while getting this far, but can someone help with this install or lend advice from a successful Snow Leopard install? Sorry for the long post, but I'm notorious for only giving partial information and I'm trying to fix that!

答:
I'm on Mac 10.5.8 Intel Core 2 duo and hitting the same issue.
The directory layout you need is

```<code>./foo/pyaudio/portaudio-v19/
./foo/pyaudio
</code>```

The reason is setup.py has the following:
portaudio_path = os.environ.get("PORTAUDIO_PATH", "./portaudio-v19")

alternatively, you should be able to set PORTAUDIO_PATH env variable and get it to work.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly!

I've tried installing the stable and svn releases of PortAudio from their website for my Core 2 Duo MacBook Pro running Snow Leopard. The stable release has a sizeof error that can be fixed(?), but the daily svn release installs fine with ./configure && make &&  make install (so this is what I'm using). The tests are compiled properly and I can get the binaries to produce output/can read microphone input.

Ok, so then PyAudio has troubles. Installing from source I get errors about not finding the libraries:

mwoods 13 pyaudio-0.2.3$ python setup.py build
running build
running build_py
running build_ext
building '_portaudio' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe -DMACOSX=1 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _portaudiomodule.c -o build/temp.macosx-10.6-universal-2.6/_portaudiomodule.o -fno-strict-aliasing
_portaudiomodule.c:35:25: error: pa_mac_core.h: No such file or directory
_portaudiomodule.c:679: error: expected specifier-qualifier-list before ‘PaMacCoreStreamInfo’
_portaudiomodule.c: In function ‘_pyAudio_MacOSX_hostApiSpecificStreamInfo_cleanup’:
_portaudiomodule.c:690: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:691: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:692: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘paMacCoreStreamInfo’
_portaudiomodule.c:695: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘channelMap’
_portaudiomodule.c:696: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘channelMap’
_portaudiomodule.c:699: error: ‘_pyAudio_Mac_HASSI’ has no member named ‘flags’

... another 100 lines of this ...

_portaudiomodule.c:2471: error: ‘paMacCoreMinimizeCPUButPlayNice’ undeclared (first use in this function)
_portaudiomodule.c:2473: error: ‘paMacCoreMinimizeCPU’ undeclared (first use in this function)
lipo: can't open input file: /var/folders/Qc/Qcl516fqHAWupTUV9BE9rU+++TI/-Tmp-//cc7BqpBc.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1

I can install PyAudio from their .dmg installer, but it targets python2.5. If I copy all of the related contents of /Library/Python/2.5/site-packages/ to /Library/Python/2.6/site-packages/ (this includes PyAudio-0.2.3-py2.5.egg-info, _portaudio.so, pyaudio.py, pyaudio.pyc, and pyaudio.pyo) then my python2.6 can recognize it.

In [1]: import pyaudio
Please build and install the PortAudio Python bindings first.
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "/Library/Python/2.6/site-packages/pyaudio.py", line 103, in <module>
    sys.exit(-1)
SystemExit: -1

Type %exit or %quit to exit IPython (%Exit or %Quit do so unconditionally).

In [2]:

So this happens because _portaudio can't be imported. If I try to import that directly:

In [2]: import _portaudio
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
ImportError: /Library/Python/2.6/site-packages/_portaudio.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode)

Ok, so if I export VERSIONER_PYTHON_PREFER_32_BIT=yes and then run python again (well, ipython I suppose), we can see it works but with consequences:

In [1]: import pyaudio

In [2]: pyaudio
Out[2]: <module 'pyaudio' from '/Library/Python/2.6/site-packages/pyaudio.pyc'>

In [3]: import pylab
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/__init__.py", line 129, in <module>
    from rcsetup import defaultParams, validate_backend, validate_toolbar
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/rcsetup.py", line 19, in <module>
    from matplotlib.colors import is_color_like
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r8037-py2.6-macosx-10.6-universal.egg/matplotlib/colors.py", line 52, in <module>
    import numpy as np
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/__init__.py", line 130, in <module>
    import add_newdocs
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/add_newdocs.py", line 9, in <module>
    from lib import add_newdoc
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/lib/__init__.py", line 4, in <module>
    from type_check import *
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/lib/type_check.py", line 8, in <module>
    import numpy.core.numeric as _nx
  File "/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py", line 5, in <module>
    import multiarray
ImportError: dlopen(/Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/multiarray.so, 2): no suitable image found.  Did find:
    /Library/Python/2.6/site-packages/numpy-1.4.0.dev7542_20091216-py2.6-macosx-10.6-universal.egg/numpy/core/multiarray.so: mach-o, but wrong architecture

We can assume pylab was working before! I spent a while getting this far, but can someone help with this install or lend advice from a successful Snow Leopard install? Sorry for the long post, but I'm notorious for only giving partial information and I'm trying to fix that!

Body:
I'm on Mac 10.5.8 Intel Core 2 duo and hitting the same issue.
The directory layout you need is

./foo/pyaudio/portaudio-v19/
./foo/pyaudio

The reason is setup.py has the following:
portaudio_path = os.environ.get("PORTAUDIO_PATH", "./portaudio-v19")

alternatively, you should be able to set PORTAUDIO_PATH env variable and get it to work.


问:
Cannot access a disposed object
I have a piece of code that throws an exception and error after running for a second time. Here it is:

```<code>static Form Window = new Form();
static public void Configuration()
{
    Window.Height = 800;
    Window.Width = 800;
    Window.Text = "Homework";

    Window.Paint += Window_Paint;

    Window.Show();
}
</code>```

This code is inside a class and it throws an exception at "Window.Show();" saying that it:

```<code>ObjectDisposedException: Cannot access a disposed object.
Object name: 'Form'.
</code>```

Please suggest a way that I can fix this so that it doesn't happen again.

答:
The code you probably want to use is:

```<code>static public void Configuration()
{
    var window = new Form();

    window.Height = 800;
    window.Width = 800;
    window.Text = "Homework";

    window.Paint += Window_Paint;

    window.Show();
}
</code>```

This will ensure that a new instance of Form is created every time that Configuration is called.

Title: Cannot access a disposed object

Body:
I have a piece of code that throws an exception and error after running for a second time. Here it is:

static Form Window = new Form();
static public void Configuration()
{
    Window.Height = 800;
    Window.Width = 800;
    Window.Text = "Homework";

    Window.Paint += Window_Paint;

    Window.Show();
}

This code is inside a class and it throws an exception at "Window.Show();" saying that it:

ObjectDisposedException: Cannot access a disposed object.
Object name: 'Form'.

Please suggest a way that I can fix this so that it doesn't happen again.

Body:
The code you probably want to use is:

static public void Configuration()
{
    var window = new Form();

    window.Height = 800;
    window.Width = 800;
    window.Text = "Homework";

    window.Paint += Window_Paint;

    window.Show();
}

This will ensure that a new instance of Form is created every time that Configuration is called.


问:
Convert to float and pad left with zero on SQL Server
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

```<code>2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00
</code>```

I tried this:

```<code>cast(Weight as decimal(6, 2))
</code>```

and also this:

```<code>REPLACE(STR(Weight, 6), SPACE(1), '0')
</code>```

and this:

```<code>REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')
</code>```

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

答:
This should do it</p>

```<code>CREATE FUNCTION [usf_PadFloat] ( @InputNum Float, @PadLen Integer )
RETURNS varchar(25)
/****************************************************************************************
-- Returns current time if null
--   (No it doesn't I just lack at changing comments when I reuse code)

select dbo.[usf_PadFloat](28.1273, 4)
select dbo.[usf_PadFloat](17, 4)
select dbo.[usf_PadFloat](2.23, 4)
select dbo.[usf_PadFloat](123.3, 4)
select dbo.[usf_PadFloat](12.65, 4)
select dbo.[usf_PadFloat](34, 4)

****************************************************************************************/
AS
    BEGIN
    DECLARE @Retval varchar(25)

        Select @InputNum = Round(@InputNum,2)

        Select @Retval = cast(@InputNum as varchar(25))

        if charindex('.',@Retval) = 0
            Select @Retval += '.00'

        While charindex('.',Reverse(@Retval)) <> 3 and len(@Retval) < 100 --just n case.
          Select @Retval += '0'

        select @Retval = Right(replicate('0',@padlen+3) + @Retval, @Padlen+3)

        return @Retval
    END
</code>```

Body:
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00

I tried this:

cast(Weight as decimal(6, 2))

and also this:

REPLACE(STR(Weight, 6), SPACE(1), '0')

and this:

REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

Body:
This should do it

CREATE FUNCTION [usf_PadFloat] ( @InputNum Float, @PadLen Integer )
RETURNS varchar(25)
/****************************************************************************************
-- Returns current time if null
--   (No it doesn't I just lack at changing comments when I reuse code)

select dbo.[usf_PadFloat](28.1273, 4)
select dbo.[usf_PadFloat](17, 4)
select dbo.[usf_PadFloat](2.23, 4)
select dbo.[usf_PadFloat](123.3, 4)
select dbo.[usf_PadFloat](12.65, 4)
select dbo.[usf_PadFloat](34, 4)

****************************************************************************************/
AS
    BEGIN
    DECLARE @Retval varchar(25)

        Select @InputNum = Round(@InputNum,2)

        Select @Retval = cast(@InputNum as varchar(25))

        if charindex('.',@Retval) = 0
            Select @Retval += '.00'

        While charindex('.',Reverse(@Retval)) <> 3 and len(@Retval) < 100 --just n case.
          Select @Retval += '0'

        select @Retval = Right(replicate('0',@padlen+3) + @Retval, @Padlen+3)

        return @Retval
    END


问:
Computing the binomial coefficient in C
I found the following code for computing nCr, but don't understand the logic behind it. Why does this code work? </p>

```<code>long long combi(int n,int k)
{
    long long ans=1;
    k=k>n-k?n-k:k;
    int j=1;
    for(;j<=k;j++,n--)
    {
        if(n%j==0)
        {
            ans*=n/j;
        }else
        if(ans%j==0)
        {
            ans=ans/j*n;
        }else
        {
            ans=(ans*n)/j;
        }
    }
    return ans;
}
</code>```

答:
yes.
[N choose K] reduces its factorials a lot because the dividend and divisor share many factors that cancel each other out to x/x=1 (for x>0)
the trick is to not calculate the large factorials, because these large factors require too much address space (too many bits)

the first trick is to reduce the fraction, before dividing.
the second trick is to do modulo within a conditional to chose one of 3 operations for the current iteration. this can be done differently, and integer modulo is chosen to be a fast operator, skipping some slower integer division approaches.

you iteratively traverse pascals triangle.
with each path that you take, you multiply something.

There are 3 possible branching paths for every iterative step:
each of the 3 steps multiplies the accumulator "ans" with a different value, representing the factor between 2 "positions" on pascals triangle.
you always end up doing N multiplications, where N is the number of iterations, and end up at the binomial coefficient's value.

N is the column # of pascals triangle that you want to know, and you accumulate an N, multiplied by something, while reducing the number of column s (and lines) of pascals triangle by N=N-1 for each iteration.

j=1;

ans=0;

//within each iteration;

```<code>ans=ans*n;

n=n-1;

ans=ans/j;

j=n+1;
</code>```

the integer division is slow and can be skipped (or made faster by making the divisor smaller) at least once, and often many more times (because there are a lot of shared prime factors in pascals triangle), this is being done by the modulo conditionals.

pascals triangle is extremely symmetric (on summing up its domains), therefore this works.

the difference between (partial) sums of columns of pascals triangle shows the symmetry that is important for the multiplications and divisions here.

just watch some youtube videos on the symmetries and identities of pascals triangle.

Title: Computing the binomial coefficient in C

Body:
I found the following code for computing nCr, but don't understand the logic behind it. Why does this code work?

long long combi(int n,int k)
{
    long long ans=1;
    k=k>n-k?n-k:k;
    int j=1;
    for(;j<=k;j++,n--)
    {
        if(n%j==0)
        {
            ans*=n/j;
        }else
        if(ans%j==0)
        {
            ans=ans/j*n;
        }else
        {
            ans=(ans*n)/j;
        }
    }
    return ans;
}

Body:
yes.
[N choose K] reduces its factorials a lot because the dividend and divisor share many factors that cancel each other out to x/x=1 (for x>0)
the trick is to not calculate the large factorials, because these large factors require too much address space (too many bits)

the first trick is to reduce the fraction, before dividing.
the second trick is to do modulo within a conditional to chose one of 3 operations for the current iteration. this can be done differently, and integer modulo is chosen to be a fast operator, skipping some slower integer division approaches.

you iteratively traverse pascals triangle.
with each path that you take, you multiply something.

There are 3 possible branching paths for every iterative step:
each of the 3 steps multiplies the accumulator "ans" with a different value, representing the factor between 2 "positions" on pascals triangle.
you always end up doing N multiplications, where N is the number of iterations, and end up at the binomial coefficient's value.

N is the column # of pascals triangle that you want to know, and you accumulate an N, multiplied by something, while reducing the number of column s (and lines) of pascals triangle by N=N-1 for each iteration.

j=1;

ans=0;

//within each iteration;

ans=ans*n;

n=n-1;

ans=ans/j;

j=n+1;

the integer division is slow and can be skipped (or made faster by making the divisor smaller) at least once, and often many more times (because there are a lot of shared prime factors in pascals triangle), this is being done by the modulo conditionals.

pascals triangle is extremely symmetric (on summing up its domains), therefore this works.

the difference between (partial) sums of columns of pascals triangle shows the symmetry that is important for the multiplications and divisions here.

just watch some youtube videos on the symmetries and identities of pascals triangle.


问:
Topological order using bfs
The following question was found in Sedgewick and Wayne book about algorithms in java:

4.2.19 Topological sort and BFS. Explain why the following algorithm does not necessarily produce a topological order: Run BFS, and label the vertices by increasing distance to their respective source.

I was trying to prove it finding a counter example. But, everytime I try, I get a topological order.
I mean, I don't understand why this not work: If the source of a vertex comes before it, why don't we have a topological order?

I think to prove it, we need to find a vertex that its source comes before, but I couldn't.

Anyone have a counterexample? Thanks in advance!

PS: this is not homework

@Edit: I've tried an hamiltonian path like 1 <- 2 <- 0 <- 3 <- 4, which gives 0 3 4 2 1, but changing the positions of 0 3 and 4 gives me a topological order (but, in the order that I obtained, it is not). I am not sure this is or not a topological order, then.

答:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

You need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

```<code>  public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

  ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
      return result;
    }
  Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
  Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

//mapping node to its indegree to the HashMap, however these nodes
//have to be directed to by one other node, nodes whose indegree == 0
//would not be mapped.
  for (DirectedGraphNode DAGNode : graph){
      for (DirectedGraphNode nei : DAGNode.neighbors){
          if(indegree.containsKey(nei)){
              indegree.put(nei, indegree.get(nei) + 1);
          } else {
              indegree.put(nei, 1);
          }
      }
  }

//find all nodes with indegree == 0. They should be at starting positon in the result
  for (DirectedGraphNode GraphNode : graph) {
      if (!indegree.containsKey(GraphNode)){
          queue.offer(GraphNode);
          result.add(GraphNode);
      }
  }

//everytime we poll out a node from the queue, it means we delete it from the
//graph, we will minus its neighbors indegree by one, this is the same meaning
//as we delete the edge from the node to its neighbors.
  while (!queue.isEmpty()) {
      DirectedGraphNode temp = queue.poll();
      for (DirectedGraphNode neighbor : temp.neighbors){
          indegree.put(neighbor, indegree.get(neighbor) - 1);
          if (indegree.get(neighbor) == 0){
              result.add(neighbor);
              queue.offer(neighbor);
          }
      }
  }
  return result;
}
</code>```

Title: Topological order using bfs

Body:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

You need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

  public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

  ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
      return result;
    }
  Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
  Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

//mapping node to its indegree to the HashMap, however these nodes
//have to be directed to by one other node, nodes whose indegree == 0
//would not be mapped.
  for (DirectedGraphNode DAGNode : graph){
      for (DirectedGraphNode nei : DAGNode.neighbors){
          if(indegree.containsKey(nei)){
              indegree.put(nei, indegree.get(nei) + 1);
          } else {
              indegree.put(nei, 1);
          }
      }
  }

//find all nodes with indegree == 0. They should be at starting positon in the result
  for (DirectedGraphNode GraphNode : graph) {
      if (!indegree.containsKey(GraphNode)){
          queue.offer(GraphNode);
          result.add(GraphNode);
      }
  }

//everytime we poll out a node from the queue, it means we delete it from the
//graph, we will minus its neighbors indegree by one, this is the same meaning
//as we delete the edge from the node to its neighbors.
  while (!queue.isEmpty()) {
      DirectedGraphNode temp = queue.poll();
      for (DirectedGraphNode neighbor : temp.neighbors){
          indegree.put(neighbor, indegree.get(neighbor) - 1);
          if (indegree.get(neighbor) == 0){
              result.add(neighbor);
              queue.offer(neighbor);
          }
      }
  }
  return result;
}


问:
Producing a batch message
Let's say there is a batch API for performing tasks List[T]. In order to do the job all the tasks needs to be pushed to kafka. There are 2 ways to do that :

1) Pushing List as a message in kafka
2) Pushing individual task T in kafka

I believe approach 1 would be better since i don't have to push the messages to kafka mutiple times for a single batch call. Can some one please tell me if there is any harm in such approach ?

答: Starting from Kafka v0.11 you can also use transactions in the producer to publish your entire batch atomically. i.e. you begin the transaction, then publish your tasks message by message, finally you commit the transaction. Even though the messages can be sent to kafka in multiple batches, they will only become visible to consumers once you commit the transaction, as long as your consumers are running in read-committed mode.</p>

Title: Producing a batch message


问:
How to declare a generic type Multi-Dimensional array in java
I want to store an array of 100 int elements in rows ie 1 row of 100 int datatypes.And every single element contains an array of 100 objects.How to do this in java or android. </p>

答:
If your type is int, it which be much more compact than using Integer type. (up to 6x smaller)
To create a fixed size array you can

```<code>int[][] matrix = new int[200][100];
// set all values to 42.
for(int[] row : matrix) Arrays.fill(row, 42);
</code>```

Body:
If your type is int, it which be much more compact than using Integer type. (up to 6x smaller)
To create a fixed size array you can

int[][] matrix = new int[200][100];
// set all values to 42.
for(int[] row : matrix) Arrays.fill(row, 42);


问:
Add fixed tab bar pinned to top with scrolled content?
I tried this answer, but I could not achieve the same look & behavior as my current main activity.

What changes should I make to my existing main activity to add a fixed tab bar pinned to top with scrolled content like in the image below?

Here's a .GIF of my current main activity: i.stack.imgur.com/Yj0cv.gif

Here's a link to the full project called android: https://github.com/firebase/friendlychat/tree/master/android

Here's styles.xml:

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:colorButtonNormal">@drawable/button_selector</item>
        <item name="colorButtonNormal">@drawable/button_selector</item>
        <item name="android:buttonStyle">@style/FriendlyButtonStyle</item>
    </style>

    <style name="FriendlyButtonStyle" parent="Widget.AppCompat.Button">
        <item name="android:textColor">@color/colorTitle</item>

    </style>
</resources>
</code>```

Here's activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.google.firebase.codelab.friendlychat.MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/messageRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linearLayout"
        android:layout_below="@+id/adView"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">

        <ImageView
            android:id="@+id/addMessageImageView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_add_black_24dp"/>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/messageEditText"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SEND"
            android:enabled="false"
            android:id="@+id/sendButton"
            android:layout_gravity="bottom"/>

    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>
</code>```

答:
Google has Design support library and with it you can implement Collapsing Toolbar and you do not need any 3rd party libraries!!

In addition to pinning a view, you can use  app:layout_collapseMode="parallax" (and optionally app:layout_collapseParallaxMultiplier="0.7" to set the parallax multiplier) to implement parallax scrolling (say of a sibling ImageView within the CollapsingToolbarLayout)

And as example you can use this:

```<code><android.support.design.widget.AppBarLayout
    android:layout_height="186dp"
    android:layout_width="match_parent">
<android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">
    <android.support.v7.widget.Toolbar
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            app:layout_collapseMode="pin"/>
    </android.support.design.widget.CollapsingToolbarLayout>
</code>```

And do not forget to add compile "com.android.support:design:25.3.1" in your module  build.gradle

UPDATE 1:
First of all, you need to create a CoordinatorLayout.

All the new components use a new concept called Behavior that is used by the Coordinator Layout to take some actions based on different interactions.

```<code><android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true">

</android.support.design.widget.CoordinatorLayout>
</code>```

You can use fitsSystemWindows on any item you want to be painted below the status bar.

Then you need to add an AppBarLayout:

```<code><android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

</android.support.design.widget.AppBarLayout>
</code>```

And then inside that, you can add something like:

```<code><android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleMarginEnd="64dp"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>
</code>```

Body:
I tried this answer, but I could not achieve the same look & behavior as my current main activity.

What changes should I make to my existing main activity to add a fixed tab bar pinned to top with scrolled content like in the image below?

Here's a .GIF of my current main activity: i.stack.imgur.com/Yj0cv.gif

Here's a link to the full project called android: https://github.com/firebase/friendlychat/tree/master/android

Here's styles.xml:

<resources>

</resources>

Here's activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.google.firebase.codelab.friendlychat.MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/messageRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linearLayout"
        android:layout_below="@+id/adView"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">

        <ImageView
            android:id="@+id/addMessageImageView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_add_black_24dp"/>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/messageEditText"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SEND"
            android:enabled="false"
            android:id="@+id/sendButton"
            android:layout_gravity="bottom"/>

    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

Body:
Google has Design support library and with it you can implement Collapsing Toolbar and you do not need any 3rd party libraries!!

In addition to pinning a view, you can use  app:layout_collapseMode="parallax" (and optionally app:layout_collapseParallaxMultiplier="0.7" to set the parallax multiplier) to implement parallax scrolling (say of a sibling ImageView within the CollapsingToolbarLayout)

And as example you can use this:

<android.support.design.widget.AppBarLayout
    android:layout_height="186dp"
    android:layout_width="match_parent">
<android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">
    <android.support.v7.widget.Toolbar
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            app:layout_collapseMode="pin"/>
    </android.support.design.widget.CollapsingToolbarLayout>

And do not forget to add compile "com.android.support:design:25.3.1" in your module  build.gradle

UPDATE 1:
First of all, you need to create a CoordinatorLayout.

All the new components use a new concept called Behavior that is used by the Coordinator Layout to take some actions based on different interactions.

<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true">

</android.support.design.widget.CoordinatorLayout>

You can use fitsSystemWindows on any item you want to be painted below the status bar.

Then you need to add an AppBarLayout:

<android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

</android.support.design.widget.AppBarLayout>

And then inside that, you can add something like:

<android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleMarginEnd="64dp"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>


问:
How to check if an object in an empty state?
How to check if an object with animator is currently in an empty state?

I need to disable the object using SetActive(false), so that:

if the object is in transition between states - finish the transition and then disable it.

if the object is in default empty state - disable it immediately.

This code works if the object is in transition, but doesn't work if it is in empty state:

```<code>MyObject.GetComponent<Animator>().IsInTransition(0)
</code>```

答:
Ok here's how I did it.

I'm assuming you know the name of your "default empty state" that you want to disable your object in.

Declare a static int variable which has the "default empty state" as a string to hash like this:

```<code> static int VAR-NAME = Animator.StringToHash("Base.NAMEOFSTATE");
</code>```

This is assuming that your base layer is called "Base".

Then in Update(), put the current state in a variable like this:

```<code>currentState = anim.GetCurrentAnimatorStateInfo(0);
</code>```

and then use an If statement to check if your "default empty state" is equal to the current state like this:

```<code>if (currentState.nameHash == VAR-NAME){
      Debug.Log("Do Stuff Here");
 }
</code>```

Have fun coding!

Body:
How to check if an object with animator is currently in an empty state?

I need to disable the object using SetActive(false), so that:

if the object is in transition between states - finish the transition and then disable it.

if the object is in default empty state - disable it immediately.

This code works if the object is in transition, but doesn't work if it is in empty state:

MyObject.GetComponent<Animator>().IsInTransition(0)

Body:
Ok here's how I did it.

I'm assuming you know the name of your "default empty state" that you want to disable your object in.

Declare a static int variable which has the "default empty state" as a string to hash like this:

 static int VAR-NAME = Animator.StringToHash("Base.NAMEOFSTATE");

This is assuming that your base layer is called "Base".

Then in Update(), put the current state in a variable like this:

currentState = anim.GetCurrentAnimatorStateInfo(0);

and then use an If statement to check if your "default empty state" is equal to the current state like this:

if (currentState.nameHash == VAR-NAME){
      Debug.Log("Do Stuff Here");
 }

Have fun coding!


问:
How can I call a method and pass arguments when a button is clicked?
I this code:

```<code>        correctButton.Clicked += (sender, e) =>
        {
            App.DB.IncrementScore(AS.cfs, AS.phrase);

            correctAns++;
            AS.pointsCount[(int)AS.cfs]++;
            scoreCountLabel.Text = FontAwesome.FAStop.Repeat(correctAns);
            Device.StartTimer(TimeSpan.FromSeconds(0.5), () =>
            {
                switch (AS.cardOrder)
                {
                    case CardOrder.FirstToLast:
                        AS.orderPhraseIndex++;
                        AS.phraseIndexList.Add(AS.orderPhraseIndex);
                        getPhraseFirstToLast();
                        break;
                    case CardOrder.Random:
                        getRandomNumber();
                        getRandomPhrase();
                        break;
                }
                return false;
            });
        };
</code>```

I would like to move the code that's run into a method and pass the arguments also.  But how can I call that method when the correctButton is clicked?

答:
```<code>correctButton.Clicked += correctButtonClicked;

protected void correctButtonClicked(object sender, EventArgs e)
{
  // code goes here
}
</code>```

Body:
I this code:

        correctButton.Clicked += (sender, e) =>
        {
            App.DB.IncrementScore(AS.cfs, AS.phrase);

            correctAns++;
            AS.pointsCount[(int)AS.cfs]++;
            scoreCountLabel.Text = FontAwesome.FAStop.Repeat(correctAns);
            Device.StartTimer(TimeSpan.FromSeconds(0.5), () =>
            {
                switch (AS.cardOrder)
                {
                    case CardOrder.FirstToLast:
                        AS.orderPhraseIndex++;
                        AS.phraseIndexList.Add(AS.orderPhraseIndex);
                        getPhraseFirstToLast();
                        break;
                    case CardOrder.Random:
                        getRandomNumber();
                        getRandomPhrase();
                        break;
                }
                return false;
            });
        };

I would like to move the code that's run into a method and pass the arguments also.  But how can I call that method when the correctButton is clicked?


问:
Finding list of installed apps on iphone
Is it possible to programatically find out name of all apps installed on my iOS device ?
Is there any API available for same ?

Thanks for the help

答:
You can use runtime objective c to get the list of all installed apps. It will give you an array of LSApplicationProxy objects.

Following is a code snippet that prints Name of all applications installed in your device.

```<code>Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
NSObject* workspace = [LSApplicationWorkspace_class performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSMutableArray *array = [workspace performSelector:NSSelectorFromString(@"allApplications")];

NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for (id lsApplicationProxy in array) {
    if(nil != [lsApplicationProxy performSelector:NSSelectorFromString(@"itemName")]){
        [mutableArray addObject:[lsApplicationProxy performSelector:NSSelectorFromString(@"itemName")]];
    }
}
NSLog(@"********* Applications List ************* : \n %@",mutableArray);
</code>```

Don't forget to include <objc/runtime.h> .

Body:
You can use runtime objective c to get the list of all installed apps. It will give you an array of LSApplicationProxy objects.

Following is a code snippet that prints Name of all applications installed in your device.

Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
NSObject* workspace = [LSApplicationWorkspace_class performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSMutableArray *array = [workspace performSelector:NSSelectorFromString(@"allApplications")];

NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for (id lsApplicationProxy in array) {
    if(nil != [lsApplicationProxy performSelector:NSSelectorFromString(@"itemName")]){
        [mutableArray addObject:[lsApplicationProxy performSelector:NSSelectorFromString(@"itemName")]];
    }
}
NSLog(@"********* Applications List ************* : \n %@",mutableArray);

Don't forget to include <objc/runtime.h> .


问:
Javascript: convert a multidimensional array to object in ajax
I try to send a javascript array to php using ajax he's what I did

```<code>var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}
</code>```

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

```<code>$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});
</code>```

In the network tab i find

```<code>date    "2017-07-08"
</code>```

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php

答:
Can simplify this using map() and by using an object for each item:

```<code>var arr = $('select').map(function() {
  return {
    val:  this.value,
    id:   this.id,
    type: $(this).attr('type')
  }
}).get();
</code>```

Body:
I try to send a javascript array to php using ajax he's what I did

var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});

In the network tab i find

date    "2017-07-08"

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php

Body:
Can simplify this using map() and by using an object for each item:

var arr = $('select').map(function() {
  return {
    val:  this.value,
    id:   this.id,
    type: $(this).attr('type')
  }
}).get();


问:
Canonical URLs and Google
As far as Google and canonical URLs go - is there any advantage to adding a 301 redirect from:

http://www.mydomain.com/index.php

to

http://www.mydomain.com/

答: I don't think there's any advantage of using a redirect..for one thing, it will add loading time to your page, and Google also ranks pages according to speed.</p>

Title: Canonical URLs and Google


问:
How to group SQL Value if the column is same value
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

```<code>CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);
</code>```

After Insert VALUES

```<code>SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much
</code>```

What I've been trying to do is to

```<code>Select * FROM DATA WHERE Sender = 'SEND1'
</code>```

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

答:
As you were suggested in the comments you can add an integer autoincrementing column Num in this way:

```<code>CREATE TABLE Data
(
Num integer IDENTITY(1,1),
Sender              VARCHAR(255),
Receiver            VARCHAR(255),
MSG                 VARCHAR(255),
);
</code>```

Hence, the latest message has the highest number. Then you add values:

```<code>insert into Data values ('SEND1','REC1','Hey whats up')

insert into Data values ('SEND1','REC2','Yoo how are you')

insert into Data values ('SEND1','REC1','Nothing much')
</code>```

Finally, you should try to run this query:

```<code>select * from Data
where Num in (
  select max(Num) from Data
      group by Sender, Receiver)
</code>```

Body:
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);

After Insert VALUES

SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much

What I've been trying to do is to

Select * FROM DATA WHERE Sender = 'SEND1'

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

Body:
As you were suggested in the comments you can add an integer autoincrementing column Num in this way:

CREATE TABLE Data
(
Num integer IDENTITY(1,1),
Sender              VARCHAR(255),
Receiver            VARCHAR(255),
MSG                 VARCHAR(255),
);

Hence, the latest message has the highest number. Then you add values:

insert into Data values ('SEND1','REC1','Hey whats up')

insert into Data values ('SEND1','REC2','Yoo how are you')

insert into Data values ('SEND1','REC1','Nothing much')

Finally, you should try to run this query:

select * from Data
where Num in (
  select max(Num) from Data
      group by Sender, Receiver)