问:
apache cordova in visual studio 2015/2017 does not build
when include the cordova plugin media capture it throws this exception:
C:........\BlankCordovaApp2\BlankCordovaApp2\platforms\android\src\org\apache\cordova\mediacapture\Capture.java:33: error: package org.apache.cordova.file does not exist   BlankCordovaApp2        1

Error       import org.apache.cordova.file.FileUtils;   BlankCordovaApp2        1

below are the plugin included:

```<code> <plugin name="cordova-plugin-device" spec="~1.1.7" />
  <plugin name="cordova-plugin-media-capture" spec="~1.4.3" />
  <plugin name="cordova-plugin-camera" spec="~2.4.1" />
  <plugin name="cordova-plugin-file" spec="~5.0.0" />
  <plugin name="cordova-plugin-file-transfer" spec="~1.7.0" />
</code>```

the cordova version is <vs:toolsetVersion>6.3.1</vs:toolsetVersion>

I am not sure why it still cannot find the File class even though the file and file transfer is already included. the same error appear when both file and file transfer is not included. the error shows up when media capture is included as the project can build without the media capture plugin. BUT media capture plugin is needed for the bardcode scanner plugin base from this tutorial: http://www.c-sharpcorner.com/UploadFile/020f8f/barcode-scanner-cross-platform-app-using-cordova-in-visual-s/

EDIT:

I tried to build the plugins one by one and turns out that the File Transfer plugin itself has problem because it cannot find FileTransfer class file, even though it self is included.

答:
Have you tried with a later version of Cordova? You find the version history at the Cordova Blog. Try installing the cordova@6.5.0 version globally from the command line:

```<code>  npm install -g cordova@6.5.0
</code>```

Later versions will give you other problems/quirks.

And in vs change config.xml to use the globally installed cordova version.

Your plugins have a mix of older and newer version numbers. Try removing and reinstalling them after the cordova upgrade without specifying version numbers. From the command line:

```<code>cordova plugin rm cordova-plugin-file
cordova plugin rm cordova-plugin-file-transfer
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
</code>```

/Big

Body:
when include the cordova plugin media capture it throws this exception:
C:........\BlankCordovaApp2\BlankCordovaApp2\platforms\android\src\org\apache\cordova\mediacapture\Capture.java:33: error: package org.apache.cordova.file does not exist   BlankCordovaApp2        1

Error       import org.apache.cordova.file.FileUtils;   BlankCordovaApp2        1

below are the plugin included:

 <plugin name="cordova-plugin-device" spec="~1.1.7" />
  <plugin name="cordova-plugin-media-capture" spec="~1.4.3" />
  <plugin name="cordova-plugin-camera" spec="~2.4.1" />
  <plugin name="cordova-plugin-file" spec="~5.0.0" />
  <plugin name="cordova-plugin-file-transfer" spec="~1.7.0" />

the cordova version is <vs:toolsetVersion>6.3.1</vs:toolsetVersion>

I am not sure why it still cannot find the File class even though the file and file transfer is already included. the same error appear when both file and file transfer is not included. the error shows up when media capture is included as the project can build without the media capture plugin. BUT media capture plugin is needed for the bardcode scanner plugin base from this tutorial: http://www.c-sharpcorner.com/UploadFile/020f8f/barcode-scanner-cross-platform-app-using-cordova-in-visual-s/

EDIT:

I tried to build the plugins one by one and turns out that the File Transfer plugin itself has problem because it cannot find FileTransfer class file, even though it self is included.

Body:
Have you tried with a later version of Cordova? You find the version history at the Cordova Blog. Try installing the cordova@6.5.0 version globally from the command line:

  npm install -g cordova@6.5.0

Later versions will give you other problems/quirks.

And in vs change config.xml to use the globally installed cordova version.

Your plugins have a mix of older and newer version numbers. Try removing and reinstalling them after the cordova upgrade without specifying version numbers. From the command line:

cordova plugin rm cordova-plugin-file
cordova plugin rm cordova-plugin-file-transfer
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer

/Big


来源: stackexchange

答:
you can use prettynum like this:

```<code>exportable <- as.data.table(
  rbind(
    c(prettyNum(total_nb_visits),
      total_nb_visits_y1,  round(((total_nb_visits - total_nb_visits_y1) / total_nb_visits_y1) * 100, 9)),
    c(total_nb_visitors,
      total_nb_visitors_y1,
      round(((total_nb_visitors - total_nb_visitors_y1) / total_nb_visitors_y1) * 100, 9)),
    c(CVR,CVR_y1, round((CVR-CVR_y1) / CVR_y1, 9))))
</code>```

the only downside is that it will convert the values to character but you will have your pretty output!

ContentLicense: CC BY-SA 3.0

Title: zeros in c() after round()

Body:
I'm trying to print a vector with:

total_nb_visits <- 20302079
total_nb_visits_y1 <- 19299803
total_nb_visitors <- 17707555
total_nb_visitors_y1 <- 17196674
CVR <- 0.02274954
CVR_y1 <- 0.02293334

When I do:

exportable <- rbind(c(total_nb_visits,total_nb_visits_y1,((total_nb_visits-total_nb_visits_y1)/total_nb_visits_y1)*100),
                    c(total_nb_visitors,total_nb_visitors_y1,((total_nb_visitors-total_nb_visitors_y1)/total_nb_visitors_y1)*100),
                    c(CVR,CVR_y1,((CVR-CVR_y1)/CVR_y1)))

I'm getting:

exportable
                  [,1]              [,2]         [,3]
[1,] 20302079.00000000 19299803.00000000  5.193192905
[2,] 17707555.00000000 17196674.00000000  2.970812844
[3,]        0.02274954        0.02293334 -0.008014533

And I'd like to get:

                  [,1]              [,2]         [,3]
[1,]          20302079          19299803  5.193192905
[2,]          17707555          17196674  2.970812844
[3,]        0.02274954        0.02293334 -0.008014533

And round() is not working...

I should add that I've been also playing with options(scipen=999) to delete the scientific notation...

Can anyone help me?

Thanks !

Body:
you can use prettynum like this:

exportable <- as.data.table(
  rbind(
    c(prettyNum(total_nb_visits),
      total_nb_visits_y1,  round(((total_nb_visits - total_nb_visits_y1) / total_nb_visits_y1) * 100, 9)),
    c(total_nb_visitors,
      total_nb_visitors_y1,
      round(((total_nb_visitors - total_nb_visitors_y1) / total_nb_visitors_y1) * 100, 9)),
    c(CVR,CVR_y1, round((CVR-CVR_y1) / CVR_y1, 9))))

the only downside is that it will convert the values to character but you will have your pretty output!


问:
PHP fileupload giving all filenames from array
I've been looking in this for a day or two now. When I upload multiple files to this script, "$finalfilename" gives me back multiple filenames from the second file.

Here's my code:

```<code>include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");

$valid_extensions = array(
    'jpeg',
    'jpg',
    'png',
    'gif',
    'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;

foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
    $imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
    $tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
    $timestamp = time();
    $extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
    $newfilename = sha1(time() . $i);
    $finalfilename = $newfilename . "." . $extension;
    if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
    {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    if ($uploadOK)
    {
        if (in_array($extension, $valid_extensions))
        {
            $path = $path . strtolower($finalfilename);
            if (move_uploaded_file($tmpname, $path))
            {

                // mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");

                echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
            }
            else
            {
                echo "error!";
            }
        }
    }

    $imgname = "";
    $tmpname = "";
    $timestamp = "";
    $extension = "";
    $newfilename = "";
    $finalfilename = "";
    $i++;
}
</code>```

As you can see, I tried resetting all the strings at the end before adding $i.

UPDATE

I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in

also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg

Which need to be separated.

I need to only get the filename of each file separately.

Thank you!

答:
Problem is in $path variable.

Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.

```<code>foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
    $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
    $imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
    $tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
    $timestamp = time();
    $extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
    $newfilename = sha1(time() . $i);
    $finalfilename = $newfilename . "." . $extension;
    if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
    {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    if ($uploadOK)
    {
        if (in_array($extension, $valid_extensions))
        {
            $path = $path . strtolower($finalfilename);
            if (move_uploaded_file($tmpname, $path))
            {

                // mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");

                echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
            }
            else
            {
                echo "error!";
            }
        }
    }

    $i++;
}
</code>```

There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.

ContentLicense: CC BY-SA 4.0

Body:
I've been looking in this for a day or two now. When I upload multiple files to this script, "$finalfilename" gives me back multiple filenames from the second file.

Here's my code:

include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");

