问:
In Neo4j how to exclude results of one query from another
Say I have two queries

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
RETURN a

MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
RETURN a

I want to combine the two. Such that I have results from query2 that donot fit query1

So far I have tried the following

MATCH (a:User)-[:Likes]->(b:Object)
 MATCH (a:User)-[:HasVisited]->(c:Location)
 WHERE
    <condition on c>
    AND NOT <condition on b>
 RETURN a

but this approach does not exclude all results that i wanted excluded.

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
WITH collect(DISTINCT a) as exc
MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
    AND NOT a IN exc
RETURN a

This gives the right results but gets inefficient once query1 and query2 start becoming more complicated

I have also tried

MATCH (a:User)-[:Likes]->(b:Object)
    WHERE <condition on b>
WITH collect(DISTINCT a) as exc
MATCH (a:User)
    WHERE NOT a IN exc
    WITH a
MATCH MATCH (a:User)-[:HasVisited]->(c:Location)
    WHERE <condition on c>
RETURN a

I had hoped reducing the number of nodes that a can match against upfront would improve performance but this approach doesnt seem to work any better.

Is there a standard/better way to exclude results matching one query from another?

答:
You can try some like this:</p>

```<code>MATCH (U1:User)-[:HasVisited]->(L:Location)
    WHERE <condition on c>
WITH distinct U1
OPTIONAL MATCH (U2:User)-[:Likes]->(O:Object)
    WHERE U2 = U1 AND
          <condition on b>
WITH U1,
     count(U2) as excl
    WHERE excl = 0
RETURN U1
</code>```

Body:
You can try some like this:

MATCH (U1:User)-[:HasVisited]->(L:Location)
    WHERE <condition on c>
WITH distinct U1
OPTIONAL MATCH (U2:User)-[:Likes]->(O:Object)
    WHERE U2 = U1 AND
          <condition on b>
WITH U1,
     count(U2) as excl
    WHERE excl = 0
RETURN U1


来源: stackexchange

问:
addEventListener IE11 bug
I am working with three.js on IE11 and have a problem with the addEventListener func;

The code inside the function is never being executed:

```<code>var fileInput = document.createElement( 'input' );
fileInput.type = 'file';
fileInput.addEventListener( 'change', function ( event ) {
        editor.loader.loadFile( fileInput.files[ 0 ] );
} );
</code>```

the browser familiar with the addEventListener func, bet somehow the inside function is not being called when i 'click' fileInput button:

```<code>var importOption = new UI.Panel();
importOption.setClass('option');
importOption.setTextContent('Import');
importOption.onClick(function () {

    fileInput.click();

} );
options.add(importOption);
</code>```

Any ideas of how can i trigger the 'change' function? I want it to be triggered by user button press, like it is written in the code.

This code was taken from the three.js source files, and works just fine on chrome.

Thanks in advance.

答:
I had a similar problem with binding a click event to an html element created in this way. It didn't work on IE11 in Windows 8, but did in IE11 on Windows 10, Edge and in all other browsers.

My code looked like:

```<code>var trigger = document.createElement( 'div' );
fileInput.addEventListener( 'click', function ( e) {
    console.log("clicked the trigger");
} );
trigger.click();
</code>```

That log wasn't appearing in my console.

I found that I could resolve the problem by adding the trigger to document.body.

```<code>var trigger = document.createElement( 'div' );
trigger.style.display = "none";
document.body.appendChild(trigger);
fileInput.addEventListener( 'click', function ( e ) {
    console.log("clicked the trigger");
} );
trigger.click();
</code>```

Hope that helps!

ContentLicense: CC BY-SA 3.0

Title: addEventListener IE11 bug

Body:
I am working with three.js on IE11 and have a problem with the addEventListener func;

The code inside the function is never being executed:

var fileInput = document.createElement( 'input' );
fileInput.type = 'file';
fileInput.addEventListener( 'change', function ( event ) {
        editor.loader.loadFile( fileInput.files[ 0 ] );
} );

the browser familiar with the addEventListener func, bet somehow the inside function is not being called when i 'click' fileInput button:

var importOption = new UI.Panel();
importOption.setClass('option');
importOption.setTextContent('Import');
importOption.onClick(function () {

    fileInput.click();

} );
options.add(importOption);

Any ideas of how can i trigger the 'change' function? I want it to be triggered by user button press, like it is written in the code.

This code was taken from the three.js source files, and works just fine on chrome.

Thanks in advance.

Body:
I had a similar problem with binding a click event to an html element created in this way. It didn't work on IE11 in Windows 8, but did in IE11 on Windows 10, Edge and in all other browsers.

My code looked like:

var trigger = document.createElement( 'div' );
fileInput.addEventListener( 'click', function ( e) {
    console.log("clicked the trigger");
} );
trigger.click();

That log wasn't appearing in my console.

I found that I could resolve the problem by adding the trigger to document.body.

var trigger = document.createElement( 'div' );
trigger.style.display = "none";
document.body.appendChild(trigger);
fileInput.addEventListener( 'click', function ( e ) {
    console.log("clicked the trigger");
} );
trigger.click();

Hope that helps!


问:
.podspec error - source_files` pattern did not match any file
I am integrating one of my github repos (full code here if it helps) with Cocopods, and I get this error when I run pod spec lint.

```<code> -> DropDownMenu (0.0.1)
  - ERROR | [iOS] The `source_files` pattern did not match any file.
</code>```

This is the relevant code of my .podspec which I believe is causing the problem.

Looking at examples here, here, and here, I have tried the following

```<code>s.source_files  = 'Classes/*.{h,m}'
s.source_files  = 'Classes/DropDownMenu.{h,m}'
s.source_files  = 'Classes'
s.source_files  = 'Classes/**/*.{h,m}'
</code>```

Is my s.source_files field incorrect? Or did I do something wrong with the .podspec? What can I do to fix this?

My problem is similar to this question, however the solution does not work for me (my code is updated on Github).

答: I've solved my issue by changing version number of my pod. Please check my answer at ERROR | [iOS] file patterns: The `source_files` pattern did not match any file</p>

Body:
I am integrating one of my github repos (full code here if it helps) with Cocopods, and I get this error when I run pod spec lint.

 -> DropDownMenu (0.0.1)
  - ERROR | [iOS] The `source_files` pattern did not match any file.

This is the relevant code of my .podspec which I believe is causing the problem.

Looking at examples here, here, and here, I have tried the following

s.source_files  = 'Classes/*.{h,m}'
s.source_files  = 'Classes/DropDownMenu.{h,m}'
s.source_files  = 'Classes'
s.source_files  = 'Classes/**/*.{h,m}'

Is my s.source_files field incorrect? Or did I do something wrong with the .podspec? What can I do to fix this?

My problem is similar to this question, however the solution does not work for me (my code is updated on Github).


问:
PHP: Previous Month from current month formula is not working
It might be Duplicate Question, but I tried but it doesn't work.
Something confusion is there, which I am not getting it.I tried for all months its working but its not working for "March" Month.I know it sound weird, but I tried everything.

Aim: Show Previous Month from Given Month.

PHP:

```<code>$month='March';
$pre_mth =Date("F", strtotime($month . " last month"));
echo $pre_mth;

