问:
valgrind says i have conditional jump or move depends on initialized value(s)
I am having an issue where valgrind is saying that i have a conditional jump or the move depends on initialized values

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

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr newNode;
    ListNodePtr leftLinkedList;
    ListNodePtr rightLinkedList;
    ListNodePtr head;

    if (root == NULL)
    {
        return NULL;
    }

    newNode = malloc(sizeof(struct ListNode));
    newNode->key = root->key;
    head = newNode;

    if(root->left != NULL)
    {
        leftLinkedList = convertBSTtoLinkedList(root->left);
        head = leftLinkedList;

        ListNodePtr conductor;
        conductor = leftLinkedList;
        while (conductor->next != NULL)
        {
            conductor = conductor->next;
        }

        conductor->next = newNode;

    }

    if(root->right != NULL)
    {
        rightLinkedList= convertBSTtoLinkedList(root->right);
        newNode->next = rightLinkedList;
    }

    return head;
    }
</code>```

valgrind the problem is somewhere in the while loop and i am assuming it is because i havent initialized that conductor->next is NULL, but i dont know how to do that since it it checking if it is NULL

答:
The problem is here:

```<code>newNode = malloc(sizeof(struct ListNode));
newNode->key = root->key;
head = newNode;
</code>```

You create a new node and set the key, but you don't set the next pointer.  While the value does get set if there is a right subtree, it will not get set if the node is a leaf node.

When your recursive call for the left side returns after processing a leaf node, it then checks the next pointer which was never written to.  By reading an uninitialized value, you invoke undefined behavior.

Make sure that you initialize this pointer to NULL when you create the node:

```<code>newNode = malloc(sizeof(struct ListNode));
newNode->key = root->key;
newNode->next = NULL;
head = newNode;
</code>```

Body:
I am having an issue where valgrind is saying that i have a conditional jump or the move depends on initialized values

#include <stdio.h>
#include<stdlib.h>

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr newNode;
    ListNodePtr leftLinkedList;
    ListNodePtr rightLinkedList;
    ListNodePtr head;

    if (root == NULL)
    {
        return NULL;
    }

    newNode = malloc(sizeof(struct ListNode));
    newNode->key = root->key;
    head = newNode;

    if(root->left != NULL)
    {
        leftLinkedList = convertBSTtoLinkedList(root->left);
        head = leftLinkedList;

        ListNodePtr conductor;
        conductor = leftLinkedList;
        while (conductor->next != NULL)
        {
            conductor = conductor->next;
        }

        conductor->next = newNode;

    }

    if(root->right != NULL)
    {
        rightLinkedList= convertBSTtoLinkedList(root->right);
        newNode->next = rightLinkedList;
    }

    return head;
    }

valgrind the problem is somewhere in the while loop and i am assuming it is because i havent initialized that conductor->next is NULL, but i dont know how to do that since it it checking if it is NULL

Body:
The problem is here:

newNode = malloc(sizeof(struct ListNode));
newNode->key = root->key;
head = newNode;

You create a new node and set the key, but you don't set the next pointer.  While the value does get set if there is a right subtree, it will not get set if the node is a leaf node.

When your recursive call for the left side returns after processing a leaf node, it then checks the next pointer which was never written to.  By reading an uninitialized value, you invoke undefined behavior.

Make sure that you initialize this pointer to NULL when you create the node:

newNode = malloc(sizeof(struct ListNode));
newNode->key = root->key;
newNode->next = NULL;
head = newNode;


来源: stackexchange

问:
How to Listen for Events in children components in React Native?
I want to implement an event listener from parents to children components in my React Native app, I'm using a StackNavigator as a router.

How can I listen for events occurred in the top/parent components?

答:
Having an Event Emitter can probably get a bit messy when tracking where the event came from or where it's being listened.

Just like you pass the event emitter down to the child via screenProps={this.eventEmitter} (which is what you are essentially doing), why not just pass an actual function your child can use to initiate actions on its parent. That'd probably be the most react way to do things.

It probably not is ideal to add an additional event listener as it will affect performance at some point.

ContentLicense: CC BY-SA 3.0


问:
PHPUnit 5.7 (autoloaded) Class Not Found
I am having trouble getting PHPUnit (Version 5.7) to find my Custom Framework classes. Any help would be appreciated as i've tried alsorts. When I run the tests it complains that the autoloaded class cannot be found.

```<code>{
"scripts": {
    "test": [
        "@clean",
        "@load",
        "@phpunit"
    ],
    "clean": "composer clear-cache",
    "load": "composer dump-autoload -o",
    "phpunit": "\"vendor/bin/phpunit\" --configuration phpunit.xml tests"
},
"autoload": {
    "psr-4": {
      "AdoptableFramework\\": "src/",
      "AdoptableFramework\\Tests\\": "tests/",
      "AdoptableFramework\\Extend\\": "src/extend/"
    }
},
"require": {
    "matthiasmullie/minify": "^1.3"
},
"require-dev": {
    "phpunit/phpunit": "5.7"
}
</code>```

}

This is what my phpunit.xml looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/5.7/phpunit.xsd"
bootstrap="vendor\autoload.php"
backupGlobals="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
backupStaticAttributes="false"
cacheTokens="false"
colors="always"
convertErrorsToExceptions="true"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
stopOnRisky="false"

verbose="true">
<filter>
    <whitelist processUncoveredFilesFromWhitelist="true">
        <directory suffix=".php">src/AdoptableFramework</directory>
    </whitelist>
</filter>
<logging>
    <log type="coverage-html" target="tests/code_coverage"
showUncoveredFiles="true"/>
</logging>
</phpunit>
</code>```

My folder structure looks like:

```<code>src
--AdoptableFramework
----Core
------Database.php tests
--databaseTest.php
--unitTestSuite.php
</code>```

This is what my databaseTest.php looks like:

```<code>    <?php

namespace AdoptableFramework\Tests;

use AdoptableFramework\Core\Database;
use AdoptableFramework\Tests\unitTestSuite;

class DatabaseTest extends UnitTestSuite
{
    public function testDatabase()
    {
        $database = new Database();

        $this->assertEquals(null, $database);
    }
}

?>
</code>```

This is my Database.php withint AdoptableFramework/Core.

```<code><?

/**
* @link      https://www.pswebsolutions.co.uk/
* @author    Paul Sonny Cook <paul.cook@pswebsolutions.co.uk>
* @copyright 2017 P S Web Solutions Ltd
* @version   1.0.0
* @package   psAdoptables
**/

namespace AdoptableFramework\Core;

class Database
{
    public function __construct($host = null, $username = null, $password = null, $database = null) {
        $this->type = __CLASS__;

        if ($host || $username || $password || $database) {
            $this->connect($host, $username, $password, $database);
        } else {
            $this->connect();
        }
    }

    public function connect($host = DB_HOST, $username = DB_USER, $password = DB_PASS, $database = DB_DATABASE)
    {
        return true;
    }
}

?>
</code>```

autoload_static.php class mappings:

I have looked into my autoload_static.php file and can see this:

```<code>'AdoptableFramework\\Core\\Database' => __DIR__ . '/../..' . '/src/AdoptableFramework/Core/Database.php',
        'AdoptableFramework\\Extend\\ExtendDatabase' => __DIR__ . '/../..' . '/src/AdoptableFramework/Extend/ExtendDatabase.php',
        'AdoptableFramework\\Game' => __DIR__ . '/../..' . '/src/AdoptableFramework/Game.php',
        'AdoptableFramework\\Tests\\DatabaseTest' => __DIR__ . '/../..' . '/tests/databaseTest.php',
        'AdoptableFramework\\Tests\\UnitTestSuite' => __DIR__ . '/../..' . '/tests/unitTestSuite.php',
</code>```

Any help would be greatly appreciated.

答:
It looks to me that your src/AdoptableFramework directory is not necessary. You can either remove it and move all files one level higher or try this use statement:

```<code>use AdoptableFramework\AdoptableFramework\Core\Database;
</code>```

This line "AdoptableFramework\\": "src/", tells autoloader that any class in src folder is already in AdoptableFramework namespace. As an example, if you create class Foo this way src/Foo.php you will import it this way:

```<code>use AdoptableFramework\Foo;
</code>```

Body:
I am having trouble getting PHPUnit (Version 5.7) to find my Custom Framework classes. Any help would be appreciated as i've tried alsorts. When I run the tests it complains that the autoloaded class cannot be found.

{
"scripts": {
    "test": [
        "@clean",
        "@load",
        "@phpunit"
    ],
    "clean": "composer clear-cache",
    "load": "composer dump-autoload -o",
    "phpunit": "\"vendor/bin/phpunit\" --configuration phpunit.xml tests"
},
"autoload": {
    "psr-4": {
      "AdoptableFramework\\": "src/",
      "AdoptableFramework\\Tests\\": "tests/",
      "AdoptableFramework\\Extend\\": "src/extend/"
    }
},
"require": {
    "matthiasmullie/minify": "^1.3"
},
"require-dev": {
    "phpunit/phpunit": "5.7"
}

}

This is what my phpunit.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/5.7/phpunit.xsd"
bootstrap="vendor\autoload.php"
backupGlobals="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
backupStaticAttributes="false"
cacheTokens="false"
colors="always"
convertErrorsToExceptions="true"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
stopOnRisky="false"

verbose="true">
<filter>
    <whitelist processUncoveredFilesFromWhitelist="true">
        <directory suffix=".php">src/AdoptableFramework</directory>
    </whitelist>
</filter>
<logging>
    <log type="coverage-html" target="tests/code_coverage"
showUncoveredFiles="true"/>
</logging>
</phpunit>

My folder structure looks like:

src
--AdoptableFramework
----Core
------Database.php tests
--databaseTest.php
--unitTestSuite.php

This is what my databaseTest.php looks like:

    <?php

namespace AdoptableFramework\Tests;

use AdoptableFramework\Core\Database;
use AdoptableFramework\Tests\unitTestSuite;

class DatabaseTest extends UnitTestSuite
{
    public function testDatabase()
    {
        $database = new Database();

        $this->assertEquals(null, $database);
    }
}

?>

This is my Database.php withint AdoptableFramework/Core.

<?

/**
* @link      https://www.pswebsolutions.co.uk/
* @author    Paul Sonny Cook <paul.cook@pswebsolutions.co.uk>
* @copyright 2017 P S Web Solutions Ltd
* @version   1.0.0
* @package   psAdoptables
**/

namespace AdoptableFramework\Core;

class Database
{
    public function __construct($host = null, $username = null, $password = null, $database = null) {
        $this->type = __CLASS__;

        if ($host || $username || $password || $database) {
            $this->connect($host, $username, $password, $database);
        } else {
            $this->connect();
        }
    }

    public function connect($host = DB_HOST, $username = DB_USER, $password = DB_PASS, $database = DB_DATABASE)
    {
        return true;
    }
}

?>

autoload_static.php class mappings:

I have looked into my autoload_static.php file and can see this:

'AdoptableFramework\\Core\\Database' => __DIR__ . '/../..' . '/src/AdoptableFramework/Core/Database.php',
        'AdoptableFramework\\Extend\\ExtendDatabase' => __DIR__ . '/../..' . '/src/AdoptableFramework/Extend/ExtendDatabase.php',
        'AdoptableFramework\\Game' => __DIR__ . '/../..' . '/src/AdoptableFramework/Game.php',
        'AdoptableFramework\\Tests\\DatabaseTest' => __DIR__ . '/../..' . '/tests/databaseTest.php',
        'AdoptableFramework\\Tests\\UnitTestSuite' => __DIR__ . '/../..' . '/tests/unitTestSuite.php',

Any help would be greatly appreciated.

Body:
It looks to me that your src/AdoptableFramework directory is not necessary. You can either remove it and move all files one level higher or try this use statement:

use AdoptableFramework\AdoptableFramework\Core\Database;

This line "AdoptableFramework\\": "src/", tells autoloader that any class in src folder is already in AdoptableFramework namespace. As an example, if you create class Foo this way src/Foo.php you will import it this way:

use AdoptableFramework\Foo;


问:
set totalPageCount programmatically in Jquery Datatable(ver:1.10.6)
There is a datatable using "serverside pagination", the trouble is its total count set by 99,999,999 for some reason. here how it seems.

Actually there 30 records and only first 3 page has rows since Displaylength equals to 10, rest of them empty which generated DT because TotalRecords set to 99,999,999

So all I need to do edit this using javascript.
When I type $('#myTable).DataTable().context[0] in console there is some properties:

```<code>_iRecordsDisplay: 99999999
_iRecordsTotal: 99999999
json: aaData:(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}], iTotalDisplayRecords:99999999 ,iTotalRecords:99999999,sEcho:"25"
</code>```

so I tried these but not work;

```<code>asd.context[0].iRecordsDisplay=30
asd.context[0]._iRecordsTotal=30
$('#myTable').DataTable().page.len(10).draw();
</code>```

how I tell dt there is 30 records actually so create 3 pages only?

答:
If you look at the example given for server side processing, you can take a look at the JSON returned by the server code. https://datatables.net/examples/server_side/simple.html

```<code>{
  "draw": 11,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    [
      "Airi",
      "Satou",
      "Accountant",
      "Tokyo",
      "28th Nov 08",
      "$162,700"
    ],
    [
      "Angelica",
      "Ramos",
      "Chief Executive Officer (CEO)",
      "London",
      "9th Oct 09",
      "$1,200,000"
    ],
//more rows here
}
</code>```

To solve this you must make your server side code include the "recordsTotal" attribute in your response JSON.

Something like this in PHP:

```<code>$response = array(
    'recordsTotal' => count($data),
    'data' => $data,
);
echo json_encode($response);
</code>```

Body:
There is a datatable using "serverside pagination", the trouble is its total count set by 99,999,999 for some reason. here how it seems.

Actually there 30 records and only first 3 page has rows since Displaylength equals to 10, rest of them empty which generated DT because TotalRecords set to 99,999,999

So all I need to do edit this using javascript.
When I type $('#myTable).DataTable().context[0] in console there is some properties:

_iRecordsDisplay: 99999999
_iRecordsTotal: 99999999
json: aaData:(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}], iTotalDisplayRecords:99999999 ,iTotalRecords:99999999,sEcho:"25"

so I tried these but not work;

asd.context[0].iRecordsDisplay=30
asd.context[0]._iRecordsTotal=30
$('#myTable').DataTable().page.len(10).draw();

how I tell dt there is 30 records actually so create 3 pages only?

Body:
If you look at the example given for server side processing, you can take a look at the JSON returned by the server code. https://datatables.net/examples/server_side/simple.html

{
  "draw": 11,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    [
      "Airi",
      "Satou",
      "Accountant",
      "Tokyo",
      "28th Nov 08",
      "$162,700"
    ],
    [
      "Angelica",
      "Ramos",
      "Chief Executive Officer (CEO)",
      "London",
      "9th Oct 09",
      "$1,200,000"
    ],
//more rows here
}

To solve this you must make your server side code include the "recordsTotal" attribute in your response JSON.

Something like this in PHP:

$response = array(
    'recordsTotal' => count($data),
    'data' => $data,
);
echo json_encode($response);


问:
Need help to find previous year using windows Batch Script
Hi need some help in finding the previous year, using windows batch code

the code I am using is

```<code>:: This is Code for D3
@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^&
right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
SET "PREVYEAR=%result:~0,4%-%1%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
SET YEAR=%DATE:~-4%
set "filename=%mm%%dd%%yyyy%"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%YYYY%_%filename%.QVD"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%PREVYEAR%_%filename%.QVD"
pause
</code>```

this gives an output

```<code>"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017_11152017.QVD"
"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017-_11152017.QVD"
</code>```

I need some advice how can I find previous year, the output of variable PREVYEAR should be 2016

答:
You can do this with one line of batch

```<code>set /a "PREVYEAR=%date:~9,4%-1"
</code>```

which sets PREVYEAR to 2016

Unlike Squashman I don't like Powershell, take a look at Ruby for a vbscript replacement.

In Ruby this would be

```<code>Time.now.year-1
#=> 2016
</code>```

Body:
Hi need some help in finding the previous year, using windows batch code

the code I am using is

:: This is Code for D3
@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^&
right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
SET "PREVYEAR=%result:~0,4%-%1%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
SET YEAR=%DATE:~-4%
set "filename=%mm%%dd%%yyyy%"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%YYYY%_%filename%.QVD"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%PREVYEAR%_%filename%.QVD"
pause

this gives an output

"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017_11152017.QVD"
"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017-_11152017.QVD"

I need some advice how can I find previous year, the output of variable PREVYEAR should be 2016

Body:
You can do this with one line of batch

set /a "PREVYEAR=%date:~9,4%-1"

which sets PREVYEAR to 2016

Unlike Squashman I don't like Powershell, take a look at Ruby for a vbscript replacement.

In Ruby this would be

Time.now.year-1
#=> 2016


问:
Incorrect stacktrace by rethrow
I rethrow an exception with "throw;", but the stacktrace is incorrect:

```<code>static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}
</code>```

The right stacktrace should be:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12
</code>```

But I get:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15
</code>```

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

答:
It's something that can be considered as expected.
Modifying stack trace is usual case if you specify throw ex;, FxCop will than notify you that stack is modified. In case you make throw;, no warning is generated, but still, the trace will be modified.
So unfortunately for now it's the best not to catch the ex or throw it as an inner one.
I think it should be considered as a Windows impact or smth like that - edited.
Jeff Richter describes this situation in more detail in his "CLR via C#":

The following code throws the same
  exception object that it caught and
  causes the CLR to reset its starting
  point for the exception:

```<code>private void SomeMethod() {
  try { ... }
  catch (Exception e) {
    ...
    throw e; // CLR thinks this is where exception originated.
    // FxCop reports this as an error
  }
}
</code>```

In contrast, if you re-throw an
  exception object by using the throw
  keyword by itself, the CLR doesn’t
  reset the stack’s starting point. The
  following code re-throws the same
  exception object that it caught,
  causing the CLR to not reset its
  starting point for the exception:

```<code>private void SomeMethod() {
  try { ... }
  catch (Exception e) {
    ...
    throw; // This has no effect on where the CLR thinks the exception
    // originated. FxCop does NOT report this as an error
  }
}
</code>```

In fact, the only difference between
  these two code fragments is what the
  CLR thinks is the original location
  where the exception was thrown.
  Unfortunately, when you throw or
  rethrow an exception, Windows does
  reset the stack’s starting point. So
  if the exception becomes unhandled,
  the stack location that gets reported
  to Windows Error Reporting is the
  location of the last throw or
  re-throw, even though the CLR knows
  the stack location where the original
  exception was thrown. This is
  unfortunate because it makes debugging
  applications that have failed in the
  field much more difficult. Some
  developers have found this so
  intolerable that they have chosen a
  different way to implement their code
  to ensure that the stack trace truly
  reflects the location where an
  exception was originally thrown:

```<code>private void SomeMethod() {
  Boolean trySucceeds = false;
  try {
    ...
    trySucceeds = true;
  }
  finally {
    if (!trySucceeds) { /* catch code goes in here */ }
  }
}
</code>```

Title: Incorrect stacktrace by rethrow

Body:
I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}

The right stacktrace should be:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

Body:
It's something that can be considered as expected.
Modifying stack trace is usual case if you specify throw ex;, FxCop will than notify you that stack is modified. In case you make throw;, no warning is generated, but still, the trace will be modified.
So unfortunately for now it's the best not to catch the ex or throw it as an inner one.
I think it should be considered as a Windows impact or smth like that - edited.
Jeff Richter describes this situation in more detail in his "CLR via C#":

The following code throws the same
  exception object that it caught and
  causes the CLR to reset its starting
  point for the exception:

private void SomeMethod() {
  try { ... }
  catch (Exception e) {
    ...
    throw e; // CLR thinks this is where exception originated.
    // FxCop reports this as an error
  }
}

In contrast, if you re-throw an
  exception object by using the throw
  keyword by itself, the CLR doesn’t
  reset the stack’s starting point. The
  following code re-throws the same
  exception object that it caught,
  causing the CLR to not reset its
  starting point for the exception:

private void SomeMethod() {
  try { ... }
  catch (Exception e) {
    ...
    throw; // This has no effect on where the CLR thinks the exception
    // originated. FxCop does NOT report this as an error
  }
}

In fact, the only difference between
  these two code fragments is what the
  CLR thinks is the original location
  where the exception was thrown.
  Unfortunately, when you throw or
  rethrow an exception, Windows does
  reset the stack’s starting point. So
  if the exception becomes unhandled,
  the stack location that gets reported
  to Windows Error Reporting is the
  location of the last throw or
  re-throw, even though the CLR knows
  the stack location where the original
  exception was thrown. This is
  unfortunate because it makes debugging
  applications that have failed in the
  field much more difficult. Some
  developers have found this so
  intolerable that they have chosen a
  different way to implement their code
  to ensure that the stack trace truly
  reflects the location where an
  exception was originally thrown:

private void SomeMethod() {
  Boolean trySucceeds = false;
  try {
    ...
    trySucceeds = true;
  }
  finally {
    if (!trySucceeds) { /* catch code goes in here */ }
  }
}

ContentLicense: CC BY-SA 2.5


问:
Can't get values submitted using thymeleaf
I am new with thymeleaf and I am having a doubt about how to retrieve a field from html (using Thymeleaf) to Java (Spring Boot). Follow the code and the error that I am having:

HTML (part with issue)

```<code>    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1.0" />
<title>Entity Migration</title>

<!-- CSS  -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet">

<link href="css/style.css" type="text/css" rel="stylesheet"
    media="screen,projection" />
<link href="css/materialize.css" type="text/css" rel="stylesheet"
    media="screen,projection" />

</head>
<body>
    <nav class="light-blue lighten-1" role="navigation">
        <div class="nav-wrapper container">
            <a id="logo-container" href="#" class="brand-logo">Entity
                Migration</a>
            <ul class="right hide-on-med-and-down">
                <li><a href="#">Logout</a></li>
            </ul>

            <ul id="nav-mobile" class="side-nav">
                <li><a href="#">Entity Migration</a></li>
            </ul>
            <a href="#" data-activates="nav-mobile" class="button-collapse"><i
                class="material-icons">Logout</i></a>
        </div>
    </nav>
    <div class="section no-pad-bot" id="index-banner">
        <div class="container">
            <br> <br>
            <div class="row center">
                <h5 class="header col s12 light">Fill the form below to
                    generate your XML:</h5>
            </div>
            <br> <br>

        </div>
    </div>
    <form class="col s12" action="#" th:action="@{/prepareData}" th:object="${entity}" method="post">
        <div class="row">
            <div class="input-field col s4">
                <input type="number" id="release" name="release" placeholder="Release"
                    class="validate" th:value="*{release}"/>

            </div>
            <div class="input-field col s4">
                <input placeholder="Version" id="version" name="version" type="number"
                    class="validate" th:value="*{version}"/>
            </div>
        </div>
        <input type="submit" value="Generate XML" id="generate"
                class="btn-large waves-effect waves-light orange" />
        </div>
    </form>
        <!--  Scripts-->
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="js/init.js"></script>
    <script src="js/materialize.js"></script>
    <script>
        $(document).ready(function() {
            $('select').material_select();
        });
    </script>

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

Java (Spring Boot Controller)

```<code> @PostMapping(value = "/prepareData")
  public String prepareData(@ModelAttribute(value="entity") EntityMigration entity) {
    TemplatePrepare tP = new TemplatePrepare();
    tP.prepareMainTemplate(entity);
    return "results";
</code>```

EntityMigration (Java Model)

```<code>public class EntityMigration {

    private String release;
    private String version;

    public String getRelease() {
        return release;
    }
    public void setRelease(String release) {
        this.release = release;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}
</code>```

Error

```<code>    2017-11-16 14:01:02.445 ERROR 26932 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "mainForm": An error happened during template parsing (template: "class path resource [templates/mainForm.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/mainForm.html]")
</code>```

(...)

```<code>Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "release" (template: "mainForm" - line 55, col 23)
</code>```

(...)

```<code>org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'release' cannot be found on null
</code>```

(...)

What am I doing wrong?
Thank you.

答:
you forgot to use the name attribute in the input, and to close you input, so replace:

<input placeholder="Version" id="version" type="number" class="validate">
        <input type="number" id="release" placeholder="Release" class="validate" th:value="*{release}">
```

<p>with: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder="Version" id="version" name="version" type="number" class="validate" />
        <input type="number" id="release" name="release" placeholder="Release" class="validate" th:value="*{release}" /></code>```

or you can use the

Body:
I am new with thymeleaf and I am having a doubt about how to retrieve a field from html (using Thymeleaf) to Java (Spring Boot). Follow the code and the error that I am having:

HTML (part with issue)

    <!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1.0" />
<title>Entity Migration</title>

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet">

<link href="css/style.css" type="text/css" rel="stylesheet"
    media="screen,projection" />
<link href="css/materialize.css" type="text/css" rel="stylesheet"
    media="screen,projection" />

            Entity
                Migration

Logout

Entity Migration

            Logout

Fill the form below to
                    generate your XML:

    <form class="col s12" action="#" th:action="@{/prepareData}" th:object="${entity}" method="post">

                <input type="number" id="release" name="release" placeholder="Release"
                    class="validate" th:value="*{release}"/>

                <input placeholder="Version" id="version" name="version" type="number"
                    class="validate" th:value="*{version}"/>

        <input type="submit" value="Generate XML" id="generate"
                class="btn-large waves-effect waves-light orange" />

    </form>

Java (Spring Boot Controller)

 @PostMapping(value = "/prepareData")
  public String prepareData(@ModelAttribute(value="entity") EntityMigration entity) {
    TemplatePrepare tP = new TemplatePrepare();
    tP.prepareMainTemplate(entity);
    return "results";

EntityMigration (Java Model)

public class EntityMigration {

    private String release;
    private String version;

    public String getRelease() {
        return release;
    }
    public void setRelease(String release) {
        this.release = release;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}

Error

    2017-11-16 14:01:02.445 ERROR 26932 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "mainForm": An error happened during template parsing (template: "class path resource [templates/mainForm.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/mainForm.html]")

(...)

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "release" (template: "mainForm" - line 55, col 23)

(...)

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'release' cannot be found on null

(...)

What am I doing wrong?
Thank you.

Body:
you forgot to use the name attribute in the input, and to close you input, so replace:

<input placeholder="Version" id="version" type="number" class="validate">
        <input type="number" id="release" placeholder="Release" class="validate" th:value="*{release}">

with:

<input placeholder="Version" id="version" name="version" type="number" class="validate" />
        <input type="number" id="release" name="release" placeholder="Release" class="validate" th:value="*{release}" />

or you can use the


问:
Running pmd on code with StringBuilder gives error about initialized size and appended size
```<code>private static String buildSomeString(Map<String, String> data) {
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, String> field : data.entrySet()) {
       result.append("some literal")
            .append(field.getKey())
            .append("another literal")
            .append(field.getKey())
            .append("and another one")
            .append(field.getValue())
            .append("and the last in this iteration");
     }
     return result.toString();
}
</code>```

When I run pmd on this I get the following error

```<code>StringBuffer constructor is initialized with size 16, but has at least 83 characters appended.
</code>```

The number of characters is probably wrong, because I changed literals before posting.

Thanks

答:
StringBuilder's constructor can optionally receive an int with the size of the internal buffer to use. If none given (as is in your code), it defaults to 16.

As you append data on the StringBuilder, it will automatically resize the internal buffer as needed. This resizing implies creating a new, larger array, and copying the old data to it. This is "a costly" operation (notes the quotes, this is a micro-optimization, if you are using bad algorithms such bubble sort you have bigger problems).

Doing a more educated guess on the expected size of the string can avoid / minimize such reallocations.

PMD doesn't know what the contents of the map are, but it knows it will include at least 83 chars (given the map is not empty).

This can be resolved by doing a more educated guess on the size, such as:

```<code>StringBuilder result = new StringBuilder(83 * data.size()); // 83 or whatever you constant strings account for
</code>```

This can be further refined if you can better approach the expected value of the map's keys and values. Usually, going slightly over the actual expected output is better, as even if it implies allocating more memory, has a better chance of avoiding reallocations completely.

Body:
private static String buildSomeString(Map<String, String> data) {
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, String> field : data.entrySet()) {
       result.append("some literal")
            .append(field.getKey())
            .append("another literal")
            .append(field.getKey())
            .append("and another one")
            .append(field.getValue())
            .append("and the last in this iteration");
     }
     return result.toString();
}

When I run pmd on this I get the following error

StringBuffer constructor is initialized with size 16, but has at least 83 characters appended.

The number of characters is probably wrong, because I changed literals before posting.

Thanks

Body:
StringBuilder's constructor can optionally receive an int with the size of the internal buffer to use. If none given (as is in your code), it defaults to 16.

As you append data on the StringBuilder, it will automatically resize the internal buffer as needed. This resizing implies creating a new, larger array, and copying the old data to it. This is "a costly" operation (notes the quotes, this is a micro-optimization, if you are using bad algorithms such bubble sort you have bigger problems).

Doing a more educated guess on the expected size of the string can avoid / minimize such reallocations.

PMD doesn't know what the contents of the map are, but it knows it will include at least 83 chars (given the map is not empty).

This can be resolved by doing a more educated guess on the size, such as:

StringBuilder result = new StringBuilder(83 * data.size()); // 83 or whatever you constant strings account for

This can be further refined if you can better approach the expected value of the map's keys and values. Usually, going slightly over the actual expected output is better, as even if it implies allocating more memory, has a better chance of avoiding reallocations completely.


问:
Create a replica of a sql table
I need a query to create a table which is the exact replica but with different table name and without any data from the source table using a sql query!</p>

答:
```<code>SELECT * INTO Table_Copy
FROM Table
where 1=2
</code>```

This worked very well, when i tried to create a replica of the table without any data's.

```<code>SELECT * INTO Table_Copy
FROM Table
</code>```

This will create a replica with the data's too.

OwnerDisplayName: Jaison

Title: Create a replica of a sql table

Body:
SELECT * INTO Table_Copy
FROM Table
where 1=2

This worked very well, when i tried to create a replica of the table without any data's.

SELECT * INTO Table_Copy
FROM Table

This will create a replica with the data's too.


问:
Declare dynamic variable from array list angular js
I created an array.

JS code

```<code>$scope.type = ["status", "category", "subCategory", "room"];
</code>```

I want to use array item as variable. I have to create dynamically. Later I will add a dynamic value. For example when I use $scope.type[0]
variable have to be $scope.status How can I do?

答:
You can do that by using the bracket notation.

```<code>$scope[$scope.type[0]] = "dynamic value";
</code>```

To create for every item in array --

```<code>$scope.type.forEach(function(value){
 $scope[value] = "any dynamic value"
})
</code>```

Body:
I created an array.

JS code

$scope.type = ["status", "category", "subCategory", "room"];

I want to use array item as variable. I have to create dynamically. Later I will add a dynamic value. For example when I use $scope.type[0]
variable have to be $scope.status How can I do?

Body:
You can do that by using the bracket notation.

$scope[$scope.type[0]] = "dynamic value";

To create for every item in array --

$scope.type.forEach(function(value){
 $scope[value] = "any dynamic value"
})


问:
using DictVectorizer to convert strings
```<code>satisfaction_level  last_evaluation number_project  average_montly_hours    time_spend_company  Work_accident   left    promotion_last_5years   dept    salary
0.38    0.53    2   157 3   0   1   0   TECHNICAL   low
0.8 0.86    5   262 6   0   1   0   HR  medium
0.11    0.88    7   272 4   0   1   0   HR  medium
0.72    0.87    5   223 5   0   1   0   FINANCE low
0.37    0.52    2   159 3   0   1   0   MARKETING   low
0.41    0.5 2   153 3   0   1   0   TECHNICAL   low
0.1 0.77    6   247 4   0   1   0   HR  low
0.92    0.85    5   259 5   0   1   0   FINANCE low
0.89    1   5   224 5   0   1   0   HR  low
</code>```

I used the above data and tried to convert C using DictVectorizer. Code is given below

```<code>import pandas as pd
from sklearn.feature_extraction import DictVectorizer

dv=DictVectorizer()
hr_data=pd.read_csv(r"C:\Users\IBM_ADMIN\Desktop\data\HR_comma_sep.csv")
dv.fit_transform(X=hr_data.dept)
</code>```

But it threw error:

'str' object has no attribute 'items'

答:
Use LabelEncoder:</p>

```<code>In [304]: df.dept
Out[304]:
0    TECHNICAL
1           HR
2           HR
3      FINANCE
4    MARKETING
5    TECHNICAL
6           HR
7      FINANCE
8           HR
Name: dept, dtype: object

In [305]: from sklearn.preprocessing import LabelEncoder

In [306]: le = LabelEncoder()

In [307]: df['dept'] = le.fit_transform(df['dept'])

In [308]: df.dept
Out[308]:
0    3
1    1
2    1
3    0
4    2
5    3
6    1
7    0
8    1
Name: dept, dtype: int64

In [309]: le.classes_
Out[309]: array(['FINANCE', 'HR', 'MARKETING', 'TECHNICAL'], dtype=object)
</code>```

Title: using DictVectorizer to convert strings

Body:
satisfaction_level  last_evaluation number_project  average_montly_hours    time_spend_company  Work_accident   left    promotion_last_5years   dept    salary
0.38    0.53    2   157 3   0   1   0   TECHNICAL   low
0.8 0.86    5   262 6   0   1   0   HR  medium
0.11    0.88    7   272 4   0   1   0   HR  medium
0.72    0.87    5   223 5   0   1   0   FINANCE low
0.37    0.52    2   159 3   0   1   0   MARKETING   low
0.41    0.5 2   153 3   0   1   0   TECHNICAL   low
0.1 0.77    6   247 4   0   1   0   HR  low
0.92    0.85    5   259 5   0   1   0   FINANCE low
0.89    1   5   224 5   0   1   0   HR  low

I used the above data and tried to convert C using DictVectorizer. Code is given below

import pandas as pd
from sklearn.feature_extraction import DictVectorizer

dv=DictVectorizer()
hr_data=pd.read_csv(r"C:\Users\IBM_ADMIN\Desktop\data\HR_comma_sep.csv")
dv.fit_transform(X=hr_data.dept)

But it threw error:

'str' object has no attribute 'items'

Body:
Use LabelEncoder:

In [304]: df.dept
Out[304]:
0    TECHNICAL
1           HR
2           HR
3      FINANCE
4    MARKETING
5    TECHNICAL
6           HR
7      FINANCE
8           HR
Name: dept, dtype: object

In [305]: from sklearn.preprocessing import LabelEncoder

In [306]: le = LabelEncoder()

In [307]: df['dept'] = le.fit_transform(df['dept'])

In [308]: df.dept
Out[308]:
0    3
1    1
2    1
3    0
4    2
5    3
6    1
7    0
8    1
Name: dept, dtype: int64

In [309]: le.classes_
Out[309]: array(['FINANCE', 'HR', 'MARKETING', 'TECHNICAL'], dtype=object)


问:
tap detection on a gameobject in unity
i'm currently making a soccer game.

In this mini-game, when the player touch the ball, it adds force, and the goal is to make the higher score.

So i wrote:

```<code> void Update()
{
    if(Input.touchCount == 1 && Input.GetTouch(0).phase== TouchPhase.Began)
      {
       AddForce, and playsound ect...
      }

}
</code>```

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

How can i do that?

Thanks! :)

答:
Take Touch Event using Co-Rouitne will be good for you. If you will not use
coroutine, then it constant check for touch event in OnUpdate. Its better to take
touch event in co-routine.
This is my link in which you can check how to use it.

http://unitycodestuff.blogspot.in/2017/11/how-to-use-co-routine-for-taking-touch.html

Title: tap detection on a gameobject in unity

Body:
i'm currently making a soccer game.

In this mini-game, when the player touch the ball, it adds force, and the goal is to make the higher score.

So i wrote:

 void Update()
{
    if(Input.touchCount == 1 && Input.GetTouch(0).phase== TouchPhase.Began)
      {
       AddForce, and playsound ect...
      }

}

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

How can i do that?

Thanks! :)


问:
Returning a string up until a header
I'm not sure why I get this line repeated multiple times when I test this function. Can anyone please help me fix this? I want to return a string up until the header and strip everything afterwards.</p>

```<code> "</head>hello python world </head> , i'm a beginner</head>hello python
world </head> , i'm a beginner</head>hello python world </head> "

def get_header(s):
'''(str) -> str
Return the start of the given string up to and including
</head>.
>>> get_header("hello python world </head> , i'm a beginner ")
'hello python world </head>'
'''
new_s = ''
tag = '</head>'
for item in s:
    new_s = new_s + tag + s.strip()
return new_s
</code>```

答:
You can use regex:

```<code>import re
def get_header(s):
   return re.findall('[\w\s]+\</head\>', s)[0]

print(get_header("hello python world </head> , i'm a beginner "))
</code>```

Output:

```<code>hello python world </head>
</code>```

Edit: without re:

```<code>def get_header(s):
    return s[:s.index('</head>')+7]
</code>```

Without hardcoding, you should pass the head value to the function as well:

```<code>def get_header(s, key):
    return s[:s.index(key)+len(key)]
</code>```

Title: Returning a string up until a header

Body:
I'm not sure why I get this line repeated multiple times when I test this function. Can anyone please help me fix this? I want to return a string up until the header and strip everything afterwards.

 "hello python world  , i'm a beginnerhello python
world  , i'm a beginnerhello python world  "

def get_header(s):
'''(str) -> str
Return the start of the given string up to and including
.
>>> get_header("hello python world  , i'm a beginner ")
'hello python world '
'''
new_s = ''
tag = ''
for item in s:
    new_s = new_s + tag + s.strip()
return new_s

Body:
You can use regex:

import re
def get_header(s):
   return re.findall('[\w\s]+\</head\>', s)[0]

print(get_header("hello python world </head> , i'm a beginner "))

Output:

hello python world </head>

Edit: without re:

def get_header(s):
    return s[:s.index('</head>')+7]

Without hardcoding, you should pass the head value to the function as well:

def get_header(s, key):
    return s[:s.index(key)+len(key)]


答:
You can try below.</p>

```<code>$scope.status = $scope.type[0];
$scope.category= $scope.type[1];
$scope.subCategory= $scope.type[2];
</code>```

Title: Declare dynamic variable from array list angular js

Body:
You can try below.

$scope.status = $scope.type[0];
$scope.category= $scope.type[1];
$scope.subCategory= $scope.type[2];


问:
Behavior of mysql_insert_id()
I am using functions from a php library that uses mysql_insert_id() every now and then. Now I've modified a few functions that insert data into tables such that the primary key value is explicitly specified e.g. I insert an a row with ID=300 followed by a row with ID=200 when the table originally had 10 rows. I am wondering if mysql_insert_id will behave as expected i.e. return the value I explicitly specified for the AUTO_INCREMENT PRIMARY KEY column.

答:
I don't think it will. It should return 0:

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established. - http://php.net/manual/en/function.mysql-insert-id.php

The ID isn't generated so should return 0.

As has been proven, in practice this is not the case.

Title: Behavior of mysql_insert_id()


问:
Interleaving of two strings
I have two strings str1 and str2.
Is there any algorithm that can be used in order to print out all interleavings of the two strings using recursion?

Update:

```<code>public class Interleave {

    private String resultString[] = new String[10];
    private String[] interStr(String str1, String str2){
    int n = ((Factorial.factorial(str1.length() + str2.length())) / (Factorial.factorial(str1.length()) * Factorial.factorial(str2.length())));
    //n is number of interleavings based on (str1.length()+str2.length())! / (str1.length()! * str2.length()!)
    if(str1.length() == 0){
        resultString[0] = str2;
        return resultString;
    }

    if(str2.length() == 0){
        resultString[0] = str1;
        return resultString;
    }

    else{
        for(int i = 0; i < n; i++){
            resultString[i]= str1.substring(0, 1) + interStr(str1.substring(1), str2.substring(1));

        }
    }
    return resultString;
}

    public static void main(String[] args) {
    Interleave obj = new Interleave();
    obj.interStr("12", "abc");
    for(int i = 0; i < obj.resultString.length; i ++){
        System.out.println(obj.resultString[i]);
    }

}

}
</code>```

答:
Here is another recursive solution:</p>

```<code>public class Interleaving2 {
    public static void main(String[] args) {
        String x = "ab";
        String y = "CD";
        int m = x.length();
        int n = y.length();
        char[] result = new char[m + n + 1];

        interleave(x, y, result, m, n, 0);
    }

    public static void interleave(String x, String y, char[] result, int m, int n, int i) {
        if (m == 0 && n == 0) {
            System.out.println(String.valueOf(result));
        }

        if (m != 0) {
            result[i] = x.charAt(0);
            interleave(x.substring(1), y, result, m - 1, n, i + 1);
        }

        if (n != 0) {
            result[i] = y.charAt(0);
            interleave(x, y.substring(1), result, m, n - 1, i + 1);
        }
    }
}
</code>```

Title: Interleaving of two strings

Body:
I have two strings str1 and str2.
Is there any algorithm that can be used in order to print out all interleavings of the two strings using recursion?

Update:

public class Interleave {

    private String resultString[] = new String[10];
    private String[] interStr(String str1, String str2){
    int n = ((Factorial.factorial(str1.length() + str2.length())) / (Factorial.factorial(str1.length()) * Factorial.factorial(str2.length())));
    //n is number of interleavings based on (str1.length()+str2.length())! / (str1.length()! * str2.length()!)
    if(str1.length() == 0){
        resultString[0] = str2;
        return resultString;
    }

    if(str2.length() == 0){
        resultString[0] = str1;
        return resultString;
    }

    else{
        for(int i = 0; i < n; i++){
            resultString[i]= str1.substring(0, 1) + interStr(str1.substring(1), str2.substring(1));

        }
    }
    return resultString;
}

    public static void main(String[] args) {
    Interleave obj = new Interleave();
    obj.interStr("12", "abc");
    for(int i = 0; i < obj.resultString.length; i ++){
        System.out.println(obj.resultString[i]);
    }

}

}

Body:
Here is another recursive solution:

public class Interleaving2 {
    public static void main(String[] args) {
        String x = "ab";
        String y = "CD";
        int m = x.length();
        int n = y.length();
        char[] result = new char[m + n + 1];

        interleave(x, y, result, m, n, 0);
    }

    public static void interleave(String x, String y, char[] result, int m, int n, int i) {
        if (m == 0 && n == 0) {
            System.out.println(String.valueOf(result));
        }

        if (m != 0) {
            result[i] = x.charAt(0);
            interleave(x.substring(1), y, result, m - 1, n, i + 1);
        }

        if (n != 0) {
            result[i] = y.charAt(0);
            interleave(x, y.substring(1), result, m, n - 1, i + 1);
        }
    }
}


问:
Using React Virtualized CellMeasurer with changing data order for List and dynamic heights
I am trying to create a chat application using React Virtualized. So far everything is working but I think think I am doing something wrong when using keyMapper and rowRenderer from the list.

The cache is using the id to store the height in the _rowHeightCache but it seems that the heights are looked up using the index and not the id. Im not sure if I should be passing the id as the rowIndex to CellMeasurer to get the right heights or something of that nature.

The issue is that the heights are wrong due to the changing order of the messages list so the index's don't have the proper heights and also that messages can be removed messing up the index orders. This I think should be fixed by using keyMapper to look up the heights but i must be doing it wrong.

The following is an edited down version of how I am using it.

```<code>constructor(props) {
        this._cache = new CellMeasurerCache({
            defaultHeight: 45,
            fixedWidth: true,
            keyMapper: (index) => _.get(this.props.messageList[index], ['msgId'])
        });
    }

    render() {
        const props = this.filterProps(this.props),
            list = this.props.messageList,
            rowCount = list.length;

        return (

            <InfiniteLoader
                threshold={0}
                isRowLoaded={this._isRowLoaded}
                loadMoreRows={this._loadMoreRows}
                rowCount={rowCount}>
                {({onRowsRendered, registerChild}) => (
                    <AutoSizer>
                        {({width, height}) => (
                            <List
                                ref={(ref) => {
                                    this.streamLane = ref;
                                    registerChild(ref);
                                }}
                                height={height}
                                width={width}
                                onRowsRendered={onRowsRendered}
                                rowCount={rowCount}
                                rowRenderer={this._rowRenderer}
                                deferredMeasurementCache={this._cache}
                                rowHeight={this._cache.rowHeight}
                            />
                        )}
                    </AutoSizer>
                )}
            </InfiniteLoader>
       );
   }

    _rowRenderer({ index, key, parent, style }) {
        return (
            <CellMeasurer
                cache={this._cache}
                columnIndex={0}
                key={key}
                parent={parent}
                rowIndex={index}>
                <div style={{...style}}>
                    {this.props.messageList[index]}
                </div>
            </CellMeasurer>
        );
    }

    _loadMoreRows({startIndex, stopIndex}) {

        return new Promise((resolve) => {
            if (!!stopIndex || !!startIndex || this.props.hasLastMessage || this.state.isPinned) {
                return resolve();
            }

            this.props.loadOlder(() => resolve);
        });
    }

    _isRowLoaded({index}) {
        if (index === 0) return false;
        return !!this.props.messageList[index];
    }
  }
</code>```

Any help, suggestions or criticisms would be amazing.

答:
The issue is that the heights are wrong due to the changing order of the messages list so the index's don't have the proper heights and also that messages can be removed messing up the index orders.

Your example code doesn't show how the order changes or what you do after it changes, so it's hard to say what you're doing wrong.

But when the order changes (eg you sort the data, or you add new items to the beginning of the list causing older items to shift) then you'll need to let List know that its cached positions may be stale. Do do this in your case, you'd need to call this.streamLane.recomputeRowHeights().

(You can pass the index of the first changed item to recomputeRowHeights but I assume in your case that maybe all items have shifted? I don't know, since I don't have all of your code.)

After you call recomputeRowHeights, List will re-calculate the layout using the heights reported to it by CellMeasurerCache. That cache uses your keyMapper function:

```<code>rowHeight = ({index}: IndexParam) => {
  const key = this._keyMapper(index, 0);

  return this._rowHeightCache.hasOwnProperty(key)
    ? this._rowHeightCache[key]
    : this._defaultHeight;
};
</code>```

So it won't need to remeasure items, even though their indices have changed.

Body:
I am trying to create a chat application using React Virtualized. So far everything is working but I think think I am doing something wrong when using keyMapper and rowRenderer from the list.

The cache is using the id to store the height in the _rowHeightCache but it seems that the heights are looked up using the index and not the id. Im not sure if I should be passing the id as the rowIndex to CellMeasurer to get the right heights or something of that nature.

The issue is that the heights are wrong due to the changing order of the messages list so the index's don't have the proper heights and also that messages can be removed messing up the index orders. This I think should be fixed by using keyMapper to look up the heights but i must be doing it wrong.

The following is an edited down version of how I am using it.

constructor(props) {
        this._cache = new CellMeasurerCache({
            defaultHeight: 45,
            fixedWidth: true,
            keyMapper: (index) => _.get(this.props.messageList[index], ['msgId'])
        });
    }

    render() {
        const props = this.filterProps(this.props),
            list = this.props.messageList,
            rowCount = list.length;

        return (

            <InfiniteLoader
                threshold={0}
                isRowLoaded={this._isRowLoaded}
                loadMoreRows={this._loadMoreRows}
                rowCount={rowCount}>
                {({onRowsRendered, registerChild}) => (
                    <AutoSizer>
                        {({width, height}) => (
                            <List
                                ref={(ref) => {
                                    this.streamLane = ref;
                                    registerChild(ref);
                                }}
                                height={height}
                                width={width}
                                onRowsRendered={onRowsRendered}
                                rowCount={rowCount}
                                rowRenderer={this._rowRenderer}
                                deferredMeasurementCache={this._cache}
                                rowHeight={this._cache.rowHeight}
                            />
                        )}
                    </AutoSizer>
                )}
            </InfiniteLoader>
       );
   }

    _rowRenderer({ index, key, parent, style }) {
        return (
            <CellMeasurer
                cache={this._cache}
                columnIndex={0}
                key={key}
                parent={parent}
                rowIndex={index}>

                    {this.props.messageList[index]}

            </CellMeasurer>
        );
    }

    _loadMoreRows({startIndex, stopIndex}) {

        return new Promise((resolve) => {
            if (!!stopIndex || !!startIndex || this.props.hasLastMessage || this.state.isPinned) {
                return resolve();
            }

            this.props.loadOlder(() => resolve);
        });
    }

    _isRowLoaded({index}) {
        if (index === 0) return false;
        return !!this.props.messageList[index];
    }
  }

Any help, suggestions or criticisms would be amazing.

Body:
The issue is that the heights are wrong due to the changing order of the messages list so the index's don't have the proper heights and also that messages can be removed messing up the index orders.

Your example code doesn't show how the order changes or what you do after it changes, so it's hard to say what you're doing wrong.

But when the order changes (eg you sort the data, or you add new items to the beginning of the list causing older items to shift) then you'll need to let List know that its cached positions may be stale. Do do this in your case, you'd need to call this.streamLane.recomputeRowHeights().

(You can pass the index of the first changed item to recomputeRowHeights but I assume in your case that maybe all items have shifted? I don't know, since I don't have all of your code.)

After you call recomputeRowHeights, List will re-calculate the layout using the heights reported to it by CellMeasurerCache. That cache uses your keyMapper function:

rowHeight = ({index}: IndexParam) => {
  const key = this._keyMapper(index, 0);

  return this._rowHeightCache.hasOwnProperty(key)
    ? this._rowHeightCache[key]
    : this._defaultHeight;
};

So it won't need to remeasure items, even though their indices have changed.


问:
Secure method for allowing users to remotely execute SSIS package
I've been tasked with creating a somewhat automated process that allows a non-SQL user to import data from an Excel spreadsheet into a table in SQL Server. We currently use SQL Server 2012. The user needs to be able to upload data whenever they finish putting it together in an Excel spreadsheet. I have created an SSIS package that checks a specific folder on a shared drive for the file. If the file exists it then goes through some transformations and is then inserted into the final table in the database. The user only really needs to do this a handful of times a year but we never know when so they want to give the user the ability to do this whenever they need to. I am at the point where I need to find a way to either allow the user to execute the package or start a job that executes the package remotely for their computer. I don't want to use anything that uses xp_cmdshell as I've heard this can create unnecessary vulnerabilities. I've read that I can use Reporting Services to execute the package but I'm not sure if this is secure or the best way to go. Microsoft says that it's possible but is not supported or recommended at this time https://msdn.microsoft.com/en-us/library/ms345250.aspx . I'm wondering if I can do this in C# without having to store credentials in plain text since the user doesn't have database access. Microsoft has an article (https://learn.microsoft.com/en-us/sql/integration-services/run-manage-packages-programmatically/loading-and-running-a-remote-package-programmatically) on remotely running an SSIS package using Integrated Security but the user wouldn't have access. I'm also not entirely opposed to using Reporting Services if someone has experience doing it this way and can speak on whether or not this would be the best way to go. Any help is greatly appreciated!</p>

答:
I'm going to address the SSRS specific part of this question since you've asked directly about this option.

It is possible to execute an SSIS package via T-SQL if connected to the SSISDB database using code like this:

```<code>Declare @execution_id bigint
EXEC [SSISDB].[catalog].[create_execution] @package_name=N'Package.dtsx',
    @execution_id=@execution_id OUTPUT,
    @folder_name=N'Deployed Projects',
      @project_name=N'Integration Services Project1',
    @use32bitruntime=False,
      @reference_id=Null
Select @execution_id
DECLARE @var0 smallint = 1
EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,
    @object_type=50,
      @parameter_name=N'LOGGING_LEVEL',
      @parameter_value=@var0
EXEC [SSISDB].[catalog].[start_execution] @execution_id
GO
</code>```

Because SSRS allows you to execute a stored procedure from a dataset, you can put any type of SQL logic into that dataset and have it execute, including something like this.  How fancy you want to get with the report is up to you, as you could have a button on the report that actually executes the package instead of just running the package on the first report run. You would need to use a parameter on report load with a default value that you check in your T-SQL and bypass the package execution, depending on the value.  Because your credentials are stored in a regular SSRS data source, this should be considered as secure as the rest of your reporting databases

Note, a nicer and cleaner way to do this would be to have a web app developer create a very simple application that allows authorized users to execute the T-SQL command.  The SSRS option may be considered a bit hacky since reports are not meant for running commands and modifying data, more as a display method for data. However, I've been in large organizations where you are tasked with a problem like this and not given the latitude to use any "better" tools so this is at least an option.

Body:
I'm going to address the SSRS specific part of this question since you've asked directly about this option.

It is possible to execute an SSIS package via T-SQL if connected to the SSISDB database using code like this:

Declare @execution_id bigint
EXEC [SSISDB].[catalog].[create_execution] @package_name=N'Package.dtsx',
    @execution_id=@execution_id OUTPUT,
    @folder_name=N'Deployed Projects',
      @project_name=N'Integration Services Project1',
    @use32bitruntime=False,
      @reference_id=Null
Select @execution_id
DECLARE @var0 smallint = 1
EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,
    @object_type=50,
      @parameter_name=N'LOGGING_LEVEL',
      @parameter_value=@var0
EXEC [SSISDB].[catalog].[start_execution] @execution_id
GO

Because SSRS allows you to execute a stored procedure from a dataset, you can put any type of SQL logic into that dataset and have it execute, including something like this.  How fancy you want to get with the report is up to you, as you could have a button on the report that actually executes the package instead of just running the package on the first report run. You would need to use a parameter on report load with a default value that you check in your T-SQL and bypass the package execution, depending on the value.  Because your credentials are stored in a regular SSRS data source, this should be considered as secure as the rest of your reporting databases

Note, a nicer and cleaner way to do this would be to have a web app developer create a very simple application that allows authorized users to execute the T-SQL command.  The SSRS option may be considered a bit hacky since reports are not meant for running commands and modifying data, more as a display method for data. However, I've been in large organizations where you are tasked with a problem like this and not given the latitude to use any "better" tools so this is at least an option.


问:
Rotating a bufferedImage changes size of image
I'm trying to rotate a bufferedImage 90° but I can't quite get it done.

I can rotate the image but the resulting image is kind of odd.

1) Black borders on the left and right side

2) A loss of information

Here's an example:

This is the original image.

After I rotate the image I get this:

I don't really know what I do wrong here.

This is the code I use to rotate a bufferedImage:

```<code>BufferedImage imgIn = ImageIO.read(new File("landscape.jpg"));
BufferedImage imgIn2 = imgIn;
        AffineTransform tx = new AffineTransform();
        tx.rotate(Math.PI / 2, imgIn2.getWidth() / 2, imgIn2.getHeight() / 2);//(radian,arbit_X,arbit_Y)
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        BufferedImage rotatedImage = new BufferedImage(imgIn2.getHeight(), imgIn2.getWidth(), imgIn2.getType());
        op.filter(imgIn2, rotatedImage);
        ImageIO.write(rotatedImage, "JPEG", new File("testRotation.jpg"));
</code>```

Help would be very appreciated!

答:
With AffineTransform

```<code>import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main(String[] arg)throws Exception
    {
        BufferedImage imgIn = ImageIO.read(new File("/home/arpit/Desktop/image.jpg"));
        BufferedImage imgIn2 =  new BufferedImage(imgIn.getHeight(), imgIn.getWidth(), imgIn.getType());

        AffineTransform tx = new AffineTransform();
        tx.rotate(Math.PI / 2, imgIn2.getWidth() / 2, imgIn.getHeight() / 2);
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        op.filter(imgIn, imgIn2);

        ImageIO.write(imgIn2, "JPEG", new File("/home/arpit/Desktop/testrotated.jpg"));
    }
}
</code>```

Without AffineTransform

```<code>import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main(String[] arg)throws Exception
    {
        BufferedImage imgIn = ImageIO.read(new File("/home/arpit/Desktop/image.jpg"));
        BufferedImage imgIn2 =  new BufferedImage(imgIn.getHeight(), imgIn.getWidth(), imgIn.getType());

        for(int x=0;x<imgIn.getWidth();x++)
        {
            for(int y=0;y<imgIn.getHeight();y++)
            {
                int color = imgIn.getRGB(x,y);
                imgIn2.setRGB(imgIn2.getWidth()-1-y,x,color);

            }
        }
        ImageIO.write(imgIn2, "JPEG", new File("/home/arpit/Desktop/testrotated.jpg"));
    }
}
</code>```

Body:
I'm trying to rotate a bufferedImage 90° but I can't quite get it done.

I can rotate the image but the resulting image is kind of odd.

1) Black borders on the left and right side

2) A loss of information

Here's an example:

This is the original image.

After I rotate the image I get this:

I don't really know what I do wrong here.

This is the code I use to rotate a bufferedImage:

BufferedImage imgIn = ImageIO.read(new File("landscape.jpg"));
BufferedImage imgIn2 = imgIn;
        AffineTransform tx = new AffineTransform();
        tx.rotate(Math.PI / 2, imgIn2.getWidth() / 2, imgIn2.getHeight() / 2);//(radian,arbit_X,arbit_Y)
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        BufferedImage rotatedImage = new BufferedImage(imgIn2.getHeight(), imgIn2.getWidth(), imgIn2.getType());
        op.filter(imgIn2, rotatedImage);
        ImageIO.write(rotatedImage, "JPEG", new File("testRotation.jpg"));

Help would be very appreciated!

Body:
With AffineTransform

import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main(String[] arg)throws Exception
    {
        BufferedImage imgIn = ImageIO.read(new File("/home/arpit/Desktop/image.jpg"));
        BufferedImage imgIn2 =  new BufferedImage(imgIn.getHeight(), imgIn.getWidth(), imgIn.getType());

        AffineTransform tx = new AffineTransform();
        tx.rotate(Math.PI / 2, imgIn2.getWidth() / 2, imgIn.getHeight() / 2);
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        op.filter(imgIn, imgIn2);

        ImageIO.write(imgIn2, "JPEG", new File("/home/arpit/Desktop/testrotated.jpg"));
    }
}

Without AffineTransform

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main(String[] arg)throws Exception
    {
        BufferedImage imgIn = ImageIO.read(new File("/home/arpit/Desktop/image.jpg"));
        BufferedImage imgIn2 =  new BufferedImage(imgIn.getHeight(), imgIn.getWidth(), imgIn.getType());

        for(int x=0;x<imgIn.getWidth();x++)
        {
            for(int y=0;y<imgIn.getHeight();y++)
            {
                int color = imgIn.getRGB(x,y);
                imgIn2.setRGB(imgIn2.getWidth()-1-y,x,color);

            }
        }
        ImageIO.write(imgIn2, "JPEG", new File("/home/arpit/Desktop/testrotated.jpg"));
    }
}


问:
Jasper Report JasperReportsPdfView SpringBoot Subreport error
Report structure:

```<code>main report - myreport.jrxml
sub report  - myreport_detail.jrxml
</code>```

Running my main report with sub report works fine in Jasper Report Studio. In my Spring Boot environment I use JasperReportsPdfView.

However running myreport.jrxml here I get:

```<code>Caused by: net.sf.jasperreports.engine.JRException: Resource not found at: jasper/repo/myreport_detail.jasper.
at net.sf.jasperreports.repo.RepositoryUtil.getResourceFromLocation(RepositoryUtil.java:153)
at net.sf.jasperreports.repo.RepositoryUtil.getReport(RepositoryUtil.java:112)
at net.sf.jasperreports.engine.fill.JRFillSubreport.loadReport(JRFillSubreport.java:411)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateReport(JRFillSubreport.java:378)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:440)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:354)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:383)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:506)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2412)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:761)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:240)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:99)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:607)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:387)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:109)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.doFillReport(AbstractJasperReportsView.java:702)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.fillReport(AbstractJasperReportsView.java:669)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.renderMergedOutputModel(AbstractJasperReportsView.java:566)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 97 common frames omitted
</code>```

Note: running one single report without sub report works fine

Endpoint:

```<code>    @RequestMapping(value = "/api", params = {"dir", "name"})
public ModelAndView report(
    HttpServletRequest request,
    @RequestParam(value = "dir") String dir,
    @RequestParam(value = "name") String name) throws Exception {

    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setJdbcDataSource(dataSource);
    view.setUrl("classpath:jasper/" + dir + "/" + name + ".jrxml");
    view.setApplicationContext(context);
    view.setHeaders(getProperties(name, false));
    return new ModelAndView(view, getParameters(request));
}
</code>```

Java code crash RepositoryUtil:

```<code>    public <K extends Resource> K getResourceFromLocation(String location, Class<K> resourceType) throws JRException
{
    K resource = null;
    List<RepositoryService> services = getServices();
    if (services != null)
    {
        for (RepositoryService service : services)
        {
            resource = service.getResource(location, resourceType);
            if (resource != null)
            {
                break;
            }
        }
    }
    if (resource == null)
    {
        throw
        new JRException(
            EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND,
            new Object[]{location});    //FIXMEREPO decide whether to return null or throw exception; check everywhere
    }
    return resource;
}
</code>```

Error line:

```<code>    resource = service.getResource(location, resourceType);
</code>```

Variable:

```<code>  location -> jasper/repo/myreport_detail.jasper
  resourceType -> class net.sf.jasperreports.repo.ReportResource
