问:
move all .cpp & .h in a filter to another project AND correct their folder location
Here is filter of my project in Visual Studio shown in Solution Explorer :-

```<code>ProjectName1
== References, External Dependencies, Header Files, Resource Files
== Source Files
==== myFilter01
------ K.h               (system folder = `D:\ProjectName1\K.h`)
------ K.cpp             (system folder = `D:\ProjectName1\K.cpp`)
==== myFilter02
====== subFilter2_1
--------- B.h            (system folder = `D:\ProjectName1\B.h`)
--------- B.cpp          (system folder = `D:\ProjectName1\B.cpp`)
========= subFilter2_2
----------- C.h          (system folder = `D:\ProjectName1\C.h`)
----------- C.cpp        (system folder = `D:\ProjectName1\C.cpp`)
ProjectName2
== ... (some existing filter/files)
</code>```

(In real case, all filters contains a lot of sub-sub-filter and files.)

Question

How to :

move all .h and .cpp files (B and C) inside myFilter02 to ProjectName2's folder (e.g. D:\ProjectName2)

don't change appearance of the filter (e.g. C must be still in subFilter2_1\subFilter2_2)

and do it in a few clicks (i.e. not depend on amount of files/sub-filters) i.e. O(1)

Here is the expected result :-

```<code>ProjectName1
== References, External Dependencies, Header Files, Resource Files
== Source Files
==== myFilter01
------ K.h               (system folder = `D:\ProjectName1\K.h` )
------ K.cpp             (system folder = `D:\ProjectName1\K.cpp` )
==== myFilter02
ProjectName2
== ... (some existing filter/files)
== subFilter2_1
----- B.h                (system folder = `D:\ProjectName2\B.h` )
----- B.cpp              (system folder = `D:\ProjectName2\B.cpp` )
===== subFilter2_2
------- C.h              (system folder = `D:\ProjectName2\C.h` )
------- C.cpp            (system folder = `D:\ProjectName2\C.cpp` )
</code>```

It can be done manually for each sub-sub-sub-filter + add existing files, but it is very tedious.

I tried to right click the filter/files, but didn't found such feature.

I currently don't use any Microsoft's source control / repository (just in case it is related).

Note: The normal drag & drop on filters don't move the files to another project's folder.

It just makes the moved files to be a shortcut of the original location (D:\ProjectName1\).

Hotkey?  Plugin?  Script?

Do I really have to create a program to do this specific thing?

A few days after asking, I have coded it with c++ using RapidXML ~ 500-1000 lines.

I have to edit .vcxproj.filters and .vcxproj of both projects, and move some system files.

I still find no answer about the question, though.

Edit

(After receive advise from Hans Passant and  Prab, thank!)

I want to use filter rather than folder for these reasons :-

Source control is easier, because all source files are in a same directory.

In Visual Studio, I can move files around different filters a little easier than around folders.

With Filter, I don't have to lengthen #include "../myFilter01/K.h" or add additional include directories for each folder.   I can simple #include "K.h".

If I change the place where a file resides in a filter, I don't have to refactor it.

In case of changing folder, I have to refactor code.

I can use very strange character e.g.  =◆██myFilter01██◆= for filters but not folder.  It is my taste.

I don't want to

Use folder instead of filter :   Beside difficulty of recreate many folders and move my .cpp/.h files manually, I will suffer the above disadvantages.

Use folder with same structure as filter :  I have to keep it in sync together manually (all the time - tedious).  I will still get some the above disadvantages.

In summary, using folder instead of filter causes me more new trouble than it solves.

答:
It's not one click solution but it could be done faster then manual.

Find out what file need to be copied. To do that move filters from one project to another. Then switch to directory view (show all files) for first project and copy but not past files with small red indicator (files that are not included in the project). Now get back to filter view for both project and move back filters to first project. After that switch both projects to directory view and do pass on second project.

Now we need to create correct filters. Move files from source and header filter to another filters in second project. Unload both projects. Open first and second project .filters files copy from first file to second all filter tags except "Source Files", "Header Files", "Resource Files". Next from second file remove all tags started with source or header. Now from second ItemGroup copy whole content and pass it to second file second ItemGroup. Save second file.

In this point you should have copy of first project filter tree without unnecessary files now just move what you want to correct places.

It is helpful to create single tree in first project.

Body:
Here is filter of my project in Visual Studio shown in Solution Explorer :-

ProjectName1
== References, External Dependencies, Header Files, Resource Files
== Source Files
==== myFilter01
------ K.h               (system folder = `D:\ProjectName1\K.h`)
------ K.cpp             (system folder = `D:\ProjectName1\K.cpp`)
==== myFilter02
====== subFilter2_1
--------- B.h            (system folder = `D:\ProjectName1\B.h`)
--------- B.cpp          (system folder = `D:\ProjectName1\B.cpp`)
========= subFilter2_2
----------- C.h          (system folder = `D:\ProjectName1\C.h`)
----------- C.cpp        (system folder = `D:\ProjectName1\C.cpp`)
ProjectName2
== ... (some existing filter/files)

(In real case, all filters contains a lot of sub-sub-filter and files.)

Question

How to :

move all .h and .cpp files (B and C) inside myFilter02 to ProjectName2's folder (e.g. D:\ProjectName2)

don't change appearance of the filter (e.g. C must be still in subFilter2_1\subFilter2_2)

and do it in a few clicks (i.e. not depend on amount of files/sub-filters) i.e. O(1)

Here is the expected result :-

ProjectName1
== References, External Dependencies, Header Files, Resource Files
== Source Files
==== myFilter01
------ K.h               (system folder = `D:\ProjectName1\K.h` )
------ K.cpp             (system folder = `D:\ProjectName1\K.cpp` )
==== myFilter02
ProjectName2
== ... (some existing filter/files)
== subFilter2_1
----- B.h                (system folder = `D:\ProjectName2\B.h` )
----- B.cpp              (system folder = `D:\ProjectName2\B.cpp` )
===== subFilter2_2
------- C.h              (system folder = `D:\ProjectName2\C.h` )
------- C.cpp            (system folder = `D:\ProjectName2\C.cpp` )

It can be done manually for each sub-sub-sub-filter + add existing files, but it is very tedious.

I tried to right click the filter/files, but didn't found such feature.

I currently don't use any Microsoft's source control / repository (just in case it is related).

Note: The normal drag & drop on filters don't move the files to another project's folder.

It just makes the moved files to be a shortcut of the original location (D:\ProjectName1\).

Hotkey?  Plugin?  Script?

Do I really have to create a program to do this specific thing?

A few days after asking, I have coded it with c++ using RapidXML ~ 500-1000 lines.

I have to edit .vcxproj.filters and .vcxproj of both projects, and move some system files.

I still find no answer about the question, though.

Edit

(After receive advise from Hans Passant and  Prab, thank!)

I want to use filter rather than folder for these reasons :-

Source control is easier, because all source files are in a same directory.

In Visual Studio, I can move files around different filters a little easier than around folders.

With Filter, I don't have to lengthen #include "../myFilter01/K.h" or add additional include directories for each folder.   I can simple #include "K.h".

If I change the place where a file resides in a filter, I don't have to refactor it.

In case of changing folder, I have to refactor code.

I can use very strange character e.g.  =◆██myFilter01██◆= for filters but not folder.  It is my taste.

I don't want to

Use folder instead of filter :   Beside difficulty of recreate many folders and move my .cpp/.h files manually, I will suffer the above disadvantages.

Use folder with same structure as filter :  I have to keep it in sync together manually (all the time - tedious).  I will still get some the above disadvantages.

In summary, using folder instead of filter causes me more new trouble than it solves.


来源: stackexchange

问:
Run jQuery Counter with value from MySQL
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

```<code><script type="text/javascript">

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: 99950,
            to: 100000,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

</script>
</code>```

HTML Code:

```<code><h2><span class="timer" style="color:#F44336;font-weight:700; font-size:20px;"></span></h2>
</code>```

答:
Do you mean, you want to get an sql query to the counter?
You could use AJAX for that, make a php file with an sql query and call it from the script using Ajax.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

HTML Code:


问:
Angular controllers: confused about the '$scope' parameter
```<code><div ng-app="myApp" ng-controller="myCtrl">

 <h1>{{carname}}</h1>

</div>

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

 app.controller('myCtrl', function($scope) {
     $scope.carname = "Volvo";
 });
</script>
</code>```

I thought $scope is merely the name of a parameter for the anonymous function, and you can't just assign it properties (carname) without it passing an object as the argument.