Actual Output: March    Expected Output:February
</code>```

Please let me know.Thanks in advance.

答:
Try this:</p>

```<code>$pre_mth = date('F',strtotime('first day of last month', strtotime($month)));
echo $pre_mth;
</code>```

Body:
It might be Duplicate Question, but I tried but it doesn't work.
Something confusion is there, which I am not getting it.I tried for all months its working but its not working for "March" Month.I know it sound weird, but I tried everything.

Aim: Show Previous Month from Given Month.

PHP:

$month='March';
$pre_mth =Date("F", strtotime($month . " last month"));
echo $pre_mth;

Actual Output: March    Expected Output:February

Please let me know.Thanks in advance.

Body:
Try this:

$pre_mth = date('F',strtotime('first day of last month', strtotime($month)));
echo $pre_mth;


问:
Force Laravel to log in a user using legacy authentication
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

```<code>// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();
</code>```

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.

答:
This is a little bit tricky because Laravel use encrypted cookies which is handled by EncryptCookies middleware. You can get your code working if you disable it but I wouldn't recommend it.

The solution is to use Laravel EncryptCookies middleware to decrypt the request and then encrypt the response. This will make the session created by your legacy authentication readable by Laravel.

Consider this is called login.php file, which needs $user_id to log the user by id to laravel.

```<code><?php

require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
$encryptCookies = new App\Http\Middleware\EncryptCookies($app['encrypter']);

$app['session']->driver()->start();

$app['auth']->loginUsingId($user_id);

$response = $encryptCookies->handle($request, function ($request) use ($startSession, $response)
{
    return $startSession->handle($request, function () use ($response)
    {
        return $response;
    });
});

$app['session']->driver()->save();

var_dump($app['auth']->user());

$response->send();
</code>```

Inside the closure of $encryptCookies->handle(), you can read the request after decryption and this is where you can modify the session. And when you return the response, it will be encrypted again and you can then send it to the browser.

To read the session in another file you can simply do this:

```<code><?php

require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
$encryptCookies = new App\Http\Middleware\EncryptCookies($app['encrypter']);

$response = $encryptCookies->handle($request, function ($request) use ($startSession, $response)
{
    return $startSession->handle($request, function () use ($response)
    {
        return $response;
    });
});

var_dump($app['auth']->user());

$response->send();
</code>```

Body:
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.

Body:
This is a little bit tricky because Laravel use encrypted cookies which is handled by EncryptCookies middleware. You can get your code working if you disable it but I wouldn't recommend it.

The solution is to use Laravel EncryptCookies middleware to decrypt the request and then encrypt the response. This will make the session created by your legacy authentication readable by Laravel.

Consider this is called login.php file, which needs $user_id to log the user by id to laravel.

<?php

require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
$encryptCookies = new App\Http\Middleware\EncryptCookies($app['encrypter']);

$app['session']->driver()->start();

$app['auth']->loginUsingId($user_id);

$response = $encryptCookies->handle($request, function ($request) use ($startSession, $response)
{
    return $startSession->handle($request, function () use ($response)
    {
        return $response;
    });
});

$app['session']->driver()->save();

var_dump($app['auth']->user());

$response->send();

Inside the closure of $encryptCookies->handle(), you can read the request after decryption and this is where you can modify the session. And when you return the response, it will be encrypted again and you can then send it to the browser.

To read the session in another file you can simply do this:

<?php

require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
$encryptCookies = new App\Http\Middleware\EncryptCookies($app['encrypter']);

$response = $encryptCookies->handle($request, function ($request) use ($startSession, $response)
{
    return $startSession->handle($request, function () use ($response)
    {
        return $response;
    });
});

var_dump($app['auth']->user());

$response->send();


问:
PHP/Javascript: Javascript not sending data to PHP
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

```<code><script type="text/javascript">
function search(str)
{
if (str=="")
  {
  document.getElementById("search").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {//IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {//IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("search").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","leaderboard.php?q="+str,true);
xmlhttp.send();
}
</script>
</code>```

Text input:

```<code><form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>
</code>```

PHP:

```<code><?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
  $i++;
 }
 }
?>
</code>```

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

```<code><table border="0" cellspacing="15" padding="0" width="200">