</code>```

Exception line thrown because resource = null:

```<code>    public static final String EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND = "repo.resource.not.found";
</code>```

Anyone?

答:
It seems as Jasper Studio problem that I had at 1 point.
Try to check expression that you are using for sub-report in main report. Depending of version Jasper Report Studio expects sub-report to be defined as

"folderOfyourSubReport/myreport_detail.jrxml"

or

"folderOfyourSubReport/myreport_detail.jasper"

Body:
Report structure:

main report - myreport.jrxml
sub report  - myreport_detail.jrxml

Running my main report with sub report works fine in Jasper Report Studio. In my Spring Boot environment I use JasperReportsPdfView.

However running myreport.jrxml here I get:

Caused by: net.sf.jasperreports.engine.JRException: Resource not found at: jasper/repo/myreport_detail.jasper.
at net.sf.jasperreports.repo.RepositoryUtil.getResourceFromLocation(RepositoryUtil.java:153)
at net.sf.jasperreports.repo.RepositoryUtil.getReport(RepositoryUtil.java:112)
at net.sf.jasperreports.engine.fill.JRFillSubreport.loadReport(JRFillSubreport.java:411)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateReport(JRFillSubreport.java:378)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:440)
at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:354)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:383)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:506)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2412)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:761)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:240)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:99)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:607)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:387)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:109)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.doFillReport(AbstractJasperReportsView.java:702)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.fillReport(AbstractJasperReportsView.java:669)
at org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView.renderMergedOutputModel(AbstractJasperReportsView.java:566)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 97 common frames omitted

Note: running one single report without sub report works fine

Endpoint:

    @RequestMapping(value = "/api", params = {"dir", "name"})
public ModelAndView report(
    HttpServletRequest request,
    @RequestParam(value = "dir") String dir,
    @RequestParam(value = "name") String name) throws Exception {

    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setJdbcDataSource(dataSource);
    view.setUrl("classpath:jasper/" + dir + "/" + name + ".jrxml");
    view.setApplicationContext(context);
    view.setHeaders(getProperties(name, false));
    return new ModelAndView(view, getParameters(request));
}

Java code crash RepositoryUtil:

    public <K extends Resource> K getResourceFromLocation(String location, Class<K> resourceType) throws JRException
{
    K resource = null;
    List<RepositoryService> services = getServices();
    if (services != null)
    {
        for (RepositoryService service : services)
        {
            resource = service.getResource(location, resourceType);
            if (resource != null)
            {
                break;
            }
        }
    }
    if (resource == null)
    {
        throw
        new JRException(
            EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND,
            new Object[]{location});    //FIXMEREPO decide whether to return null or throw exception; check everywhere
    }
    return resource;
}

Error line:

    resource = service.getResource(location, resourceType);

Variable:

  location -> jasper/repo/myreport_detail.jasper
  resourceType -> class net.sf.jasperreports.repo.ReportResource

Exception line thrown because resource = null:

    public static final String EXCEPTION_MESSAGE_KEY_RESOURCET_NOT_FOUND = "repo.resource.not.found";

Anyone?


问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答:
Simple,It will crash at aribitary points at where you used  the .net 3.5 specific functionality.

But basic question ... why do you want to do that ?

If you have migrated a project from .net freamework version 2.0 to 3.5 and not using any feature of .net 3.5 does not represent a valid framework migration


问:
How to make VBA do the same actions while changing criteria until it hits an empty cell?
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

```<code>Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"
</code>```

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

答:
Tried to understand what you were wanting to do but this will copy any thing from sheet one A1 to A100 that contains "_" which you can change to match your filter, if you can clear this up what your filtering by ill amend. it then puts it in sheet2 and puts a "+" between each entry  </p>

```<code>Sub test()
Dim myArray(1 To 1000) As Variant, cell As Range, myRng As Range, myRng2 As Range, cell2 As Range, Pos As Long, criteria As Variant