So does Angular automatically create an argument called something like myCtrlScope to pass to the $scope parameter? Otherwise, I don't see any way that an actually object is being passed to $scope, which is merely a parameter.

答:
use this Inline Array Annotation like this </p>

<p>

    </p>

```<code><div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', function($scope){
    $scope.carname = "volvo";
}]);
</script>

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

Body:
{{carname}}

I thought $scope is merely the name of a parameter for the anonymous function, and you can't just assign it properties (carname) without it passing an object as the argument.

So does Angular automatically create an argument called something like myCtrlScope to pass to the $scope parameter? Otherwise, I don't see any way that an actually object is being passed to $scope, which is merely a parameter.

Body:
use this Inline Array Annotation like this

<div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', function($scope){
    $scope.carname = "volvo";
}]);
</script>

</body>
</html>


问:
Insert shows all empty values
I am rather new to this library (knex) and have run across a problem I have not been able to find a solution for on the interwebs.

Here is my Knex connection:

```<code>Knex({client: 'pg', connection: config.DB, searchPath:'syp,public', debug: true})
</code>```

Here is my insert:

```<code>Knex('users')
    .returning('id')
    .insert(data)
    .then(function(user) {
      console.log(user);
    }, function(err) {
      console.log(err)
    });
</code>```

This is my data from the above query:

```<code>{
    "first_name": "Kenneth",
    "last_name": "Stowell",
    "email": "ken@bakuahtsu.codes" }
</code>```

The resulting error is:

```<code>code:"42703"
file:"parse_target.c"
length:119
line:"943"
name:"error"
position:"230"
routine:"checkInsertTargets"
severity:"ERROR"
</code>```

Which would make sense as the debugger is showing the following as the sql:

```<code>sql:"insert into "users" ("first_name", "last_name", "email") values (?, ?, ?) returning "id""
</code>```

I hope I am just making a newbie mistake but I cannot for the life of me figure out why. It appears to be making the bindings correctly but never applying them.

Any help appreciated!

答: The code 42703 is a postgres error code that means you're trying to insert data into a column that doesn't exist. </p>

Title: Insert shows all empty values

Body:
I am rather new to this library (knex) and have run across a problem I have not been able to find a solution for on the interwebs.

Here is my Knex connection:

Knex({client: 'pg', connection: config.DB, searchPath:'syp,public', debug: true})

Here is my insert:

Knex('users')
    .returning('id')
    .insert(data)
    .then(function(user) {
      console.log(user);
    }, function(err) {
      console.log(err)
    });

This is my data from the above query:

{
    "first_name": "Kenneth",
    "last_name": "Stowell",
    "email": "ken@bakuahtsu.codes" }

The resulting error is:

code:"42703"
file:"parse_target.c"
length:119
line:"943"
name:"error"
position:"230"
routine:"checkInsertTargets"
severity:"ERROR"

Which would make sense as the debugger is showing the following as the sql:

sql:"insert into "users" ("first_name", "last_name", "email") values (?, ?, ?) returning "id""

I hope I am just making a newbie mistake but I cannot for the life of me figure out why. It appears to be making the bindings correctly but never applying them.

Any help appreciated!


问:
Visual Studio Team Service: TF31002 Unable to connect to this Team Foundation Server
I have VS2013 Ultimate Update 5 and VS2015 Enterprise Update 1 installed on the same machine, Windows Server 2012 R2. Using VS2013 I'm able to connect to VSTS without anyn issues, however with VS2015 I'm getting the below connection failure:

Any help on how I can resolve this issues is much appreciated.

答:
While connecting, I was putting the project name also as part of the server URL.
It was a silly mistake but got connected after removing the project name from the URL.</p>


问:
`CI` return wrong value
I have no idea why my CI return wrong value from phpMyAdmin
Model :

```<code>    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>
</code>```

And

Controller :

```<code>    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '```';
    print_r($posts);

    }
}
?>
```

enter image description here

答:
If you want to get return your result as as array then use </p>

```<code>return $this->db->get('post')->result_array();
</code>```

<p>And if you want to get return your result as object then use </p>

```<code>return $this->db->get('post')->result();
</code>```

Title: `CI` return wrong value

Body:
I have no idea why my CI return wrong value from phpMyAdmin
Model :

    <?php

class Post extends CI_Model
{
function __construct()
{
    parent::__construct();

}
function getallpost()
{
    return $this->db->get('post');

}

}
?>

And

Controller :

    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Postc extends CI_Controller {
    function index()
    {
    $this->load->model('post');
    $posts=$this->post->getallpost();
    echo '
';
    print_r($posts);

    }
}
?>

enter image description here

Body:
If you want to get return your result as as array then use

return $this->db->get('post')->result_array();

And if you want to get return your result as object then use

return $this->db->get('post')->result();


问:
Passing JSON array to view CodeIgniter through AJAX
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

```<code>$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});
</code>```

This is the controller (Inventory)

```<code>public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}
</code>```

This is the model: Inventory_Model

```<code><?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}
</code>```

?>

答:
I think you have to set response type - json to get a json reponse.
By adding the line dataType:"json"

```<code>url: "index.php/Sales/topClients",
method: "GET",
dataType:"json"
</code>```

Body:
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});

This is the controller (Inventory)

public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}

This is the model: Inventory_Model

<?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}

?>

Body:
I think you have to set response type - json to get a json reponse.
By adding the line dataType:"json"

url: "index.php/Sales/topClients",
method: "GET",
dataType:"json"


问:
Convert an int to ASCII character
I have

```<code>int i = 6;
</code>```

and I want

```<code>char c = '6'
</code>```

by conversion. Any simple way to suggest?

EDIT:
also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.

答:
I suppose that

```<code>std::to_string(i)
</code>```

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

Title: Convert an int to ASCII character

Body:
I have

int i = 6;

and I want

char c = '6'

by conversion. Any simple way to suggest?

EDIT:
also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.

Body:
I suppose that

std::to_string(i)

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

ContentLicense: CC BY-SA 4.0


问:
How do I get the current version of my iOS project in code?
I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places.

The value needs to be updated when I bump my version in the Project target summary.

答:
Just for note

To obtain localized value of any key you should use CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), "CFBundleShortVersionString" as CFString)


问:
Adding matching labels to a dataframe after filter()
how can I match and add the associated strings in a column after using filter()?

```<code>x<- c("1","2","3","4")
y<- c("yes","no","maybe","NA")
df3<-cbind.data.frame(x,y)
unx<- unique(df3$x)
x<- c(1:10)
y<- LETTERS[1:10]
df4<-cbind.data.frame(x,y )
all<- df4 %>% filter(x %in% unx)
</code>```

To "all" I would like to add a column with the matching responses in y.

I am out of thoughts, what is the most efficient way of doing it? I would like to apply it to a large dataset. Any help will be much appreciated.

Thank you

答:
in dplyr a left_join() should do the trick.

In your question above, factors sneak in and x is being cast into different types; thus the complete answer would be to begin your script with options(stringsAsFactors = FALSE) (unless you choose to take the even better approach and start working with tibbles.)
Then the complete answer would be as below:

```<code>all <-
    df4 %>%
    filter(x %in% unx) %>%
    mutate(x = as.character(x)) %>%
    left_join(df3, by = "x")
</code>```

Body:
how can I match and add the associated strings in a column after using filter()?

x<- c("1","2","3","4")
y<- c("yes","no","maybe","NA")
df3<-cbind.data.frame(x,y)
unx<- unique(df3$x)
x<- c(1:10)
y<- LETTERS[1:10]
df4<-cbind.data.frame(x,y )
all<- df4 %>% filter(x %in% unx)

To "all" I would like to add a column with the matching responses in y.

I am out of thoughts, what is the most efficient way of doing it? I would like to apply it to a large dataset. Any help will be much appreciated.

Thank you

Body:
in dplyr a left_join() should do the trick.

In your question above, factors sneak in and x is being cast into different types; thus the complete answer would be to begin your script with options(stringsAsFactors = FALSE) (unless you choose to take the even better approach and start working with tibbles.)
Then the complete answer would be as below:

all <-
    df4 %>%
    filter(x %in% unx) %>%
    mutate(x = as.character(x)) %>%
    left_join(df3, by = "x")


问:
How to detect an iOS App installed or upgraded?
I am developing an application and i need to know whether user installed the app for the first time or upgraded it from the App Store.

How can i detect whether app is installed for the first time or upgraded or re-installed?

Thanks for your answers in advance.

答:
Just for note:

To obtain localized value of any key you should use CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), "CFBundleShortVersionString" as CFString)


问:
How to create repository and push code from server/cpanel to bitbucket
We have wordpress website and hosted on server. We got to know that GIT us already installed on our server. We checked it as well by ran command git --version

What we are trying is to push code from server to bit bucket via command line/SSH.

We have followed following steps but unable to complete process :

Created account on bit bucket.

Created blank repository

Run command git init <directory>, We can see .git file into server where code exists. i.e [public_html/website/]

Run command git add

Now really confuse that what we should do next? Should we create clone or add remote origin?

From SSH, We have run command git remote add origin user@bitbucket.org: pathtogit

But above command is not working[It returns me usage of command].

Have done lot of research for easy steps to push code from server to bitbucket but every search result has diff. methods and I am confused.

If command line is difficult then any easy way to achieve it via sourcetree?

答:
I have tried and tested this and it works.

login using ssh
go to public_html directory

Now type the following command

```<code>git clone repository_name
</code>```

where repository_name  is your bitbucket or github repo name

after you clone the repo you will get a a git folder

copy the .git file in you main root folder.

```<code> git add .
 git commit -m "message"
 git pull origin master
 git push -u origin master
