问:
Unable to toggle LED through AJAX request to Arduino
I am trying to toggle an LED through a button in the web server created by the ESP8266. But when I click the button nothing is happening. The Arduino code is perfect. something is wrong with the HTML and/or JS code.

```<code><html>
  <head>
    <script
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    <script>
      $(document).ready(function() {
        $(".led").click(function() {
          var p = $(this).attr('id');
          $.get("http://192.168.4.1:80/", { pin: p }); // Sending the get request
        });
      });
    </script>
  </head>
  <head>
    <title>Home Automation System</title>
  </head>
  <body>
    <button id="13" class="led">Toggle Pin 13</button>
  </body>
</html>
</code>```

The below code is the original code

```<code><html>
    <head>
        <title>ESP8266 LED Control</title>
    </head>
    <body>
    <button id="13" class="led">Toggle Pin 13</button>
    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(".led").click(function(){
                var p = $(this).attr('id');

                $.get("http://192.168.4.1:80/", {pin:p});
            });
        });
    </script>
    </body>
</html>
</code>```

答:
script tag is not a self closing tag. A closing </script> is needed.

head tag should be only one.

Check this:

```<code><html>
  <head>
    <script
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $(".led").click(function() {
          var p = $(this).attr('id');
          $.get("http://192.168.4.1:80/", { pin: p }); // Sending the get request
        });
      });
    </script>
    <title>Home Automation System</title>
  </head>
  <body>
    <button id="13" class="led">Toggle Pin 13</button>
  </body>
</html>
</code>```

Body:
I am trying to toggle an LED through a button in the web server created by the ESP8266. But when I click the button nothing is happening. The Arduino code is perfect. something is wrong with the HTML and/or JS code.

    <title>Home Automation System</title>

    <button id="13" class="led">Toggle Pin 13</button>

The below code is the original code

        <title>ESP8266 LED Control</title>

    <button id="13" class="led">Toggle Pin 13</button>

Body:
script tag is not a self closing tag. A closing </script> is needed.

head tag should be only one.

Check this:

<html>
  <head>
    <script
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $(".led").click(function() {
          var p = $(this).attr('id');
          $.get("http://192.168.4.1:80/", { pin: p }); // Sending the get request
        });
      });
    </script>
    <title>Home Automation System</title>
  </head>
  <body>
    <button id="13" class="led">Toggle Pin 13</button>
  </body>
</html>


来源: stackexchange

问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is  a good solution:

```<code>import urllib2
from BeautifulSoup import BeautifulSoup

html = urllib2.urlopen("http://www.google.com").read()
soup = BeautifulSoup(html)
all_links = soup.findAll("a")
</code>```

As for the second question, yes, HTML links ought to be well-defined, but the HTML you actually encounter is very unlikely to be standard. The beauty of BeautifulSoup is that it uses browser-like heuristics to try to parse the non-standard, malformed HTML that you are likely to actually come across.

If you are certain to be working on standard XHTML, you can use (much) faster XML parsers like expat.

Regex, for the reasons above (the parser must maintain state, and regex can't do that) will never be a general solution.

OwnerDisplayName: Udi Pasmon

ContentLicense: CC BY-SA 3.0

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

Body:
As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is  a good solution:

import urllib2
from BeautifulSoup import BeautifulSoup

html = urllib2.urlopen("http://www.google.com").read()
soup = BeautifulSoup(html)
all_links = soup.findAll("a")

As for the second question, yes, HTML links ought to be well-defined, but the HTML you actually encounter is very unlikely to be standard. The beauty of BeautifulSoup is that it uses browser-like heuristics to try to parse the non-standard, malformed HTML that you are likely to actually come across.

If you are certain to be working on standard XHTML, you can use (much) faster XML parsers like expat.

Regex, for the reasons above (the parser must maintain state, and regex can't do that) will never be a general solution.

OwnerDisplayName: Triptych

ContentLicense: CC BY-SA 2.5


问:
Copying stuff from vim running in putty
I am running Vim 6.3 through putty and putty connection manager. I have the mouse option set (set mouse = a). I am able to paste things from the (windows) clipboard to vim by  but selecting text in vim  isn't copying anything to the clipboard. Does anyone know how do I do this?

Note: I can't update Vim to a newer version.

答:
You can select some text with the mouse and then type:

"*y to yank the selected text to the clipboard, then you should be able to use the clipboard content in another application.

if "*y is to cumbersome to type, you can put the following in host .vimrc

:noremap y "*y

Title: Copying stuff from vim running in putty


问:
I met a trouble in MongoDB, help me
```<code>let user = await User.findOne({name: userInfo.name});
console.log("user is: " + user);
console.log("user's name is: " + user.name);
</code>```

I got a query result for mongodb, and I print it on the console，then I got:

user is: { _id: 58de51fd5e34037274f790d5,
    name: 'ygy',
    password: 'ygy',
    studentId: '2013302580183',
    class: '1' }

but when I print user.name, it is:

user's name is: undefined

but I print typeof user, and I got object.I do not know if the problem is async / await

答:
I find the answer.
when I export user's schema,I use es6 module, but I use commonJS to import user's schema.</p>

Title: I met a trouble in MongoDB, help me

Body:
let user = await User.findOne({name: userInfo.name});
console.log("user is: " + user);
console.log("user's name is: " + user.name);

I got a query result for mongodb, and I print it on the console，then I got:

user is: { _id: 58de51fd5e34037274f790d5,
    name: 'ygy',
    password: 'ygy',
    studentId: '2013302580183',
    class: '1' }

but when I print user.name, it is:

user's name is: undefined

but I print typeof user, and I got object.I do not know if the problem is async / await


问:
It is said, that InfoWindow of Google Maps node content does not work
It is said in documentation, that I can set content to node, not only to string, in InfoWindow.

Unfortunately, when I try to set node, it doesn't work:

```<code>var point;

    point = new google.maps.LatLng(43.65654, -79.90138);
    // html = 'hello world';
    html = $('<div>hello world</div>');
    var marker = new google.maps.Marker({
        position: point,
        map: map
    });

    google.maps.event.addListener(marker, 'click', function () {

        infowindow.setContent(html);
        infowindow.open(map, marker);
    });
</code>```

Jsfiddle is here: https://jsfiddle.net/pmek2zhs/3/

Click on marked and you'll see nothing appears. If you change html variable assignment to commented one, it will work.

答:
$('
hello world
'); is not an HTML node, it is a JQuery object.

Use $('
hello world
')[0] to get something the API can use.

updated fiddle

code snippet:

var map = null;
var infowindow = new google.maps.InfoWindow();

function initialize() {

  var myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.907787, -79.359741),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });

  // Add markers to the map
  // Set up three markers with info windows

  var point;

  point = new google.maps.LatLng(43.65654, -79.90138);
  // html = 'hello world';
  html = $('
hello world
')[0];
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });

  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent(html);
    infowindow.open(map, marker);
  });
  google.maps.event.trigger(marker, 'click');

}

initialize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
}

#map_canvas {
  width: 100%;
  height: 100%;
}</code>```

```

Body:
It is said in documentation, that I can set content to node, not only to string, in InfoWindow.

Unfortunately, when I try to set node, it doesn't work:

var point;

    point = new google.maps.LatLng(43.65654, -79.90138);
    // html = 'hello world';
    html = $('
hello world
');
    var marker = new google.maps.Marker({
        position: point,
        map: map
    });

    google.maps.event.addListener(marker, 'click', function () {

        infowindow.setContent(html);
        infowindow.open(map, marker);
    });

Jsfiddle is here: https://jsfiddle.net/pmek2zhs/3/

Click on marked and you'll see nothing appears. If you change html variable assignment to commented one, it will work.

Body:
$('<div>hello world</div>'); is not an HTML node, it is a JQuery object.

Use $('<div>hello world</div>')[0] to get something the API can use.

updated fiddle

code snippet:

var map = null;
var infowindow = new google.maps.InfoWindow();

function initialize() {

  var myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.907787, -79.359741),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });

  // Add markers to the map
  // Set up three markers with info windows

  var point;

  point = new google.maps.LatLng(43.65654, -79.90138);
  // html = 'hello world';
  html = $('<div>hello world</div>')[0];
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });

  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent(html);
    infowindow.open(map, marker);
  });
  google.maps.event.trigger(marker, 'click');

}

initialize();

html,
body {
  height: 100%;
}

#map_canvas {
  width: 100%;
  height: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

ContentLicense: CC BY-SA 4.0


问:
PHP cURL cannot connect to IIS on local machine
I have a PHP script that tries to connect with an other PHP script located on a IIS installation running on a local machine in my office using the cURL protocol but fails to do so.