Set myRng = ThisWorkbook.Sheets("Sheet1").Range("A1:A1000") 'You can change this to be your correct source sheet, and range

Set myRng2 = ThisWorkbook.Sheets("Sheet2").Range("A1:A1000") 'You can change this to be your correct destination sheet, and range

criteria = ThisWorkbook.Sheets("Sheet3").Range("A1").Value 'Your search criteria lives here

Pos = 1

    For Each cell In myRng
        If cell.Value <> "" And InStr(cell.Value, criteria) > 0 Then 'you can change the criteria to anything you want.
             myArray(Pos) = cell.Value
             Pos = Pos + 1
        End If
    Next cell

Pos = 1

    For Each cell2 In myRng2
        If cell2.Value = "" Then
            cell2.Value = myArray(Pos)

            If cell2.Value <> "" Then
               cell2.Offset(1, 0).Value = "+"
            End If

            Pos = Pos + 1
        End If
    Next cell2

Set myRng = Nothing
Set myRng2 = Nothing

End Sub
</code>```

Body:
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

Body:
Tried to understand what you were wanting to do but this will copy any thing from sheet one A1 to A100 that contains "_" which you can change to match your filter, if you can clear this up what your filtering by ill amend. it then puts it in sheet2 and puts a "+" between each entry

Sub test()
Dim myArray(1 To 1000) As Variant, cell As Range, myRng As Range, myRng2 As Range, cell2 As Range, Pos As Long, criteria As Variant

Set myRng = ThisWorkbook.Sheets("Sheet1").Range("A1:A1000") 'You can change this to be your correct source sheet, and range

Set myRng2 = ThisWorkbook.Sheets("Sheet2").Range("A1:A1000") 'You can change this to be your correct destination sheet, and range

criteria = ThisWorkbook.Sheets("Sheet3").Range("A1").Value 'Your search criteria lives here

Pos = 1

    For Each cell In myRng
        If cell.Value <> "" And InStr(cell.Value, criteria) > 0 Then 'you can change the criteria to anything you want.
             myArray(Pos) = cell.Value
             Pos = Pos + 1
        End If
    Next cell

Pos = 1

    For Each cell2 In myRng2
        If cell2.Value = "" Then
            cell2.Value = myArray(Pos)

            If cell2.Value <> "" Then
               cell2.Offset(1, 0).Value = "+"
            End If

            Pos = Pos + 1
        End If
    Next cell2

Set myRng = Nothing
Set myRng2 = Nothing

End Sub


问:
setting ports for container in docker for docker golang api
I am looking forward to do something below like this using docker golang api

cmd : docker run -t -i -p 8989:8080 "image-name" /bin/bash

Also I am using golang sdk https://github.com/moby/moby/client or https://godoc.org/github.com/moby/moby/client and my docker api version is 1.30 (Client & Server both)

Here is the piece of code I am using

```<code> package main

 import (
       "fmt"

       "github.com/docker/docker/client"
       "github.com/docker/docker/api/types"
       "github.com/docker/docker/api/types/container"
       "golang.org/x/net/context"
       "github.com/docker/go-connections/nat"
    //"github.com/docker/docker/vendor/github.com/docker/go-connections/nat"
)