<th><font color="#00FF00">Rank</font></th>
<th><font color="#00FF00">Username</font></th>
<th><font color="#00FF00">Score</font></th>
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
    $i++;
}
}
?>
</table>
</code>```

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.

答:
I'm assuming you want to implement a kind of autocomplete.

I think this line:

```<code> document.getElementById("search").innerHTML=xmlhttp.responseText;
</code>```

should be:

```<code> document.getElementById("search_result").value=xmlhttp.responseText;
</code>```

You need to have a search_result table, as Pointy pointed out.

In case you are interested in going the jQuery route, this would be your new code:

```<code>function search(str){
    if (str != "")
        $.get("leaderboard.php", {q : str}, function(r){
            $("#search_result").html(r);
        });
}
</code>```

If you want to use the Enter key, I would (again) recommend jQuery because you can accomplish this with a few lines of code, instead of several more with pure JavaScript.

ContentLicense: CC BY-SA 2.5

Body:
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

Text input:

<form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>

PHP:

<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
  $i++;
 }
 }
?>

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

Rank
Username
Score
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
    $i++;
}
}
?>

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.

Body:
I'm assuming you want to implement a kind of autocomplete.

I think this line:

 document.getElementById("search").innerHTML=xmlhttp.responseText;

should be:

 document.getElementById("search_result").value=xmlhttp.responseText;

You need to have a search_result table, as Pointy pointed out.

In case you are interested in going the jQuery route, this would be your new code:

function search(str){
    if (str != "")
        $.get("leaderboard.php", {q : str}, function(r){
            $("#search_result").html(r);
        });
}

If you want to use the Enter key, I would (again) recommend jQuery because you can accomplish this with a few lines of code, instead of several more with pure JavaScript.


问:
Travis CI skipping SonarQube analysis
I'm trying to configure SonarQube analysis in a github project. I've followed the official travis ci documentation but SonarQube analysis is not performed.

I'm getting the following message: "Skipping SonarQube Scan because it is not running in a secure environment"

pull request link: https://github.com/zakshya/cronos/pull/4

Full build log: https://s3.amazonaws.com/archive.travis-ci.org/jobs/216125526/log.txt

Does some one encountered this problem ?
I'm i missing some config ?

答:
As mentioned in the official documentation of the SonarQube Travis Add-on about analysing pull requests:

For security reasons, this advanced feature
  [i.e. pull request analysis]
  works only for internal pull requests. In other words, pull requests
  built from forks won’t be inspected.

Title: Travis CI skipping SonarQube analysis


问:
Upgrading K8S cluster from v1.2.0 to v1.3.0
I have 1 master and 4 minions all running on version 1.2.0. I am planning to upgrade them to 1.3.0. I want this done with minimal downtime.

So I did the following on one minion.

```<code>systemctl stop kubelet
yum update kubernetes-1.3.0-0.3.git86dc49a.el7
systemctl start kubelet
</code>```

Once I bring up the service, i see the following ERROR.

```<code>Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.215614    9902 kubelet.go:1222] Unable to register node "172.29.240.169" with API server: the body of the request was in an unknown format - accepted media types include: application/json, application/yaml
Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.217612    9902 event.go:198] Server rejected event '&api.Event{TypeMeta:unversioned.TypeMeta{Kind:"", APIVersion:""}, ObjectMeta:api.ObjectMeta{Name:"172.29.240.169.14b01ded8fb2d07b", GenerateName:"", Namespace:"default", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:unversioned.Time{Time:time.Time{sec:0, nsec:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*unversioned.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string(nil), Annotations:map[string]string(nil), OwnerReferences:[]api.OwnerReference(nil), Finalizers:[]string(nil)}, InvolvedObject:api.ObjectReference{Kind:"Node", Namespace:"", Name:"172.29.240.169", UID:"172.29.240.169", APIVersion:"", ResourceVersion:"", FieldPath:""}, Reason:"NodeHasSufficientDisk", Message:"Node 172.29.240.169 status is now: NodeHasSufficientDisk", Source:api.EventSource{Component:"kubelet", Host:"172.29.240.169"}, FirstTimestamp:unversioned.Time{Time:time.Time{sec:63626321182, nsec:814949499, loc:(*time.Location)(0x4c8a780)}}, LastTimestamp:unversioned.Time{Time:time.Time{sec:63626330215, nsec:213372890, loc:(*time.Location)(0x4c8a780)}}, Count:1278, Type:"Normal"}': 'the body of the request was in an unknown format - accepted media types include: application/json, application/yaml' (will not retry!)
Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.246100    9902 event.go:198] Server rejected event '&api.Event{TypeMeta:unversioned.TypeMeta{Kind:"", APIVersion:""}, ObjectMeta:api.ObjectMeta{Name:"172.29.240.169.14b01ded8fb2fc88", GenerateName:"", Namespace:"default", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:unversioned.Time{Time:time.Time{sec:0, nsec:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*unversioned.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string(nil), Annotations:map[string]string(nil), OwnerReferences:[]api.OwnerReference(nil), Finalizers:[]string(nil)}, InvolvedObject:api.ObjectReference{Kind:"Node", Namespace:"", Name:"172.29.240.169", UID:"172.29.240.169", APIVersion:"", ResourceVersion:"", FieldPath:""}, Reason:"NodeHasSufficientMemory", Message:"Node 172.29.240.169 status is now: NodeHasSufficientMemory", Source:api.EventSource{Component:"kubelet", Host:"172.29.240.169"}, FirstTimestamp:unversioned.Time{Time:time.Time{sec:63626321182, nsec:814960776, loc:(*time.Location)(0x4c8a780)}}, LastTimestamp:unversioned.Time{Time:time.Time{sec:63626330215, nsec:213381138, loc:(*time.Location)(0x4c8a780)}}, Count:1278, Type:"Normal"}': 'the body of the request was in an unknown format - accepted media types include: application/json, application/yaml' (will not retry!)
</code>```

Is v1.2.0 incompatible with v1.3.0 ?

Seems like the issue is with JSON incompatibility ? application/json, application/yaml

From master standpoint ::

```<code>[root@kubernetes-master ~]# kubectl get nodes
NAME             STATUS     AGE
172.29.219.105   Ready      3h
172.29.240.146   Ready      3h
172.29.240.168   Ready      3h
172.29.240.169   NotReady   3h
</code>```

The node that I upgraded is in NotReady state.

答:
As per the documentation you must upgrade your master components (kube-scheduler, kube-apiserver and kube-controller-manager) before your node components (kubelet, kube-proxy).

https://kubernetes.io/docs/getting-started-guides/ubuntu/upgrades/

Body:
I have 1 master and 4 minions all running on version 1.2.0. I am planning to upgrade them to 1.3.0. I want this done with minimal downtime.

So I did the following on one minion.

systemctl stop kubelet
yum update kubernetes-1.3.0-0.3.git86dc49a.el7
systemctl start kubelet

Once I bring up the service, i see the following ERROR.

Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.215614    9902 kubelet.go:1222] Unable to register node "172.29.240.169" with API server: the body of the request was in an unknown format - accepted media types include: application/json, application/yaml
Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.217612    9902 event.go:198] Server rejected event '&api.Event{TypeMeta:unversioned.TypeMeta{Kind:"", APIVersion:""}, ObjectMeta:api.ObjectMeta{Name:"172.29.240.169.14b01ded8fb2d07b", GenerateName:"", Namespace:"default", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:unversioned.Time{Time:time.Time{sec:0, nsec:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*unversioned.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string(nil), Annotations:map[string]string(nil), OwnerReferences:[]api.OwnerReference(nil), Finalizers:[]string(nil)}, InvolvedObject:api.ObjectReference{Kind:"Node", Namespace:"", Name:"172.29.240.169", UID:"172.29.240.169", APIVersion:"", ResourceVersion:"", FieldPath:""}, Reason:"NodeHasSufficientDisk", Message:"Node 172.29.240.169 status is now: NodeHasSufficientDisk", Source:api.EventSource{Component:"kubelet", Host:"172.29.240.169"}, FirstTimestamp:unversioned.Time{Time:time.Time{sec:63626321182, nsec:814949499, loc:(*time.Location)(0x4c8a780)}}, LastTimestamp:unversioned.Time{Time:time.Time{sec:63626330215, nsec:213372890, loc:(*time.Location)(0x4c8a780)}}, Count:1278, Type:"Normal"}': 'the body of the request was in an unknown format - accepted media types include: application/json, application/yaml' (will not retry!)
Mar 28 20:36:55 csdp-e2e-kubernetes-minion-6 kubelet[9902]: E0328 20:36:55.246100    9902 event.go:198] Server rejected event '&api.Event{TypeMeta:unversioned.TypeMeta{Kind:"", APIVersion:""}, ObjectMeta:api.ObjectMeta{Name:"172.29.240.169.14b01ded8fb2fc88", GenerateName:"", Namespace:"default", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:unversioned.Time{Time:time.Time{sec:0, nsec:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*unversioned.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string(nil), Annotations:map[string]string(nil), OwnerReferences:[]api.OwnerReference(nil), Finalizers:[]string(nil)}, InvolvedObject:api.ObjectReference{Kind:"Node", Namespace:"", Name:"172.29.240.169", UID:"172.29.240.169", APIVersion:"", ResourceVersion:"", FieldPath:""}, Reason:"NodeHasSufficientMemory", Message:"Node 172.29.240.169 status is now: NodeHasSufficientMemory", Source:api.EventSource{Component:"kubelet", Host:"172.29.240.169"}, FirstTimestamp:unversioned.Time{Time:time.Time{sec:63626321182, nsec:814960776, loc:(*time.Location)(0x4c8a780)}}, LastTimestamp:unversioned.Time{Time:time.Time{sec:63626330215, nsec:213381138, loc:(*time.Location)(0x4c8a780)}}, Count:1278, Type:"Normal"}': 'the body of the request was in an unknown format - accepted media types include: application/json, application/yaml' (will not retry!)

Is v1.2.0 incompatible with v1.3.0 ?

Seems like the issue is with JSON incompatibility ? application/json, application/yaml

From master standpoint ::

[root@kubernetes-master ~]# kubectl get nodes
NAME             STATUS     AGE
172.29.219.105   Ready      3h
172.29.240.146   Ready      3h
172.29.240.168   Ready      3h
172.29.240.169   NotReady   3h

The node that I upgraded is in NotReady state.


问:
Convert recursive function to iterative
I have this recursive defined function:

Function

And I've already implemented it in C++:

```<code>int f_recursive(int n) {
if (n <= 2) {
    return 1;
}
else {
    return ( n * f_recursive(n - 1) - f_recursive(n - 2) );
}
</code>```

How can I calculate the same function iteratively?

答:
For fun, my first attempt. Can anyone improve?

```<code>#include <iostream>
#include <iomanip>

int f_recursive(int n)
{
    if (n <= 2) {
        return 1;
    }
    else {
        return (n * f_recursive(n - 1) - f_recursive(n - 2));
    }
}

int f_iterative(int n)
{
    int result = 1, result_1 = 1;

    for (int i = 3 ; i <= n ; ++i) {
        int result_2 = result_1;
        result_1 = result;
        result = i * result_1 - result_2;
    }
    return result;
}

int main()
{
    for(int i = 0 ; i < 14 ; ++i) {
        std::cout << std::setw(10) << f_recursive(i) << " " << f_iterative(i) << std::endl;
    }
}
</code>```

sample output:

```<code>         1 1
         1 1
         1 1
         2 2
         7 7
        33 33
       191 191
      1304 1304
     10241 10241
     90865 90865
    898409 898409
   9791634 9791634
 116601199 116601199
1506023953 1506023953
</code>```

Title: Convert recursive function to iterative

Body:
I have this recursive defined function:

Function

And I've already implemented it in C++:

int f_recursive(int n) {
if (n <= 2) {
    return 1;
}
else {
    return ( n * f_recursive(n - 1) - f_recursive(n - 2) );
}

How can I calculate the same function iteratively?

Body:
For fun, my first attempt. Can anyone improve?

#include <iostream>
#include <iomanip>

int f_recursive(int n)
{
    if (n <= 2) {
        return 1;
    }
    else {
        return (n * f_recursive(n - 1) - f_recursive(n - 2));
    }
}

int f_iterative(int n)
{
    int result = 1, result_1 = 1;

    for (int i = 3 ; i <= n ; ++i) {
        int result_2 = result_1;
        result_1 = result;
        result = i * result_1 - result_2;
    }
    return result;
}

int main()
{
    for(int i = 0 ; i < 14 ; ++i) {
        std::cout << std::setw(10) << f_recursive(i) << " " << f_iterative(i) << std::endl;
    }
}

sample output:

         1 1
         1 1
         1 1
         2 2
         7 7
        33 33
       191 191
      1304 1304
     10241 10241
     90865 90865
    898409 898409
   9791634 9791634
 116601199 116601199
1506023953 1506023953


问:
Extract properties file from JAR dependency and use it in own classpath
I want to use a small program as a dependency in my Maven project. This program is configured by a properties file which can be edited before its execution. So far I have added the dependency as JAR in a local repository.

Now I want to make that dependency's properties file accessible in my own superior classpath, i.e. in myprogram/src/main/resources/config/myprogram.properties and not in myprogram/local-repository/com/example/mydependency/mydependency.jar/mydependency.properties.

I tried to modify the part of the code where the path for the properties file is defined:

```<code>public example() {

    Properties prop = new Properties();
    InputStream input = example.class.getResourceAsStream("/config/myprogram.properties");
    prop.load(input);

    ...

}
</code>```

I also deleted the original properties file of the dependency before adding it to my local repository.

The whole program is working, but not as expected. Strangely, neither my new properties file in /src/main/resources/config nor the old one in the mydependency.jar is used. It seems that some kind of default properties file is put into my final fat JAR. But I cannot find its source anywhere - even when I try to debug it. That default properties file just seems to appear out of nowhere.

Now, how can I properly move the dependency's properties file to my own classpath?

And where could this default properties file appear from?

Is this an issue with Maven or with the source code itself?

Thanks in advance!

答:
You can do something like this:

```<code>    public static String getValueFromDependencyProps(ClassLoader cl, String propertiesFile, String key) throws IOException {
    Properties prop = new Properties();
    prop.load(cl.getResourceAsStream(propertiesFile));
    String value = prop.getProperty(key);

    if (value == null)
        throw new NullPointerException();
    else
        return value;
}
</code>```

And then:

```<code>String value = getValueFromDependencyProps(YourDependencyClass.class.getClassLoader(), "your.properties", key);
</code>```

Tested and working. With that I'm able to access any properties file from an external Maven dependency (using one of its classes, YourDependencyClass, to reach it).

Body:
I want to use a small program as a dependency in my Maven project. This program is configured by a properties file which can be edited before its execution. So far I have added the dependency as JAR in a local repository.

Now I want to make that dependency's properties file accessible in my own superior classpath, i.e. in myprogram/src/main/resources/config/myprogram.properties and not in myprogram/local-repository/com/example/mydependency/mydependency.jar/mydependency.properties.

I tried to modify the part of the code where the path for the properties file is defined:

public example() {

    Properties prop = new Properties();
    InputStream input = example.class.getResourceAsStream("/config/myprogram.properties");
    prop.load(input);

    ...

}

I also deleted the original properties file of the dependency before adding it to my local repository.

The whole program is working, but not as expected. Strangely, neither my new properties file in /src/main/resources/config nor the old one in the mydependency.jar is used. It seems that some kind of default properties file is put into my final fat JAR. But I cannot find its source anywhere - even when I try to debug it. That default properties file just seems to appear out of nowhere.

Now, how can I properly move the dependency's properties file to my own classpath?

And where could this default properties file appear from?

Is this an issue with Maven or with the source code itself?

Thanks in advance!

Body:
You can do something like this:

    public static String getValueFromDependencyProps(ClassLoader cl, String propertiesFile, String key) throws IOException {
    Properties prop = new Properties();
    prop.load(cl.getResourceAsStream(propertiesFile));
    String value = prop.getProperty(key);

    if (value == null)
        throw new NullPointerException();
    else
        return value;
}

And then:

String value = getValueFromDependencyProps(YourDependencyClass.class.getClassLoader(), "your.properties", key);

Tested and working. With that I'm able to access any properties file from an external Maven dependency (using one of its classes, YourDependencyClass, to reach it).


问:
com.ibm.msg.client.wmq.WMQConstants cannot rsolve
I am implementing an IBM MQ client using java class as follows;

```<code>    import javax.jms.JMSException;

        import com.ibm.msg.client.jms.JmsConnectionFactory;
        import com.ibm.msg.client.jms.JmsFactoryFactory;
        import com.ibm.msg.client.wmq.WMQConstants;

        import javax.jms.JMSContext;
        import javax.jms.Topic;
        import javax.jms.Queue;
        import javax.jms.JMSConsumer;
        import javax.jms.Message;
        import javax.jms.JMSProducer;

   /*
    * Implements both Subscriber and Publisher
    */
    class SharedNonDurableSubscriberAndPublisher implements Runnable {
    private Thread t;
    private String threadName;

    SharedNonDurableSubscriberAndPublisher( String name){
        threadName = name;
        System.out.println("Creating Thread:" +  threadName );
    }

    /*
     * Demonstrates shared non-durable subscription in JMS 2.0
     */
    private void sharedNonDurableSubscriptionDemo(){
        JmsConnectionFactory cf = null;
        JMSContext msgContext = null;

        try {
            // Create Factory for WMQ JMS provider
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            // Create connection factory
            cf = ff.createConnectionFactory();
            // Set MQ properties
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QM3");
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_BINDINGS);
            // Create message context
            msgContext = cf.createContext();

            // Create a topic destination
            Topic fifaScores = msgContext.createTopic("/FIFA2014/UPDATES");

            // Create a consumer. Subscription name specified, required for sharing of subscription.
            JMSConsumer msgCons = msgContext.createSharedConsumer(fifaScores, "FIFA2014SUBID");

            // Loop around to receive publications
            while(true){

                String msgBody=null;

                // Use JMS 2.0 receiveBody method as we are interested in message body only.
                msgBody = msgCons.receiveBody(String.class);

                if(msgBody != null){
                    System.out.println(threadName + " : " + msgBody);
                }
            }
        }catch(JMSException jmsEx){
            System.out.println(jmsEx);
        }
    }

    /*
     * Publisher publishes match updates like current attendance in the stadium, goal score and ball possession by teams.
     */
    private void matchUpdatePublisher(){
        JmsConnectionFactory cf = null;
        JMSContext msgContext = null;
        int nederlandsGoals = 0;
        int chileGoals = 0;
        int stadiumAttendence = 23231;
        int switchIndex = 0;
        String msgBody = "";
        int nederlandsHolding = 60;
        int chileHolding = 40;

        try {
            // Create Factory for WMQ JMS provider
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);

            // Create connection factory
            cf = ff.createConnectionFactory();
            // Set MQ properties
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QM3");
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_BINDINGS);

            // Create message context
            msgContext = cf.createContext();

            // Create a topic destination
            Topic fifaScores = msgContext.createTopic("/FIFA2014/UPDATES");

            // Create publisher to publish updates from stadium
            JMSProducer msgProducer = msgContext.createProducer();

            while(true){
                // Send match updates
                switch(switchIndex){
                    // Attendance
                    case 0:
                        msgBody ="Stadium Attendence " + stadiumAttendence;
                        stadiumAttendence += 314;
                        break;

                    // Goals
                    case 1:
                        msgBody ="SCORE: The Netherlands: " + nederlandsGoals + " - Chile:" + chileGoals;
                        break;

                    // Ball possession percentage
                    case 2:
                        msgBody ="Ball possession: The Netherlands: " + nederlandsHolding + "% - Chile: " + chileHolding + "%";
                        if((nederlandsHolding > 60) && (nederlandsHolding < 70)){
                            nederlandsHolding -= 2;
                            chileHolding += 2;
                        }else{
                            nederlandsHolding += 2;
                            chileHolding -= 2;
                        }
                        break;
                }

                // Publish and wait for two seconds to publish next update
                msgProducer.send (fifaScores, msgBody);
                try{
                    Thread.sleep(2000);
                }catch(InterruptedException iex){

                }

                // Increment and reset the index if greater than 2
                switchIndex++;
                if(switchIndex > 2)
                    switchIndex = 0;
            }
        }catch(JMSException jmsEx){
            System.out.println(jmsEx);
        }
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    public void run() {
        // If this is a publisher thread
        if(threadName == "PUBLISHER"){
            matchUpdatePublisher();
        }else{
            // Create subscription and start receiving publications
            sharedNonDurableSubscriptionDemo();
        }
    }

    // Start thread
    public void start (){
        System.out.println("Starting " +  threadName );
        if (t == null)
        {
            t = new Thread (this, threadName);
            t.start ();
        }
      }
   }