Local configuration:
I've opened the port 8789 on the firewall, I made the router redirect correctly to the IP of the machine running IIS and I've set the default port of IIS to 8789.
If I try to connect to the script (93.144.xxx.xxx:8987/curl_response.php) through a browser I get the resulting output so this setup is working correctly.

When I try to run the PHP script on a remote webserver though it gives my either cUrl error (#7): couldn't connect to host or cUrl error (#28): connect() timed out! (I'm trying different webservers)

The curl part of my PHP script is the following:

```<code>$url = 'http://93.144.xxx.xxx:8789/curl_response.php';

$verbose = fopen('php://temp', 'w+');
$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_STDERR, $verbose);
curl_setopt ($curl, CURLOPT_URL, $rurl);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 8789);

$response = curl_exec($curl);

if ($response === FALSE) {
    printf("cUrl error (#%d): %s<br>\n", curl_errno($curl),
           htmlspecialchars(curl_error($curl)));
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);

    echo "Verbose information:\n```", htmlspecialchars($verboseLog),"```\n";
}else{
    curl_close($curl);
    // trim response (serialized array)
    $response = trim($response);
    // unserialize
    $response = unserialize($response);
    print_r($response);
}
</code>```

I've tried several different CURLOPT_ configurations and I've even tried using a dyndns host instead of the IP, but to no avail.

Is there a IIS configuration to set so it will accept incomming cURL requests or is there a specific header to be sent though cURL?

Thanks.

答:
Run cURL from the command line with --verbose to see more detailed information.

And check if ISS it's with cURL enabled:

```<code>extension=php_curl.dll
</code>```

Body:
I have a PHP script that tries to connect with an other PHP script located on a IIS installation running on a local machine in my office using the cURL protocol but fails to do so.

Local configuration:
I've opened the port 8789 on the firewall, I made the router redirect correctly to the IP of the machine running IIS and I've set the default port of IIS to 8789.
If I try to connect to the script (93.144.xxx.xxx:8987/curl_response.php) through a browser I get the resulting output so this setup is working correctly.

When I try to run the PHP script on a remote webserver though it gives my either cUrl error (#7): couldn't connect to host or cUrl error (#28): connect() timed out! (I'm trying different webservers)

The curl part of my PHP script is the following:

$url = 'http://93.144.xxx.xxx:8789/curl_response.php';

$verbose = fopen('php://temp', 'w+');
$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_STDERR, $verbose);
curl_setopt ($curl, CURLOPT_URL, $rurl);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 8789);

$response = curl_exec($curl);

if ($response === FALSE) {
    printf("cUrl error (#%d): %s
\n", curl_errno($curl),
           htmlspecialchars(curl_error($curl)));
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);

    echo "Verbose information:\n
", htmlspecialchars($verboseLog),"
\n";
}else{
    curl_close($curl);
    // trim response (serialized array)
    $response = trim($response);
    // unserialize
    $response = unserialize($response);
    print_r($response);
}

I've tried several different CURLOPT_ configurations and I've even tried using a dyndns host instead of the IP, but to no avail.

Is there a IIS configuration to set so it will accept incomming cURL requests or is there a specific header to be sent though cURL?

Thanks.

Body:
Run cURL from the command line with --verbose to see more detailed information.

And check if ISS it's with cURL enabled:

extension=php_curl.dll


问:
How to use Angular ng-include
I just started with angularjs on a Express Framework and I am trying to load html pages as includes. Now I've setup my routing in angular and works fine, but when I try to use ng-include in my html pages, it kinda loops and gives the following error:

```<code>Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…Be()%3Breturn%20d(a)%7D%22%2C%22newVal%22%3A%22nav-mobile.html%22%7D%5D%5D
at angular.js:38
at m.$digest (angular.js:18048)
at angular.js:18211
at e (angular.js:6274)
at angular.js:6554
</code>```

Now I am trying to make an inlcude of the nav-bar-mobile.html to inject it into the page, but I do not get this working. Someone have an idea?

My routing looks like this:

var app = angular.module("myApp", ["ngRoute", "ngAnimate"]);

/* ROUTING */

app.config(function($routeProvider,$locationProvider) {
    $routeProvider

            .when('/', {
                templateUrl: 'partials/home.html',
                controller: 'homeController'
            })

            .when('/wie', {
                templateUrl: 'partials/wie.html',
                controller: 'aboutController'
            })

            .when('/portfolio', {
                templateUrl: 'partials/portfolio.html',
                controller: 'portfolioController'
            })

            .when('/channel', {
                templateUrl: 'partials/channel.html',
                controller: 'channelController'
            })

            .when('/contact', {
                templateUrl: 'partials/contact.html',
                controller: 'contactController'
            });

        $locationProvider.html5Mode(true);
    });

/* CONTROLLERS */

app.controller('homeController', function($scope) {
   $scope.pageClass = 'home';
});

app.controller('aboutController', function($scope) {
   $scope.pageClass = 'wie';
});

app.controller('portfolioController', function($scope) {
   $scope.pageClass = 'portfolio';
});

app.controller('channelController', function($scope) {
   $scope.pageClass = 'channel';
});

app.controller('contactController', function($scope) {
   $scope.pageClass = 'contact';
});```
</div>
</div>
</p>

<p>And my index.html page looks like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html ng-app="myApp" ng-init="CompanyName='MyApp'">
  <head>
    <title>My App</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CSS  -->
    <!-- load bootstrap & font awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel='stylesheet' href='/stylesheets/style.css'>
    <link rel='stylesheet' href='/stylesheets/mobile.css'>
    <link rel='stylesheet' href='/stylesheets/font-awesome.css'>

    <!-- JS  -->
    <!-- load angular, ngRoute, ngAnimate  -->
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js'></script>
    <script src='//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-route.js'></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-animate.js"></script>
    <script src='/javascripts/app.js'></script>
    <base  href="/">
  </head>

  <body>

    <div class="container">
      <div class="logo">
      <div class="wrap">
          <img src="/images/my-logo.png" alt="my-logo" />
      </div>
      </div>

        <div ng-include="'nav-bar-mobile.html'"></div>

        <div class="box panels tinted">
            <div class="page {{ pageClass }}" ng-view></div>
        </div>
        <div class="nav-bar desktop">
          <div class="inner">
            <ul>
                <li>Home</li>
                <li>Wie zijn wij?</li>
                <li>Portfolio</li>
                <li>My Channel</li>
                <li>Contact</li>
            </ul>
          </div>
        </div>
    </div>
  </body>

</html></code>```

答: You need to provide the full path of the HTML page if it is not in same folder.</p>

Title: How to use Angular ng-include

Body:
I just started with angularjs on a Express Framework and I am trying to load html pages as includes. Now I've setup my routing in angular and works fine, but when I try to use ng-include in my html pages, it kinda loops and gives the following error:

Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…Be()%3Breturn%20d(a)%7D%22%2C%22newVal%22%3A%22nav-mobile.html%22%7D%5D%5D
at angular.js:38
at m.$digest (angular.js:18048)
at angular.js:18211
at e (angular.js:6274)
at angular.js:6554

Now I am trying to make an inlcude of the nav-bar-mobile.html to inject it into the page, but I do not get this working. Someone have an idea?

My routing looks like this:

var app = angular.module("myApp", ["ngRoute", "ngAnimate"]);

/* ROUTING */

app.config(function($routeProvider,$locationProvider) {
    $routeProvider

            .when('/', {
                templateUrl: 'partials/home.html',
                controller: 'homeController'
            })

            .when('/wie', {
                templateUrl: 'partials/wie.html',
                controller: 'aboutController'
            })

            .when('/portfolio', {
                templateUrl: 'partials/portfolio.html',
                controller: 'portfolioController'
            })

            .when('/channel', {
                templateUrl: 'partials/channel.html',
                controller: 'channelController'
            })

            .when('/contact', {
                templateUrl: 'partials/contact.html',
                controller: 'contactController'
            });

        $locationProvider.html5Mode(true);
    });

/* CONTROLLERS */

app.controller('homeController', function($scope) {
   $scope.pageClass = 'home';
});

app.controller('aboutController', function($scope) {
   $scope.pageClass = 'wie';
});

app.controller('portfolioController', function($scope) {
   $scope.pageClass = 'portfolio';
});

app.controller('channelController', function($scope) {
   $scope.pageClass = 'channel';
});

app.controller('contactController', function($scope) {
   $scope.pageClass = 'contact';
});

And my index.html page looks like this:

<!DOCTYPE html>

    <title>My App</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel='stylesheet' href='/stylesheets/style.css'>
    <link rel='stylesheet' href='/stylesheets/mobile.css'>
    <link rel='stylesheet' href='/stylesheets/font-awesome.css'>

    <base  href="/">

Home

Wie zijn wij?

Portfolio

My Channel

Contact


问:
Using Notepad++ to compile Java code
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

```<code>javac “$(FILE_NAME)”
</code>```

and

```<code>java “$(NAME_PART)”
</code>```

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

```<code>cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)
</code>```

errors from the console in Notepad++ are:

```<code>java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"
</code>```

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

```<code> //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }
</code>```

答:
Although I'm convinced that you have to work with an IDE (NetBeans, Eclipse, IntelliJ IDEA (which I use), I think it's always good to know and learn what is failing in your small example.
With an IDE, the compile and runtime environment are configured, but as a developper, it's important to understand the basic concepts hidden.
Anyway,

From the link you've posted, here are the environnement variables you must define

```<code>FULL_CURRENT_PATH: C:\Documents and Settings\Administrator\My Documents\JavaP\ExampleProgram.java
CURRENT_DIRECTORY: C:\Documents and Settings\Administrator\My Documents\JavaP\
FILE_NAME: ExampleProgram.java
NAME_PART: ExampleProgram
EXT_PART:java
</code>```

Make sure that all is named according to these settings, ie:

```<code>- your source file is under C:\Documents and Settings\Administrator\My Documents\JavaP\
- your source file is named ExampleProgram.java
</code>```

Title: Using Notepad++ to compile Java code

Body:
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

javac “$(FILE_NAME)”

and

java “$(NAME_PART)”

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)

errors from the console in Notepad++ are:

java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

 //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }

Body:
Although I'm convinced that you have to work with an IDE (NetBeans, Eclipse, IntelliJ IDEA (which I use), I think it's always good to know and learn what is failing in your small example.
With an IDE, the compile and runtime environment are configured, but as a developper, it's important to understand the basic concepts hidden.
Anyway,

From the link you've posted, here are the environnement variables you must define

FULL_CURRENT_PATH: C:\Documents and Settings\Administrator\My Documents\JavaP\ExampleProgram.java
CURRENT_DIRECTORY: C:\Documents and Settings\Administrator\My Documents\JavaP\
FILE_NAME: ExampleProgram.java
NAME_PART: ExampleProgram
EXT_PART:java

Make sure that all is named according to these settings, ie:

- your source file is under C:\Documents and Settings\Administrator\My Documents\JavaP\
- your source file is named ExampleProgram.java


问:
Assign part of a command's output to a variable in bash?
I have this update script i am working on and i am using ssh to log onto the machine and simply run apt-get update && apt-get upgrade -y. Now the thing is i want to be able to say something like "hostname" updated successfully.

Here's what i have written right now:

```<code>#!/bin/bash

ip=(192.168.1.23 192.168.1.40 192.168.1.41 192.168.1.42 192.168.1.43)
#ssh-key=~/.ssh/id_ed25519

for i in "${ip[@]}"; do {
  ssh -t victor@$i "sudo apt-get update && sudo apt-get upgrade -y"
    if [ $? -eq 0 ]; then
      echo "Update went successfully";
    else
      echo "$(tput smul)$(tput setaf 1)Update failed$(tput rmul)";
      exit 1;
    fi
} done;
</code>```

with the same ssh -t command i was thinking if i could get the hostname and assign it to a variable at the same time i'm using the first ssh session. That is so i dont have to write in my password for the ssh key twice.

So something like this:

```<code>hostname=$"(ssh -t victor@$i hostname && sudo apt-get update && sudo apt-get upgrade -y"
</code>```

And then i just echo $hostname.

答:
```<code>{ read -r hostname; read -r -d '' rest; retval=$?; } < <(
  ssh "victor@$i" "
    hostname || echo
    sudo apt-get update && sudo apt-get upgrade -y && printf '\0'
  "
)
printf '%s\n' "$rest"
if [[ $retval = 0 ]]; then  ## this is intentionally a string comparison, not numeric
  echo "Remote SSH command was successful"
else
  echo "Remote SSH command failed"
fi
</code>```

Let's break this down into pieces:

<(...) is process substitution syntax, which substitutes a filename which will, when read from, return the output of a subshell running the given commands. Thus, < <(...) is redirecting from this process substitution.

read -r hostname, run locally, reads a single line into the variable named hostname.

read -r -d '' rest reads up to the next NUL character, with a successful exit status if such a NUL is seen, and an unsuccessful exit status if not.

hostname || echo writes the system's hostname (if successful) or an empty line (otherwise).

... && printf '\0' puts a NUL on the end of the output from ssh (causing read -r -d '' rest to exit with a successful exit status) only if the commands in ... succeeded.

(Simplified from the original answer to no longer need bash 4.4 to detect when the remote apt-get commands failed).

Body:
I have this update script i am working on and i am using ssh to log onto the machine and simply run apt-get update && apt-get upgrade -y. Now the thing is i want to be able to say something like "hostname" updated successfully.

Here's what i have written right now:

#!/bin/bash

ip=(192.168.1.23 192.168.1.40 192.168.1.41 192.168.1.42 192.168.1.43)
#ssh-key=~/.ssh/id_ed25519

for i in "${ip[@]}"; do {
  ssh -t victor@$i "sudo apt-get update && sudo apt-get upgrade -y"
    if [ $? -eq 0 ]; then
      echo "Update went successfully";
    else
      echo "$(tput smul)$(tput setaf 1)Update failed$(tput rmul)";
      exit 1;
    fi
} done;

with the same ssh -t command i was thinking if i could get the hostname and assign it to a variable at the same time i'm using the first ssh session. That is so i dont have to write in my password for the ssh key twice.

So something like this:

hostname=$"(ssh -t victor@$i hostname && sudo apt-get update && sudo apt-get upgrade -y"

And then i just echo $hostname.

Body:
{ read -r hostname; read -r -d '' rest; retval=$?; } < <(
  ssh "victor@$i" "
    hostname || echo
    sudo apt-get update && sudo apt-get upgrade -y && printf '\0'
  "
)
printf '%s\n' "$rest"
if [[ $retval = 0 ]]; then  ## this is intentionally a string comparison, not numeric
  echo "Remote SSH command was successful"
else
  echo "Remote SSH command failed"
fi

Let's break this down into pieces:

<(...) is process substitution syntax, which substitutes a filename which will, when read from, return the output of a subshell running the given commands. Thus, < <(...) is redirecting from this process substitution.

read -r hostname, run locally, reads a single line into the variable named hostname.

read -r -d '' rest reads up to the next NUL character, with a successful exit status if such a NUL is seen, and an unsuccessful exit status if not.

hostname || echo writes the system's hostname (if successful) or an empty line (otherwise).

... && printf '\0' puts a NUL on the end of the output from ssh (causing read -r -d '' rest to exit with a successful exit status) only if the commands in ... succeeded.

(Simplified from the original answer to no longer need bash 4.4 to detect when the remote apt-get commands failed).


问:
jpeg binary file header with inverted width & height
I am calculating a jpg file size by parsing it as a binary file with nodejs.
But the computed width height gives 4032x3024 when the actual size is 3024x4032.
Its header 0xFFC0 block is as follow:
ffc0 0011 080b d00f c003

According to JPEG format, sizes should be :
height = 0bd0 (i.e:3024)
width = 0fc0 (i.e:4032)

(Using Imagemagick identify program confirms this calculation:
identify HJ7XFd9le.jpg
HJ7XFd9le.jpg JPEG 4032x3024 4032x3024+0+0 8-bit sRGB 380KB 0.000u 0:00.000)

But when viewing the image in my mac viewer, the inspector indicates a size of 3024x 4032!

How can i compute the correct size programmatically by parsing the file as a binary file?

Thanks!

答: Ah - it's not that the size is inverted, it's that you need to respect the EXIF orientation (rotated 90/270). The sensor is in a certain orientation and if you capture the image rotated, the camera software may signify the change by putting a non-0 orientation in the APP1 EXIF data. – BitBank


问:
How can I run a Unix script every hour, but after 4AM?
I would like to let a script run every hour, but only if its after 4AM. My current attempt:

```<code>if [ -e filename ] || [ date +%k%M < 400 ]
then don't do anything
else do something
fi
</code>```

I am assuming that at 4AM date +%k%M would show 400 or is it 0400? Is there a better way to check if 4AM has been passed?

Cheers

Edit: I'm not able to use cron jobs. The script will run 24/7 and should check if it is after or before 5AM.