$valid_extensions = array(
    'jpeg',
    'jpg',
    'png',
    'gif',
    'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;

foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
    $imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
    $tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
    $timestamp = time();
    $extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
    $newfilename = sha1(time() . $i);
    $finalfilename = $newfilename . "." . $extension;
    if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
    {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    if ($uploadOK)
    {
        if (in_array($extension, $valid_extensions))
        {
            $path = $path . strtolower($finalfilename);
            if (move_uploaded_file($tmpname, $path))
            {

                // mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");

                echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
            }
            else
            {
                echo "error!";
            }
        }
    }

    $imgname = "";
    $tmpname = "";
    $timestamp = "";
    $extension = "";
    $newfilename = "";
    $finalfilename = "";
    $i++;
}

As you can see, I tried resetting all the strings at the end before adding $i.

UPDATE

I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in

also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg

Which need to be separated.

I need to only get the filename of each file separately.

Thank you!

Body:
Problem is in $path variable.

Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.

foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
    $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
    $imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
    $tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
    $timestamp = time();
    $extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
    $newfilename = sha1(time() . $i);
    $finalfilename = $newfilename . "." . $extension;
    if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
    {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    if ($uploadOK)
    {
        if (in_array($extension, $valid_extensions))
        {
            $path = $path . strtolower($finalfilename);
            if (move_uploaded_file($tmpname, $path))
            {

                // mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");

                echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
            }
            else
            {
                echo "error!";
            }
        }
    }

    $i++;
}

There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.


问:
Access Global javascript variables inside AngularJS
I'm working on a site, and I started building it before I realized I needed some dynamic framework. After learning about AngularJS, I decided to use it, where I needed (not the whole site).

I have a very long script in JS, and I want to be able to get and set the variables from within AngularJS directives and controllers.

I found this answer, and it was quite good - I was able to get the variable from within the function. But when the variable changed outside the function, AngularJS' variable won't update.

My code looked something like this:

JS:

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

app.controller('PageController', ['$window','$scope', function($window,$scope){

    this.currentPage = $window.currentPage;

    this.isPage = function(page){
        return (page == this.currentPage);
    };
}]);

function button1onClick(){
    currentPage = 'Game';
}
</code>```

HTML:

```<code><div ng-controller="PageController">
    <div id="Game" ng-show="page.isPage('Game')">
        ...
    </div>
    <div id="Menu" ng-show="page.isPage('Menu')">
        ...
    </div>
</div>
</code>```

(button1onClick was called when I clicked some button on the page)

The idea is that I have two dives I want to switch between, using a globle variable. 'Menu' page was visible at first but upon clicking I was supposed to see only the 'Game' div.

The variable inside the controller didn't upadte, but was only given the initial value of currentPage.

I decided to use the $window service inside the isPage function, but this didn't work either. Only when I called a function that tested the $window.currentPage variable, the pages switched - like I wanted:

JS:

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

var currentPage = 'Menu';

app.controller('PageController', ['$window','$scope', function($window,$scope){

    this.isPage = function(page){
        return (page == $window.currentPage);
    };

    this.button2onClick = function() {
        $window.alert($window.currentPage);
    }
}]);

function button1onClick(){
    currentPage = 'Game';
}
</code>```

HTML:

```<code><button onclick="button1onClick()">CLICK ME</button> //Button 1
<div ng-controller="PageController">
    <button ng-click="page.button2onClick">CLICK ME</button> //Button 2

    <div id="Game" ng-show="page.isPage('Game')">
        ...
    </div>

    <div id="Menu" ng-show="page.isPage('Menu')">
        ...
    </div>
</div>
</code>```

So the only way I was able to update the pages is to call a function that tests the variable, thus updating the variable in AngularJS.

Is there a way to access a global variable without needing to test it to update it?

Am I doing something wrong? I don't want to convert my whole site to AngularJS-style, I like the code the way it is. Is AngularJS not the framework for me?

EDIT:

some things to clear out:

I'm new to AngularJS, so if you could explain what your answer does it would be great.

The whole reason why I do this instead of redirecting to another page is not to shut down socket.io 's connection

答:
It can be done using $rootScope. Variable initialize once can be accessible in other controllers.

```<code>function Ctrl1($scope, $rootScope) {
    $rootScope.GlobalJSVariableA= window.GlobalJSVariable;  }
</code>```

Any controller & any view can access it now

```<code>function CtrlN($scope, $rootScope) {
    $scope.GlobalJSVariableA= $rootScope.GlobalJSVariableA;
}
</code>```

Body:
I'm working on a site, and I started building it before I realized I needed some dynamic framework. After learning about AngularJS, I decided to use it, where I needed (not the whole site).

I have a very long script in JS, and I want to be able to get and set the variables from within AngularJS directives and controllers.

I found this answer, and it was quite good - I was able to get the variable from within the function. But when the variable changed outside the function, AngularJS' variable won't update.

My code looked something like this:

JS:

var app = angular.module('someName', []);
var currentPage = 'Menu';

app.controller('PageController', ['$window','$scope', function($window,$scope){

    this.currentPage = $window.currentPage;

    this.isPage = function(page){
        return (page == this.currentPage);
    };
}]);

function button1onClick(){
    currentPage = 'Game';
}

HTML:

        ...

        ...

(button1onClick was called when I clicked some button on the page)

The idea is that I have two dives I want to switch between, using a globle variable. 'Menu' page was visible at first but upon clicking I was supposed to see only the 'Game' div.

The variable inside the controller didn't upadte, but was only given the initial value of currentPage.

I decided to use the $window service inside the isPage function, but this didn't work either. Only when I called a function that tested the $window.currentPage variable, the pages switched - like I wanted:

JS:

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

var currentPage = 'Menu';

app.controller('PageController', ['$window','$scope', function($window,$scope){

    this.isPage = function(page){
        return (page == $window.currentPage);
    };

    this.button2onClick = function() {
        $window.alert($window.currentPage);
    }
}]);

function button1onClick(){
    currentPage = 'Game';
}

HTML:

<button onclick="button1onClick()">CLICK ME</button> //Button 1

    <button ng-click="page.button2onClick">CLICK ME</button> //Button 2

        ...

        ...

So the only way I was able to update the pages is to call a function that tests the variable, thus updating the variable in AngularJS.

Is there a way to access a global variable without needing to test it to update it?

Am I doing something wrong? I don't want to convert my whole site to AngularJS-style, I like the code the way it is. Is AngularJS not the framework for me?

EDIT:

some things to clear out:

I'm new to AngularJS, so if you could explain what your answer does it would be great.

The whole reason why I do this instead of redirecting to another page is not to shut down socket.io 's connection

Body:
It can be done using $rootScope. Variable initialize once can be accessible in other controllers.

function Ctrl1($scope, $rootScope) {
    $rootScope.GlobalJSVariableA= window.GlobalJSVariable;  }

Any controller & any view can access it now

function CtrlN($scope, $rootScope) {
    $scope.GlobalJSVariableA= $rootScope.GlobalJSVariableA;
}


问:
How do I represent my joins in Relational Algebra?
I am new to relational algebra and for my assignment I have to create two. I have written out the problem I have faced in SQL but I am unsure of how to represent such joins in relational algebra. Any help/pointers would be greatly appreciated.</p>

```<code>SELECT ps.FirstName AS StudentFirstName, ps.LastName AS StudentLastName, pst.FirstName AS StaffFirstName , pst.LastName AS StaffLastName, pg.FirstName AS GuardianFirstName, pg.LastName AS GuadianLastName, i.DateTimeReported, i.NatureOfIllness
FROM Incident i
JOIN Student s USING (StudentID)
JOIN Person ps ON (s.StudentID = ps.PersonID)
JOIN Staff st USING (StaffID)
JOIN Person pst ON (st.StaffID = pst.PersonID)
JOIN Guardian g USING (GuardianID)
JOIN Person pg ON (g.GuardianID = pg.PersonID)
WHERE i.DecisionMade IS NULL;
</code>```

答:
Those left joins you're doing are referred to in relational algebra as theta-joins, sometimes more specifically specifically as equijoins. You'll want to use the symbol that looks like a bow tie and write "StudentID = PersonID" underneath it (for the second join in your example). I can't do the fancy symbols, but http://en.wikipedia.org/wiki/Relational_algebra#.CE.B8-join_and_equijoin has some examples.

Also, there's nothing wrong with 6-way joins and they'll indeed happen in the real world.

OwnerDisplayName: Malachi

ContentLicense: CC BY-SA 2.5

Body:
I am new to relational algebra and for my assignment I have to create two. I have written out the problem I have faced in SQL but I am unsure of how to represent such joins in relational algebra. Any help/pointers would be greatly appreciated.

SELECT ps.FirstName AS StudentFirstName, ps.LastName AS StudentLastName, pst.FirstName AS StaffFirstName , pst.LastName AS StaffLastName, pg.FirstName AS GuardianFirstName, pg.LastName AS GuadianLastName, i.DateTimeReported, i.NatureOfIllness
FROM Incident i
JOIN Student s USING (StudentID)
JOIN Person ps ON (s.StudentID = ps.PersonID)
JOIN Staff st USING (StaffID)
JOIN Person pst ON (st.StaffID = pst.PersonID)
JOIN Guardian g USING (GuardianID)
JOIN Person pg ON (g.GuardianID = pg.PersonID)
WHERE i.DecisionMade IS NULL;

LastEditorDisplayName: Eddie


问:
PHP redirect without header() or meta
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?

答:
It is possible to use header() with require() when I use output buffering. That means that the whole script is buffered and first send when the script has come to an end.

I have done it by doing this

```<code>ob_start("ob_gzhandler");  //begin buffering the output

require_once('/classes/mysql.php');

// Some code where I access the database.

header('/somepage.php');
exit;

ob_flush(); //output the data in the buffer
</code>```

Title: PHP redirect without header() or meta

Body:
It is possible to use header() with require() when I use output buffering. That means that the whole script is buffered and first send when the script has come to an end.

I have done it by doing this

ob_start("ob_gzhandler");  //begin buffering the output

require_once('/classes/mysql.php');

// Some code where I access the database.

header('/somepage.php');
exit;

ob_flush(); //output the data in the buffer


问:
could configure jenkins slave in docker container from jenkins server in docker
I'm practicing docker in practice by manning.

The technical recipe is about configuring jenkins slave which is docker container.

Below is the Dockerfile for jenkins_slave

```<code>FROM ubuntu:latest
ENV DEBIAN_FRONTEND noninteractive
RUN groupadd -g 1000 jenkins_slave
RUN useradd -d /home/jenkins_slave -s /bin/bash \
-m jenkins_slave -u 1000 -g jenkins_slave
RUN echo jenkins_slave:jpass | chpasswd
RUN apt-get update && \
apt-get install -y openssh-server openjdk-8-jre wget iproute2
RUN mkdir -p /var/run/sshd
CMD ip route | grep "default via" \
| awk '{print $3}' && /usr/sbin/sshd -D
</code>```

I built docker images using the command

```<code>docker build -t jenkins_slave .
</code>```

Then I run the docker images as container using the command

```<code>$ docker run --name jenkins_slave -it -p 2222:22 jenkins_slave
172.17.0.1
</code>```

Then I run the jenkins server using the below docker command

```<code>$ docker run --name jenkins_server -p 8080:8080 -p 50000:50000 dockerinpractice/jenkins:server
</code>```

Below is the node configuration details -

Then I get the error message saying This agent is offline because Jenkins failed to launch the agent process on it

Below is the error stack trace

```<code>[12/07/17 08:50:00] [SSH] Opening SSH connection to 172.17.0.1:2222.
/var/jenkins_home/.ssh/known_hosts [SSH] No Known Hosts file was found at
/var/jenkins_home/.ssh/known_hosts. Please ensure one is created at this path and that Jenkins can read it.
Key exchange was not finished, connection is closed.
java.io.IOException: There was a problem while connecting to 172.17.0.1:2222
at com.trilead.ssh2.Connection.connect(Connection.java:834)
at com.trilead.ssh2.Connection.connect(Connection.java:703)
at com.trilead.ssh2.Connection.connect(Connection.java:617)
at hudson.plugins.sshslaves.SSHLauncher.openConnection(SSHLauncher.java:1284)
at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:804)
at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:793)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Caused by: java.io.IOException: Key exchange was not finished, connection is closed.
at com.trilead.ssh2.transport.KexManager.getOrWaitForConnectionInfo(KexManager.java:95)
at com.trilead.ssh2.transport.TransportManager.getConnectionInfo(TransportManager.java:237)
at com.trilead.ssh2.Connection.connect(Connection.java:786)
... 9 more
Caused by: java.io.IOException: The server hostkey was not accepted by the verifier callback
at com.trilead.ssh2.transport.KexManager.handleMessage(KexManager.java:548)
at com.trilead.ssh2.transport.TransportManager.receiveLoop(TransportManager.java:790)
at com.trilead.ssh2.transport.TransportManager$1.run(TransportManager.java:502)
... 1 more
</code>```

I have a simple build configuration called test but the build is not running since the slave is offline.

Any idea why the jenkins master is not identifying the slave server.

答: Just change the Host Key verification strategy to Non verfiying Verification Strategy in the node configuration.

Body:
I'm practicing docker in practice by manning.

The technical recipe is about configuring jenkins slave which is docker container.

Below is the Dockerfile for jenkins_slave

FROM ubuntu:latest
ENV DEBIAN_FRONTEND noninteractive
RUN groupadd -g 1000 jenkins_slave
RUN useradd -d /home/jenkins_slave -s /bin/bash \
-m jenkins_slave -u 1000 -g jenkins_slave
RUN echo jenkins_slave:jpass | chpasswd
RUN apt-get update && \
apt-get install -y openssh-server openjdk-8-jre wget iproute2
RUN mkdir -p /var/run/sshd
CMD ip route | grep "default via" \
| awk '{print $3}' && /usr/sbin/sshd -D

I built docker images using the command

docker build -t jenkins_slave .

Then I run the docker images as container using the command

$ docker run --name jenkins_slave -it -p 2222:22 jenkins_slave
172.17.0.1

Then I run the jenkins server using the below docker command

$ docker run --name jenkins_server -p 8080:8080 -p 50000:50000 dockerinpractice/jenkins:server

Below is the node configuration details -

Then I get the error message saying This agent is offline because Jenkins failed to launch the agent process on it

Below is the error stack trace

[12/07/17 08:50:00] [SSH] Opening SSH connection to 172.17.0.1:2222.
/var/jenkins_home/.ssh/known_hosts [SSH] No Known Hosts file was found at
/var/jenkins_home/.ssh/known_hosts. Please ensure one is created at this path and that Jenkins can read it.
Key exchange was not finished, connection is closed.
java.io.IOException: There was a problem while connecting to 172.17.0.1:2222
at com.trilead.ssh2.Connection.connect(Connection.java:834)
at com.trilead.ssh2.Connection.connect(Connection.java:703)
at com.trilead.ssh2.Connection.connect(Connection.java:617)
at hudson.plugins.sshslaves.SSHLauncher.openConnection(SSHLauncher.java:1284)
at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:804)
at hudson.plugins.sshslaves.SSHLauncher$2.call(SSHLauncher.java:793)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Caused by: java.io.IOException: Key exchange was not finished, connection is closed.
at com.trilead.ssh2.transport.KexManager.getOrWaitForConnectionInfo(KexManager.java:95)
at com.trilead.ssh2.transport.TransportManager.getConnectionInfo(TransportManager.java:237)
at com.trilead.ssh2.Connection.connect(Connection.java:786)
... 9 more
Caused by: java.io.IOException: The server hostkey was not accepted by the verifier callback
at com.trilead.ssh2.transport.KexManager.handleMessage(KexManager.java:548)
at com.trilead.ssh2.transport.TransportManager.receiveLoop(TransportManager.java:790)
at com.trilead.ssh2.transport.TransportManager$1.run(TransportManager.java:502)
... 1 more