</code>```

I am new to IBM MQ and can't understand how to resolve following imports.

```<code>import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
</code>```

Just resolved other dependencies through jars. Please help on this.

答:
I recently used IBM MQ classes for JMS to place messages onto queues and was successful. Please ensure you have the following jar files in your build path before compilation. You can either google this and download or if you have installed WebSphere MQ on your pc then go to the installation folder(WebSphere MQ)/Java/lib to find the jar files:

com.ibm.mq.jmqi.jar

com.ibm.mqjms.jar

jms.jar

Body:
I am implementing an IBM MQ client using java class as follows;

    import javax.jms.JMSException;

        import com.ibm.msg.client.jms.JmsConnectionFactory;
        import com.ibm.msg.client.jms.JmsFactoryFactory;
        import com.ibm.msg.client.wmq.WMQConstants;

        import javax.jms.JMSContext;
        import javax.jms.Topic;
        import javax.jms.Queue;
        import javax.jms.JMSConsumer;
        import javax.jms.Message;
        import javax.jms.JMSProducer;

   /*
    * Implements both Subscriber and Publisher
    */
    class SharedNonDurableSubscriberAndPublisher implements Runnable {
    private Thread t;
    private String threadName;

    SharedNonDurableSubscriberAndPublisher( String name){
        threadName = name;
        System.out.println("Creating Thread:" +  threadName );
    }

    /*
     * Demonstrates shared non-durable subscription in JMS 2.0
     */
    private void sharedNonDurableSubscriptionDemo(){
        JmsConnectionFactory cf = null;
        JMSContext msgContext = null;

        try {
            // Create Factory for WMQ JMS provider
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            // Create connection factory
            cf = ff.createConnectionFactory();
            // Set MQ properties
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QM3");
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_BINDINGS);
            // Create message context
            msgContext = cf.createContext();

            // Create a topic destination
            Topic fifaScores = msgContext.createTopic("/FIFA2014/UPDATES");

            // Create a consumer. Subscription name specified, required for sharing of subscription.
            JMSConsumer msgCons = msgContext.createSharedConsumer(fifaScores, "FIFA2014SUBID");

            // Loop around to receive publications
            while(true){

                String msgBody=null;

                // Use JMS 2.0 receiveBody method as we are interested in message body only.
                msgBody = msgCons.receiveBody(String.class);

                if(msgBody != null){
                    System.out.println(threadName + " : " + msgBody);
                }
            }
        }catch(JMSException jmsEx){
            System.out.println(jmsEx);
        }
    }

    /*
     * Publisher publishes match updates like current attendance in the stadium, goal score and ball possession by teams.
     */
    private void matchUpdatePublisher(){
        JmsConnectionFactory cf = null;
        JMSContext msgContext = null;
        int nederlandsGoals = 0;
        int chileGoals = 0;
        int stadiumAttendence = 23231;
        int switchIndex = 0;
        String msgBody = "";
        int nederlandsHolding = 60;
        int chileHolding = 40;

        try {
            // Create Factory for WMQ JMS provider
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);

            // Create connection factory
            cf = ff.createConnectionFactory();
            // Set MQ properties
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QM3");
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_BINDINGS);

            // Create message context
            msgContext = cf.createContext();

            // Create a topic destination
            Topic fifaScores = msgContext.createTopic("/FIFA2014/UPDATES");

            // Create publisher to publish updates from stadium
            JMSProducer msgProducer = msgContext.createProducer();

            while(true){
                // Send match updates
                switch(switchIndex){
                    // Attendance
                    case 0:
                        msgBody ="Stadium Attendence " + stadiumAttendence;
                        stadiumAttendence += 314;
                        break;

                    // Goals
                    case 1:
                        msgBody ="SCORE: The Netherlands: " + nederlandsGoals + " - Chile:" + chileGoals;
                        break;

                    // Ball possession percentage
                    case 2:
                        msgBody ="Ball possession: The Netherlands: " + nederlandsHolding + "% - Chile: " + chileHolding + "%";
                        if((nederlandsHolding > 60) && (nederlandsHolding < 70)){
                            nederlandsHolding -= 2;
                            chileHolding += 2;
                        }else{
                            nederlandsHolding += 2;
                            chileHolding -= 2;
                        }
                        break;
                }

                // Publish and wait for two seconds to publish next update
                msgProducer.send (fifaScores, msgBody);
                try{
                    Thread.sleep(2000);
                }catch(InterruptedException iex){

                }

                // Increment and reset the index if greater than 2
                switchIndex++;
                if(switchIndex > 2)
                    switchIndex = 0;
            }
        }catch(JMSException jmsEx){
            System.out.println(jmsEx);
        }
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    public void run() {
        // If this is a publisher thread
        if(threadName == "PUBLISHER"){
            matchUpdatePublisher();
        }else{
            // Create subscription and start receiving publications
            sharedNonDurableSubscriptionDemo();
        }
    }

    // Start thread
    public void start (){
        System.out.println("Starting " +  threadName );
        if (t == null)
        {
            t = new Thread (this, threadName);
            t.start ();
        }
      }
   }

I am new to IBM MQ and can't understand how to resolve following imports.

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

Just resolved other dependencies through jars. Please help on this.


问:
How to fix - 41: non-static variable cannot be referenced from a static context -> What is the reason for this?
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

```<code>import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