</code>```

where master is your branch

Body:
I have tried and tested this and it works.

login using ssh
go to public_html directory

Now type the following command

git clone repository_name

where repository_name  is your bitbucket or github repo name

after you clone the repo you will get a a git folder

copy the .git file in you main root folder.

 git add .
 git commit -m "message"
 git pull origin master
 git push -u origin master

where master is your branch


问:
Generating PDFs with PHP
I have a PHP application and a need to generate a PDF with the result of query. The easiest way a found to do this was to use the DOMPDF to generate the PDF for me. So a made a function that generates the HTML for me then a pass this to DOMPDF. In the development and testing enviroment everything was fine but on production enviroment I had some problems with memory usage.

So I would like to know if my strategy was the best one or if there's a better and easy way to do this.

How would you do that?

答: I'm amazed nobody uses FOP:) http://xmlgraphics.apache.org/fop/ ... you basically feed it an XML flie and it generates a PDF file... very quick, and dosent kill your server.</p>

ContentLicense: CC BY-SA 2.5

Title: Generating PDFs with PHP

LastEditorDisplayName: John Topley

OwnerDisplayName: Misquamaqus


问:
Call React.render() multiple time throw error: _registerComponent(...): Target container is not a DOM element
From this question (Is it OK to use React.render() multiple times in the DOM?) it seem like we can call React.render() multiple times in a page. However when I tried following code I got " _registerComponent(...): Target container is not a DOM element." error on the second component.</p>

```<code>import React, {Component} from 'react';
import {render} from 'react-dom';
import {Button} from 'office-ui-fabric-react/lib/components/Button'
class App extends Component {

  render () {
    </div>;
    return(
        <div><Button>I am a button.</Button></div>

    )
  }
}

render(<App/>, document.getElementById('app'));
render(<App/>, document.getElementById('app2'));

<html>
  <head>
    <meta charset="utf-8">
  <title>React.js using NPM, Babel6 and Webpack</title>
  </head>
  <body>
    <div id="app" />
    <div id="app2" />
    <script src="public/bundle.js" type="text/javascript"></script>
  </body>
</html>
</code>```

答:
You have a closing div above the return statement in you render function,apart from that as stated in the docs of office-ui-fabric-react Button is being import from lib and not lib/components

Import it like

```<code>import { Button } from 'office-ui-fabric-react/lib/Button';
</code>```

class App extends React.Component {

  render () {

    return(

I am a button

    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
ReactDOM.render(<App/>, document.getElementById('app2'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
<div id="app2"></div></code>```

Body:
From this question (Is it OK to use React.render() multiple times in the DOM?) it seem like we can call React.render() multiple times in a page. However when I tried following code I got " _registerComponent(...): Target container is not a DOM element." error on the second component.

import React, {Component} from 'react';
import {render} from 'react-dom';
import {Button} from 'office-ui-fabric-react/lib/components/Button'
class App extends Component {

  render () {

;
    return(

<Button>I am a button.</Button>

    )
  }
}

render(<App/>, document.getElementById('app'));
render(<App/>, document.getElementById('app2'));

    <meta charset="utf-8">
  <title>React.js using NPM, Babel6 and Webpack</title>

Body:
You have a closing div above the return statement in you render function,apart from that as stated in the docs of office-ui-fabric-react Button is being import from lib and not lib/components

Import it like

import { Button } from 'office-ui-fabric-react/lib/Button';

class App extends React.Component {

  render () {

    return(
        <div>I am a button</div>

    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
ReactDOM.render(<App/>, document.getElementById('app2'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
<div id="app2"></div>


问:
JavaScript tag with rocket property
In the site: pro emoji keyboard online at http://www.emojiselector.com, I saw in source code, something as follows:

```<code><script data-rocketsrc="assets/web/assets/jquery/jquery.min.js" type="text/rocketscript"></script>
<script data-rocketsrc="assets/tether/tether.min.js" type="text/rocketscript"></script>
</code>```

What does this mean? data-rocketsrc, text/rocketscript??? I know for traditional tag in html is src and text/javascript. Is this another languages or another standards? I saw in code of JS, nothing is different!

答: HTML tags can contain custom attributes. These can be useful for implementing application-specific features. See "Using data attributes" over at MDN for more information.</p>

Title: JavaScript tag with rocket property

Body:
In the site: pro emoji keyboard online at http://www.emojiselector.com, I saw in source code, something as follows:

What does this mean? data-rocketsrc, text/rocketscript??? I know for traditional tag in html is src and text/javascript. Is this another languages or another standards? I saw in code of JS, nothing is different!


问:
Avoiding kubernetes scheduler to run all pods in single node of kubernetes cluster
I have one kubernetes cluster with 4 nodes and one master. I am trying to run 5 nginx pod in all nodes. Currently sometimes the scheduler runs all the pods in one machine and sometimes in different machine.

What happens if my node goes down and all my pods were running in same node? We need to avoid this.

How to enforce scheduler to run pods on the nodes in round-robin fashion, so that if any node goes down then at at least one node should have NGINX pod in running mode.

Is this possible or not? If possible, how can we achieve this scenario?

答:
I think the inter-pod anti-affinity feature will help you.
Inter-pod anti-affinity allows you to constrain which nodes your pod is eligible to schedule on based on labels on pods that are already running on the node. Here is an example.

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: nginx-service
  name: nginx-service
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx-service
  template:
    metadata:
      labels:
        service-type: nginx
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: service-type
                operator: In
                values:
                - nginx
            topologyKey: kubernetes.io/hostname
      containers:
      - name: nginx-service
        image: nginx:latest
</code>```

Note: I use preferredDuringSchedulingIgnoredDuringExecution here since you have more pods than nodes.

For more detailed information, you can refer to the Inter-pod affinity and anti-affinity (beta feature) part of following link:
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

Body:
I think the inter-pod anti-affinity feature will help you.
Inter-pod anti-affinity allows you to constrain which nodes your pod is eligible to schedule on based on labels on pods that are already running on the node. Here is an example.

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    run: nginx-service
  name: nginx-service
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx-service
  template:
    metadata:
      labels:
        service-type: nginx
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: service-type
                operator: In
                values:
                - nginx
            topologyKey: kubernetes.io/hostname
      containers:
      - name: nginx-service
        image: nginx:latest

Note: I use preferredDuringSchedulingIgnoredDuringExecution here since you have more pods than nodes.

For more detailed information, you can refer to the Inter-pod affinity and anti-affinity (beta feature) part of following link:
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/


问:
How can I open a socket on a specific url?
NOTE: I do not know c++ very well.
I am using a site hosting (000webhost.com) and I have a php script designed to receive the data, in a post request. The code I am currently using, which gets the HOST of 000webhost, which is not what I want, I want to use the url (SomeName.000webhostapp.com) but it is redirecting to the host.
Here is the code:

```<code>SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)gethostbyname("SomeName.000webhost.com")->h_addr);
</code>```

Thank you for any help provided.

答:
Sockets don't connect to a URL, they connect to a host and port.  The rest of the URL (i.e. the path part) is something you send through the socket, in an HTTP request, after you've connected.

It sounds like you're saying that you're trying to look up "SomeName.000webhostapp.com", but you're getting the IP address of "000webhost.com".  That's not surprising.  It's likely that your provider is using name-based virtual hosting, where all the subdomains are actually handled by a single server on a single IP address.

When you send your HTTP request, you need to include a Host: SomeName.000webhostapp.com header, as required by the HTTP 1.1 protocol.  Based on that header, the server knows which site to respond with.

Body:
NOTE: I do not know c++ very well.
I am using a site hosting (000webhost.com) and I have a php script designed to receive the data, in a post request. The code I am currently using, which gets the HOST of 000webhost, which is not what I want, I want to use the url (SomeName.000webhostapp.com) but it is redirecting to the host.
Here is the code:

SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)gethostbyname("SomeName.000webhost.com")->h_addr);

Thank you for any help provided.


问:
Python 2D array i C using ctypes
i'm trying to use a self written c lib to proces 2d array from python but with little success.

Here is my c code:

CamLibC.c

```<code>int TableCam(const int x, const int y, int **Array) {
    int i = 0;
    int j = 0;

    for (i; i < x; i++) {
        for (j; j < y; j++) {
            Array[i][j] = 1;
        };

    };
}
</code>```

cc -nostartfiles -shared -fPIC -o CamLibOS.os CamLibC.c

Now here is my python wrapper:

CamLibPy.py

```<code>import os,sys
import ctypes

dirname     = os.path.dirname(os.path.realpath(sys.argv[0]))
CamLibFile  = dirname + '/CamLibOS.os'

_CamLib = ctypes.CDLL(CamLibFile)
_CamLib.TableCam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]

def TableCam (A) :
    global _CamLib

    x = len(A)
    y = len(A[0])

    print('x: ', x, ' y: ', y);

    arrayType = ((ctypes.c_int * x) * y)
    array = arrayType()

    _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array)