func check(err error) {
   if err != nil {
       panic(err)
   }
}

func main(){
    ctx := context.Background()
cli, err := client.NewEnvClient()
check(err)

config := &container.Config{
Image : image-name,
ExposedPorts: nat.PortSet{
    "8080/tcp": struct{}{},
},
Cmd : [] string {"sh","-c","while true; do sleep always; done","/bin/bash"},
}

host_config := &container.HostConfig{
     PortBindings: nat.PortMap{
     "8080/tcp": []nat.PortBinding{
         {
             HostIP: "0.0.0.0",
             HostPort: "8989",
         },
      },
   },
}

  resp, err := cli.ContainerCreate(ctx,config,host_config, nil,"")
  check(err)

  if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{});
      err != nil {
        panic(err)
  }

}
</code>```

After Compiling this code I get the following error

```<code># command-line-arguments
src\main\createcontainer1.go:53: cannot use "github.com/docker/go-connections/nat".PortSet literal (type "github.com/docker/go-connections/nat".PortSet) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortSet in field value

src\main\createcontainer1.go:65: cannot use "github.com/docker/go-connections/nat".PortMap literal (type "github.com/docker/go-connections/nat".PortMap) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortMap in field value
</code>```

If somebody knows what could be the problem and how to fix it.
Please answer to it as I am beginner with docker.

答:
My solution for OSX:</p>

```<code>mv /Users/<user>/go/src/github.com/docker/docker/vendor/github.com/docker/go-connections/{nat,nat.old}
</code>```

Body:
I am looking forward to do something below like this using docker golang api

cmd : docker run -t -i -p 8989:8080 "image-name" /bin/bash

Also I am using golang sdk https://github.com/moby/moby/client or https://godoc.org/github.com/moby/moby/client and my docker api version is 1.30 (Client & Server both)

Here is the piece of code I am using

 package main

 import (
       "fmt"

       "github.com/docker/docker/client"
       "github.com/docker/docker/api/types"
       "github.com/docker/docker/api/types/container"
       "golang.org/x/net/context"
       "github.com/docker/go-connections/nat"
    //"github.com/docker/docker/vendor/github.com/docker/go-connections/nat"
)

func check(err error) {
   if err != nil {
       panic(err)
   }
}

func main(){
    ctx := context.Background()
cli, err := client.NewEnvClient()
check(err)

config := &container.Config{
Image : image-name,
ExposedPorts: nat.PortSet{
    "8080/tcp": struct{}{},
},
Cmd : [] string {"sh","-c","while true; do sleep always; done","/bin/bash"},
}

host_config := &container.HostConfig{
     PortBindings: nat.PortMap{
     "8080/tcp": []nat.PortBinding{
         {
             HostIP: "0.0.0.0",
             HostPort: "8989",
         },
      },
   },
}

  resp, err := cli.ContainerCreate(ctx,config,host_config, nil,"")
  check(err)

  if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{});
      err != nil {
        panic(err)
  }

}

After Compiling this code I get the following error

# command-line-arguments
src\main\createcontainer1.go:53: cannot use "github.com/docker/go-connections/nat".PortSet literal (type "github.com/docker/go-connections/nat".PortSet) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortSet in field value

src\main\createcontainer1.go:65: cannot use "github.com/docker/go-connections/nat".PortMap literal (type "github.com/docker/go-connections/nat".PortMap) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortMap in field value

If somebody knows what could be the problem and how to fix it.
Please answer to it as I am beginner with docker.

Body:
My solution for OSX:

mv /Users/<user>/go/src/github.com/docker/docker/vendor/github.com/docker/go-connections/{nat,nat.old}