```<code>import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}
</code>```

答:
Your code isn't working because you aren't even using candidateNo in isPrime.

As for the difference between static things and non-static things, a non-static belongs to a specific instance, while a static belongs to the class.

You can't refer to a non-static from within a static method (or other static context) without first specifying which instance you're talking about. It'd be like if I said "what color are cars?" Your response would probably be something like "which car?".

Body:
I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

  public static void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
}


问:
How to store csv file into webjob
I have created a azure webjob with queue trigger with search parameters.
I want to process searching using these parameters and save records into a csv file.

I want a way to store csv file on azure, so that i can send download link for that to user?

答:
I want a way to store csv file on azure, so that i can send download link for that to user?

You could generate csv file and write it to Azure blob storage, here is a simple sample, please refer to it.

```<code>public static void ProcessQueueMessage([QueueTrigger("myqueue")] string message, [Blob("mycontainer/{queueTrigger}.csv")] out string output, TextWriter log)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Name");

    dt.Rows.Add("1", "fred");

    //your logic to query the result
    //and generate CSV string

    StringBuilder sb = new StringBuilder();

    IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                        Select(column => column.ColumnName);
    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRow row in dt.Rows)
    {
        IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
        sb.AppendLine(string.Join(",", fields));
    }

    output = sb.ToString();

    log.WriteLine(message);
}
</code>```