    print(array)
</code>```

And my python code where i use the function:

Test.py

```<code>import CamLibPy
from numpy import zeros

Anum = zeros((3,3))
print('Start: ', Anum)

CamLibPy.TableCam(Anum)

print('Ended: ', Anum)
</code>```

In this test program i try to change all the zeros in the array to ones. but as soon as i try to run this is get the following output:

Start:  [[ 0.  0.  0.]  [ 0.  0.  0.]  [ 0.  0.  0.]]

x:  3  y:  3

Traceback (most recent call last):   File "/media/pi/USB
  DISK/Test/Test.py", line 7, in
      CamLibPy.TableCam(Anum)   File "/media/pi/USB DISK/Test/CamLibPy.py", line 21, in TableCam
      _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array) ctypes.ArgumentError: argument 3: : expected
  LP_c_long instance instead of c_long_Array_3_Array_3

it's saying it expected a c_long but i clearly used c_int to make the arrayType

Can somebody tell me what i did wrong?

答:
c_long is the same as c_int, but that is not the problem.

There are a number of issues:

The type of numpy.zeros is default float.

In the Python TableCam, A is never modified.

In the C TableCam, the 3rd parameter should be int* Array and the elements modified by computing i*y+j.  That also agrees with argtypes, which was correct.

The numpy array can be coerced to the right ctypes type.

Corrected code (on Windows, for my testing):

cam.c

```<code>#include <stdio.h>
__declspec(dllexport) void TableCam(const int x, const int y, int *Array)
{
    int i,j;
    for (i = 0; i < x; i++)
        for (j = 0; j < y; j++)
            Array[i*y+j] = 1;
}
</code>```

camlib.py

```<code>import ctypes

_CamLib = ctypes.CDLL('cam')
_CamLib.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
_CamLib.restype = None

def TableCam(A):
    x,y = A.shape
    array = A.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
    _CamLib.TableCam(x,y,array)
</code>```

test.py

```<code>import camlib
import numpy as np

Anum = np.zeros((3,3),dtype=np.int)
print('Start:')
print(Anum)
camlib.TableCam(Anum)
print('Ended:')
print(Anum)
</code>```

Output

```<code>Start:
[[0 0 0]
 [0 0 0]
 [0 0 0]]
Ended:
[[1 1 1]
 [1 1 1]
 [1 1 1]]
</code>```

Title: Python 2D array i C using ctypes

Body:
i'm trying to use a self written c lib to proces 2d array from python but with little success.

Here is my c code:

CamLibC.c

int TableCam(const int x, const int y, int **Array) {
    int i = 0;
    int j = 0;

    for (i; i < x; i++) {
        for (j; j < y; j++) {
            Array[i][j] = 1;
        };

    };
}

cc -nostartfiles -shared -fPIC -o CamLibOS.os CamLibC.c

Now here is my python wrapper:

CamLibPy.py

import os,sys
import ctypes

dirname     = os.path.dirname(os.path.realpath(sys.argv[0]))
CamLibFile  = dirname + '/CamLibOS.os'

_CamLib = ctypes.CDLL(CamLibFile)
_CamLib.TableCam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]

def TableCam (A) :
    global _CamLib

    x = len(A)
    y = len(A[0])

    print('x: ', x, ' y: ', y);

    arrayType = ((ctypes.c_int * x) * y)
    array = arrayType()

    _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array)

    print(array)

And my python code where i use the function:

Test.py

import CamLibPy
from numpy import zeros

Anum = zeros((3,3))
print('Start: ', Anum)

CamLibPy.TableCam(Anum)

print('Ended: ', Anum)

In this test program i try to change all the zeros in the array to ones. but as soon as i try to run this is get the following output:

Start:  [[ 0.  0.  0.]  [ 0.  0.  0.]  [ 0.  0.  0.]]

x:  3  y:  3

Traceback (most recent call last):   File "/media/pi/USB
  DISK/Test/Test.py", line 7, in
      CamLibPy.TableCam(Anum)   File "/media/pi/USB DISK/Test/CamLibPy.py", line 21, in TableCam
      _CamLib.TableCam(ctypes.c_int(x), ctypes.c_int(y), array) ctypes.ArgumentError: argument 3: : expected
  LP_c_long instance instead of c_long_Array_3_Array_3

it's saying it expected a c_long but i clearly used c_int to make the arrayType

Can somebody tell me what i did wrong?

Body:
c_long is the same as c_int, but that is not the problem.

There are a number of issues:

The type of numpy.zeros is default float.

In the Python TableCam, A is never modified.

In the C TableCam, the 3rd parameter should be int* Array and the elements modified by computing i*y+j.  That also agrees with argtypes, which was correct.

The numpy array can be coerced to the right ctypes type.

Corrected code (on Windows, for my testing):

cam.c

#include <stdio.h>
__declspec(dllexport) void TableCam(const int x, const int y, int *Array)
{
    int i,j;
    for (i = 0; i < x; i++)
        for (j = 0; j < y; j++)
            Array[i*y+j] = 1;
}

camlib.py

import ctypes

_CamLib = ctypes.CDLL('cam')
_CamLib.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
_CamLib.restype = None

def TableCam(A):
    x,y = A.shape
    array = A.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
    _CamLib.TableCam(x,y,array)

test.py

import camlib
import numpy as np

Anum = np.zeros((3,3),dtype=np.int)
print('Start:')
print(Anum)
camlib.TableCam(Anum)
print('Ended:')
print(Anum)

Output

Start:
[[0 0 0]
 [0 0 0]
 [0 0 0]]
Ended:
[[1 1 1]
 [1 1 1]
 [1 1 1]]


问:
Issue with parsing Go Command().Output()
I am using a third party tool in Go with the help of exec.Command and that program will print out a large integer value which obviously is in string format. I having trouble converting that string to int (or more specifically uint64).

Details:
(You can ignore what program it is etc. but after running it will return me a large integer)

```<code>cmd := exec.Command(app, arg0, arg1, arg3)
stdout, err := cmd.Output()
if err != nil {
    fmt.Println(err.Error())
    return
}
temp := string(stdout)
</code>```

After I ran above, I am trying to parse it as below

```<code>myanswer, err = strconv.Atoi(temp)  //I know this is not for uint64 but I am first trying for int but I actually need uint64 conversion
if err != nil {
    fmt.Println(err)
    return
}
</code>```

Problem here is that the stdout is appending \r\n to its output which AtoI is not able to parse and gives the error

strconv.Atoi: parsing "8101832828\r\n": invalid syntax

Can someone pls help me on how to convert this string output to a uint64 and also int format pls?

答:
The output contains special characters. First, you need to strip any these characters (e.g. \n or \r).

You can use strings.TrimSpace.

Then to parse a string as an int64, you would use:

```<code>if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}
</code>```

Body:
I am using a third party tool in Go with the help of exec.Command and that program will print out a large integer value which obviously is in string format. I having trouble converting that string to int (or more specifically uint64).

Details:
(You can ignore what program it is etc. but after running it will return me a large integer)

cmd := exec.Command(app, arg0, arg1, arg3)
stdout, err := cmd.Output()
if err != nil {
    fmt.Println(err.Error())
    return
}
temp := string(stdout)

After I ran above, I am trying to parse it as below

myanswer, err = strconv.Atoi(temp)  //I know this is not for uint64 but I am first trying for int but I actually need uint64 conversion
if err != nil {
    fmt.Println(err)
    return
}

Problem here is that the stdout is appending \r\n to its output which AtoI is not able to parse and gives the error

strconv.Atoi: parsing "8101832828\r\n": invalid syntax

Can someone pls help me on how to convert this string output to a uint64 and also int format pls?

Body:
The output contains special characters. First, you need to strip any these characters (e.g. \n or \r).

You can use strings.TrimSpace.

Then to parse a string as an int64, you would use:

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}


问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答:
Well marc, when you are using include, you can simply just set up a variable to use:

```<code><?php
  $var = "Testing";
  include("header.php");