答:
You could use just crontab to set hour limits:

```<code>1 4-18 * * * command
</code>```

This executes "command" between 4 am and 6 pm, at the first minute of every hour.

Body:
I would like to let a script run every hour, but only if its after 4AM. My current attempt:

if [ -e filename ] || [ date +%k%M < 400 ]
then don't do anything
else do something
fi

I am assuming that at 4AM date +%k%M would show 400 or is it 0400? Is there a better way to check if 4AM has been passed?

Cheers

Edit: I'm not able to use cron jobs. The script will run 24/7 and should check if it is after or before 5AM.

Body:
You could use just crontab to set hour limits:

1 4-18 * * * command

This executes "command" between 4 am and 6 pm, at the first minute of every hour.


问:
Produce list of directories and files based on directory using T-SQL
I have a massive list of files stored as paths in sql server.  It's easy enough to break the paths up into directories, however, I need to be able to present a list of all the files and folders on one level at a time.  SQL Server has some built in utilities to handle this for files local to the server, but they do not apply in this case.

Using a wildcard will return everything below the current directory, so I've discarded that.

Data:

```<code>C:\test\file.txt
C:\test\level2\file.txt
C:\test\level2\bc.txt
C:\test\level3\another.txt
</code>```

Ideally, I'd like to pass in a folder, and see all the files and folders at that level.  Then I can present that in a treegrid control, but that part is outside the scope of the question.

Passing in 'C:\test\' should return:

```<code>C:\test\file.txt
C:\test\level2
C:\test\level3
</code>```

答:
This does the trick. OrderBy is included to output file names before folder names. If you don't care about the order you can drop it and the order by clause.

```<code>-- Sample data.
declare @Filenames as Table ( Filename VarChar(128) );
insert into @Filenames ( Filename ) values
  ( 'C:\test\file.txt' ), ( 'C:\test\level2\file.txt' ),
  ( 'C:\test\level2\bc.txt' ), ( 'C:\test\level3\another.txt' ),
  ( 'C:\test\level3\deeper\nothing.txt' );
select * from @Filenames;

declare @Path as VarChar(128) = 'C:\test\';

-- Get the files.
--   Filename longer than   @Path , but not containing an additional reverse solidus ('\').
select Filename, 1 as OrderBy
  from @Filenames
  where Filename like @Path + '%' and Filename not like @Path + '%\%'
union
-- Get the directories.
--   Filename longer than   @Path   and containing one additional reverse solidus ('\').
--   Locate the reverse solidus after the length of   @Path   and trim from that point onwards.
--   Since there may be many files in each folder, use   distinct   to get each folder once.
select distinct SubString( Filename, 1, CharIndex( '\', Filename, Len( @Path ) + 1 ) - 1 ), 2
  from @Filenames
  where Filename like @Path + '%\%' and Filename not like @Path + '%\%\%'
order by OrderBy, Filename;
</code>```

Body:
I have a massive list of files stored as paths in sql server.  It's easy enough to break the paths up into directories, however, I need to be able to present a list of all the files and folders on one level at a time.  SQL Server has some built in utilities to handle this for files local to the server, but they do not apply in this case.

Using a wildcard will return everything below the current directory, so I've discarded that.

Data:

C:\test\file.txt
C:\test\level2\file.txt
C:\test\level2\bc.txt
C:\test\level3\another.txt

Ideally, I'd like to pass in a folder, and see all the files and folders at that level.  Then I can present that in a treegrid control, but that part is outside the scope of the question.

Passing in 'C:\test\' should return:

C:\test\file.txt
C:\test\level2
C:\test\level3

Body:
This does the trick. OrderBy is included to output file names before folder names. If you don't care about the order you can drop it and the order by clause.

-- Sample data.
declare @Filenames as Table ( Filename VarChar(128) );
insert into @Filenames ( Filename ) values
  ( 'C:\test\file.txt' ), ( 'C:\test\level2\file.txt' ),
  ( 'C:\test\level2\bc.txt' ), ( 'C:\test\level3\another.txt' ),
  ( 'C:\test\level3\deeper\nothing.txt' );
select * from @Filenames;

declare @Path as VarChar(128) = 'C:\test\';