After you store csv file in Azure blob, you could provide user with the URL of mycontainer/{blobname}.csv. And you could allow anonymous access or provide clients with a shared access signature (SAS) to make blob available to other users.

Please check "Controlling access to blob data" section to know how to control access to blob data.

Title: How to store csv file into webjob

Body:
I want a way to store csv file on azure, so that i can send download link for that to user?

You could generate csv file and write it to Azure blob storage, here is a simple sample, please refer to it.

public static void ProcessQueueMessage([QueueTrigger("myqueue")] string message, [Blob("mycontainer/{queueTrigger}.csv")] out string output, TextWriter log)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Name");

    dt.Rows.Add("1", "fred");

    //your logic to query the result
    //and generate CSV string

    StringBuilder sb = new StringBuilder();

    IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                        Select(column => column.ColumnName);
    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRow row in dt.Rows)
    {
        IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
        sb.AppendLine(string.Join(",", fields));
    }

    output = sb.ToString();

    log.WriteLine(message);
}

After you store csv file in Azure blob, you could provide user with the URL of mycontainer/{blobname}.csv. And you could allow anonymous access or provide clients with a shared access signature (SAS) to make blob available to other users.

Please check "Controlling access to blob data" section to know how to control access to blob data.


问:
Grouping row by specified column from array
I have this array

```<code>   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)
</code>```

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

```<code><table class="table ">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>ItemCode</th>
                            <th>ItemName</th>
                            <th>TransNo</th>
                            <th>Original Price</th>
                            <th>Price</th>
                             <th>QtyBeginning</th>
                            <th>QtyIn</th>
                            <th>QtySales</th>
                            <th>QtyMutasi</th>
                            <th>QtyStock</th>
                            <th>QtyOpname</th>
                            <th>QtyAdjust</th>
                            <th>TotalAdjust</th>
                            <th>Rak</th>
                            <th>Line</th>
                        </tr>
                    </thead>
                    <tbody> <?php $x=0; foreach ($datadetail as $data) { $x++;?>
                                 <tr>
                                    <td><?=$x;?></td>
                                    <td><?=$data->ItemCode;?></td>
                                    <td><?=$data->ItemName;?></td>
                                    <td><?=$data->StokOpnameTransNo;?></td>
                                    <td><?=$data->OriginalPrice;?></td>
                                    <td><?=$data->Price;?></td>
                                    <td><?=$data->QtyBegining;?></td>
                                    <td><?=$data->QtyIn;?></td>
                                    <td><?=$data->QtySales;?></td>
                                    <td><?=$data->QtyMutasi;?></td>
                                    <td><?=$data->QtyStock;?></td>
                                    <td><?=$data->QtyOpname;?></td>
                                    <td><?=$data->QtyAdjust;?></td>
                                    <td><?=currency($data->TotalAdjust);?></td>
                                    <td><?=$data->rak;?></td>
                                    <td><?=$data->line;?></td>
                                </tr>
                            <?php } ?>

                    </tbody>

            </table>
</code>```

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.

答:
i dont know your table structure but in my opinion you should be able to organize your data from your db

either way i try to show you a way how to do it (a fulltestscript)

TestData:

```<code>$arrTestData = [];

$obj = new stdClass();
$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150400005";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "289900.00";
$obj->Price = "289900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "4";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "4";
$obj->QtyOpname = "2";
$obj->QtyAdjust = "-4";
$obj->TotalAdjust = "-1159600.00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();
$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150400005";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "289900.00";
$obj->Price = "289900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "2";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "4";
$obj->QtyOpname = "4";
$obj->QtyAdjust = "-4";
$obj->TotalAdjust = "-1159600.00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500063";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "479900.00";
$obj->Price = "479900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "0";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "0";
$obj->QtyOpname = "1";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "SS";
$obj->line = "SS";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500063";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "479900.00";
$obj->Price = "479900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "1";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "1";
$obj->QtyOpname = "0";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.6";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500081";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "229900.00";
$obj->Price = "229900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "0";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "0";
$obj->QtyOpname = "1";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "SS";
$obj->line = "SS";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;
</code>```

You need an Item Collection or something like that which holds and structurize your data