?>
</code>```

In your header file:

```<code><?php
  echo $var;
?>
</code>```

Allow your previously defined variables are usable in any include you have.

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?

Body:
Well marc, when you are using include, you can simply just set up a variable to use:

<?php
  $var = "Testing";
  include("header.php");
?>

In your header file:

<?php
  echo $var;
?>

Allow your previously defined variables are usable in any include you have.


问:
Positioning div right under an a tag
I'm trying to make a drop down menu to appear right under the URL that opens it up. So far I've managed to make a menu appear, but I can't figure out how to position it properly. My HTML looks like this

```<code><div id="container">
  Content here
  <div class="line-gray-footer"></div>
  <div class="footer">
    <a href="#">Link 1</a> | <a id="langSwitch">English ▼</a>
    <div id="dropdown" class="drop-choices">
      <a class="choice" href="/de">Deutsch</a>
      <a class="choice" href="/fr">Français</a>
      <a class="choice" href="/it">Italiano</a>
      <a class="choice" href="/es">Español</a>
    </div>
  </div>
  <div class="morestuff">
  <table>
  <tr>
    <th>Test</th><th>Test</th>
  </tr>
  <tr>
    <td>A</td><td>b</td>
  </tr>
  </table>
  </div>
</div>
</code>```

CSS

```<code>#container{
  width:70%;
  background: red;
  margin: 0 auto;
  height:800px;
}
.line-gray-footer {
    background: #ececec none repeat scroll 0 0;
    height: 3px;
    margin: 10px 10px;
}
.footer {
    text-align: center;
}

.drop-choices.inuse {
    opacity: 1;
    visibility: visible;
    display: block;
}

.drop-choices {
    background-color: white;
    border: 1px solid gray;
    border: medium none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.24);
    display: none;
    line-height: normal;
    margin-top: 0;
    opacity: 0;
    position: absolute;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) 0s;
    visibility: hidden;
    white-space: nowrap;
    z-index: 100;

}

.drop-choices a.choice {
    border-bottom: 1px solid #edf1f3;
    color: #777;
    padding: 3px 12px;
    transition: all 0.1s ease 0s;
    cursor: pointer;
    display: block;
    padding: 2px 3px 1px;
}
.morestuff table{
  width: 100%;
  border: 1px solid black;
}
</code>```

Here is a jsFiddle URL of the whole thing https://jsfiddle.net/jaktav3t/

答: Add left:50%; in .drop-choices class so it will display in center of the div and also below of the dropdown.</p>

Title: Positioning div right under an a tag

Body:
I'm trying to make a drop down menu to appear right under the URL that opens it up. So far I've managed to make a menu appear, but I can't figure out how to position it properly. My HTML looks like this

  Content here

    Link 1 | English ▼

      Deutsch
      Français
      Italiano
      Español

    Test	Test

    A	b

CSS

#container{
  width:70%;
  background: red;
  margin: 0 auto;
  height:800px;
}
.line-gray-footer {
    background: #ececec none repeat scroll 0 0;
    height: 3px;
    margin: 10px 10px;
}
.footer {
    text-align: center;
}

.drop-choices.inuse {
    opacity: 1;
    visibility: visible;
    display: block;
}

.drop-choices {
    background-color: white;
    border: 1px solid gray;
    border: medium none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.24);
    display: none;
    line-height: normal;
    margin-top: 0;
    opacity: 0;
    position: absolute;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) 0s;
    visibility: hidden;
    white-space: nowrap;
    z-index: 100;

}

.drop-choices a.choice {
    border-bottom: 1px solid #edf1f3;
    color: #777;
    padding: 3px 12px;
    transition: all 0.1s ease 0s;
    cursor: pointer;
    display: block;
    padding: 2px 3px 1px;
}
.morestuff table{
  width: 100%;
  border: 1px solid black;
}

Here is a jsFiddle URL of the whole thing https://jsfiddle.net/jaktav3t/


问:
Python - UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 44: character maps to <undefined>
Using pandas on Python 3 Jupyter notebook, I got

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
  44: character maps to

error while trying to read a json file that looks like this:

```<code>{
    "Test1": {
        "A": "攻撃を続ける",
        "B": "残り資源",
        "C": "残りの資源を得るため小隊を修理し戦闘を続けろ："
    },
    "Test2": {
        "D": "{x} 日目",
        "E": "CC レベル {x}",
        "F": "本当にこれから全てのデバイスでこの基地を使用しますか？",
        "G": "この{social_network}アカウントには2つの基地が存在してます。基地の数は一人のプレイヤーにつき一つに限定されています。基地を選択するか、キャンセルしてください。",
    }
}
</code>```

Any idea how to solve this?

See full error message here

```<code>import pandas as pd

json_df = pd.read_json('input.json')
json_df
</code>```

EDIT: I have also tried reading the json with the JSON module, it still the same error.

答:
Your .json file is encoded as UTF-8. pd.read_json tries to decode it as CP1252. You need to make it decode it as UTF-8:

```<code>import pandas as pd

json_df = pd.read_json('input.json', encoding='UTF-8')
json_df
</code>```

Body:
Using pandas on Python 3 Jupyter notebook, I got

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
  44: character maps to

error while trying to read a json file that looks like this:

{
    "Test1": {
        "A": "攻撃を続ける",
        "B": "残り資源",
        "C": "残りの資源を得るため小隊を修理し戦闘を続けろ："
    },
    "Test2": {
        "D": "{x} 日目",
        "E": "CC レベル {x}",
        "F": "本当にこれから全てのデバイスでこの基地を使用しますか？",
        "G": "この{social_network}アカウントには2つの基地が存在してます。基地の数は一人のプレイヤーにつき一つに限定されています。基地を選択するか、キャンセルしてください。",
    }
}

Any idea how to solve this?

See full error message here

import pandas as pd

json_df = pd.read_json('input.json')
json_df

EDIT: I have also tried reading the json with the JSON module, it still the same error.

Body:
Your .json file is encoded as UTF-8. pd.read_json tries to decode it as CP1252. You need to make it decode it as UTF-8:

import pandas as pd

json_df = pd.read_json('input.json', encoding='UTF-8')
json_df


问:
App unable to find AVAudio BluetoothHFP Handsfree port Swift
In my app I want to check for the AVAudio portTypes already connected to the phone. The code below works for BluetoothA2DP and Headphones, but not BluetoothHFP when I connect the phone to my car handsfree. Can anyone help me?! I think have been through all the SO posts on Handsfree/AV/Bluetooth, and many others, but can't work out why it is not recognising the BluetoothHFP output portType. </p>

```<code>import AVFoundation

func startCheckAVConnection() {

    // set the AVAudioSession to allow bluetooth. This do/try/catch doesn't seem to make a difference if it is here or not.
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.allowBluetooth)
    } catch{
        print(error)
    }

    // Check possible outputs for handsfree
    let outputs = AVAudioSession.sharedInstance().currentRoute.outputs

    if outputs.count != 0 {
        for output in outputs {
            if output.portType == AVAudioSessionPortBluetoothA2DP {
                peripheralLabel.text = "connected to BluetoothA2DP"
            } else if output.portType == AVAudioSessionPortBluetoothHFP { // NOT RECOGNISED
                peripheralLabel.text = "connected to BluetoothHFP"
            } else if output.portType == AVAudioSessionPortHeadphones {
                peripheralLabel.text = "connected to Headphones"
            }
        }
    } else {
        peripheralLabel.text = "Please connect handsfree"
    }

    // Add observer for audioRouteChangeListener
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(TopVC.audioRouteChangeListener(_:)),
        name: NSNotification.Name.AVAudioSessionRouteChange,
        object: nil)
}
</code>```

答:
I needed to add setActive after setCategory.</p>

```<code> do { try AVAudioSession.sharedInstance().setActive(true)
        print("setActive")
    } catch {
        print(error)
    }