-- Get the files.
--   Filename longer than   @Path , but not containing an additional reverse solidus ('\').
select Filename, 1 as OrderBy
  from @Filenames
  where Filename like @Path + '%' and Filename not like @Path + '%\%'
union
-- Get the directories.
--   Filename longer than   @Path   and containing one additional reverse solidus ('\').
--   Locate the reverse solidus after the length of   @Path   and trim from that point onwards.
--   Since there may be many files in each folder, use   distinct   to get each folder once.
select distinct SubString( Filename, 1, CharIndex( '\', Filename, Len( @Path ) + 1 ) - 1 ), 2
  from @Filenames
  where Filename like @Path + '%\%' and Filename not like @Path + '%\%\%'
order by OrderBy, Filename;


问:
How to show "No results found" in UITableView, if there is no search result returned?
In a table view, i am showing "No results found" if no results returned by search controller by adding an else condition as below-

In numberOfRowsInSection:

```<code>else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        return 1
}
</code>```

In cellForRowAtIndexPath:

```<code>else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        cell.textLabel?.text = "No results found"
        cellImage = nil
        cell.userInteractionEnabled = false
        isNoResultCell = true
}

if filteredIndexPath!.row == userSettings.valueForKey("selectedRow") as? Int  && !isNoResultCell {
        cell.tintColor = UIColor.whiteColor()
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        lastSelectedRow = filteredIndexPath
}
</code>```

I did some research about approaches to show "No results found" in table view but that after writing above logic.

And as per few posts, i can add a UILabel as sub view in background view of table in numberOfSectionsInTableView when there are no search results and remove the subview if search results are returned.

My question is - Which is the most resource/performance savvy option ?

答: Place a UILabel behind the table. When the table count is 0 then make the table "isHidden" = true. This will hide the table and you will then see the layer underneath it. The UI label will be shown since it is directly beneath the tableview.</p>

Body:
In a table view, i am showing "No results found" if no results returned by search controller by adding an else condition as below-

In numberOfRowsInSection:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        return 1
}

In cellForRowAtIndexPath:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        cell.textLabel?.text = "No results found"
        cellImage = nil
        cell.userInteractionEnabled = false
        isNoResultCell = true
}

if filteredIndexPath!.row == userSettings.valueForKey("selectedRow") as? Int  && !isNoResultCell {
        cell.tintColor = UIColor.whiteColor()
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        lastSelectedRow = filteredIndexPath
}

I did some research about approaches to show "No results found" in table view but that after writing above logic.

And as per few posts, i can add a UILabel as sub view in background view of table in numberOfSectionsInTableView when there are no search results and remove the subview if search results are returned.

My question is - Which is the most resource/performance savvy option ?


问:
Show all multidimensional array keys without their values?
I am working with multidimensional arrays and i need dumping they keys. But their values are wery huge. Is there some easy and quick way dump keys like print_r or var_dump but without values? Or truncated values?

Own function or 'helper' i can write by myself i want know whether exist some default function which one knows...

答:
What about array_walk_recursive? </p>

```<code> array_walk_recursive($mutliDimArray, function($v, $key){
    echo "<br/> key: ".$key."    val: ".$v;
 });
</code>```

Body:
What about array_walk_recursive?

 array_walk_recursive($mutliDimArray, function($v, $key){
    echo "<br/> key: ".$key."    val: ".$v;
 });


问:
PHP unexpected end of file happens in online testing environment, but doesn't happen in development environment
After I pulled the last code updates to an AWS instance where a test environment is running, a page displayed HTTP Error 500. I'm using CodeIgniter and the AWS instance was set to run as "production" (SetEnv CI_ENV production on .htaccess), so I changed that to "development" to display PHP error messagens. That's when I get the following mesage.

An uncaught Exception was encountered

Type: ParseError

Message: syntax error, unexpected end of file

Filename: /var/www/html/flip/application/views/flip_list.php

Line Number: 58

Backtrace:

File: /var/www/html/flip/application/controllers/Flip.php
  Line: 131
  Function: view

File: /var/www/html/flip/index.php
  Line: 315
  Function: require_once

On my localhost environment it does not happen, the page is displayed without errors or warnings.

Localhost is running PHP 7.0.15-0ubuntu0.16.04.4. And the AWS instance is running PHP 7.0.14 on CentOS. CodeIgniter version is 3.1.3.

I checked flip_list.php and Flip.php, but I didn't find where the problem is.

The controller file (Flip.php) is 350+ lines long, so I'm posting it on a pastebin: https://pastebin.com/agyMuf1T

Below the code of the view (flip_list.php):

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<?php
$first = true;
$second = false;
foreach ($editions->result() as $edition) {
    $edition_hash = $this->flip->encrypt_decrypt_edition_id($edition->edition_id, 'encrypt');

    $date = date_create($edition->edition_date);
    $date = date_format($date, 'd\/m\/Y');

    if( $first ) {
        $first = false;
        $second = true;
    ?>
    <div class="latest">
        <div class="item">
            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <span>Edição <?php echo $date; ?></span>
                <span>Número <?php echo $edition->edition_number; ?></span>
            </a>
        </div>
    </div>
    <?php
    }
    else {
    if( $second ) {
        $second = false;
    ?>
    <div class="editions">
    <div class="d-flex flex-row align-content-stretch flex-wrap">
    <?
    }
    ?>
        <div class="item">
            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <span><?php echo $date; ?></span>
            </a>
        </div>
    <?php
    }
} // foreach
?>
    </div><!-- .d-flex -->
    </div><!-- .editions -->
</code>```

I'd like some help debbuging this. Thanks!

答:
You probably have short tags (http://php.net/manual/en/language.basic-syntax.phptags.php) disabled on your test server. You have two choices, enable short tags in your php.ini or change <? to <?php.  It's generally not considered great practice to use short tags, and errors like this are one reason why, so I'd suggest changing your tags to use <?php.

I'll post part of the view which has your short tag:

```<code> <div class="editions">
    <div class="d-flex flex-row align-content-stretch flex-wrap">
    <?
    }
    ?>
        <div class="item">
</code>```

Body:
After I pulled the last code updates to an AWS instance where a test environment is running, a page displayed HTTP Error 500. I'm using CodeIgniter and the AWS instance was set to run as "production" (SetEnv CI_ENV production on .htaccess), so I changed that to "development" to display PHP error messagens. That's when I get the following mesage.

An uncaught Exception was encountered

Type: ParseError

Message: syntax error, unexpected end of file

Filename: /var/www/html/flip/application/views/flip_list.php

Line Number: 58

Backtrace:

File: /var/www/html/flip/application/controllers/Flip.php
  Line: 131
  Function: view

File: /var/www/html/flip/index.php
  Line: 315
  Function: require_once

On my localhost environment it does not happen, the page is displayed without errors or warnings.

Localhost is running PHP 7.0.15-0ubuntu0.16.04.4. And the AWS instance is running PHP 7.0.14 on CentOS. CodeIgniter version is 3.1.3.

I checked flip_list.php and Flip.php, but I didn't find where the problem is.

The controller file (Flip.php) is 350+ lines long, so I'm posting it on a pastebin: https://pastebin.com/agyMuf1T

Below the code of the view (flip_list.php):

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<?php
$first = true;
$second = false;
foreach ($editions->result() as $edition) {
    $edition_hash = $this->flip->encrypt_decrypt_edition_id($edition->edition_id, 'encrypt');

    $date = date_create($edition->edition_date);
    $date = date_format($date, 'd\/m\/Y');

    if( $first ) {
        $first = false;
        $second = true;
    ?>

            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                Edição <?php echo $date; ?>
                Número <?php echo $edition->edition_number; ?>

    <?php
    }
    else {
    if( $second ) {
        $second = false;
    ?>

    <?
    }
    ?>

            <a href="<?php echo base_url('flip/'.$slug.'/view/'.$edition_hash); ?>" class="view-edition">
                <img src="<?php echo $edition->edition_cover; ?>" class="edition-cover">
                <?php echo $date; ?>

    <?php
    }
} // foreach
?>

I'd like some help debbuging this. Thanks!

Body:
You probably have short tags (http://php.net/manual/en/language.basic-syntax.phptags.php) disabled on your test server. You have two choices, enable short tags in your php.ini or change <? to <?php.  It's generally not considered great practice to use short tags, and errors like this are one reason why, so I'd suggest changing your tags to use <?php.

I'll post part of the view which has your short tag:

 <div class="editions">
    <div class="d-flex flex-row align-content-stretch flex-wrap">
    <?
    }
    ?>
        <div class="item">


问:
DatabaseGenerated unique string annotation not working
I have an Entity Framework 6 Code-First database maintained via migrations. My entity A is like this:

```<code>public class A {
    [Key]
    [DataMember]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [DataMember]
    [StringLength(100)]
    public string Name { get; set; }

    [DataMember]
    [StringLength(6)]
    [Index(IsUnique = true)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Code { get; set; }
}
</code>```

I would like the DB to automatically populate the Code field with a unique code when inserting the new A object, without me worrying about race conditions.

However, when I try to add a new A { Name = "a1" } entry when populating the DB, the DB complaints that I Cannot insert the value NULL into column 'Code', table 'A'; column does not allow nulls. INSERT fails..

If I try to add A { Name = "a1", Code="abcdef" } the error is the same.
The only way to "solve" it is to remove the "DatabaseGenerated" annotation.

What am I doing wrong? It is not possible to have db-generated unique strings, as currently happens for int IDs?

Thank you in advance.

答: You can only have 1 AutoGenerated field on a database table and it must be a whole number type (i.e. int, bigint).  Strings can't be autogenerated like that.  If you want something unique here, just do a UniqueIdentifier or GUID as the field type instead of string and you can just assign a new Guid to it in code.  If you want it specifically to be a string, use a new Random() class to generate a random 6 characters, but you won't know if it is unique.  You'd have to manually verify that.</p>

Body:
I have an Entity Framework 6 Code-First database maintained via migrations. My entity A is like this:

public class A {
    [Key]
    [DataMember]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [DataMember]
    [StringLength(100)]
    public string Name { get; set; }

    [DataMember]
    [StringLength(6)]
    [Index(IsUnique = true)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Code { get; set; }
}

I would like the DB to automatically populate the Code field with a unique code when inserting the new A object, without me worrying about race conditions.

However, when I try to add a new A { Name = "a1" } entry when populating the DB, the DB complaints that I Cannot insert the value NULL into column 'Code', table 'A'; column does not allow nulls. INSERT fails..

If I try to add A { Name = "a1", Code="abcdef" } the error is the same.
The only way to "solve" it is to remove the "DatabaseGenerated" annotation.

What am I doing wrong? It is not possible to have db-generated unique strings, as currently happens for int IDs?

Thank you in advance.


问:
Remove stopwords with nltk.corpus from list with lists
I have a list containing lists with all seperated words of a review, that looks like this:

```<code>texts = [['fine','for','a','night'],['it','was','good']]
</code>```

I want to remove all stopwords, using the nltk.corpus package, and put all the words without stopwords back into the list. The end results should be a list, consisting of a lists of words without stopwords. This it was I tried:

```<code>import nltk
nltk.download() # to download stopwords corpus
from nltk.corpus import stopwords
stopwords=stopwords.words('english')
words_reviews=[]

for review in texts:
    wr=[]
    for word in review:
        if word not in stopwords:
            wr.append(word)
        words_reviews.append(wr)
</code>```

This code actually worked, but now I get the error: AttributeError: 'list' object has no attribute 'words', referring to stopwords. I made sure that I installed all packages. What could be the problem?

答:
The problem is that you redefine stopwords in your code:

```<code>from nltk.corpus import stopwords
stopwords=stopwords.words('english')
</code>```

After the first line, stopwords is a corpus reader with a words() method. After the second line, it is a list. Proceed accordingly.

Actually looking things up in a list is really slow, so you'll get much better performance if you use this:

```<code>stopwords = set(stopwords.words('english'))
</code>```

Body:
I have a list containing lists with all seperated words of a review, that looks like this:

texts = [['fine','for','a','night'],['it','was','good']]

I want to remove all stopwords, using the nltk.corpus package, and put all the words without stopwords back into the list. The end results should be a list, consisting of a lists of words without stopwords. This it was I tried:

import nltk
nltk.download() # to download stopwords corpus
from nltk.corpus import stopwords
stopwords=stopwords.words('english')
words_reviews=[]

for review in texts:
    wr=[]
    for word in review:
        if word not in stopwords:
            wr.append(word)
        words_reviews.append(wr)

This code actually worked, but now I get the error: AttributeError: 'list' object has no attribute 'words', referring to stopwords. I made sure that I installed all packages. What could be the problem?

Body:
The problem is that you redefine stopwords in your code:

from nltk.corpus import stopwords
stopwords=stopwords.words('english')

After the first line, stopwords is a corpus reader with a words() method. After the second line, it is a list. Proceed accordingly.

Actually looking things up in a list is really slow, so you'll get much better performance if you use this:

stopwords = set(stopwords.words('english'))


问:
C# add Embedded Resources to project while running
This is a weird question because i tought about it for some time and it doesnt really make sence to me because the program would need to re-compile, but, because if it is possible it would make my program much simpler, i need to know it there is a way to do it.
Basicly i have a .exe program.
The program has a combobox, that gets its value off a .txt file.
Its pretty simple to edit the values on the combobox, all the user has to do is to edit the .txt file and restart the program, but I need to make so that, if we move the .exe to another computer, it brings the .txt with him, so i added the .txt to my project.

The problem:
I need the user to, if needed, edit my .txt file.
If he edits the .txt file, it means i would have to update the file embedded in my .exe and from what i have searched, its not possible to do that.

My idea to solve this:
When the program starts, i copy the .txt out of the program, delete the embedded file on the project, and when the user closes my program, it copies the .txt that's on the outside, inside, like if i were to manually add it to the program again, that way if the user did edit it, if he moved the .exe to another computer, it would have its combobox values updated. It makes some sence to me, thats why im curious to see if it is possible, and if so, how do i add a external file to my project while it is running.

Thanks!

答:
You could try the other way around.

You can add an application configuration file and in that you can maintain the values for your comboBox inside appSettings section with comma separated values. During the load it will take from config and during closure of the application you just need to update the appSettings section with the updated value.

Code to update the configuration file:

```<code>Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["comboKey"].Value = "comboValues with comma separated";
config.Save(ConfigurationSaveMode.Minimal);
</code>```

When you are copying your application to some other system then you should copy the app.exe.config along with the app.exe file.

If you are trying with any installer file in different system and you would to have a user settings, then you could also use the Settings.setting file with User level scope variables.

Body:
You could try the other way around.

You can add an application configuration file and in that you can maintain the values for your comboBox inside appSettings section with comma separated values. During the load it will take from config and during closure of the application you just need to update the appSettings section with the updated value.

Code to update the configuration file:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["comboKey"].Value = "comboValues with comma separated";
config.Save(ConfigurationSaveMode.Minimal);

When you are copying your application to some other system then you should copy the app.exe.config along with the app.exe file.

If you are trying with any installer file in different system and you would to have a user settings, then you could also use the Settings.setting file with User level scope variables.


问:
Ask user to turn on Location
How can I prompt the user to turn on Location?

The app is supposed to filter a list of locations with the current location of the user. If the user has the Location service turned off, the app should prompt the user asking for the Location to be turned on.

For instance Trip Advisor app does this:

( Not sure if I can post other apps screenshots here, but if I shouldn't be doing it, please say so. And apologize for the full sized images, tried to make them smaller, but SO didn't liked it... )

In the first image, you can see I have the Location service turned off. The, after opening the Trip Advisor app, and tapping the Near me now option, I'm prompted with the second image, where I'm asked to Turn on Location services. After I tap the button, a dialog shows up so I can allow, or disallow, the Location service to be turned on. If I tap OK, the Location service is turned on on the device, and the app consumes it.

How can I achieve this?

答:
Found the solution I was asking for.

Requirements

Nuget Xamarin.GooglePlayServices.Location

Code

```<code>Int64
    interval = 1000 * 60 * 1,
    fastestInterval = 1000 * 50;

try {
    GoogleApiClient
        googleApiClient = new GoogleApiClient.Builder( this )
            .AddApi( LocationServices.API )
            .Build();

    googleApiClient.Connect();

    LocationRequest
        locationRequest = LocationRequest.Create()
            .SetPriority( LocationRequest.PriorityBalancedPowerAccuracy )
            .SetInterval( interval )
            .SetFastestInterval( fastestInterval );

    LocationSettingsRequest.Builder
        locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
            .AddLocationRequest( locationRequest );

    locationSettingsRequestBuilder.SetAlwaysShow( false );

    LocationSettingsResult
        locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(
            googleApiClient, locationSettingsRequestBuilder.Build() );

    if( locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired ) {
        locationSettingsResult.Status.StartResolutionForResult( this, 0 );
    }
} catch( Exception exception ) {
    // Log exception
}
</code>```

With this code, if the locationSettingsResult.Status.StatusCode is LocationSettingsStatusCodes.ResolutionRequired ( 6 ) it means -- probably -- that the Location is turned off, although I've found one situation that it didn't return the value when the device had the option turned off. After turning on and off, it worked, might be a bug on the device, or not.

Title: Ask user to turn on Location

Body:
Found the solution I was asking for.

Requirements

Nuget Xamarin.GooglePlayServices.Location

Code

Int64
    interval = 1000 * 60 * 1,
    fastestInterval = 1000 * 50;

try {
    GoogleApiClient
        googleApiClient = new GoogleApiClient.Builder( this )
            .AddApi( LocationServices.API )
            .Build();

    googleApiClient.Connect();

    LocationRequest
        locationRequest = LocationRequest.Create()
            .SetPriority( LocationRequest.PriorityBalancedPowerAccuracy )
            .SetInterval( interval )
            .SetFastestInterval( fastestInterval );

    LocationSettingsRequest.Builder
        locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
            .AddLocationRequest( locationRequest );

    locationSettingsRequestBuilder.SetAlwaysShow( false );

    LocationSettingsResult
        locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(
            googleApiClient, locationSettingsRequestBuilder.Build() );

    if( locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired ) {
        locationSettingsResult.Status.StartResolutionForResult( this, 0 );
    }
} catch( Exception exception ) {
    // Log exception
}

With this code, if the locationSettingsResult.Status.StatusCode is LocationSettingsStatusCodes.ResolutionRequired ( 6 ) it means -- probably -- that the Location is turned off, although I've found one situation that it didn't return the value when the device had the option turned off. After turning on and off, it worked, might be a bug on the device, or not.


问:
How to prevent overflow of div content
I have a html that when the window shrinks, the content of sub divs gets cutoff. Even though the outermost div is overflow:auto, and there is a scroll bar..
I notice that overflow:hidden is set in multiple child divs. The thing is the inner html are generated from some API and it would impractical to reset all these overflow properties.

My question is:

the height/width of these child divs are not set, why the overflow property still applies?

is there another way to prevent cutoff in child div? Like making sure the parent div has enough height?

Below is a simplified version of my html:

          Section A

          Section B

 subtitle A

 paragrah A

                       some text for the ssdfasdfdsfffffffffffffffffffffffffffffffffffffffffffffffffffff.
dddddd

 subtitle B

 paragrah A

                       some text for the testing. This text will get cutoff when the window is small enough....
dddddd

 paragrah B

                       some text for the testing. This text will get cutoff when the window is small enough....
dddddd

```

答:
This text...

```<code>some text for the ssdfasdfdsfffffffffffffffffffffffffffffffffffffffffffffffffffff.
</code>```

is most likely the cause (it appears several times). It contains one extremely long "word" which forces the table-cell which is in to be extended. But that's completely unrealistic. Use real text with real word lenghts, this will change the whole scenario.

(If you don't want to type text, just google "blindtext generator" - there are pages that generate random text for you which you can copy.)

Title: How to prevent overflow of div content

Body:
This text...

some text for the ssdfasdfdsfffffffffffffffffffffffffffffffffffffffffffffffffffff.

is most likely the cause (it appears several times). It contains one extremely long "word" which forces the table-cell which is in to be extended. But that's completely unrealistic. Use real text with real word lenghts, this will change the whole scenario.

(If you don't want to type text, just google "blindtext generator" - there are pages that generate random text for you which you can copy.)


问:
Oracle get last inserted row id using OCCI and C++
Given the code above, how can I grab the ID of the row inserted into database. I´m using C++ and oracle OCCI interface:

```<code>    std::stringstream sqlStream("");
    sqlStream << "INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :my_id_param";
    std::string sql(sqlStream.str());
    std::cout << sql << std::endl;

    std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement());
    stmt->execute(sql.c_str());

    //??? How can I access here the my_id_param ?
</code>```

Thanks for helping.

答:
You can use anonymous PL/SQL and register an OUT parameter to capture the resulting ID. This works with a sequence directly, I've not tried with a sequence used in a trigger.</p>

```<code>std::stringstream sqlStream("");
sqlStream << "BEGIN INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :1; END;";
std::string sql(sqlStream.str());
std::cout << sql << std::endl;

std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement(sql.c_str()));
stmt->registerOutParam(1, oracle::occi::OCCIINT);
stmt->executeUpdate();
int id = stmt->get(1);
// Use id...
</code>```

Body:
Given the code above, how can I grab the ID of the row inserted into database. I´m using C++ and oracle OCCI interface:

    std::stringstream sqlStream("");
    sqlStream << "INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :my_id_param";
    std::string sql(sqlStream.str());
    std::cout << sql << std::endl;

    std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement());
    stmt->execute(sql.c_str());

    //??? How can I access here the my_id_param ?

Thanks for helping.

Body:
You can use anonymous PL/SQL and register an OUT parameter to capture the resulting ID. This works with a sequence directly, I've not tried with a sequence used in a trigger.

std::stringstream sqlStream("");
sqlStream << "BEGIN INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (1, 2, 3) RETURNING ID INTO :1; END;";
std::string sql(sqlStream.str());
std::cout << sql << std::endl;

std::unique_ptr<oracle::occi::Statement> stmt(connection->createStatement(sql.c_str()));
stmt->registerOutParam(1, oracle::occi::OCCIINT);
stmt->executeUpdate();
int id = stmt->get(1);
// Use id...


问:
Optimal design of Spark job, and ensuring narrow dependencies on pre-partitioned data
Suppose I have activity data for all countries in the world (relationally speaking each record will have a country column), and I want to enrich that with some reference data also available per country and thereafter use this as input to some ML algorithm. Moreover, I know that each joined set (keyed and joined by country) fits in memory on a single executor, what is the most effecient way of processing this data at country level and unioning the results to aggregate the overall output.

My current thoughts are:

Partition and key both data sets by country, join the two data sets at country level, and thereafter use pure Scala code (within a map function) to process the data before converting the partial outputs to datasets for a final union.

Partition and key both data sets by country, join the two data sets at country level, stick to Datasets throughout and let Spark 2 optimize the computation - e.g. benefit from efficient serialized representation of the data, whole-stage-code-generation e.t.c.

Secondly, with option 2), how can I ensure after the initial keying and joining by country that all subsequent aggregation operations like groupBy() e.t.c. have narrow dependencies (since all data will be in the same 'country' partition). Would I simply need to include the country column in the keys I use in my aggregation function - e.g. groupBy(country, key1, key2...)?

答:
I would do three basic things:

Partition on country key

Use mapPartitions to transform Iterables of data on a per-partition base

Use reduceByKey or aggregateBykey for aggregations

All of this should allow you be as efficient as possible in terms of minimizing network shuffle and disk I/O while you do all your real work before you perform your write action at the end.


问:
RibbonComboBox doesn't display selected item
Very simple program. Maybe too simple?
XMAL:

```<code><RibbonComboBox x:Name="cbxRibbonCommsGroupBaud"  LargeImageSource="Resource/Cheetah.png">
   <RibbonGallery Name="RBaudGGallery" SelectionChanged="RBaudGGallery_OnSelectionChanged">
       <RibbonGalleryCategory Name="RBaudGGalleryC" ItemsSource="{Binding}"></RibbonGalleryCategory>
   </RibbonGallery>
</RibbonComboBox>
</code>```

The code behind:

```<code>private int[] baudRateList = { 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600 };
cbxRibbonCommsGroupBaud.Items.Clear();
cbxRibbonCommsGroupBaud.ItemsSource = baudRateList;
</code>```

When I run the program, the items are in the combobox drop down but when I select the item, it doesn't stay and the box appears empty. Also, RBaudGGallery_OnSelectionChanged is never called. So I'm missing something but have no clue what since other combo boxes are working just fine that aren't in the ribbon. I'm using the Reference of System.Windows.Controls.Ribbon.

答:
I think I might have found another answer : IsSynchronizedWithCurrentItem="True" on the RibbonGallery control sets the SelectedItem correctly</p>

```<code><RibbonGallery
  IsSynchronizedWithCurrentItem="True"
  SelectedItem="{Binding SelectedRule, Mode=TwoWay}"
  x:Name="RulesItems" >
      <RibbonGalleryCategory
             ItemsSource="{Binding RulesCollection, Mode=TwoWay}"
             DisplayMemberPath="DisplayName" />
</RibbonGallery>
</code>```

Body:
Very simple program. Maybe too simple?
XMAL:

<RibbonComboBox x:Name="cbxRibbonCommsGroupBaud"  LargeImageSource="Resource/Cheetah.png">
   <RibbonGallery Name="RBaudGGallery" SelectionChanged="RBaudGGallery_OnSelectionChanged">
       <RibbonGalleryCategory Name="RBaudGGalleryC" ItemsSource="{Binding}"></RibbonGalleryCategory>
   </RibbonGallery>
</RibbonComboBox>

The code behind:

private int[] baudRateList = { 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600 };
cbxRibbonCommsGroupBaud.Items.Clear();
cbxRibbonCommsGroupBaud.ItemsSource = baudRateList;

When I run the program, the items are in the combobox drop down but when I select the item, it doesn't stay and the box appears empty. Also, RBaudGGallery_OnSelectionChanged is never called. So I'm missing something but have no clue what since other combo boxes are working just fine that aren't in the ribbon. I'm using the Reference of System.Windows.Controls.Ribbon.

Body:
I think I might have found another answer : IsSynchronizedWithCurrentItem="True" on the RibbonGallery control sets the SelectedItem correctly

<RibbonGallery
  IsSynchronizedWithCurrentItem="True"
  SelectedItem="{Binding SelectedRule, Mode=TwoWay}"
  x:Name="RulesItems" >
      <RibbonGalleryCategory
             ItemsSource="{Binding RulesCollection, Mode=TwoWay}"
             DisplayMemberPath="DisplayName" />
</RibbonGallery>


问:
Update Style/Remove Attribute
I need remove style attribute of a div

Line 85
https://github.com/PolymerElements/app-layout/blob/master/app-toolbar/app-toolbar.html

```<code>::content > [condensed-title] {
        pointer-events: none;
        @apply(--layout-flex)*;
      }
</code>```

*(I don't wanna apply flexbox to [condensed-title] in a espefic head component I had made)

Line 133 https://github.com/PolymerElements/iron-flex-layout/blob/master/iron-flex-layout.html

```<code>    --layout-flex: {
  -ms-flex: 1 1 0.000000001px;
  -webkit-flex: 1;
  flex: 1;
  -webkit-flex-basis: 0.000000001px;
  flex-basis: 0.000000001px;
};
</code>```

My code

```<code><app-toolbar>
        <div class="logo-title">
          <iron-icon icon="custom-icons:casinha"></iron-icon>
        </div>
        <div id="outAlert" condensed-title>
          <paper-icon-button icon="card-membership"></paper-icon-button>
        </div>
        <div class="sublogo-title">
          <h4>Sublogo</h4>
        </div>
      </app-toolbar>
</code>```

答:
You can achieve this in 3 three ways

You can style #outAlert in your element and set flex: 0. This will overwrite app-layout's styling.

```<code>#outerAlert {
    flex: 0;
}
</code>```

Use inline style to overwrite flex and set it to 0

```<code> <div id="outAlert" condensed-title style="flex:0">
</code>```

And lastly overwrite the --layout-flex mixin for the app-layout where you don't want flex to be there.

```<code>app-layout {
   --layout-flex: {
      flex: 0; /* You can have any other value also. Not sure if empty mixin will work or not */
   };
}
</code>```

Title: Update Style/Remove Attribute

Body:
I need remove style attribute of a div

Line 85
https://github.com/PolymerElements/app-layout/blob/master/app-toolbar/app-toolbar.html

::content > [condensed-title] {
        pointer-events: none;
        @apply(--layout-flex)*;
      }

*(I don't wanna apply flexbox to [condensed-title] in a espefic head component I had made)

Line 133 https://github.com/PolymerElements/iron-flex-layout/blob/master/iron-flex-layout.html

    --layout-flex: {
  -ms-flex: 1 1 0.000000001px;
  -webkit-flex: 1;
  flex: 1;
  -webkit-flex-basis: 0.000000001px;
  flex-basis: 0.000000001px;
};

My code

<app-toolbar>

          <iron-icon icon="custom-icons:casinha"></iron-icon>

          <paper-icon-button icon="card-membership"></paper-icon-button>

Sublogo

      </app-toolbar>

Body:
You can achieve this in 3 three ways

You can style #outAlert in your element and set flex: 0. This will overwrite app-layout's styling.

#outerAlert {
    flex: 0;
}

Use inline style to overwrite flex and set it to 0

 <div id="outAlert" condensed-title style="flex:0">

And lastly overwrite the --layout-flex mixin for the app-layout where you don't want flex to be there.

app-layout {
   --layout-flex: {
      flex: 0; /* You can have any other value also. Not sure if empty mixin will work or not */
   };
}


问:
Jenkins / Slack integration
I need to configure Jenkins to send notification on our Slack channel #builds.
I configured the Jenkins CI integration in Slack. As a result, I have a token "abcdefgh666", and when I expand the "Setup instructions", I can see our team domain is "mysuperteam". We connect to slack with the url http://mysuperteam.slack.com

I am stuck on step 3. On Slack doc, the screenshot is the following:

But in our Jenkins version, the view looks like:

Obviously, the Test Connection button always return a Failure. In Jenkins logs, I have this many times:

```<code>Mar 30, 2017 2:14:38 PM WARNING jenkins.plugins.slack.StandardSlackService publish
Error posting to Slack
java.lang.IllegalStateException: Target host is null
    at org.apache.http.util.Asserts.notNull(Asserts.java:46)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at jenkins.plugins.slack.StandardSlackService.publish(StandardSlackService.java:126)
    at jenkins.plugins.slack.SlackNotifier$DescriptorImpl.doTestConnection(SlackNotifier.java:510)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:335)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:175)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:108)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:124)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:126)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:80)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:553)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
    at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I tried using the credentials menu to avoid putting the token directly, I tried to put "slack.com" in "Base URL" field, I tried to check or uncheck the "Is Bot User ?" field, and I tried to put "http://mysuperteam.slack.com" in "Base URL" field.

Is my configuration correct ? What could prevent Jenkins to connect to Slack ?

答:
I had the same issue and found out that I had to create an incoming webhook on the slack interface (https://slack.com/apps/A0F7XDUAZ-incoming-webhooks)

But still I cant get it working...

edit: I may have misinterpreted the installation instruction at https://github.com/jenkinsci/slack-plugin, anyway it's not up to date

Title: Jenkins / Slack integration

Body:
I need to configure Jenkins to send notification on our Slack channel #builds.
I configured the Jenkins CI integration in Slack. As a result, I have a token "abcdefgh666", and when I expand the "Setup instructions", I can see our team domain is "mysuperteam". We connect to slack with the url http://mysuperteam.slack.com

I am stuck on step 3. On Slack doc, the screenshot is the following:

But in our Jenkins version, the view looks like:

Obviously, the Test Connection button always return a Failure. In Jenkins logs, I have this many times:

Mar 30, 2017 2:14:38 PM WARNING jenkins.plugins.slack.StandardSlackService publish
Error posting to Slack
java.lang.IllegalStateException: Target host is null
    at org.apache.http.util.Asserts.notNull(Asserts.java:46)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at jenkins.plugins.slack.StandardSlackService.publish(StandardSlackService.java:126)
    at jenkins.plugins.slack.SlackNotifier$DescriptorImpl.doTestConnection(SlackNotifier.java:510)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:335)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:175)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:108)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:124)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:126)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:80)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:553)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
    at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

I tried using the credentials menu to avoid putting the token directly, I tried to put "slack.com" in "Base URL" field, I tried to check or uncheck the "Is Bot User ?" field, and I tried to put "http://mysuperteam.slack.com" in "Base URL" field.

Is my configuration correct ? What could prevent Jenkins to connect to Slack ?


问:
C# - Transparent Form
I currently have a Form with all the desired effects except one. The current form consists out of a menustrip at the top with a panel underneath which contains labels and pictureboxes. When the form is launched the menustrip is not visible, it only becomes visible while the user presses the 'Alt'-button and disappears in the same manner.

The panel will have a background-image with a transparent background (.PNG). This image will become the main layout of the form as I set the borderstyle to none. Now the problem is that the form still has the white/grayish background underneath the panel.

Now my question is how do I make the form transparent so the image on the panel becomes the main layout rather than just the image with the forms backcolor underneath it. I do not want to use the Opacity property as I want the panel to be visible 100%.

答:
Assuming WinForms.

You can do this, but you cannot make the edges semi-transparent.

Try this.

On the form, set the following properties:

```<code>BackColor = Color.Lime;
TransparencyKey = Color.Lime;
</code>```

This will make the form transparent. Then set the backgroundimage:

```<code>BackgroundImage = myImage:
</code>```

The parts of the backgroundimage that is also Color.Limewill also get transparent.

If you also want to get rid of the Forms borders, add this line as well:

```<code>FormBorderStyle = FormBorderStyle.None;
</code>```

Title: C# - Transparent Form

Body:
Assuming WinForms.

You can do this, but you cannot make the edges semi-transparent.

Try this.

On the form, set the following properties:

BackColor = Color.Lime;
TransparencyKey = Color.Lime;

This will make the form transparent. Then set the backgroundimage:

BackgroundImage = myImage:

The parts of the backgroundimage that is also Color.Limewill also get transparent.

If you also want to get rid of the Forms borders, add this line as well:

FormBorderStyle = FormBorderStyle.None;


问:
Changed JAVA_HOME and PATH but java version remains the same
I have a Red Hat Linux machine where I am trying to use Java 8.

So I did this:

```<code>export JAVA_HOME=/my/path/to/oracle/jdk/1.8/exec
export PATH=$PATH:$JAVA_HOME
</code>```

However, if I run java -version I get java version "1.7.0_121".

I looked at this similar question, but I don't seem to have the same problem.

If I run $JAVA_HOME/bin/java -version I get java version "1.8.0_72-b15", so JAVA_HOME does point to Java 8.

which java outputs /usr/bin/java.

So how can JAVA_HOME point to Java 8, while java -version points to Java 7?

答:
Default java binary is managed in Linux using alternatives

```<code>someuser@linux:~/tmp> /usr/sbin/alternatives --display java | grep 'priority'
/usr/lib64/jvm/jre-1.7.0-openjdk/bin/java - priority 1705
/usr/lib64/jvm/jre-1.8.0-openjdk/bin/java - priority 1805
</code>```

Java 8 gets the higher priority. Also, Linux does not use $JAVA_HOME to determine the path to a binary so setting it has no effect in this case.

To set default java version using alternatives refer to this answer: https://askubuntu.com/questions/121654/how-to-set-default-java-version

Body:
I have a Red Hat Linux machine where I am trying to use Java 8.

So I did this:

export JAVA_HOME=/my/path/to/oracle/jdk/1.8/exec
export PATH=$PATH:$JAVA_HOME

However, if I run java -version I get java version "1.7.0_121".

I looked at this similar question, but I don't seem to have the same problem.

If I run $JAVA_HOME/bin/java -version I get java version "1.8.0_72-b15", so JAVA_HOME does point to Java 8.

which java outputs /usr/bin/java.

So how can JAVA_HOME point to Java 8, while java -version points to Java 7?

Body:
Default java binary is managed in Linux using alternatives

someuser@linux:~/tmp> /usr/sbin/alternatives --display java | grep 'priority'
/usr/lib64/jvm/jre-1.7.0-openjdk/bin/java - priority 1705
/usr/lib64/jvm/jre-1.8.0-openjdk/bin/java - priority 1805

Java 8 gets the higher priority. Also, Linux does not use $JAVA_HOME to determine the path to a binary so setting it has no effect in this case.

To set default java version using alternatives refer to this answer: https://askubuntu.com/questions/121654/how-to-set-default-java-version


问:
How to analyze movie titles?
I want to predict movie gross collections using data that is available before release, eg title, actors, director, studio, critic ratings, genre, etc. I found a way to numerically quantify most of these, but could not quantify title. The title conveys much useful information, such as if the movie is a sequel, length of title, sentiment associated, etc. How to extract these information quantitatively from title?</p>

答:
BoWs are the standard way to create text based features, though I wouldn't recommend it since movie titles are short and many of them contains out of context words, named entity.. which will make your feature vector even more sparse.

You can create a word2vec encoding of each word of the title and then take the mean vector of the title as your feature. My favorite tools to do it: gensim or Facebook fast Text

Title: How to analyze movie titles?


问:
PHP - ZF2 - render template from string variable
i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:

```<code>$template = "<div>easy</div>";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);
</code>```

This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.

Thx for your time and respond.

答: Try by replacing '\' with _ underscore as Zend_View_Renderer_PhpRenderer

Body:
i have problem with rendering template in ZF2, where template is in string in variable. There is simple example:

$template = "
easy
";
$view = new \Zend\View\Model\ViewModel();
$view->setTemplate($template);

$renderer = new \Zend\View\Renderer\PhpRenderer();
$html = $renderer->render($view);

This code fail on rendering, the renderer think that the template is a path to file. And iam reallz not sure how to tell rendere its a string.

Thx for your time and respond.