```<code>class ItemCollection extends ArrayObject
{

    private $strCollectionCode;
    private $strCollectionName;

    public function addItem($objItem)
    {
        $this->strCollectionCode = $objItem->ItemCode;
        $this->strCollectionName = $objItem->ItemName;
        $this->append($objItem);
    }

    public function get($key)
    {
        return $this->$key;
    }

    public function getSummaries($strKey)
    {
        $floatNumber = 0;
        foreach($this AS $objItem)
        {
            $floatNumber += floatval($objItem->$strKey);
        }
        return $floatNumber;
    }
}
</code>```

And a Wrapper should contain this Collections

```<code>class ItemCollectionWrapper
{
    private $arrCollections = array();

    public function __construct($arrData = false)
    {
        if (is_array($arrData))
        {
            $this->addItemsFromArray($arrData);
        }
    }

    public function addItem($objItem)
    {
        if (isset($this->arrCollections[$objItem->ItemCode]))
        {
            $objCollection = $this->arrCollections[$objItem->ItemCode];
        }
        else
        {
            $objCollection = new ItemCollection();
            $this->arrCollections[$objItem->ItemCode] = $objCollection;
        }

        $objCollection->addItem($objItem);
    }

    public function addItemsFromArray($arrData)
    {
        foreach($arrData AS $obj)
        {
            $this->addItem($obj);
        }
    }

    public function getCollections()
    {
        return $this->arrCollections;
    }
}
</code>```

and finally our view

```<code><?php
    $obj = new ItemCollectionWrapper($arrTestData);

?>
<!DOCTYPE html>
<html lang=en>
<head>
    <meta charset=utf-8>
    <meta content="IE=edge" http-equiv=X-UA-Compatible>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<style type="text/css">
    td.summaries
    {
        background:#c6c600;
    }
</style>
<table class="table">
<thead>
    <tr>
        <th>No</th>
        <th>ItemCode</th>
        <th>ItemName</th>
        <th>TransNo</th>
        <th>Original Price</th>
        <th>Price</th>
         <th>QtyBeginning</th>
        <th>QtyIn</th>
        <th>QtySales</th>
        <th>QtyMutasi</th>
        <th>QtyStock</th>
        <th>QtyOpname</th>
        <th>QtyAdjust</th>
        <th>TotalAdjust</th>
        <th>Rak</th>
        <th>Line</th>
    </tr>
</thead>
<tbody>
<?php
foreach($obj->getCollections() AS $objCollection)
{
    $number = 1;
?>
    <?php
    foreach($objCollection AS $key => $objItem) :
    ?>
     <tr>
        <?php
        if ($key == 0)  :
        ?>
        <td rowspan="<?=$objCollection->count();?>"><?=$number;?></td>
        <td rowspan="<?=$objCollection->count();?>"><?=$objCollection->get("strCollectionCode");?></td>
        <td rowspan="<?=$objCollection->count();?>"><?=$objCollection->get("strCollectionName");?></td>
        <?php endif; ?>
        <td><?=$objItem->StokOpnameTransNo;?></td>
        <td><?=$objItem->OriginalPrice;?></td>
        <td><?=$objItem->Price;?></td>
        <td><?=$objItem->QtyBegining;?></td>
        <td><?=$objItem->QtyIn;?></td>
        <td><?=$objItem->QtySales;?></td>
        <td><?=$objItem->QtyMutasi;?></td>
        <td><?=$objItem->QtyStock;?></td>
        <td><?=$objItem->QtyOpname;?></td>
        <td><?=$objItem->QtyAdjust;?></td>
        <td><?=($objItem->TotalAdjust);?></td>
        <td><?=$objItem->rak;?></td>
        <td><?=$objItem->line;?></td>
    </tr>
    <?php
    endforeach;
    ?>
    <tr>
        <td colspan="6"></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyBegining");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyIn");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtySales");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyMutasi");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyStock");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyOpname");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyAdjust");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("TotalAdjust");?></td>
        <td colspan="2"></td>
    </tr>
<?php
    $number++;
}
?>
</tbody>
</table>
</body>
</html>
</code>```

i hope it helps - if you study this code - you should be able to extend it in whatever way you like.

btw: You can put the classes ItemCollectionWrapper and ItemCollection below your model Code
if you dont know how to do that - show me your model and your controller and i'll show you.

Body:
I have this array

   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

                            No
                            ItemCode
                            ItemName
                            TransNo
                            Original Price
                            Price
                             QtyBeginning
                            QtyIn
                            QtySales
                            QtyMutasi
                            QtyStock
                            QtyOpname
                            QtyAdjust
                            TotalAdjust
                            Rak
                            Line

 <?php $x=0; foreach ($datadetail as $data) { $x++;?>

                                    <?=$x;?>
                                    <?=$data->ItemCode;?>
                                    <?=$data->ItemName;?>
                                    <?=$data->StokOpnameTransNo;?>
                                    <?=$data->OriginalPrice;?>
                                    <?=$data->Price;?>
                                    <?=$data->QtyBegining;?>
                                    <?=$data->QtyIn;?>
                                    <?=$data->QtySales;?>
                                    <?=$data->QtyMutasi;?>
                                    <?=$data->QtyStock;?>
                                    <?=$data->QtyOpname;?>
                                    <?=$data->QtyAdjust;?>
                                    <?=currency($data->TotalAdjust);?>
                                    <?=$data->rak;?>
                                    <?=$data->line;?>

                            <?php } ?>

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.

Body:
i dont know your table structure but in my opinion you should be able to organize your data from your db

either way i try to show you a way how to do it (a fulltestscript)

TestData:

$arrTestData = [];

$obj = new stdClass();
$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150400005";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "289900.00";
$obj->Price = "289900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "4";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "4";
$obj->QtyOpname = "2";
$obj->QtyAdjust = "-4";
$obj->TotalAdjust = "-1159600.00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();
$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150400005";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "289900.00";
$obj->Price = "289900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "2";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "4";
$obj->QtyOpname = "4";
$obj->QtyAdjust = "-4";
$obj->TotalAdjust = "-1159600.00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500063";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "479900.00";
$obj->Price = "479900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "0";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "0";
$obj->QtyOpname = "1";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "SS";
$obj->line = "SS";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500063";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "479900.00";
$obj->Price = "479900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "1";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "1";
$obj->QtyOpname = "0";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "";
$obj->line = "";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

$obj = new stdClass();

$obj->TransactionNo = "OPM-EC-K-LFMCD2-21.6";
$obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
$obj->ItemCode = "BBG150500081";
$obj->ItemName = "BIG BAG";
$obj->OriginalPrice = "229900.00";
$obj->Price = "229900.00";
$obj->QtyBegining = "0";
$obj->QtyIn = "0";
$obj->QtySales = "0";
$obj->QtyMutasi = "0";
$obj->QtyStock = "0";
$obj->QtyOpname = "1";
$obj->QtyAdjust = "0";
$obj->TotalAdjust = ".00";
$obj->rak = "SS";
$obj->line = "SS";
$obj->TransDate = "2017-03-31 10:46:00.000";
$obj->CustomerCode = "K-LFMCD2";
$obj->CreatedBy = "1208496.";
$obj->Remark = "re";
$obj->Remark2 = "re";
$obj->SOTerakhir = "";
$obj->TglSoTerakhir = "";
$arrTestData[] = $obj;

You need an Item Collection or something like that which holds and structurize your data

class ItemCollection extends ArrayObject
{