I have a simple build configuration called test but the build is not running since the slave is offline.

Any idea why the jenkins master is not identifying the slave server.


问:
How to average time intervals?
In Oracle 10g I have a table that holds timestamps showing how long certain operations took. It has two timestamp fields: starttime and endtime. I want to find averages of the durations given by these timestamps.  I try:

```<code>select avg(endtime-starttime) from timings;
</code>```

But get:

SQL Error: ORA-00932: inconsistent
  datatypes: expected NUMBER got
  INTERVAL DAY TO SECOND

This works:

```<code>select
     avg(extract( second from  endtime - starttime) +
        extract ( minute from  endtime - starttime) * 60 +
        extract ( hour   from  endtime - starttime) * 3600) from timings;
</code>```

But is really slow.

Any better way to turn intervals into numbers of seconds, or some other way do this?

EDIT:
 What was really slowing this down was the fact that I had some endtime's before the starttime's. For some reason that made this calculation incredibly slow.  My underlying problem was solved by eliminating them from the query set.  I also just defined a function to do this conversion easier:

```<code>FUNCTION fn_interval_to_sec ( i IN INTERVAL DAY TO SECOND )
RETURN NUMBER
IS
  numSecs NUMBER;
BEGIN
  numSecs := ((extract(day from i) * 24
         + extract(hour from i) )*60
         + extract(minute from i) )*60
         + extract(second from i);
  RETURN numSecs;
END;
</code>```

答:
SQL Fiddle

Oracle 11g R2 Schema Setup:

Create a type to use when performing a custom aggregation:

```<code>CREATE TYPE IntervalAverageType AS OBJECT(
  total INTERVAL DAY(9) TO SECOND(9),
  ct    INTEGER,

  STATIC FUNCTION ODCIAggregateInitialize(
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateIterate(
    self        IN OUT IntervalAverageType,
    value       IN     INTERVAL DAY TO SECOND
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateTerminate(
    self        IN OUT IntervalAverageType,
    returnValue    OUT INTERVAL DAY TO SECOND,
    flags       IN     NUMBER
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateMerge(
    self        IN OUT IntervalAverageType,
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
);
/

CREATE OR REPLACE TYPE BODY IntervalAverageType
IS
  STATIC FUNCTION ODCIAggregateInitialize(
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
  IS
  BEGIN
    ctx := IntervalAverageType( INTERVAL '0' DAY, 0 );
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateIterate(
    self        IN OUT IntervalAverageType,
    value       IN     INTERVAL DAY TO SECOND
  ) RETURN NUMBER
  IS
  BEGIN
    IF value IS NOT NULL THEN
      self.total := self.total + value;
      self.ct    := self.ct + 1;
    END IF;
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateTerminate(
    self        IN OUT IntervalAverageType,
    returnValue    OUT INTERVAL DAY TO SECOND,
    flags       IN     NUMBER
  ) RETURN NUMBER
  IS
  BEGIN
    IF self.ct = 0 THEN
      returnValue := NULL;
    ELSE
      returnValue := self.total / self.ct;
    END IF;
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateMerge(
    self        IN OUT IntervalAverageType,
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
  IS
  BEGIN
    self.total := self.total + ctx.total;
    self.ct    := self.ct + ctx.ct;
    RETURN ODCIConst.SUCCESS;
  END;
END;
/
</code>```

Then you can create a custom aggregation function:

```<code>CREATE FUNCTION AVERAGE( difference INTERVAL DAY TO SECOND )
RETURN INTERVAL DAY TO SECOND
PARALLEL_ENABLE AGGREGATE USING IntervalAverageType;
/
</code>```

Query 1:

```<code>WITH INTERVALS( diff ) AS (
  SELECT INTERVAL '0' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '1' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '-1' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '8' HOUR FROM DUAL UNION ALL
  SELECT NULL FROM DUAL
)
SELECT AVERAGE( diff ) FROM intervals
</code>```

Results:

```<code>| AVERAGE(DIFF) |
|---------------|
|     0 2:0:0.0 |
</code>```

OwnerDisplayName: Justsalt

Title: How to average time intervals?

Body:
In Oracle 10g I have a table that holds timestamps showing how long certain operations took. It has two timestamp fields: starttime and endtime. I want to find averages of the durations given by these timestamps.  I try:

select avg(endtime-starttime) from timings;

But get:

SQL Error: ORA-00932: inconsistent
  datatypes: expected NUMBER got
  INTERVAL DAY TO SECOND

This works:

select
     avg(extract( second from  endtime - starttime) +
        extract ( minute from  endtime - starttime) * 60 +
        extract ( hour   from  endtime - starttime) * 3600) from timings;

But is really slow.

Any better way to turn intervals into numbers of seconds, or some other way do this?

EDIT:
 What was really slowing this down was the fact that I had some endtime's before the starttime's. For some reason that made this calculation incredibly slow.  My underlying problem was solved by eliminating them from the query set.  I also just defined a function to do this conversion easier:

FUNCTION fn_interval_to_sec ( i IN INTERVAL DAY TO SECOND )
RETURN NUMBER
IS
  numSecs NUMBER;
BEGIN
  numSecs := ((extract(day from i) * 24
         + extract(hour from i) )*60
         + extract(minute from i) )*60
         + extract(second from i);
  RETURN numSecs;
END;

LastEditorDisplayName: Justsalt

Body:
SQL Fiddle

Oracle 11g R2 Schema Setup:

Create a type to use when performing a custom aggregation:

CREATE TYPE IntervalAverageType AS OBJECT(
  total INTERVAL DAY(9) TO SECOND(9),
  ct    INTEGER,

  STATIC FUNCTION ODCIAggregateInitialize(
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateIterate(
    self        IN OUT IntervalAverageType,
    value       IN     INTERVAL DAY TO SECOND
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateTerminate(
    self        IN OUT IntervalAverageType,
    returnValue    OUT INTERVAL DAY TO SECOND,
    flags       IN     NUMBER
  ) RETURN NUMBER,

  MEMBER FUNCTION ODCIAggregateMerge(
    self        IN OUT IntervalAverageType,
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
);
/

CREATE OR REPLACE TYPE BODY IntervalAverageType
IS
  STATIC FUNCTION ODCIAggregateInitialize(
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
  IS
  BEGIN
    ctx := IntervalAverageType( INTERVAL '0' DAY, 0 );
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateIterate(
    self        IN OUT IntervalAverageType,
    value       IN     INTERVAL DAY TO SECOND
  ) RETURN NUMBER
  IS
  BEGIN
    IF value IS NOT NULL THEN
      self.total := self.total + value;
      self.ct    := self.ct + 1;
    END IF;
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateTerminate(
    self        IN OUT IntervalAverageType,
    returnValue    OUT INTERVAL DAY TO SECOND,
    flags       IN     NUMBER
  ) RETURN NUMBER
  IS
  BEGIN
    IF self.ct = 0 THEN
      returnValue := NULL;
    ELSE
      returnValue := self.total / self.ct;
    END IF;
    RETURN ODCIConst.SUCCESS;
  END;

  MEMBER FUNCTION ODCIAggregateMerge(
    self        IN OUT IntervalAverageType,
    ctx         IN OUT IntervalAverageType
  ) RETURN NUMBER
  IS
  BEGIN
    self.total := self.total + ctx.total;
    self.ct    := self.ct + ctx.ct;
    RETURN ODCIConst.SUCCESS;
  END;
END;
/

Then you can create a custom aggregation function:

CREATE FUNCTION AVERAGE( difference INTERVAL DAY TO SECOND )
RETURN INTERVAL DAY TO SECOND
PARALLEL_ENABLE AGGREGATE USING IntervalAverageType;
/

Query 1:

WITH INTERVALS( diff ) AS (
  SELECT INTERVAL '0' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '1' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '-1' DAY FROM DUAL UNION ALL
  SELECT INTERVAL '8' HOUR FROM DUAL UNION ALL
  SELECT NULL FROM DUAL
)
SELECT AVERAGE( diff ) FROM intervals

Results:

| AVERAGE(DIFF) |
|---------------|
|     0 2:0:0.0 |


问:
How to format a perl oneliner?
If I have a perl one liner running it from the command line: e.g

```<code>perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'
</code>```

How could I format it so that it is more readable i.e. add new lines? If I do something like:

Ma

The command breaks when I add the new lines like that to format the code

答:
Write an actual perl script?

```<code>#!/usr/bin/env perl
use strict;
use warnings;

use JSON qw ( decode_json );

my $json = decode_json ( do{ local $/; <> } ); #read from stdin/file specified on command line

foreach my $element ( @$json ) { #iterate
   # do things
}
</code>```

Otherwise - you can add linefeeds in between your quotes - they've no semantic significance, unlike some other languages.

So:

```<code>perl -MData::Dumper -MJSON=decode_json -e '
    my @array = @{decode_json($data)};
    foreach my $i (@array) { etc }
'
</code>```

But seriously - if you're looking at making a one liner more readable, then the answer is 'write it as a script, that's what they're for'.

Title: How to format a perl oneliner?

Body:
If I have a perl one liner running it from the command line: e.g

perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'

How could I format it so that it is more readable i.e. add new lines? If I do something like:

Ma

The command breaks when I add the new lines like that to format the code

Body:
Write an actual perl script?

#!/usr/bin/env perl
use strict;
use warnings;

use JSON qw ( decode_json );

my $json = decode_json ( do{ local $/; <> } ); #read from stdin/file specified on command line

foreach my $element ( @$json ) { #iterate
   # do things
}

Otherwise - you can add linefeeds in between your quotes - they've no semantic significance, unlike some other languages.

So:

perl -MData::Dumper -MJSON=decode_json -e '
    my @array = @{decode_json($data)};
    foreach my $i (@array) { etc }
'

But seriously - if you're looking at making a one liner more readable, then the answer is 'write it as a script, that's what they're for'.


问:
Custom URL Scheme maximum URL length
As per title, what is the maximum length a URL can be, when using a custom URL scheme with an app?

e.g. If I'm launching another app via URL, and passing a blob of data using something like

   myappscheme://some/path?data=0123456789ABCDEF

how long can that string get before the URL gets cut off (or the system refuses to launch the other app at all)?

答: I have created a simple project to measure the limit, at the moment it seems that even a whopping megabyte is fine. It would not be wise to depend on that number for the future, obviously.</p>

Title: Custom URL Scheme maximum URL length


问:
How to create desktop python game application in Ubuntu 16.04?
I have written a python game using pygame module. It runs fine from terminal.

I have a game directory (let's call it myGame) which contain all the resources(images and sounds) and all the python scripts which use those.

When I run the game through terminal (let's say python3 mainPythonModule.py), the game runs fine.

I tried to create a game.desktop file. But when I click it, a black window appears and crashes almost instantly.

I am using Ubuntu 16.04 LTS. And my game is written in python3.5 and uses pygame module.

My game.desktop file looks like  this

I don't want the solution answered for  this question  because I still  have to type in terminal.

I would like to create a desktop applcation, such that by clicking on the icon, the game would start.
Just like when we download any game, after installation, we just click on the game icon and it runs, I want something like that. How can I do that?

Edit :
I don't think this question is a possible duplicate of this question.
I want to know how to develop a desktop application in Ubuntu 16.04, such that by clicking on some icon, the game would start.

Final Edit :
First of all, I would like to thank everyone who responded. I really am sorry for wasting your precious time.

The issue is resolved. The problem was all the resource (images and sounds) were loaded via relative path and not through absolute path. Now the game.desktop file runs fine.

答:
I think what are you trying to do is some kind of launcher.

Here you have my repo, it contains a Tkinter GUI with a PyGame call on a button.

Feel free to study/use it as you want, look at the file desktop_application.py and if you don`t care about the coin part you can just skip that and take what you need.

https://github.com/FilippoLeone/PyGameLauncher

And you can compile everything as an executable with PyInstaller.

Install PyInstaller from PyPI:

pip install pyinstaller

Go to your program’s directory and run:

pyinstaller yourprogram.py


问:
How to search for a specified value within an array using jquery
I would like to search for a specific value in an array and return its index.

html:

```<code><div class="container">
  <div class="col-md-6">
    <div id="task0">Task0</div>
  </div>
  <div class="col-md-6">
    <div id="task1">Task1</div>
    <div id="task2">Task2</div>
    <div id="task3">Task3</div>
    <div id="task4">Task4</div>
  </div>
</div>
</code>```

jquery:

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

  $childArr = $(".col-md-6:last").children().toArray();

  $indexNumber = $.inArray("div#task3", $childArr);

  console.log($indexNumber);

});
</code>```

Unfortunately I get -1. This means that the specified value was not found. But why do I get the -1 ?
If i output the $childArr in console.log I get an array with this values (4) [div#task1, div#task2, div#task3, div#task4].

https://jsfiddle.net/DTcHh/39987/

答:
The array is a list of HTML node elements, so you must pass the node element you want to search, not the string:

$(document).ready(function() {

 $childArr = $(".col-md-6:last").children().toArray();

  $indexNumber = $.inArray($("div#task3")[0], $childArr);

  console.log($indexNumber);
  console.log($childArr);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
}</code>```

Task0

Task1

Task2

Task3

Task4

```

Body:
I would like to search for a specific value in an array and return its index.

html:

Task0

Task1

Task2

Task3

Task4

jquery:

$(document).ready(function() {

  $childArr = $(".col-md-6:last").children().toArray();

  $indexNumber = $.inArray("div#task3", $childArr);

  console.log($indexNumber);

});

Unfortunately I get -1. This means that the specified value was not found. But why do I get the -1 ?
If i output the $childArr in console.log I get an array with this values (4) [div#task1, div#task2, div#task3, div#task4].

https://jsfiddle.net/DTcHh/39987/

Body:
The array is a list of HTML node elements, so you must pass the node element you want to search, not the string:

$(document).ready(function() {

 $childArr = $(".col-md-6:last").children().toArray();

  $indexNumber = $.inArray($("div#task3")[0], $childArr);

  console.log($indexNumber);
  console.log($childArr);
});

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="col-md-6">
    <div id="task0">Task0</div>
  </div>
  <div class="col-md-6">
    <div id="task1">Task1</div>
    <div id="task2">Task2</div>
    <div id="task3">Task3</div>
    <div id="task4">Task4</div>
  </div>
</div>


问:
Show icon on ng-bind-html when value is false
I need to show a fontawesome icon within the ng-bind-html on the ui-select, based on a boolean value

```<code><span  ng-bind-html="project.IsActive == false && <i class="fa fa-ban" aria-hidden="true"></i> | highlight: $select.search"></span>
</code>```

of course this code does not work,it's just to explain what i need, any idea on how to do it ?

答:
Ng-bind-html is a directive with should take the trusted html as an argument. So, you should move your logic with wether to show your icon to controller and also make your html trusted by angulars $sce service:

```<code>let icon = $sce.trustAsHtml('<i class="fa fa-ban" aria-hidden="true"></i>');
$scope.html = !IsActive ? icon : null;
</code>```

and then in view you go like:

```<code><span ng-bind-html="html"></span>
</code>```

All these done by angular is to prevent unsafe resources or some xss to be injected to your app.

Look up this fiddle

Body:
I need to show a fontawesome icon within the ng-bind-html on the ui-select, based on a boolean value

<span  ng-bind-html="project.IsActive == false &&  | highlight: $select.search">

of course this code does not work,it's just to explain what i need, any idea on how to do it ?

Body:
Ng-bind-html is a directive with should take the trusted html as an argument. So, you should move your logic with wether to show your icon to controller and also make your html trusted by angulars $sce service:

let icon = $sce.trustAsHtml('<i class="fa fa-ban" aria-hidden="true"></i>');
$scope.html = !IsActive ? icon : null;

and then in view you go like:

<span ng-bind-html="html"></span>

All these done by angular is to prevent unsafe resources or some xss to be injected to your app.

Look up this fiddle


问:
Specifying a custom path of beans.xml for CDI
When I use Spring and want to write a unit test, I can specify a custom context configuration in various ways, for example, by providing a different path of the context.xml.

But I don't see the way how to do that for CDI if I want to use a custom dependencies configuration for testing in the same maven module.

The documentation is very strict about this point:

For EJB modules or JAR files, the beans.xml deployment descriptor, if
present, must be in the META-INF directory.

If there is already /META-INF/beans.xml in the sources, I can not place a different one into the test-resources (it simply will be ignored).

Is any way to configure Weld/CDI, may be by using some system variables, to change the path of the beans.xml?

答:
For EJB modules or JAR files, the beans.xml deployment descriptor, if present, must be in the META-INF directory.

That is true, however that concerns an already created/packaged JAR which you then use as a dependency of your app. But your app can have it's own beans.xml too. beans.xml is just a means to define one bean archive and certain structures (interceptors, decorators, ...) within that archive. That means, for instance, that an interceptor enabled via beans.xml inside that JAR library will not be enabled in your application unless you specify it in beans.xml of that app too. Hence the link you see between the documentation and the testing you are asking about might not be correct/relevant. Not sure if I got you right there, though.

Is any way to configure Weld, may be through using some system variables, to change the path of the beans.xml?

No, there isn't. But in EE you mostly test with Arquillian and that allows you (among other things) to define a test deployment. There you can include any custom beans.xml you desire. That's also what Weld/CDI TCK tests use most of the time.


问:
Nexmo restricted to sent messages globally
Currently, I am using a Test account to sent the messages and It is restricted me to sent the messages to only added numbers. I have to send messages globally to any number. How can I do this? Will this allow me to sent messages globally If I use a paid account?</p>

答: Yes, I am using paid account and it allows me to send global messages.</p>


问:
redirecting stdin to file
I want to write a program that takes whatever I type in terminal and writes it to file. Here is the code that I wrote.

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int fd[2];
void pri(){
   char a[10];
   int ad=open("t.txt",O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
   if(read(fd[0],a,10)>0){
       write(ad,a,10);
   }
}
int main()
{
   int a;
   char s[10];
   pipe(fd);
   while(read(0,s,10)>0){
      write(fd[1],s,10);
      pri();
   }
   return 0;
}
</code>```

Currently I am using arrays and a pipe for achieving this. Is there any way that I can achieve the same without using any arrays?

答:
I want to write a program that takes whatever I type in terminal and writes it to file.

That's actually very simple and you don't need a pipe for this. (Your application itself takes the role of the pipe.)

This is what I did to demonstrate this: mycat.c

```<code>#include <stdio.h>

int main(int argc, char **argv)
{
  if (argc < 2) {
    fprintf(stderr, "ERROR: No output file!\n");
    fprintf(stderr, "Usage: mycat FILE\n");
    return 1;
  }
  FILE *fOut = fopen(argv[1], "w");
  if (!fOut) {
    fprintf(stderr, "ERROR: Cannot open file '%s' for writing!", argv[1]);
  }
  int c;
  while ((c = getc(stdin)) >= 0) {
    if (putc(c, fOut) < 0) {
      fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
    }
  }
  if (fclose(fOut)) {
    fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
  }
  return 0;
}
</code>```

It reads a character from stdin and writes it to the file stream fOut which has been opened by fopen() before. This is repeated until getc() fails which might happen e.g. due to end of input.

Sample session in bash on Cygwin/Windows 10:

$ gcc --version
gcc (GCC) 6.4.0

$ gcc -std=c11 -o mycat mycat.c

$ ./mycat
ERROR: No output file!
Usage: mycat FILE

$ ./mycat mycat.txt
Hello World.
tip tip tip
```

<p>At this point, I typed <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal <code>bash</code> the end of input.</p>

<pre class="lang-none prettyprint-override"><code>$ cat mycat.txt
Hello World.
tip tip tip

$
</code>```

I used cat to output the contents of mycat.txt. It is what typed in before (as expected).

cat was actually my first idea when I read the question but then I thought: It's a question tagged c (not bash). Hence my C sample code.

For completeness, the same with cat:

$ cat >mycat.txt <<'EOF'
> Hello cat.
> key key key
> EOF

$ cat mycat.txt
Hello cat.
key key key

$
```

<p>This remembered me that <code><<'EOF'</code> is something interpreted by <code>bash</code>. Hence, the following works as well:</p>

<pre class="lang-none prettyprint-override"><code>$ ./mycat mycat.txt <<'EOF'
Hello World.
tip tip tip
EOF

$ cat mycat.txt
Hello World.
tip tip tip

$
</code>```

This let me belief that cat works quite similar though it takes input file(s) as argument(s) and writes to stdout (which in turn might be re-directed when calling it in a shell). In opposition to mine, cat doesn't fail if no arguments are provided – it reads from stdin instead.

Title: redirecting stdin to file

Body:
I want to write a program that takes whatever I type in terminal and writes it to file. Here is the code that I wrote.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int fd[2];
void pri(){
   char a[10];
   int ad=open("t.txt",O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
   if(read(fd[0],a,10)>0){
       write(ad,a,10);
   }
}
int main()
{
   int a;
   char s[10];
   pipe(fd);
   while(read(0,s,10)>0){
      write(fd[1],s,10);
      pri();
   }
   return 0;
}

Currently I am using arrays and a pipe for achieving this. Is there any way that I can achieve the same without using any arrays?

Body:
I want to write a program that takes whatever I type in terminal and writes it to file.

That's actually very simple and you don't need a pipe for this. (Your application itself takes the role of the pipe.)

This is what I did to demonstrate this: mycat.c

#include <stdio.h>

int main(int argc, char **argv)
{
  if (argc < 2) {
    fprintf(stderr, "ERROR: No output file!\n");
    fprintf(stderr, "Usage: mycat FILE\n");
    return 1;
  }
  FILE *fOut = fopen(argv[1], "w");
  if (!fOut) {
    fprintf(stderr, "ERROR: Cannot open file '%s' for writing!", argv[1]);
  }
  int c;
  while ((c = getc(stdin)) >= 0) {
    if (putc(c, fOut) < 0) {
      fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
    }
  }
  if (fclose(fOut)) {
    fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
  }
  return 0;
}

It reads a character from stdin and writes it to the file stream fOut which has been opened by fopen() before. This is repeated until getc() fails which might happen e.g. due to end of input.

Sample session in bash on Cygwin/Windows 10:

$ gcc --version
gcc (GCC) 6.4.0

$ gcc -std=c11 -o mycat mycat.c

$ ./mycat
ERROR: No output file!
Usage: mycat FILE

$ ./mycat mycat.txt
Hello World.
tip tip tip

At this point, I typed Ctrl+D to signal bash the end of input.

$ cat mycat.txt
Hello World.
tip tip tip

$

I used cat to output the contents of mycat.txt. It is what typed in before (as expected).

cat was actually my first idea when I read the question but then I thought: It's a question tagged c (not bash). Hence my C sample code.

For completeness, the same with cat:

$ cat >mycat.txt <<'EOF'
> Hello cat.
> key key key
> EOF

$ cat mycat.txt
Hello cat.
key key key

$

This remembered me that <<'EOF' is something interpreted by bash. Hence, the following works as well:

$ ./mycat mycat.txt <<'EOF'
Hello World.
tip tip tip
EOF

$ cat mycat.txt
Hello World.
tip tip tip

$

This let me belief that cat works quite similar though it takes input file(s) as argument(s) and writes to stdout (which in turn might be re-directed when calling it in a shell). In opposition to mine, cat doesn't fail if no arguments are provided – it reads from stdin instead.


问:
Cloning a PHP PDO recordset object to count the rows returned by a select statement
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

```<code>function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}
</code>```

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?

答:
Maybe a possibility is to do like col shrapnel suggested and store the result in an array. You might be able to keep the interface clean by extending PDOStatement and then

http://www.php.net/manual/en/pdo.setattribute.php
PDO::ATTR_STATEMENT_CLASS

So it will return you EugenioEnhancedPDOStatement

Body:
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?


答:
If you want to get index of element inside .col-md-6:last you can use index() function

$(document).ready(function() {

  var index = $(".col-md-6:last #task3").index();

  console.log(index);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="col-md-6">
    <div id="task0">Task0</div>
  </div>
  <div class="col-md-6">
    <div id="task1">Task1</div>
    <div id="task2">Task2</div>
    <div id="task3">Task3</div>
    <div id="task4">Task4</div>
  </div>
</div></code>```

Title: How to search for a specified value within an array using jquery

Body:
If you want to get index of element inside .col-md-6:last you can use index() function

$(document).ready(function() {

  var index = $(".col-md-6:last #task3").index();

  console.log(index);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="col-md-6">
    <div id="task0">Task0</div>
  </div>
  <div class="col-md-6">
    <div id="task1">Task1</div>
    <div id="task2">Task2</div>
    <div id="task3">Task3</div>
    <div id="task4">Task4</div>
  </div>
</div>


问:
What is the Python way to walk a directory tree?
I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2</p>

```<code>from os import *
from os.path import *

def dir_contents(path):
    contents = listdir(path)
    files = []
    folders = []
    for i, item in enumerate(contents):
        if isfile(contents[i]):
            files += [item]
        elif isdir(contents[i]):
            folders += [item]
    return files, folders
</code>```

答:
Since Python 3.4 there is new module pathlib. So to get all dirs and files one can do:

```<code>from pathlib import Path

dirs = [str(item) for item in Path(path).iterdir() if item.is_dir()]
files = [str(item) for item in Path(path).iterdir() if item.is_file()]
</code>```

Body:
I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2

from os import *
from os.path import *

def dir_contents(path):
    contents = listdir(path)
    files = []
    folders = []
    for i, item in enumerate(contents):
        if isfile(contents[i]):
            files += [item]
        elif isdir(contents[i]):
            folders += [item]
    return files, folders

Body:
Since Python 3.4 there is new module pathlib. So to get all dirs and files one can do:

from pathlib import Path

dirs = [str(item) for item in Path(path).iterdir() if item.is_dir()]
files = [str(item) for item in Path(path).iterdir() if item.is_file()]


问:
unable to select an item in cxImageComboBox1
I added 3 items to cxImageComboBox1.

Assigned ImageList1 for the images.
Looks like this :

At runtime it displays images correctly. However only the first image (1) can be selected. I can not select the '2' or '3' :

Why wont it allow me to make the selection ? I do not understand.
Also it wont allow me to set the ImageIndex to -1 so it displays empty at runtime.

答: You only set the descriptions. Try also setting the values.


问:
C# Making an Async Call Synchronously
I have a library that only allows for Async calls, my code needs to be synchronous. Will the following code work correctly? Can anyone foresee any problems with it?</p>

```<code>RestResponse<T> response = null;
bool executedCallBack = false;
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    executedCallBack = true;
    response = aSyncResponse;
});

while (!executedCallBack){
    Thread.Sleep(100);
}
..continue execution synchronously
</code>```

答:
Usually async calls return you some sort of token (e.g. IAsyncResult) which lets you just wait for it, without polling. Does your API not do that at all?

Another option is to use ManualResetEvent or Monitor.Wait/Pulse instead of the sleep loop.

Title: C# Making an Async Call Synchronously

Body:
I have a library that only allows for Async calls, my code needs to be synchronous. Will the following code work correctly? Can anyone foresee any problems with it?

RestResponse<T> response = null;
bool executedCallBack = false;
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
    executedCallBack = true;
    response = aSyncResponse;
});

while (!executedCallBack){
    Thread.Sleep(100);
}
..continue execution synchronously


问:
Algorithm to get indexes in order
I want to assign indexes, in order, starting from 0, to objects. When an object is destroyed, the index should be freed for another use, eg.:

```<code>allocate_index() returns 0
allocate_index() returns 1
allocate_index() returns 2
allocate_index() returns 3
allocate_index() returns 4
release_index(1)
release_index(3)
allocate_index() returns 1
allocate_index() returns 3
allocate_index() returns 5
</code>```

This is similar to allocating file descriptor in a unix with open() and releasing with close().

But there is no bound fixed in advance.

Is there an efficient algorithm/data structure for allocating/freeing those indices?

答: I'll go with a binary heap of available indexes. Thanks for everybody's help + downvoting + closing votes: always a pleasure to ask a question on Stakoverflow!</p>

Title: Algorithm to get indexes in order

Body:
I want to assign indexes, in order, starting from 0, to objects. When an object is destroyed, the index should be freed for another use, eg.:

allocate_index() returns 0
allocate_index() returns 1
allocate_index() returns 2
allocate_index() returns 3
allocate_index() returns 4
release_index(1)
release_index(3)
allocate_index() returns 1
allocate_index() returns 3
allocate_index() returns 5

This is similar to allocating file descriptor in a unix with open() and releasing with close().

But there is no bound fixed in advance.

Is there an efficient algorithm/data structure for allocating/freeing those indices?


问:
Calling flet or labels functions in clisp
I new to common lisp (clisp-2.49)

Can I call an flet or labels function from a different outside function?
If so, how? (In a source file)

This code works except for the last print statement where it loses scope to f(n) on the last line.

```<code>(labels ((f (n)
         (+ n 10)))
  (print(f 5)))

(print (f 2))
</code>```

答:
Can I call an flet or labels function from a different outside function?

Yes! As others have mentioned, the lexical scope of the flet
definition is local.  But the extent of the value is infinite.  I.e. as long as 'something' within the Lisp system is pointing to it, its value will be preserved indefinitely.

But you might ask, how can that be done if lexical scoping denies you the name of the flet outside of the function?  The following will illustrate:

```<code>(defun my-closure ()
  (let ((i 5))
    (flet ((my-flet ()
         (setf i (+ i 1))))
      #'my-flet)))

;; Assign the returned value (a closure) to the 'global' special
;; variable global-my-closure
(defparameter global-my-closure (my-closure))

;; Call it *without* using the #' style prefix that you would use for
;; globally bound functions.  This is a special variable whose value
;; happens to be that of a function.
(funcall global-my-closure)
6
(funcall global-my-closure)
7
(funcall global-my-closure)
8
</code>```

Note, this is an extrodinarily powerful concept.  One of the best programming books of all time, The Structure and Interpretation of Computer Programs, explores this topic in detail using the related Lisp languange, Scheme, which has a slightly more convenient syntax for manipulating closures.

Body:
I new to common lisp (clisp-2.49)

Can I call an flet or labels function from a different outside function?
If so, how? (In a source file)

This code works except for the last print statement where it loses scope to f(n) on the last line.

(labels ((f (n)
         (+ n 10)))
  (print(f 5)))

(print (f 2))

Body:
Can I call an flet or labels function from a different outside function?

Yes! As others have mentioned, the lexical scope of the flet
definition is local.  But the extent of the value is infinite.  I.e. as long as 'something' within the Lisp system is pointing to it, its value will be preserved indefinitely.

But you might ask, how can that be done if lexical scoping denies you the name of the flet outside of the function?  The following will illustrate:

(defun my-closure ()
  (let ((i 5))
    (flet ((my-flet ()
         (setf i (+ i 1))))
      #'my-flet)))

;; Assign the returned value (a closure) to the 'global' special
;; variable global-my-closure
(defparameter global-my-closure (my-closure))

;; Call it *without* using the #' style prefix that you would use for
;; globally bound functions.  This is a special variable whose value
;; happens to be that of a function.
(funcall global-my-closure)
6
(funcall global-my-closure)
7
(funcall global-my-closure)
8

Note, this is an extrodinarily powerful concept.  One of the best programming books of all time, The Structure and Interpretation of Computer Programs, explores this topic in detail using the related Lisp languange, Scheme, which has a slightly more convenient syntax for manipulating closures.


问:
Swift ambiguous reference to member '=='
Is this a bug in Swift 3 compiler? It's not ambiguous, it's == and two Strings.

It says:

```<code>error: ambiguous reference to member '=='
let strs = things.filter { return $0.id == "1" } .map { t in
                                        ^~
</code>```

For this example code:

```<code>class Thing {
    var id: String = ""
}
let things = [Thing]()
let x = 1
let strs = things.filter { return $0.id == "1" } .map { t in
    if x == 1 {
        return "a"
    }
    else {
        return "b"
    }
}
</code>```

答:
I've just had a similar issue where the < operator was marked as ambiguous when trying to use my own filter function:

```<code>let shortNames = names.myFilter { (name) -> Bool in
    return name.count < 4
}
</code>```

Similarly to the answer from @Hamish I fixed this by explicitly setting the type of name:

```<code>(name: String)
</code>```

I shouldn't have to do this of course but it works.

Body:
Is this a bug in Swift 3 compiler? It's not ambiguous, it's == and two Strings.

It says:

error: ambiguous reference to member '=='
let strs = things.filter { return $0.id == "1" } .map { t in
                                        ^~

For this example code:

class Thing {
    var id: String = ""
}
let things = [Thing]()
let x = 1
let strs = things.filter { return $0.id == "1" } .map { t in
    if x == 1 {
        return "a"
    }
    else {
        return "b"
    }
}

Body:
I've just had a similar issue where the < operator was marked as ambiguous when trying to use my own filter function:

let shortNames = names.myFilter { (name) -> Bool in
    return name.count < 4
}

Similarly to the answer from @Hamish I fixed this by explicitly setting the type of name:

(name: String)

I shouldn't have to do this of course but it works.


问:
Reset whole Flex application - all form fields and other user data (without URLRequest/Javascript)
What are the best practices to reset multi user Flex applications?
With reset i mean:

Reset all form fields and other data the user left throughout the application during his session

Reset all datagrids and other components containing specific data

...when the user logs out of the application.

I know the approaches of doing an URL reload with navigateToURL, or by using Javascript. But i don't like these approaches. Mainly because the whole application has to be loaded again, which costs its time and is a bit brute for just resetting data.

Are there any nice alternative approaches which don't require a URL reload?

答:
Write a method for setting your app into the default state; whatever that is.  Run that as part of the log out procedure.

If you're looking for some automatic way to do that, I can't think of one.  How would the person writing such an 'automatic' algorithm know what your defaults would be?


问:
Unit Test using MS fakes: HttpClient and await
I have class which creates instance of HttpClient and call some method and returns response in async mode.

For ReadAsAsync, I have used nuget package "System.Net.Http.Formatting".

Source Code:

```<code>    public class MyClass
    {
        readonly HttpClient client = new HttpClient();
        public MyClass()
        {
             string myUrl = ConfigurationManager.AppSettings["MyWebAPI"];
             client.BaseAddress = new Uri(myUrl);
        }
        public async Task<List<YourClass>> GetYourClass()
        {
            var filters = "string";
            HttpResponseMessage response = await client.GetAsync(filters).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var notes = await response.Content.ReadAsAsync<List<YourClass>>();
                return notes;
            }
            return null;
        }
    }
    public class YourClass
    {
        private string Address { get; set; }

        public YourClass(string address)
        {
            Address = address;
        }
    }
</code>```

Unit Test:

```<code>    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            using (ShimsContext.Create())
            {
                MyClass obj = new MyClass();
                ShimHttpClient shimHttpClient = new ShimHttpClient();
                ShimHttpClient.Constructor = (t) =>
                {
                    shimHttpClient = new ShimHttpClient();
                    shimHttpClient.GetAsyncString = (a) =>
                    {
                        return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
                    };
                };
                var returnVal = obj.GetYourClass();
            }
        }

        private System.Net.Http.HttpResponseMessage function1()
        {
            return new System.Net.Http.HttpResponseMessage();
        }
    }
</code>```

We can't change the source code. but need to unit test GetAsync and ReadAsAync call through dummy call test.

答:
Declare that your test to run async and await the response from the source class</p>

```<code>[TestMethod]
public async Task TestMethod1()
{
    using (ShimsContext.Create())
    {
        MyClass obj = new MyClass();
        ShimHttpClient shimHttpClient = new ShimHttpClient();
        ShimHttpClient.Constructor = (t) =>
        {
            shimHttpClient = new ShimHttpClient();
            await shimHttpClient.GetAsyncString = (a) =>
            {
                return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
            };
        };
        var returnVal = await obj.GetYourClass();
        Assert.IsNotNull(returnVal);
        //make more assertations on the returnVal
    }
}
</code>```

Body:
I have class which creates instance of HttpClient and call some method and returns response in async mode.

For ReadAsAsync, I have used nuget package "System.Net.Http.Formatting".

Source Code:

    public class MyClass
    {
        readonly HttpClient client = new HttpClient();
        public MyClass()
        {
             string myUrl = ConfigurationManager.AppSettings["MyWebAPI"];
             client.BaseAddress = new Uri(myUrl);
        }
        public async Task<List<YourClass>> GetYourClass()
        {
            var filters = "string";
            HttpResponseMessage response = await client.GetAsync(filters).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var notes = await response.Content.ReadAsAsync<List<YourClass>>();
                return notes;
            }
            return null;
        }
    }
    public class YourClass
    {
        private string Address { get; set; }

        public YourClass(string address)
        {
            Address = address;
        }
    }

Unit Test:

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            using (ShimsContext.Create())
            {
                MyClass obj = new MyClass();
                ShimHttpClient shimHttpClient = new ShimHttpClient();
                ShimHttpClient.Constructor = (t) =>
                {
                    shimHttpClient = new ShimHttpClient();
                    shimHttpClient.GetAsyncString = (a) =>
                    {
                        return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
                    };
                };
                var returnVal = obj.GetYourClass();
            }
        }

        private System.Net.Http.HttpResponseMessage function1()
        {
            return new System.Net.Http.HttpResponseMessage();
        }
    }

We can't change the source code. but need to unit test GetAsync and ReadAsAync call through dummy call test.

Body:
Declare that your test to run async and await the response from the source class

[TestMethod]
public async Task TestMethod1()
{
    using (ShimsContext.Create())
    {
        MyClass obj = new MyClass();
        ShimHttpClient shimHttpClient = new ShimHttpClient();
        ShimHttpClient.Constructor = (t) =>
        {
            shimHttpClient = new ShimHttpClient();
            await shimHttpClient.GetAsyncString = (a) =>
            {
                return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
            };
        };
        var returnVal = await obj.GetYourClass();
        Assert.IsNotNull(returnVal);
        //make more assertations on the returnVal
    }
}


问:
Whats is the correct way to sum different dataframe columns in a list in pyspark?
I want to sum different columns in a spark dataframe.

Code

```<code>from pyspark.sql import functions as F
cols = ["A.p1","B.p1"]
df = spark.createDataFrame([[1,2],[4,89],[12,60]],schema=cols)

# 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))
</code>```

Why isn't approach #2. & #3. not working?
I am on Spark 2.2

答:
Because,

```<code># 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))
</code>```

Here you are using python in-built sum function which takes iterable as input,so it works. https://docs.python.org/2/library/functions.html#sum

```<code>#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))
</code>```

Here you are using pyspark sum function which takes column as input but you are trying to get it at row level.
http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.sum

```<code>#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))
</code>```

Here, df.select() returns a dataframe and trying to sum over a dataframe. In this case, I think, you got to iterate rowwise and apply sum over it.

Body:
I want to sum different columns in a spark dataframe.

Code

from pyspark.sql import functions as F
cols = ["A.p1","B.p1"]
df = spark.createDataFrame([[1,2],[4,89],[12,60]],schema=cols)

# 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))

Why isn't approach #2. & #3. not working?
I am on Spark 2.2

Body:
Because,

# 1. Works
df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

Here you are using python in-built sum function which takes iterable as input,so it works. https://docs.python.org/2/library/functions.html#sum

#2. Doesnt work
df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]]))

Here you are using pyspark sum function which takes column as input but you are trying to get it at row level.
http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.sum

#3. Doesnt work
df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"])))

Here, df.select() returns a dataframe and trying to sum over a dataframe. In this case, I think, you got to iterate rowwise and apply sum over it.


问:
Can't get MySql string working from other cs file
i try to connect with my MySql connection in a other .cs file but i cant reach the connection string con which is located in the MySQL.cs here is the code i am using:

MainPage.cs

```<code>Data_Layer.MySQL mm = new Data_Layer.MySQL();

        private async void LoginKlik(object sender, EventArgs e)
        {

            try
            {
              mm.con.Open();
            }
         catch
         {}
         finally
         {}
</code>```

I am getting a red line under the line mm.con.Open(); with the statement inaccisebale due protection level

MySQL.cs

```<code>namespace VerlofXamarin.Data_Layer
{
    public class MySQL
    {
            MySqlConnection con = new MySqlConnection("Server=arabig.nl;Port=3306;database=arabignl_project;User Id=arabignl_project;Password=JariR0800;charset=utf8");
    }
}
</code>```

答:
As  Sebastian Hofmann pointed c# declares fields as private by default. Like MySqlConnection con doesn't have a modifier is private, change it to public and will be accecible.

```<code>public MySqlConnection con = new MySqlConnection("Server=arabig.nl;Port=3306;database=arabignl_project;User Id=arabignl_project;Password=JariR0800;charset=utf8");
</code>```

An extended explanation about this here

More  info of access modifiers

Body:
i try to connect with my MySql connection in a other .cs file but i cant reach the connection string con which is located in the MySQL.cs here is the code i am using:

MainPage.cs

Data_Layer.MySQL mm = new Data_Layer.MySQL();

        private async void LoginKlik(object sender, EventArgs e)
        {

            try
            {
              mm.con.Open();
            }
         catch
         {}
         finally
         {}

I am getting a red line under the line mm.con.Open(); with the statement inaccisebale due protection level

MySQL.cs

namespace VerlofXamarin.Data_Layer
{
    public class MySQL
    {
            MySqlConnection con = new MySqlConnection("Server=arabig.nl;Port=3306;database=arabignl_project;User Id=arabignl_project;Password=JariR0800;charset=utf8");
    }
}

Body:
As  Sebastian Hofmann pointed c# declares fields as private by default. Like MySqlConnection con doesn't have a modifier is private, change it to public and will be accecible.

public MySqlConnection con = new MySqlConnection("Server=arabig.nl;Port=3306;database=arabignl_project;User Id=arabignl_project;Password=JariR0800;charset=utf8");

An extended explanation about this here

More  info of access modifiers


问:
Check if Key Exists in NameValueCollection
Is there a quick and simple way to check if a key exists in a NameValueCollection without looping through it?

Looking for something like Dictionary.ContainsKey() or similar.

There are many ways to solve this of course. Just wondering if someone can help scratch my brain itch.

答:
```<code>NameValueCollection n = Request.QueryString;

if (n.HasKeys())
   {
       //something
   }
</code>```

Return Value
Type: System.Boolean
true if the NameValueCollection contains keys that are not null; otherwise, false. LINK

Body:
NameValueCollection n = Request.QueryString;

if (n.HasKeys())
   {
       //something
   }

Return Value
Type: System.Boolean
true if the NameValueCollection contains keys that are not null; otherwise, false. LINK


问:
ASP.NET app - Webfonts not loading until user is logged in to the site

Edited

Debugged again, finally realised what the real problem is (not how to solve it though).

When a browser tries to load fonts for the page in question, the response has status code 302 and

```<code>Location: /Login.aspx?ReturnUrl=%2ffonts%2ffontawesome-webfont.woff2
</code>```

Our authentication mode redirects all request to login page by default, and looks like that includes the fonts, too:

```<code><authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" defaultUrl="~/Login.aspx" slidingExpiration="true" protection="All" timeout="60" path="/" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>
</code>```

It wasn't a problem before, because you have log in to even see most pages on the site, and after you did, fonts are loading fine. But the page I'm working on doesn't require a login (or even having a user account on the site), hence the problem.

The updated question is: how to make the font to load without authentication, and not compromise the authentication itself (security risks etc)?

Original post

We have an ASP.NET Webforms app that has some years behind it, and I've started experimenting with adding Bootstrap to it. So far so good, but I cannot get glyphicons to work - keep getting error squares instead of icons. We have been successfully using Fonts Awesome for some time, so I tried their icons - nope, same error squares (again, on the pages without Bootstrap Fonts Awesome work normally).

The Bootstrap was installed as Nuget package (the latest version, 3.3.7). Font Awesome is 4.4.0 and was installed manually. We do use Sass/Less.

We add scripts/css via bundles:

```<code>        bundles.Add(new StyleBundle("~/css/styles").Include(
            "~/css/bootstrap.css",
            "~/css/font-awesome.min.css"));
</code>```

And this is how the web.config looks right now:

```<code><staticContent>
  <mimeMap fileExtension="apk" mimeType="application/vnd.android.package-archive" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  <remove fileExtension=".otf" />
  <mimeMap fileExtension=".otf" mimeType="font/otf" />
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
  <remove fileExtension=".eot" />
  <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
  <remove fileExtension=".ttf" />
  <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
  <remove fileExtension=".svg" />
  <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>
</code>```

Now, many people seem to have a similar problem. Here's the solutions I've tried so far:

Put css files and fonts into default folders (/css and /fonts on the same level, where Bootstrap expects to see them; overriding urls in @font-face doesn't work either) - that sort of improved matters, because now both fonts work in Firefox (most of the time) and Chrome (half of the time), but not in Edge/IE.

Different combinations of MimeTypes in web.config (didn't make any difference).

Updating Font Awesome to the latest version - no difference either.

Internet Explorer won't display Glyphicons or WebFonts - thought about it, but if that's the case, why the problem only shows up with Bootstrap enabled?

Clearing browser caches (repeatedly).

Untrusted Fonts Blocking option in IE security settings - turned off by default, so not the case.

Checking with the dev tools whether the fonts are actually loading - now this is where it gets interesting.

Chrome gives the "Failed to decode downloaded font: (...) OTS parsing error: invalid version tag" errors (when it does), and Edge the "CSS3114: @font-face unable to load invalid OpenType font" (the reference says it should be CSS3115, but whatever, "get permission or licenses" doesn't help much).

For both browsers the Network tab shows font files loaded as text/html with 302 Found (and the page/console still have errors). For Chrome, if I reload the page several times, eventually font files load status changes to 200 OK and type to font. That implies a problem with mimetypes, but why does it fix itself after enough reloads?

Again, Font Awesome works on pages that don't use Bootstrap, and files load as intended.

What am I missing here? Any ideas will be appreciated, because I'm stuck.

答:
In the end, I've added the fonts folder as an exception to the web.config and that was it (yes, it really was that simple. Sigh):

```<code><location path="fonts">
  <system.web>
    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>
</location>
</code>```

Leaving the original question here as a reminder how easy you can misinterpret things and get desperate when you don't quite know what you are doing :)

Body:
Edited

Debugged again, finally realised what the real problem is (not how to solve it though).

When a browser tries to load fonts for the page in question, the response has status code 302 and

Location: /Login.aspx?ReturnUrl=%2ffonts%2ffontawesome-webfont.woff2

Our authentication mode redirects all request to login page by default, and looks like that includes the fonts, too:

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" defaultUrl="~/Login.aspx" slidingExpiration="true" protection="All" timeout="60" path="/" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>

It wasn't a problem before, because you have log in to even see most pages on the site, and after you did, fonts are loading fine. But the page I'm working on doesn't require a login (or even having a user account on the site), hence the problem.

The updated question is: how to make the font to load without authentication, and not compromise the authentication itself (security risks etc)?

Original post

We have an ASP.NET Webforms app that has some years behind it, and I've started experimenting with adding Bootstrap to it. So far so good, but I cannot get glyphicons to work - keep getting error squares instead of icons. We have been successfully using Fonts Awesome for some time, so I tried their icons - nope, same error squares (again, on the pages without Bootstrap Fonts Awesome work normally).

The Bootstrap was installed as Nuget package (the latest version, 3.3.7). Font Awesome is 4.4.0 and was installed manually. We do use Sass/Less.

We add scripts/css via bundles:

        bundles.Add(new StyleBundle("~/css/styles").Include(
            "~/css/bootstrap.css",
            "~/css/font-awesome.min.css"));

And this is how the web.config looks right now:

<staticContent>
  <mimeMap fileExtension="apk" mimeType="application/vnd.android.package-archive" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  <remove fileExtension=".otf" />
  <mimeMap fileExtension=".otf" mimeType="font/otf" />
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
  <remove fileExtension=".eot" />
  <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
  <remove fileExtension=".ttf" />
  <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
  <remove fileExtension=".svg" />
  <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>

Now, many people seem to have a similar problem. Here's the solutions I've tried so far:

Put css files and fonts into default folders (/css and /fonts on the same level, where Bootstrap expects to see them; overriding urls in @font-face doesn't work either) - that sort of improved matters, because now both fonts work in Firefox (most of the time) and Chrome (half of the time), but not in Edge/IE.

Different combinations of MimeTypes in web.config (didn't make any difference).

Updating Font Awesome to the latest version - no difference either.

Internet Explorer won't display Glyphicons or WebFonts - thought about it, but if that's the case, why the problem only shows up with Bootstrap enabled?

Clearing browser caches (repeatedly).

Untrusted Fonts Blocking option in IE security settings - turned off by default, so not the case.

Checking with the dev tools whether the fonts are actually loading - now this is where it gets interesting.

Chrome gives the "Failed to decode downloaded font: (...) OTS parsing error: invalid version tag" errors (when it does), and Edge the "CSS3114: @font-face unable to load invalid OpenType font" (the reference says it should be CSS3115, but whatever, "get permission or licenses" doesn't help much).

For both browsers the Network tab shows font files loaded as text/html with 302 Found (and the page/console still have errors). For Chrome, if I reload the page several times, eventually font files load status changes to 200 OK and type to font. That implies a problem with mimetypes, but why does it fix itself after enough reloads?

Again, Font Awesome works on pages that don't use Bootstrap, and files load as intended.

What am I missing here? Any ideas will be appreciated, because I'm stuck.

Body:
In the end, I've added the fonts folder as an exception to the web.config and that was it (yes, it really was that simple. Sigh):

<location path="fonts">
  <system.web>
    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>
</location>

Leaving the original question here as a reminder how easy you can misinterpret things and get desperate when you don't quite know what you are doing :)


问:
Get the value from an Array
I have some code I need help with:

```<code>var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.
</code>```

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

答:
You have a number of things confused here. You have a global variable bob and you also have bob as a function argument. Also, you have an array of results, which local to the foo function is called resultArr, but you do not assign it anywhere when you call the foo function.

Try the following code instead:

```<code>var bob = [10,30,50,20,8];

var foo = function(arrayOfNumbers){
  var resultObj = {
    max: 0,
    min: 0,
    average: 0,
    sum: 0
  };

  resultObj.max = Math.max.apply( null, arrayOfNumbers); // Get the max value.
  resultObj.min = Math.min.apply( null, arrayOfNumbers); // Get the min value.

  for( var i = 0; i < arrayOfNumbers.length; i++ ){
    resultObj.sum += arrayOfNumbers[ i ];
  }

  resultObj.average = sum / l;

  return resultObj;
}

// Call the function

var theResult = foo(bob);

document.getElementById('max').innerHTML = "Max value: "+theResult.max;
</code>```

Here's a description of the changes I made to your code, and why:

I made sure that the names of your variables don't conflict. This should help you see where each variable is used and how they relate to each other. bob contains your numbers. You pass bob to the foo() function. Inside foo, the numbers are now referred to as v. This means you could also have frank, joe, and tom, and you could call foo on all of them. arrayOfNumbers is a local variable to foo.

I changed resultArr from an array to an object. An object makes more sense because you can assign labels to the values. So now the max value is can be accessed at .max instead of [0]. I also showed how the result object is called resultObj inside foo but gets assigned to theResult outside foo. You can then refer to theResult.min, theResult.max, and theResult.average.

I cleaned up a little bit, fixing indentation and moving the function to the top, to increase readability.

I hope this helps you see what's going on here!

Title: Get the value from an Array

Body:
I have some code I need help with:

var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

Body:
You have a number of things confused here. You have a global variable bob and you also have bob as a function argument. Also, you have an array of results, which local to the foo function is called resultArr, but you do not assign it anywhere when you call the foo function.

Try the following code instead:

var bob = [10,30,50,20,8];

var foo = function(arrayOfNumbers){
  var resultObj = {
    max: 0,
    min: 0,
    average: 0,
    sum: 0
  };

  resultObj.max = Math.max.apply( null, arrayOfNumbers); // Get the max value.
  resultObj.min = Math.min.apply( null, arrayOfNumbers); // Get the min value.

  for( var i = 0; i < arrayOfNumbers.length; i++ ){
    resultObj.sum += arrayOfNumbers[ i ];
  }

  resultObj.average = sum / l;

  return resultObj;
}

// Call the function

var theResult = foo(bob);

document.getElementById('max').innerHTML = "Max value: "+theResult.max;

Here's a description of the changes I made to your code, and why:

I made sure that the names of your variables don't conflict. This should help you see where each variable is used and how they relate to each other. bob contains your numbers. You pass bob to the foo() function. Inside foo, the numbers are now referred to as v. This means you could also have frank, joe, and tom, and you could call foo on all of them. arrayOfNumbers is a local variable to foo.

I changed resultArr from an array to an object. An object makes more sense because you can assign labels to the values. So now the max value is can be accessed at .max instead of [0]. I also showed how the result object is called resultObj inside foo but gets assigned to theResult outside foo. You can then refer to theResult.min, theResult.max, and theResult.average.

I cleaned up a little bit, fixing indentation and moving the function to the top, to increase readability.

I hope this helps you see what's going on here!