</code>```

Body:
In my app I want to check for the AVAudio portTypes already connected to the phone. The code below works for BluetoothA2DP and Headphones, but not BluetoothHFP when I connect the phone to my car handsfree. Can anyone help me?! I think have been through all the SO posts on Handsfree/AV/Bluetooth, and many others, but can't work out why it is not recognising the BluetoothHFP output portType.

import AVFoundation

func startCheckAVConnection() {

    // set the AVAudioSession to allow bluetooth. This do/try/catch doesn't seem to make a difference if it is here or not.
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.allowBluetooth)
    } catch{
        print(error)
    }

    // Check possible outputs for handsfree
    let outputs = AVAudioSession.sharedInstance().currentRoute.outputs

    if outputs.count != 0 {
        for output in outputs {
            if output.portType == AVAudioSessionPortBluetoothA2DP {
                peripheralLabel.text = "connected to BluetoothA2DP"
            } else if output.portType == AVAudioSessionPortBluetoothHFP { // NOT RECOGNISED
                peripheralLabel.text = "connected to BluetoothHFP"
            } else if output.portType == AVAudioSessionPortHeadphones {
                peripheralLabel.text = "connected to Headphones"
            }
        }
    } else {
        peripheralLabel.text = "Please connect handsfree"
    }

    // Add observer for audioRouteChangeListener
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(TopVC.audioRouteChangeListener(_:)),
        name: NSNotification.Name.AVAudioSessionRouteChange,
        object: nil)
}

Body:
I needed to add setActive after setCategory.

 do { try AVAudioSession.sharedInstance().setActive(true)
        print("setActive")
    } catch {
        print(error)
    }


问:
Android ViewPager Prev/Next Button
Okay, so I'm developing an Android app that utilises a ViewPager to display pages.

Within each page, I have a set of buttons to use for navigating between pages (in addition to the swiping between pages). These buttons are for "first page", "previous page", "next page" and "last page".

What I can't figure out how to do is engineer a mechanism to enable a page change on a button click.

Anyone have any ideas?

ETA: To better explain the setup, the buttons are declared within each page's layout, and are inflated with the rest of the layout within the PagerAdapter. My problem is that I can't reference the ViewPager from within the PagerAdapter. Or at least, I can't think of a way to do it.

答:
Update code

```<code>Button preButton = (Button)findViewById(R.id.pre_button);
        Button nextButton = (Button)findViewById(R.id.next_button);

        preButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()-1, true);

            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1, true);

            }
        });
</code>```

Title: Android ViewPager Prev/Next Button

Body:
Update code

Button preButton = (Button)findViewById(R.id.pre_button);
        Button nextButton = (Button)findViewById(R.id.next_button);

        preButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()-1, true);

            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1, true);

            }
        });


问:
Message error after deleting all rows (codeigniter)
I have made a program that fetch data from a database and show a table with different rows.

The problem is when i want to delete every single row in the table :/

After deleting all rows in a table i got this error:

Here is my home file:

```<code>    <tbody>
    <?php
        foreach($records as $record) {

            echo "<tr>
                      <td>".$record->id."</td>
                      <td>".$record->carrera."</td>
                      <td>".$record->nombre."</td>
                      <td>".$record->descripcion."</td>
                      <td>".$record->carga_horaria."</td>
                      <td align='center'>
                        <a href='".site_url('Home/edit')."/$record->id'>
                         <button type='button' class='btn btn-primary'>EDIT</button></a> |
                        <a href='".site_url('Home/delete')."/$record->id'>
                         <button type='button' class='btn btn-danger'>DELETE</button></a>

                  </tr>";
        }
    ?>

</tbody>
</code>```

Here is my controller file (with index and delete functions)

```<code>    class Home extends CI_Controller{

     public function __construct(){
         parent::__construct();

         $this->load->model("Crudmodel");

    }
    public function index(){

        $data['records'] = $this->Crudmodel->getRecords();

        $this->load->view('home', $data);

    }
    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('materias');

        redirect('Home/index');

    }
</code>```

Model file:

Dont know what to do :S

答:
Or you can do simply,</p>

```<code>if ($records) {
  foreach($records as $record) {
    // the rest of your code
  }
}
</code>```

Body:
I have made a program that fetch data from a database and show a table with different rows.

The problem is when i want to delete every single row in the table :/

After deleting all rows in a table i got this error:

Here is my home file:

    <?php
        foreach($records as $record) {

            echo "

                      ".$record->id."
                      ".$record->carrera."
                      ".$record->nombre."
                      ".$record->descripcion."
                      ".$record->carga_horaria."

                        id'>
                         <button type='button' class='btn btn-primary'>EDIT</button> |
                        id'>
                         <button type='button' class='btn btn-danger'>DELETE</button>

";
        }
    ?>

Here is my controller file (with index and delete functions)

    class Home extends CI_Controller{

     public function __construct(){
         parent::__construct();

         $this->load->model("Crudmodel");

    }
    public function index(){

        $data['records'] = $this->Crudmodel->getRecords();

        $this->load->view('home', $data);

    }
    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('materias');

        redirect('Home/index');

    }

Model file:

Dont know what to do :S

Body:
Or you can do simply,

if ($records) {
  foreach($records as $record) {
    // the rest of your code
  }
}


问:
Correctly Writing a Range Based Constructor
I had a question to do with writing a range based constructor for a class but couldn't find the right phrasing to search for help on google.

Suppose I am writing a simple class, like vector, which involves having a range based constructor that inserts elements from the range into the current container:

```<code>// foo.h
#ifndef FOO_H
#define FOO_H

#include <iostream>

class Foo {
public:
    Foo() {
        std::cout << "Default constructor called" << std::endl;
    }
    template<class InputIterator> Foo(InputIterator first, InputIterator last) {
        std::cout << "Range based constructor called" << std::endl;
    }

    Foo(size_t n, int val) {
        std::cout << "size_t, int constructor called" << std::endl;
    }

};

#endif // FOO_H
</code>```

and have a cpp file

```<code>#include <iostream>
#include <vector>
#include "foo.h"

using std::cout;    using std::endl;

int main() {
    std::vector<int> v(10, 5);
    Foo f_default;
    Foo f_range(v.begin(), v.end());
    Foo f_int(314, 159);       // want this to call size_t, int ctctr
    return 0;
}
</code>```

In the third line in main, we create a Foo f_int(314, 159) which intuitively we want to call the size_t, int constructor. However it is matching the generic template constructor for ranges instead. Is there a way issues like this are addressed in C++? I feel like I am incorrectly dealing with writing range based constructors.

I can imagine you can use template specialization maybe, but don't really see how.

An example where such a situation might happen is if we are writing a vector class where there is a constructor based on a size_t and default value (which would be templatised on the class but I simplified here) and another constructor based on iterator ranges.

答:
The constructor template is a better match in the third case because you're passing two int arguments, while the Foo(size_t n, int val) requires an int to size_t conversion for the first argument. If you modify your code to

```<code>Foo f_int(static_cast<size_t>(314), 159);
</code>```

the constructor you want is called. But of course, this is not a good solution because it's easy to accidentally call the wrong constructor. Instead, you can use SFINAE to drop the constructor template from the overload resolution set by ensuring the argument types are iterators.

```<code>template<class InputIterator,
         class = std::enable_if_t<
                    std::is_base_of<
                        std::input_iterator_tag,
                        typename std::iterator_traits<InputIterator>::iterator_category
                    >{}
                >
        >