    private $strCollectionCode;
    private $strCollectionName;

    public function addItem($objItem)
    {
        $this->strCollectionCode = $objItem->ItemCode;
        $this->strCollectionName = $objItem->ItemName;
        $this->append($objItem);
    }

    public function get($key)
    {
        return $this->$key;
    }

    public function getSummaries($strKey)
    {
        $floatNumber = 0;
        foreach($this AS $objItem)
        {
            $floatNumber += floatval($objItem->$strKey);
        }
        return $floatNumber;
    }
}

And a Wrapper should contain this Collections

class ItemCollectionWrapper
{
    private $arrCollections = array();

    public function __construct($arrData = false)
    {
        if (is_array($arrData))
        {
            $this->addItemsFromArray($arrData);
        }
    }

    public function addItem($objItem)
    {
        if (isset($this->arrCollections[$objItem->ItemCode]))
        {
            $objCollection = $this->arrCollections[$objItem->ItemCode];
        }
        else
        {
            $objCollection = new ItemCollection();
            $this->arrCollections[$objItem->ItemCode] = $objCollection;
        }

        $objCollection->addItem($objItem);
    }

    public function addItemsFromArray($arrData)
    {
        foreach($arrData AS $obj)
        {
            $this->addItem($obj);
        }
    }

    public function getCollections()
    {
        return $this->arrCollections;
    }
}

and finally our view

<?php
    $obj = new ItemCollectionWrapper($arrTestData);

?>
<!DOCTYPE html>
<html lang=en>
<head>
    <meta charset=utf-8>
    <meta content="IE=edge" http-equiv=X-UA-Compatible>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<style type="text/css">
    td.summaries
    {
        background:#c6c600;
    }
</style>
<table class="table">
<thead>
    <tr>
        <th>No</th>
        <th>ItemCode</th>
        <th>ItemName</th>
        <th>TransNo</th>
        <th>Original Price</th>
        <th>Price</th>
         <th>QtyBeginning</th>
        <th>QtyIn</th>
        <th>QtySales</th>
        <th>QtyMutasi</th>
        <th>QtyStock</th>
        <th>QtyOpname</th>
        <th>QtyAdjust</th>
        <th>TotalAdjust</th>
        <th>Rak</th>
        <th>Line</th>
    </tr>
</thead>
<tbody>
<?php
foreach($obj->getCollections() AS $objCollection)
{
    $number = 1;
?>
    <?php
    foreach($objCollection AS $key => $objItem) :
    ?>
     <tr>
        <?php
        if ($key == 0)  :
        ?>
        <td rowspan="<?=$objCollection->count();?>"><?=$number;?></td>
        <td rowspan="<?=$objCollection->count();?>"><?=$objCollection->get("strCollectionCode");?></td>
        <td rowspan="<?=$objCollection->count();?>"><?=$objCollection->get("strCollectionName");?></td>
        <?php endif; ?>
        <td><?=$objItem->StokOpnameTransNo;?></td>
        <td><?=$objItem->OriginalPrice;?></td>
        <td><?=$objItem->Price;?></td>
        <td><?=$objItem->QtyBegining;?></td>
        <td><?=$objItem->QtyIn;?></td>
        <td><?=$objItem->QtySales;?></td>
        <td><?=$objItem->QtyMutasi;?></td>
        <td><?=$objItem->QtyStock;?></td>
        <td><?=$objItem->QtyOpname;?></td>
        <td><?=$objItem->QtyAdjust;?></td>
        <td><?=($objItem->TotalAdjust);?></td>
        <td><?=$objItem->rak;?></td>
        <td><?=$objItem->line;?></td>
    </tr>
    <?php
    endforeach;
    ?>
    <tr>
        <td colspan="6"></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyBegining");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyIn");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtySales");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyMutasi");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyStock");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyOpname");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("QtyAdjust");?></td>
        <td class="summaries"><?=$objCollection->getSummaries("TotalAdjust");?></td>
        <td colspan="2"></td>
    </tr>
<?php
    $number++;
}
?>
</tbody>
</table>
</body>
</html>

i hope it helps - if you study this code - you should be able to extend it in whatever way you like.

btw: You can put the classes ItemCollectionWrapper and ItemCollection below your model Code
if you dont know how to do that - show me your model and your controller and i'll show you.


问:
Friend funcitons of template classes
I want to return a nested class object using a friend function

```<code>template <typename T>
class X{
public:
    class Y{
    public:
        int y;
    }test;
public:
    X(){
        test.y=10;
    }

    template <typename U>
    friend Y fun(X<U>);
};

template <typename T>
X<T>::Y fun(X<T> x){
    return x.test;
}
</code>```

But I get an error saying

need 'typename' before 'X::Y' because 'X' is a dependent scope

What is wrong?

答:
You need to do literally what the error says: put typename before X<T>::Y:

```<code>template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}
</code>```

Because the meaning of X<T>::Y is type-dependent on T, the compiler can't know in general whether X<T>::Y refers to a typename or a variable. In such circumstances the rule is that if you want it to be typename, you must say so explicitly with the typename keyword.

Title: Friend funcitons of template classes

Body:
I want to return a nested class object using a friend function

template <typename T>
class X{
public:
    class Y{
    public:
        int y;
    }test;
public:
    X(){
        test.y=10;
    }

    template <typename U>
    friend Y fun(X);
};

template <typename T>
X<T>::Y fun(X<T> x){
    return x.test;
}

But I get an error saying

need 'typename' before 'X::Y' because 'X' is a dependent scope

What is wrong?

Body:
You need to do literally what the error says: put typename before X<T>::Y:

template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}

Because the meaning of X<T>::Y is type-dependent on T, the compiler can't know in general whether X<T>::Y refers to a typename or a variable. In such circumstances the rule is that if you want it to be typename, you must say so explicitly with the typename keyword.


问:
AVPlayer Custrom Scrubbing
I am using AVPlayer for my tvOS project. Its size is smaller than fullscreen, so its controls are hidden. This is limitation of using AVPlayer.

But, I must show the video controls to user, so that user can do play, pause, fast forward, backward, scrubbing etc.

Anyone knows about any third party library or framework or have implemented it before? Please share. I searched a lot but couldn't find any help on internet.

Thanks.

答: I believe Apple discourages interaction with Video when you are displaying it in non fullscreen mode. The idea is if the viewer is to be fully engaged in the video, then the video needs to be shown in full screen mode, especially on a TV sized device. Hence AVPlayerViewController is provided which has all default controls as well as Metadata displays/Content Proposals but is available only in full screen mode. Mimicking this behavior in non full screen mode is probably a lot of work and I am unaware of any libraries out there that will provide you with a custom slider that will be help with playback. I highly encourage you to show video in full screen and use the default controls. </p>

Title: AVPlayer Custrom Scrubbing


问:
String search
What is the best way to search strings for something like forum? i seen horrible string search and typically get worse the more strings you use rather then better.

I also may implement a title search so if the way to search title that is better then a body of string i'd love to hear that too

答:
I would in most cases suggest using the "Boyer Moore" string search algorithm.

You can read about it on wikipedia:

http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm

There's also a lot of example code around to look at, if you're not interested in trying to implement it yourself.

If performance isn't important at all, I would agree with using regular expressions.

Title: String search