Foo(InputIterator first, InputIterator last) {
    std::cout << "Range based constructor called" << std::endl;
}
</code>```

If you look at the table here, all iterators you can read from are InputIterators or derived types. So the code above is checking that the InputIterator type being passed to the constructor is of that type or something derived from that type.

Body:
I had a question to do with writing a range based constructor for a class but couldn't find the right phrasing to search for help on google.

Suppose I am writing a simple class, like vector, which involves having a range based constructor that inserts elements from the range into the current container:

// foo.h
#ifndef FOO_H
#define FOO_H

#include <iostream>

class Foo {
public:
    Foo() {
        std::cout << "Default constructor called" << std::endl;
    }
    template<class InputIterator> Foo(InputIterator first, InputIterator last) {
        std::cout << "Range based constructor called" << std::endl;
    }

    Foo(size_t n, int val) {
        std::cout << "size_t, int constructor called" << std::endl;
    }

};

#endif // FOO_H

and have a cpp file

#include <iostream>
#include <vector>
#include "foo.h"

using std::cout;    using std::endl;

int main() {
    std::vector<int> v(10, 5);
    Foo f_default;
    Foo f_range(v.begin(), v.end());
    Foo f_int(314, 159);       // want this to call size_t, int ctctr
    return 0;
}

In the third line in main, we create a Foo f_int(314, 159) which intuitively we want to call the size_t, int constructor. However it is matching the generic template constructor for ranges instead. Is there a way issues like this are addressed in C++? I feel like I am incorrectly dealing with writing range based constructors.

I can imagine you can use template specialization maybe, but don't really see how.

An example where such a situation might happen is if we are writing a vector class where there is a constructor based on a size_t and default value (which would be templatised on the class but I simplified here) and another constructor based on iterator ranges.

Body:
The constructor template is a better match in the third case because you're passing two int arguments, while the Foo(size_t n, int val) requires an int to size_t conversion for the first argument. If you modify your code to

Foo f_int(static_cast<size_t>(314), 159);

the constructor you want is called. But of course, this is not a good solution because it's easy to accidentally call the wrong constructor. Instead, you can use SFINAE to drop the constructor template from the overload resolution set by ensuring the argument types are iterators.

template<class InputIterator,
         class = std::enable_if_t<
                    std::is_base_of<
                        std::input_iterator_tag,
                        typename std::iterator_traits<InputIterator>::iterator_category
                    >{}
                >
        >
Foo(InputIterator first, InputIterator last) {
    std::cout << "Range based constructor called" << std::endl;
}

If you look at the table here, all iterators you can read from are InputIterators or derived types. So the code above is checking that the InputIterator type being passed to the constructor is of that type or something derived from that type.


问:
MVC Ajax prevent redirect to action controller
In my view I have a modal window, it have the next form...

```<code>@using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="container" id="editRecordForm">
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Author)
                @Html.TextBoxFor(model => model.Author, new { @class = "form-control", @style = "height:auto" })
                @Html.ValidationMessageFor(model => model.Author)
            </div>
        </div>
        <br/>
        <div class="row">
            <div class="col-md-6">
                @Html.LabelFor(model => model.Image)
                <input type="file" name="file" accept="image/*">
            </div>
        </div>
        <br />
        <input type="submit" value="Submit" class="btn btn-primary">
    </div>
}
</code>```

this is the JS that contains the ajax request

```<code><script>
    var formdata = new FormData($('form').get(0));
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                cache: false,
                data: formdata,
                success: function (status, data) {
                    console.log(data);
                }
            });
        }
        return false;
    });
</script>
</code>```

The action controller receives two parameters the model and file

```<code>[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
  var json = new
  {
      Success = true,
      StatusCode = "200",
      ErrorDesc = "OK",
      ErrorCode = "",
      NewId = ""
  };

  //some process

  return Json(json, JsonRequestBehavior.AllowGet);
}
</code>```

The problem is why when the controller action finish, it redirects to the action controller url

```<code>http://controller/action
</code>```

and it does not stay on the same page?

What Im doing wrong?

答:
The problem was the bad config on the javascript- ajax part

```<code>$('form').submit(function () {
    var formdata = new FormData($('form').get(0));
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            processData: false,
            contentType: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});
</code>```

thanks to Stephen for the help.

Body:
In my view I have a modal window, it have the next form...

@using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

                @Html.LabelFor(model => model.Author)
                @Html.TextBoxFor(model => model.Author, new { @class = "form-control", @style = "height:auto" })
                @Html.ValidationMessageFor(model => model.Author)

                @Html.LabelFor(model => model.Image)
                <input type="file" name="file" accept="image/*">

        <input type="submit" value="Submit" class="btn btn-primary">

}

this is the JS that contains the ajax request

The action controller receives two parameters the model and file

[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
  var json = new
  {
      Success = true,
      StatusCode = "200",
      ErrorDesc = "OK",
      ErrorCode = "",
      NewId = ""
  };

  //some process

  return Json(json, JsonRequestBehavior.AllowGet);
}

The problem is why when the controller action finish, it redirects to the action controller url

http://controller/action

and it does not stay on the same page?

What Im doing wrong?

Body:
The problem was the bad config on the javascript- ajax part

$('form').submit(function () {
    var formdata = new FormData($('form').get(0));
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            processData: false,
            contentType: false,
            data: formdata,
            success: function (status, data) {
                console.log(data);
            }
        });
    }
    return false;
});

thanks to Stephen for the help.


问:
Cordova build android - error: android sdk not found (but is installed and ANDROID_HOME set correctly on OS X)
On a fresh system I installed:

Android Studio (current version downloaded from https://developer.android.com/studio/index.html)

Oracle JDK 1.8.0_121

I then ran Android Studio and installed the default SDK, plus SDKs for versions 23, 22, 14, 11 and 8 (a selection of targets I've used for previous projects).  I downloaded platform tools 25.0.4 and SDK tools 26.0.1.

Then installed:

NodeJS

Phonegap

I set up my environment:

```<code>export ANDROID_HOME=~/Library/Android/sdk
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/
export PATH=$PATH:$ANDROID_HOME/bin:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
</code>```

I pulled my existing Cordova project from a local git repo and ran:

```<code>phonegap platform add android@5.1.1
</code>```

(because I have the plugin from https://github.com/Wizcorp/phonegap-facebook-plugin which has an issue that causes it to fail to build with the current version of the android platform spec; this command is suggested as a workaround)

```<code>phonegap build android
</code>```

This gave the error:

```<code>[phonegap] executing 'cordova build android ' ...
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
</code>```

Any suggestions what might be going wrong?

答:
The latest version of the SDK tools has removed support for a number of functions that the Cordova tools have been relying on, so no longer function correctly.  In order to use the latest Android SDK, you need to use version 6.2.0 of the Android platform module.  This hasn't been officially released yet, but is up on the NPM repository so can be used like this:

```<code>cordova platform add android@6.2.0
</code>```

This clearly doesn't work with the phonegap-facebook-plugin module. Fortunately, there's a fork available that does work with this latest version:

```<code>cordova plugin rm phonegap-facebook-plugin
cordova plugin add cordova-plugin-facebook4 --variable APP_ID=appid --variable APP_NAME="app name here"
</code>```

I also had to hunt down references to phonegap-facebook-plugin in my config.xml file, because it kept coming back otherwise.

Body:
On a fresh system I installed:

Android Studio (current version downloaded from https://developer.android.com/studio/index.html)

Oracle JDK 1.8.0_121

I then ran Android Studio and installed the default SDK, plus SDKs for versions 23, 22, 14, 11 and 8 (a selection of targets I've used for previous projects).  I downloaded platform tools 25.0.4 and SDK tools 26.0.1.

Then installed:

NodeJS

Phonegap

I set up my environment:

export ANDROID_HOME=~/Library/Android/sdk
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/
export PATH=$PATH:$ANDROID_HOME/bin:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

I pulled my existing Cordova project from a local git repo and ran:

phonegap platform add android@5.1.1

(because I have the plugin from https://github.com/Wizcorp/phonegap-facebook-plugin which has an issue that causes it to fail to build with the current version of the android platform spec; this command is suggested as a workaround)

phonegap build android

This gave the error:

[phonegap] executing 'cordova build android ' ...
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.

Any suggestions what might be going wrong?

Body:
The latest version of the SDK tools has removed support for a number of functions that the Cordova tools have been relying on, so no longer function correctly.  In order to use the latest Android SDK, you need to use version 6.2.0 of the Android platform module.  This hasn't been officially released yet, but is up on the NPM repository so can be used like this:

cordova platform add android@6.2.0

This clearly doesn't work with the phonegap-facebook-plugin module. Fortunately, there's a fork available that does work with this latest version:

cordova plugin rm phonegap-facebook-plugin
cordova plugin add cordova-plugin-facebook4 --variable APP_ID=appid --variable APP_NAME="app name here"

I also had to hunt down references to phonegap-facebook-plugin in my config.xml file, because it kept coming back otherwise.


问:
The requested resource does not support http method 'POST' when sending multipart-form data
I have a controller like below:

```<code>[RoutePrefix("api/File")]
public class FileController : ApiController
{
        [HttpPost]
        [Route("Add")]
        public async Task<HttpResponseMessage> AddFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    if (key == "companyName")
                    {
                        var companyName = val;
                    }
                }
            }

            //Do whatever you want to do with your file here

            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
}
</code>```

If i do a post request in postman like in picture:

WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.MapHttpAttributeRoutes();

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.Formatters.Add(new BrowserJsonFormatter());
    }
}
</code>```

The function does not get hit

Any idea what I am doing wrong?

答:
Try changing the order in which you register the attribute routes:

```<code>// This must come first
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</code>```

Also if you always use attribute based routing I would recommend you removing the default route registration.

Body:
I have a controller like below:

[RoutePrefix("api/File")]
public class FileController : ApiController
{
        [HttpPost]
        [Route("Add")]
        public async Task<HttpResponseMessage> AddFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    if (key == "companyName")
                    {
                        var companyName = val;
                    }
                }
            }

            //Do whatever you want to do with your file here

            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
}

If i do a post request in postman like in picture:

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.MapHttpAttributeRoutes();

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.Formatters.Add(new BrowserJsonFormatter());
    }
}

The function does not get hit

Any idea what I am doing wrong?

Body:
Try changing the order in which you register the attribute routes:

// This must come first
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Also if you always use attribute based routing I would recommend you removing the default route registration.


问:
Why does host_statistics64() return inconsistent results?
Why does host_statistics64() in OS X 10.6.8 (I don't know if other versions have this problem) return counts for free, active, inactive, and wired memory that don't add up to the total amount of ram?  And why is it missing an inconsistent number of pages?

The following output represents the number of pages not classified as free, active, inactive, or wired over ten seconds (sampled roughly once per second).

```<code>458
243
153
199
357
140
304
93
181
224
</code>```

The code that produces the numbers above is:

```<code>#include <stdio.h>
#include <mach/mach.h>
#include <mach/vm_statistics.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char** argv) {
        struct vm_statistics64 stats;
        mach_port_t host    = mach_host_self();
        natural_t   count   = HOST_VM_INFO64_COUNT;
        natural_t   missing = 0;
        int         debug   = argc == 2 ? !strcmp(argv[1], "-v") : 0;
        kern_return_t ret;
        int           mib[2];
        long          ram;
        natural_t     pages;
        size_t        length;
        int           i;

        mib[0] = CTL_HW;
        mib[1] = HW_MEMSIZE;
        length = sizeof(long);
        sysctl(mib, 2, &ram, &length, NULL, 0);
        pages  = ram / getpagesize();

        for (i = 0; i < 10; i++) {
                if ((ret = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&stats, &count)) != KERN_SUCCESS) {
                        printf("oops\n");
                        return 1;
                }

                /* updated for 10.9 */
                missing = pages - (
                        stats.free_count     +
                        stats.active_count   +
                        stats.inactive_count +
                        stats.wire_count     +
                        stats.compressor_page_count
                );

                if (debug) {
                        printf(
                                "%11d pages (# of pages)\n"
                                "%11d free_count (# of pages free) \n"
                                "%11d active_count (# of pages active) \n"
                                "%11d inactive_count (# of pages inactive) \n"
                                "%11d wire_count (# of pages wired down) \n"
                                "%11lld zero_fill_count (# of zero fill pages) \n"
                                "%11lld reactivations (# of pages reactivated) \n"
                                "%11lld pageins (# of pageins) \n"
                                "%11lld pageouts (# of pageouts) \n"
                                "%11lld faults (# of faults) \n"
                                "%11lld cow_faults (# of copy-on-writes) \n"
                                "%11lld lookups (object cache lookups) \n"
                                "%11lld hits (object cache hits) \n"
                                "%11lld purges (# of pages purged) \n"
                                "%11d purgeable_count (# of pages purgeable) \n"
                                "%11d speculative_count (# of pages speculative (also counted in free_count)) \n"
                                "%11lld decompressions (# of pages decompressed) \n"
                                "%11lld compressions (# of pages compressed) \n"
                                "%11lld swapins (# of pages swapped in (via compression segments)) \n"
                                "%11lld swapouts (# of pages swapped out (via compression segments)) \n"
                                "%11d compressor_page_count (# of pages used by the compressed pager to hold all the compressed data) \n"
                                "%11d throttled_count (# of pages throttled) \n"
                                "%11d external_page_count (# of pages that are file-backed (non-swap)) \n"
                                "%11d internal_page_count (# of pages that are anonymous) \n"
                                "%11lld total_uncompressed_pages_in_compressor (# of pages (uncompressed) held within the compressor.) \n",
                                pages, stats.free_count, stats.active_count, stats.inactive_count,
                                stats.wire_count, stats.zero_fill_count, stats.reactivations,
                                stats.pageins, stats.pageouts, stats.faults, stats.cow_faults,
                                stats.lookups, stats.hits, stats.purges, stats.purgeable_count,
                                stats.speculative_count, stats.decompressions, stats.compressions,
                                stats.swapins, stats.swapouts, stats.compressor_page_count,
                                stats.throttled_count, stats.external_page_count,
                                stats.internal_page_count, stats.total_uncompressed_pages_in_compressor
                        );
                }

                printf("%i\n", missing);
                sleep(1);
        }

        return 0;
}
</code>```

答:
Just noticed that if you add compressor_page_count into the mix you get much closer to the actual amount of RAM in the machine.

This is an observation, not an explanation, and links to where this was properly documented would be nice to have!

Body:
Why does host_statistics64() in OS X 10.6.8 (I don't know if other versions have this problem) return counts for free, active, inactive, and wired memory that don't add up to the total amount of ram?  And why is it missing an inconsistent number of pages?

The following output represents the number of pages not classified as free, active, inactive, or wired over ten seconds (sampled roughly once per second).

458
243
153
199
357
140
304
93
181
224

The code that produces the numbers above is:

#include <stdio.h>
#include <mach/mach.h>
#include <mach/vm_statistics.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char** argv) {
        struct vm_statistics64 stats;
        mach_port_t host    = mach_host_self();
        natural_t   count   = HOST_VM_INFO64_COUNT;
        natural_t   missing = 0;
        int         debug   = argc == 2 ? !strcmp(argv[1], "-v") : 0;
        kern_return_t ret;
        int           mib[2];
        long          ram;
        natural_t     pages;
        size_t        length;
        int           i;

        mib[0] = CTL_HW;
        mib[1] = HW_MEMSIZE;
        length = sizeof(long);
        sysctl(mib, 2, &ram, &length, NULL, 0);
        pages  = ram / getpagesize();

        for (i = 0; i < 10; i++) {
                if ((ret = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&stats, &count)) != KERN_SUCCESS) {
                        printf("oops\n");
                        return 1;
                }

                /* updated for 10.9 */
                missing = pages - (
                        stats.free_count     +
                        stats.active_count   +
                        stats.inactive_count +
                        stats.wire_count     +
                        stats.compressor_page_count
                );

                if (debug) {
                        printf(
                                "%11d pages (# of pages)\n"
                                "%11d free_count (# of pages free) \n"
                                "%11d active_count (# of pages active) \n"
                                "%11d inactive_count (# of pages inactive) \n"
                                "%11d wire_count (# of pages wired down) \n"
                                "%11lld zero_fill_count (# of zero fill pages) \n"
                                "%11lld reactivations (# of pages reactivated) \n"
                                "%11lld pageins (# of pageins) \n"
                                "%11lld pageouts (# of pageouts) \n"
                                "%11lld faults (# of faults) \n"
                                "%11lld cow_faults (# of copy-on-writes) \n"
                                "%11lld lookups (object cache lookups) \n"
                                "%11lld hits (object cache hits) \n"
                                "%11lld purges (# of pages purged) \n"
                                "%11d purgeable_count (# of pages purgeable) \n"
                                "%11d speculative_count (# of pages speculative (also counted in free_count)) \n"
                                "%11lld decompressions (# of pages decompressed) \n"
                                "%11lld compressions (# of pages compressed) \n"
                                "%11lld swapins (# of pages swapped in (via compression segments)) \n"
                                "%11lld swapouts (# of pages swapped out (via compression segments)) \n"
                                "%11d compressor_page_count (# of pages used by the compressed pager to hold all the compressed data) \n"
                                "%11d throttled_count (# of pages throttled) \n"
                                "%11d external_page_count (# of pages that are file-backed (non-swap)) \n"
                                "%11d internal_page_count (# of pages that are anonymous) \n"
                                "%11lld total_uncompressed_pages_in_compressor (# of pages (uncompressed) held within the compressor.) \n",
                                pages, stats.free_count, stats.active_count, stats.inactive_count,
                                stats.wire_count, stats.zero_fill_count, stats.reactivations,
                                stats.pageins, stats.pageouts, stats.faults, stats.cow_faults,
                                stats.lookups, stats.hits, stats.purges, stats.purgeable_count,
                                stats.speculative_count, stats.decompressions, stats.compressions,
                                stats.swapins, stats.swapouts, stats.compressor_page_count,
                                stats.throttled_count, stats.external_page_count,
                                stats.internal_page_count, stats.total_uncompressed_pages_in_compressor
                        );
                }

                printf("%i\n", missing);
                sleep(1);
        }

        return 0;
}