问:
Add Column values in sql server query
I have result of two queries like:

Result of query 1

```<code>ID   Value
1    4
2    0
3    6
4    9
</code>```

Result of query 2

```<code>ID   Value
1    6
2    4
3    0
4    1
</code>```

I want to add values column "Value" and show final result:

Result of Both queries

```<code>ID   Value
1    10
2    4
3    6
4    10
</code>```

plz guide me...

答:
A not particularly nice but fairly easy to comprehend way would be:

```<code>SELECT ID,SUM(Value) FROM
(
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableA) t1
OUTER JOIN
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableB) t2
) a GROUP BY a.ID
</code>```

It has the benefits of

a) I don't know your actual table structure so you should be able to work out how to get the two 'SELECT's working from your original queries
b) If ID doesn't appear in either table, that's fine

Title: Add Column values in sql server query

Body:
I have result of two queries like:

Result of query 1

ID   Value
1    4
2    0
3    6
4    9

Result of query 2

ID   Value
1    6
2    4
3    0
4    1

I want to add values column "Value" and show final result:

Result of Both queries

ID   Value
1    10
2    4
3    6
4    10

plz guide me...

Body:
A not particularly nice but fairly easy to comprehend way would be:

SELECT ID,SUM(Value) FROM
(
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableA) t1
OUTER JOIN
(SELECT IDColumn AS ID,ValueColumn AS Value FROM TableB) t2
) a GROUP BY a.ID

It has the benefits of

a) I don't know your actual table structure so you should be able to work out how to get the two 'SELECT's working from your original queries
b) If ID doesn't appear in either table, that's fine


来源: stackexchange

问:
PHPExcel memory error
i convert excel files to HTML table with PHPExcel Reader function.

i'm getting this error : Fatal error: Out of memory (allocated 1827405824) (tried to allocate 106 bytes)

I've changed my memory_limit to 2048M in my php.ini file..

Still getting the error..

So How can i only load the first sheet of my Excel file, it can maybe solve my issue ?

```<code>$excel = glob(''.$test.'\\'.$client.'.{xlsx,xls,xlsm,xlsm.ink}',GLOB_BRACE);
$filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
$objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
$objReader->setReadFilter($filterSubset);

$objPHPExcel = $objReader->load($excel[0]);

## THIS DOESNT WORK ?! ##
$objPHPExcel->setActiveSheetIndex(1);

    $links = $objPHPExcel->getActiveSheet()->getHyperlinkCollection();
    var_dump($links);

    foreach ($links as $link){
        $url = $link->getUrl();
        $url = str_replace('file','mnt', $url);
        $link->setUrl($url);
    }

$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
$writer->generateStyles();
$writer->generateSheetData();
</code>```

EDIT :

I do it like that :

```<code>    public function showClientAction($client)
{
    $excel = glob(''.$path'.{xlsx,xls,xlsm,xlsm.ink}', GLOB_BRACE);
    $filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
    $objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
    $objReader->setReadFilter($filterSubset);

    $worksheetList = $objReader->listWorksheetNames($excel[0]);
    $sheetname = $worksheetList[0];

    /**  Advise the Reader of which WorkSheets we want to load  **/

    $objReader->setLoadSheetsOnly($sheetname);

    $objPHPExcel = $objReader->load($excel[0]);

    var_dump($sheetname);

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
    $writer->generateStyles();
    $writer->generateSheetData();

    return $this->render('MonextPerfclientBundle:Default:testexcel.html.twig', array(
        'excelHtml'=>$writer,
        'stylesExcel'=>$writer,
    ));
}
</code>```

the var_dump($sheetname); output is the good one, it Works great !

But how can i be sure to load only the first sheet ?

It dont seem to be a faster loading..  *scuze my english..

答:
So How can i only load the first sheet of my Excel file, it can maybe solve my issue ?

Straight from the PHPExcel Documentation

```<code>$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetname = 'Data Sheet #2';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);
</code>```

If you don't know the name of the first worksheet, then PHPExcel provides a helper method to get a list of the worksheet names without having to load the whole file.

ContentLicense: CC BY-SA 3.0

Title: PHPExcel memory error

Body:
i convert excel files to HTML table with PHPExcel Reader function.

i'm getting this error : Fatal error: Out of memory (allocated 1827405824) (tried to allocate 106 bytes)

I've changed my memory_limit to 2048M in my php.ini file..

Still getting the error..

So How can i only load the first sheet of my Excel file, it can maybe solve my issue ?

$excel = glob(''.$test.'\\'.$client.'.{xlsx,xls,xlsm,xlsm.ink}',GLOB_BRACE);
$filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
$objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
$objReader->setReadFilter($filterSubset);

$objPHPExcel = $objReader->load($excel[0]);

## THIS DOESNT WORK ?! ##
$objPHPExcel->setActiveSheetIndex(1);

    $links = $objPHPExcel->getActiveSheet()->getHyperlinkCollection();
    var_dump($links);

    foreach ($links as $link){
        $url = $link->getUrl();
        $url = str_replace('file','mnt', $url);
        $link->setUrl($url);
    }

$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
$writer->generateStyles();
$writer->generateSheetData();

EDIT :

I do it like that :

    public function showClientAction($client)
{
    $excel = glob(''.$path'.{xlsx,xls,xlsm,xlsm.ink}', GLOB_BRACE);
    $filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
    $objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
    $objReader->setReadFilter($filterSubset);

    $worksheetList = $objReader->listWorksheetNames($excel[0]);
    $sheetname = $worksheetList[0];

    /**  Advise the Reader of which WorkSheets we want to load  **/

    $objReader->setLoadSheetsOnly($sheetname);

    $objPHPExcel = $objReader->load($excel[0]);

    var_dump($sheetname);

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
    $writer->generateStyles();
    $writer->generateSheetData();

    return $this->render('MonextPerfclientBundle:Default:testexcel.html.twig', array(
        'excelHtml'=>$writer,
        'stylesExcel'=>$writer,
    ));
}

the var_dump($sheetname); output is the good one, it Works great !

But how can i be sure to load only the first sheet ?

It dont seem to be a faster loading..  *scuze my english..

Body:
So How can i only load the first sheet of my Excel file, it can maybe solve my issue ?

Straight from the PHPExcel Documentation

$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetname = 'Data Sheet #2';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

If you don't know the name of the first worksheet, then PHPExcel provides a helper method to get a list of the worksheet names without having to load the whole file.


问:
Bootstrap Tour n.popover is not a function
I try to make a bootstrap tour but when i check the javascript i get

n.popover is not a function from  bootstrap-tour.min.js

I try to fix it since 2 days it's a nightmare ...

Hope someone could help me .. thanks a lot in advance

Here my code :

```<code><a href="#" class="btn btn-block btn-primary" id="startTour">Start tour</a>

<div class="col-md-5" id="tour1" data-toggle="popover">
      <div class="form-group">
      <label>Nom </label>
       {!! Form::text('lb_nom', null, ['class' => 'form-control', 'placeholder' => 'Nom']) !!}
      </div>
</div>
<div class="col-md-5" id="tour2">
    <div class="form-group">
    <label>Prénom </label>
    {!! Form::text('lb_prenom', null, ['class' => 'form-control', 'placeholder' => 'Prénom']) !!}
    </div>
</div>
</code>```

Here my script :

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ns3005219.ip-151-80-34.eu/licences/public/css/bootstrap-tour.min.css" />
<script src="http://ns3005219.ip-151-80-34.eu/licences/public/js/bootstrap-tour.min.js"></script>

<script type="text/javascript">

    // Instance the tour
    var tour = new Tour({
        steps: [{
            element: "#tour1",
            title: "Exam Enrolment",
            content: "First let's enrol to an exam"
        }, {
            element: "#tour2",
            title: "Your Schedule",
            content: "Great, let's see your new schedule."
        }]
    }).init().start(true);

    $("#startTour").click(function(){
        tour.restart();

        console.log(tour);
    })
</script>
</code>```

答:
You have to use bootstrap tour standalone files if you are using bootstrap
  tour without bootstrap core files

I have made fiddle for you.

Check : https://jsfiddle.net/hgfcbhas/

Include

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/css/bootstrap-tour-standalone.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/js/bootstrap-tour-standalone.min.js"></script>
</code>```

Rest of your code is correct

Body:
I try to make a bootstrap tour but when i check the javascript i get

n.popover is not a function from  bootstrap-tour.min.js

I try to fix it since 2 days it's a nightmare ...

Hope someone could help me .. thanks a lot in advance

Here my code :

Start tour

      Nom
       {!! Form::text('lb_nom', null, ['class' => 'form-control', 'placeholder' => 'Nom']) !!}

    Prénom
    {!! Form::text('lb_prenom', null, ['class' => 'form-control', 'placeholder' => 'Prénom']) !!}

Here my script :

<link rel="stylesheet" href="http://ns3005219.ip-151-80-34.eu/licences/public/css/bootstrap-tour.min.css" />

Body:
You have to use bootstrap tour standalone files if you are using bootstrap
  tour without bootstrap core files

I have made fiddle for you.

Check : https://jsfiddle.net/hgfcbhas/

Include

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/css/bootstrap-tour-standalone.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tour/0.11.0/js/bootstrap-tour-standalone.min.js"></script>

Rest of your code is correct


问:
How do I calculate the derivative of an input-function?
I'm currently trying to write a program for error propagation.
For this reason I need the partial derivative.

```<code>Function = input("Function: ")

#Function should look something like this: u**2 + 3*x/(v+w)

print ("s = "f"{Function}")

#Derivate by u
k = float(Function.derivatives[u])
print("Partial Derivative by u = "f"{k}")
</code>```

When I try to run this, there's an error message: "str function has no attribute 'derivatives', but when I try to change the first line to:

Function = float(input("Function: "))

there's an error message as well, it says it can't be transformed to a floating point number.

I'm still quite a beginner, excuse me if my question is too banal.

答:
From the scipy docs:

```<code>>>> from scipy.misc import derivative
>>> def f(x):
...     return x**3 + x**2
...
>>> derivative(f, 1.0, dx=1e-6)
4.9999999999217337
</code>```

The first argument is the function, the second argument is the value of x0, and the 3rd is an optional param to specify spacing.

More here: https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.misc.derivative.html

Body:
I'm currently trying to write a program for error propagation.
For this reason I need the partial derivative.

Function = input("Function: ")

#Function should look something like this: u**2 + 3*x/(v+w)

print ("s = "f"{Function}")

#Derivate by u
k = float(Function.derivatives[u])
print("Partial Derivative by u = "f"{k}")

When I try to run this, there's an error message: "str function has no attribute 'derivatives', but when I try to change the first line to:

Function = float(input("Function: "))

there's an error message as well, it says it can't be transformed to a floating point number.

I'm still quite a beginner, excuse me if my question is too banal.

Body:
From the scipy docs:

>>> from scipy.misc import derivative
>>> def f(x):
...     return x**3 + x**2
...
>>> derivative(f, 1.0, dx=1e-6)
4.9999999999217337

The first argument is the function, the second argument is the value of x0, and the 3rd is an optional param to specify spacing.

More here: https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.misc.derivative.html


问:
Ordering and converting a numeric index array that begins with [0] in PHP
I have a numeric index array.

It can begin with any number, and then go on a hundred times.

I would rather have it ordered.

Example:

```<code>$myarray = array();

$myarray[500] = 2;
$myarray[501] = 3;
</code>```

Should be:

```<code>$myarray[0] = 2;
$myarray[1] = 3;
</code>```

I know I could do this with a foreach:

```<code>$i = 0;

foreach($myarray as $key => $value){
$myarray[$i] = $value;
$i++
}
</code>```

Is there any function for this in PHP?

答:
try with array_value

```<code>$myArray  = array_values($myArray);
</code>```

Array_value will reset the key numerically and returns all the values from the array.

Body:
I have a numeric index array.

It can begin with any number, and then go on a hundred times.

I would rather have it ordered.

Example:

$myarray = array();

$myarray[500] = 2;
$myarray[501] = 3;

Should be:

$myarray[0] = 2;
$myarray[1] = 3;

I know I could do this with a foreach:

$i = 0;

foreach($myarray as $key => $value){
$myarray[$i] = $value;
$i++
}

Is there any function for this in PHP?

Body:
try with array_value

$myArray  = array_values($myArray);

Array_value will reset the key numerically and returns all the values from the array.


问:
Difference between {$_GET['id']} and '".$_GET['id']."'?
Is the any difference between writing

```
{$_GET['id']}
```

and

'".$_GET['id']."'

in a sql statement? both works the same

答:
As far as I know there's no difference, but should you be doing that? You're allowing unsanitised input into your sql query which means if your website is internet facing you're leaving it wide open to sql injection attacks.

Here's a Q&A you should read before going any further:

How can I prevent SQL injection in PHP?

OwnerDisplayName: Bartek

LastEditorDisplayName: Ross

ContentLicense: CC BY-SA 2.5

Body:
Is the any difference between writing

{$_GET['id']}

and

'".$_GET['id']."'

in a sql statement? both works the same

OwnerDisplayName: Kev


问:
Mock a WP_REST_Request Object
I'm currently running some unit tests on a WordPress plug-in, using PHPUnit and WP_Mock (without connecting to WordPress database).
As the title states, I need to mock a WP_REST_Request Object, to give it as a parameter to a method under test.

Maybe I could do it by mocking the return of the URL used by the WP_REST_Request::from_url() method, or maybe with the use of getMockFromWsdl().
I'm open to every kind of ideas

答:
The WP_REST_Request class implements the ArrayAccess interface so you can create a mock in this way:

```<code>$request = $this->getMockBuilder( 'ArrayAccess' )
    ->setMockClassName( 'WP_REST_Request' )
    ->getMock();
</code>```

Title: Mock a WP_REST_Request Object

Body:
The WP_REST_Request class implements the ArrayAccess interface so you can create a mock in this way:

$request = $this->getMockBuilder( 'ArrayAccess' )
    ->setMockClassName( 'WP_REST_Request' )
    ->getMock();


问:
passing array of strings to value attribute of input jquery
I have this input tag with id="clientAdd" when user write on it and click enter the written can be added in div as a tag and all tags are saved as array of strings I want to pass this array to the value of the hidden input tag id="clientAddCode"

```<code><input type="text" id="clientAdd" value="" class="form-control required">
<input type="hidden" id="clientAddCode" name="address">
</code>```

I try to pass the array of strings as it to the value of the hidden input tag id="clientAddCode" but it always gives me empty value.

```<code>var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
     $(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
        stringList.push(this.value);
        this.value = "";
        $(document).on("click", ".removeAddress", function() {
            var removeItem = $(this).parent().clone().children().remove().end().text();
            stringList = $('.removeAddress').map(function(){
              return $(this).parent().clone().children().remove().end().text()
            }).get()
            $(this).parent().remove();
            $("#clientAddCode").val(stringList);
            console.log(stringList);
        });
     }
});
</code>```

答:
You should convert the array in a single string, you could do this using the join function:

The join() method joins the elements of an array into a string, and returns the string.

array.join(separator)

separator Optional. The separator to be used. If omitted, the elements are separated with a comma

See following please:

var arr = ["test1", "test2", "test3"];
var stringList = arr.join(", ");
console.log(stringList);
//Write in a div
$("#clientAddCode").html(stringList);
//Write in a text
$("#myList").val(stringList);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clientAddCode"></div>
<input id="myList" type="text" /></code>```

In the above example, I've concatenated all the items with a comma.
I hope it helps you, bye.

Body:
I have this input tag with id="clientAdd" when user write on it and click enter the written can be added in div as a tag and all tags are saved as array of strings I want to pass this array to the value of the hidden input tag id="clientAddCode"

<input type="text" id="clientAdd" value="" class="form-control required">
<input type="hidden" id="clientAddCode" name="address">

I try to pass the array of strings as it to the value of the hidden input tag id="clientAddCode" but it always gives me empty value.

var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
     $(".target").append("" +""+'+'+""+ this.value + "");
        stringList.push(this.value);
        this.value = "";
        $(document).on("click", ".removeAddress", function() {
            var removeItem = $(this).parent().clone().children().remove().end().text();
            stringList = $('.removeAddress').map(function(){
              return $(this).parent().clone().children().remove().end().text()
            }).get()
            $(this).parent().remove();
            $("#clientAddCode").val(stringList);
            console.log(stringList);
        });
     }
});

Body:
You should convert the array in a single string, you could do this using the join function:

The join() method joins the elements of an array into a string, and returns the string.

array.join(separator)

separator Optional. The separator to be used. If omitted, the elements are separated with a comma

See following please:

var arr = ["test1", "test2", "test3"];
var stringList = arr.join(", ");
console.log(stringList);
//Write in a div
$("#clientAddCode").html(stringList);
//Write in a text
$("#myList").val(stringList);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clientAddCode"></div>
<input id="myList" type="text" />

In the above example, I've concatenated all the items with a comma.
I hope it helps you, bye.


问:
Filter DataGrid using a ComboBox
I am trying to filter my data in a DataGrid using a ComboBox.

I have this in the xaml :

```<code>    <ComboBox x:Name="cmbFilter" SelectionChanged="cmbFilter_SelectionChanged" />
       <Grid>
             <DataGrid x:Name="dataList">
                   <DataGrid.Columns >
                       <DataGridTextColumn Header="School" Binding="{Binding SchoolName}"></DataGridTextColumn>
                       <DataGridTextColumn Header="Category" Binding="{Binding CategorySchool}"></DataGridTextColumn>
                   </DataGrid.Columns>
             </DataGrid>
       </Grid>
</code>```

And in the code behind :

```<code>//fill the list with the datas
this.dataList.ItemsSource = MainWindow._RE.ListDatas;

//fill the combobox with the school names
this.cmbFilter.ItemsSource = MainWindow._RE.ListNameSchool;

private void cmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ??????
}
</code>```

I manage to fill the DataGrid with all the datas et the ComboBox with all the school names.
What I want is to be able to filter the Datagrid depending on which School name is selected from the ComboBox with the column "School". That the data displayed are only those from the school selected in the ComboBox

Thank you

答:
You can use Where():

```<code>private void cmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    this.dataList.ItemsSource = MainWindow._RE.ListDatas.Where(i => i.SchoolName == (string)cmbFilter.SelectedItem);
}
</code>```

Title: Filter DataGrid using a ComboBox

Body:
I am trying to filter my data in a DataGrid using a ComboBox.

I have this in the xaml :

    <ComboBox x:Name="cmbFilter" SelectionChanged="cmbFilter_SelectionChanged" />
       <Grid>
             <DataGrid x:Name="dataList">
                   <DataGrid.Columns >
                       <DataGridTextColumn Header="School" Binding="{Binding SchoolName}"></DataGridTextColumn>
                       <DataGridTextColumn Header="Category" Binding="{Binding CategorySchool}"></DataGridTextColumn>
                   </DataGrid.Columns>
             </DataGrid>
       </Grid>

And in the code behind :

//fill the list with the datas
this.dataList.ItemsSource = MainWindow._RE.ListDatas;

//fill the combobox with the school names
this.cmbFilter.ItemsSource = MainWindow._RE.ListNameSchool;

private void cmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ??????
}

I manage to fill the DataGrid with all the datas et the ComboBox with all the school names.
What I want is to be able to filter the Datagrid depending on which School name is selected from the ComboBox with the column "School". That the data displayed are only those from the school selected in the ComboBox

Thank you

Body:
You can use Where():

private void cmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    this.dataList.ItemsSource = MainWindow._RE.ListDatas.Where(i => i.SchoolName == (string)cmbFilter.SelectedItem);
}


问:
how to convert the flex date object to MySQL date and time?
how to convert flex date objec to sql date and time,

i am using AMFPHP to connect with mysql

need help

cheers

答:
actually the date to string of flex will give you the format like

Day Mon Date HH:MM:SS TZD YYYY

but sql is like

2010-12-14 00:00:00

so what you do is make a string of the sql format and just pass as object to AMFPHP that will save it to sql

and sql will accept it as date time

```<code>private function dateToString(date:Date):String
        {
            var dateString:String = date.fullYear+"-"+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+":"+date.seconds;
            return dateString;
        }//end function
</code>```

cheers....

Body:
actually the date to string of flex will give you the format like

Day Mon Date HH:MM:SS TZD YYYY

but sql is like

2010-12-14 00:00:00

so what you do is make a string of the sql format and just pass as object to AMFPHP that will save it to sql

and sql will accept it as date time

private function dateToString(date:Date):String
        {
            var dateString:String = date.fullYear+"-"+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+":"+date.seconds;
            return dateString;
        }//end function

cheers....


问:
create calendar array by moment.js
I want to create array like this.

var date_ = [
{ "DateText": "Mon - 2nd April", "Date": "2/4/2017", "WeekNumber" : 13 },
{ "DateText": "Tue - 3rd April", "Date": "3/4/2017", "WeekNumber": 14 },
{ "DateText": "Wed - 4th April", "Date": "4/4/2017", "WeekNumber": 14 }
];
```

<p>I got everything just this 2nd, 3rd and 4th number convention is remaining, can you check my piece of code.</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-js lang-js prettyprint-override"><code>var date_ = [];

var prevDate = moment().subtract(15, 'days');
var nextDate = moment().add(15, 'days');

var start = new Date(prevDate);
var end = new Date(nextDate);

while(start < end){
   date_.push(
      {
        "DateText" : moment(start).format('ddd - DD MMM'),
        "Date" : moment(start).format('DD/MM/YYYY'),
        "WeekNumber" : moment(start).week()
      }
    );
   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}

console.log(date_);</code>```

```

Thanks

答:
You need Do token see Display Format

```<code>moment(start).format('ddd - Do MMM')
</code>```

var date_ = [];

var prevDate = moment().subtract(15, 'days');
var nextDate = moment().add(15, 'days');

while (prevDate.isBefore(nextDate)) {
  date_.push({
    "DateText": prevDate.format('ddd - Do MMM'),
    "Date": prevDate.format('DD/MM/YYYY'),
    "WeekNumber": prevDate.week()
  });
  prevDate.add(1, 'days');
}

console.log(date_);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script></code>```

Title: create calendar array by moment.js

Body:
I want to create array like this.

var date_ = [
{ "DateText": "Mon - 2nd April", "Date": "2/4/2017", "WeekNumber" : 13 },
{ "DateText": "Tue - 3rd April", "Date": "3/4/2017", "WeekNumber": 14 },
{ "DateText": "Wed - 4th April", "Date": "4/4/2017", "WeekNumber": 14 }
];

I got everything just this 2nd, 3rd and 4th number convention is remaining, can you check my piece of code.

var date_ = [];

var prevDate = moment().subtract(15, 'days');
var nextDate = moment().add(15, 'days');

var start = new Date(prevDate);
var end = new Date(nextDate);

while(start < end){
   date_.push(
      {
        "DateText" : moment(start).format('ddd - DD MMM'),
        "Date" : moment(start).format('DD/MM/YYYY'),
        "WeekNumber" : moment(start).week()
      }
    );
   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}

console.log(date_);

Thanks

Body:
You need Do token see Display Format

moment(start).format('ddd - Do MMM')

var date_ = [];

var prevDate = moment().subtract(15, 'days');
var nextDate = moment().add(15, 'days');

while (prevDate.isBefore(nextDate)) {
  date_.push({
    "DateText": prevDate.format('ddd - Do MMM'),
    "Date": prevDate.format('DD/MM/YYYY'),
    "WeekNumber": prevDate.week()
  });
  prevDate.add(1, 'days');
}

console.log(date_);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>


问:
Parsing Xml response with key named "class" using retrofit
I am using retrofit with simpleXmlConverter every where in the app it's working fine except one place where in response I'm getting class as key like following

```<code><Car onRequest="0" id="10624043" group="Cars" class="PWAR" internalClass="LDAR" >Mercedes-Benz</Car>
</code>```

while conveting to POJO it gives Class not found exception:unable to find class "PWAR"  i.e. the value of the key. I have tried not using this class key value using restrict=false  and required=false and create converter factory non-strict non of them helped
here is my pojo

```<code>@Root(name = "Car",restrict=false
public class Car
{
@Attribute(name="id", required = false)
public String id;

@Text(required = false)
public String text;

@Attribute(name="group", required = false)
public String group;
}
</code>```

答:
```<code><Car onRequest="0" id="10624043" group="Cars" class="PWAR" internalClass="LDAR" >Mercedes-Benz</Car>
</code>```

save this api response in a string then replace the word class as it is a keyword then parse the response

Body:
I am using retrofit with simpleXmlConverter every where in the app it's working fine except one place where in response I'm getting class as key like following

<Car onRequest="0" id="10624043" group="Cars" class="PWAR" internalClass="LDAR" >Mercedes-Benz</Car>

while conveting to POJO it gives Class not found exception:unable to find class "PWAR"  i.e. the value of the key. I have tried not using this class key value using restrict=false  and required=false and create converter factory non-strict non of them helped
here is my pojo

@Root(name = "Car",restrict=false
public class Car
{
@Attribute(name="id", required = false)
public String id;

@Text(required = false)
public String text;

@Attribute(name="group", required = false)
public String group;
}

Body:
<Car onRequest="0" id="10624043" group="Cars" class="PWAR" internalClass="LDAR" >Mercedes-Benz</Car>

save this api response in a string then replace the word class as it is a keyword then parse the response


问:
Large image update in WPF is delayed for real time monitoring
I am getting Sequence of images from USB and with each image grabbed I convert grabbed result to System.Drawing.Bitmap and after that I convert it to System.Windows.Mesia.Imging.BitmapImage to be able to assign it to Imagesource and finally update UI in dispatcher thread, all this process takes time and it doesn't go live, the sample codes of the camera company (Basler) has used C# and directly assigns System.Drawing.Bitmap to picture box and can show live view without delay.
What is the best solution to handle it ? it worth mentioning that with 2048*2000 pixel size the frame rate is almost 50 fps

```<code>PixelDataConverter converter = new PixelDataConverter();
            Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
            BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            converter.OutputPixelFormat = PixelType.BGRA8packed;
            IntPtr ptrBmp = bmpData.Scan0;
            converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
            bitmap.UnlockBits(bmpData);

            BitmapImage bitmapimage = new BitmapImage();
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, ImageFormat.Bmp);
                memory.Position = 0;
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapimage.EndInit();
                bitmapimage.Freeze();
            }
            Dispatcher.Invoke(new Action(() =>
            {
                imgMain.Source = bitmapimage;
            }));
</code>```

And this is the sample code for c# by company :

```<code>Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
                    // Lock the bits of the bitmap.
                    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    // Place the pointer to the buffer of the bitmap.
                    converter.OutputPixelFormat = PixelType.BGRA8packed;
                    IntPtr ptrBmp = bmpData.Scan0;
                    converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
                    bitmap.UnlockBits(bmpData);

                    // Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
                    Bitmap bitmapOld = pictureBox.Image as Bitmap;
                    // Provide the display control with the new bitmap. This action automatically updates the display.
                    pictureBox.Image = bitmap;
                    if (bitmapOld != null)
                    {
                        // Dispose the bitmap.
                        bitmapOld.Dispose();
                    }
                }
enter code here
</code>```

答:
Use  Dispatcher.BeginInvoke instead of Dispatcher.Invoke(...to set the image asynchronous.

```<code>       Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
       {
             imgMain.Source = bitmapimage;
       }));
</code>```

Body:
I am getting Sequence of images from USB and with each image grabbed I convert grabbed result to System.Drawing.Bitmap and after that I convert it to System.Windows.Mesia.Imging.BitmapImage to be able to assign it to Imagesource and finally update UI in dispatcher thread, all this process takes time and it doesn't go live, the sample codes of the camera company (Basler) has used C# and directly assigns System.Drawing.Bitmap to picture box and can show live view without delay.
What is the best solution to handle it ? it worth mentioning that with 2048*2000 pixel size the frame rate is almost 50 fps

PixelDataConverter converter = new PixelDataConverter();
            Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
            BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            converter.OutputPixelFormat = PixelType.BGRA8packed;
            IntPtr ptrBmp = bmpData.Scan0;
            converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
            bitmap.UnlockBits(bmpData);

            BitmapImage bitmapimage = new BitmapImage();
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, ImageFormat.Bmp);
                memory.Position = 0;
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapimage.EndInit();
                bitmapimage.Freeze();
            }
            Dispatcher.Invoke(new Action(() =>
            {
                imgMain.Source = bitmapimage;
            }));

And this is the sample code for c# by company :

Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
                    // Lock the bits of the bitmap.
                    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    // Place the pointer to the buffer of the bitmap.
                    converter.OutputPixelFormat = PixelType.BGRA8packed;
                    IntPtr ptrBmp = bmpData.Scan0;
                    converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
                    bitmap.UnlockBits(bmpData);

                    // Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
                    Bitmap bitmapOld = pictureBox.Image as Bitmap;
                    // Provide the display control with the new bitmap. This action automatically updates the display.
                    pictureBox.Image = bitmap;
                    if (bitmapOld != null)
                    {
                        // Dispose the bitmap.
                        bitmapOld.Dispose();
                    }
                }
enter code here

Body:
Use  Dispatcher.BeginInvoke instead of Dispatcher.Invoke(...to set the image asynchronous.

       Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
       {
             imgMain.Source = bitmapimage;
       }));


问:
Forward period correlations R
I'm not sure if this qualifies as question, but I need help to make my coding more efficient. I think this can be done more efficiently, I'm just really lousy writing functions and maybe seeing answer will help me improve.

Example: I have timeseries data and would like to calculate indicators Y correlation to forward period changes of my X values (multiple X). (dput is in the end).

My solution:

```<code>str(data.dt)
Classes ‘data.table’ and 'data.frame':  210 obs. of  3 variables:
 $ id     : chr  "X1" "X1" "X1" "X1" ...
 $ date   : Date, format: "2016-11-18" "2016-11-25" "2016-12-02" "2016-12-09" ...
 $ PX_LAST: num  2.72 2.76 2.86 2.81 2.83 ...
 - attr(*, ".internal.selfref")=<externalptr>

#separate indicator value
y.dt <- data.dt[id=="Y"]

#add indicator as own column for each X
step1.dt <- y.dt[data.dt, on="date"]
#rename
correl.dt <-  step1.dt[, .(date=date, x_id=i.id, x_value=i.PX_LAST, y_id = id,  y_value=PX_LAST)]
#discard NAs and Y from x_id
correl.dt <- na.omit(correl.dt[x_id != "Y"])
#calculate change for each X
correl.dt[, x.chg := c(rep(NA, 1), diff(x_value, 1)), by=list(x_id)]
#create forward change by leading changes
correl.dt[, fwd.xchg := shift(x.chg, type='lead', 1), by = list(x_id)]

#create multiple Y changes to test correlations
correl.dt[, y.chg1 := c(rep(NA, 1), diff(y_value, 1)), by=list(x_id)]
correl.dt[, y.chg2 := c(rep(NA, 2), diff(y_value, 2)), by=list(x_id)]
correl.dt[, y.chg3 := c(rep(NA, 3), diff(y_value, 3)), by=list(x_id)]
correl.dt[, y.chg4 := c(rep(NA, 4), diff(y_value, 4)), by=list(x_id)]
correl.dt[, y.chg5 := c(rep(NA, 5), diff(y_value, 5)), by=list(x_id)]
correl.dt[, y.chg6 := c(rep(NA, 6), diff(y_value, 6)), by=list(x_id)]

#cbind results together
cbind(correl.dt[, cor(fwd.xchg, y.chg1, method='spearman', use='pairwise'), by=.(x_id)],
      correl.dt[, cor(fwd.xchg, y.chg2, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg3, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg4, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg5, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg6, method='spearman', use='pairwise'), by=.(x_id)][,2])
</code>```

Result, don't make sense as I have very small subset. Also I have chosen short periods of correlations to fit my subset. Help is appreciated, what is best method to test forward correlations. I'm in love with datatable, not very good at it yet, but improving. I have about 100-200 indicators to test.

Here is dput:

```<code>structure(list(id = c("X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2",
"X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2",
"X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y"), date = structure(c(17123L, 17130L, 17137L, 17144L, 17151L,
17158L, 17165L, 17172L, 17179L, 17186L, 17193L, 17200L, 17207L,
17214L, 17221L, 17228L, 17235L, 17242L, 17249L, 17256L, 17263L,
17270L, 17277L, 17284L, 17291L, 17298L, 17305L, 17312L, 17319L,
17326L, 17123L, 17130L, 17137L, 17144L, 17151L, 17158L, 17165L,
17172L, 17179L, 17186L, 17193L, 17200L, 17207L, 17214L, 17221L,
17228L, 17235L, 17242L, 17249L, 17256L, 17263L, 17270L, 17277L,
17284L, 17291L, 17298L, 17305L, 17312L, 17319L, 17326L, 17123L,
17130L, 17137L, 17144L, 17151L, 17158L, 17165L, 17172L, 17179L,
17186L, 17193L, 17200L, 17207L, 17214L, 17221L, 17228L, 17235L,
17242L, 17249L, 17256L, 17263L, 17270L, 17277L, 17284L, 17291L,
17298L, 17305L, 17312L, 17319L, 17326L, 17123L, 17130L, 17137L,
17144L, 17151L, 17158L, 17165L, 17172L, 17179L, 17186L, 17193L,
17200L, 17207L, 17214L, 17221L, 17228L, 17235L, 17242L, 17249L,
17256L, 17263L, 17270L, 17277L, 17284L, 17291L, 17298L, 17305L,
17312L, 17319L, 17326L, 17123L, 17130L, 17137L, 17144L, 17151L,
17158L, 17165L, 17172L, 17179L, 17186L, 17193L, 17200L, 17207L,
17214L, 17221L, 17228L, 17235L, 17242L, 17249L, 17256L, 17263L,
17270L, 17277L, 17284L, 17291L, 17298L, 17305L, 17312L, 17319L,
17326L, 17123L, 17130L, 17137L, 17144L, 17151L, 17158L, 17165L,
17172L, 17179L, 17186L, 17193L, 17200L, 17207L, 17214L, 17221L,
17228L, 17235L, 17242L, 17249L, 17256L, 17263L, 17270L, 17277L,
17284L, 17291L, 17298L, 17305L, 17312L, 17319L, 17326L, 17123L,
17130L, 17137L, 17144L, 17151L, 17158L, 17165L, 17172L, 17179L,
17186L, 17193L, 17200L, 17207L, 17214L, 17221L, 17228L, 17235L,
17242L, 17249L, 17256L, 17263L, 17270L, 17277L, 17284L, 17291L,
17298L, 17305L, 17312L, 17319L, 17326L), class = "Date"), PX_LAST = c(2.719,
2.761, 2.863, 2.815, 2.831, 2.872, 2.765, 2.681, 2.692, 2.783,
2.779, 2.795, 2.696, 2.803, 2.73, 2.807, 2.977, 2.861, 2.75,
2.701, 2.551, 2.474, 2.538, 2.575, 2.648, 2.635, 2.475, 2.41,
2.412, 2.373, 1.579, 1.56, 1.619, 1.73, 1.833, 1.796, 1.721,
1.731, 1.715, 1.751, 1.782, 1.766, 1.697, 1.711, 1.607, 1.702,
1.811, 1.761, 1.642, 1.625, 1.596, 1.494, 1.47, 1.547, 1.542,
1.571, 1.475, 1.445, 1.4, 1.413, 1.455, 1.417, 1.38, 1.453, 1.438,
1.345, 1.239, 1.383, 1.364, 1.431, 1.471, 1.352, 1.256, 1.211,
1.078, 1.185, 1.231, 1.244, 1.196, 1.139, 1.075, 1.043, 1.034,
1.085, 1.117, 1.086, 1.093, 1.012, 1.038, 1.02, 0.272, 0.24,
0.281, 0.365, 0.314, 0.221, 0.208, 0.298, 0.338, 0.421, 0.462,
0.412, 0.32, 0.302, 0.186, 0.356, 0.485, 0.435, 0.403, 0.328,
0.228, 0.187, 0.253, 0.317, 0.418, 0.391, 0.368, 0.331, 0.274,
0.268, 2.3548, 2.3572, 2.3831, 2.4675, 2.5916, 2.5373, 2.4443,
2.4193, 2.3964, 2.4668, 2.4843, 2.4648, 2.4073, 2.4147, 2.3117,
2.478, 2.5745, 2.5005, 2.4123, 2.3874, 2.3822, 2.2374, 2.248,
2.2802, 2.3487, 2.3257, 2.2346, 2.2465, 2.1591, 2.1538, 0.517,
0.534, 0.559, 0.611, 0.64, 0.615, 0.556, 0.628, 0.628, 0.699,
0.749, 0.71, 0.665, 0.678, 0.549, 0.694, 0.774, 0.75, 0.673,
0.605, 0.548, 0.516, 0.564, 0.587, 0.653, 0.572, 0.518, 0.514,
0.425, 0.43, 0.8906, 0.895, 0.8999, 0.9062, 0.89, 0.8864, 0.8802,
0.8839, 0.8964, 0.899, 0.9145, 0.9039, 0.9054, 0.9044, 0.8934,
0.8978, 0.9041, 0.9048, 0.8979, 0.9023, 0.892, 0.8842, 0.8942,
0.9107, 0.9121, 0.9163, 0.8944, 0.8965, 0.8995, 0.8965)), row.names = c(NA,
-210L), class = c("data.table", "data.frame"), .Names = c("id",
"date", "PX_LAST"), .internal.selfref = <pointer: 0x003c24a0>)
</code>```

答:
This is something I came up with. A bit faster because a smaller number of times to assign variables, but the performance gain is not that much. Probably the simplicity of the code is the biggest advantage

```<code>library(dplyr)
lapply(as.list(1:6),
     function(x) {correl.dt[, cor(fwd.xchg, y_value - shift(y_value, x),
                                  method='spearman', use='pairwise'), by=.(x_id)][, 2]}) %>%
do.call(cbind, .)
</code>```

Here is a benchmark:

```<code>my_code <- function(){
  lapply(as.list(1:6),
         function(x) {correl.dt[, cor(fwd.xchg, y_value - shift(y_value, x),
                                      method='spearman', use='pairwise'), by=.(x_id)][, 2]}) %>%
    do.call(cbind, .)

}

your_code <- function(){
  #create multiple Y changes to test correlations
  correl.dt[, y.chg1 := c(rep(NA, 1), diff(y_value, 1)), by=list(x_id)]
  correl.dt[, y.chg2 := c(rep(NA, 2), diff(y_value, 2)), by=list(x_id)]
  correl.dt[, y.chg3 := c(rep(NA, 3), diff(y_value, 3)), by=list(x_id)]
  correl.dt[, y.chg4 := c(rep(NA, 4), diff(y_value, 4)), by=list(x_id)]
  correl.dt[, y.chg5 := c(rep(NA, 5), diff(y_value, 5)), by=list(x_id)]
  correl.dt[, y.chg6 := c(rep(NA, 6), diff(y_value, 6)), by=list(x_id)]

  #cbind results together
  cbind(correl.dt[, cor(fwd.xchg, y.chg1, method='spearman', use='pairwise'), by=.(x_id)],
        correl.dt[, cor(fwd.xchg, y.chg2, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg3, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg4, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg5, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg6, method='spearman', use='pairwise'), by=.(x_id)][,2])
}

microbenchmark::microbenchmark(my_code(), your_code())
## Unit: milliseconds
##        expr       min        lq     mean    median        uq      max neval
##   my_code()  8.818589  9.160749  9.47846  9.293391  9.605331 13.12389   100
## your_code() 11.068776 11.436789 11.98425 11.600102 11.926878 16.94066   100
</code>```

Title: Forward period correlations R

Body:
I'm not sure if this qualifies as question, but I need help to make my coding more efficient. I think this can be done more efficiently, I'm just really lousy writing functions and maybe seeing answer will help me improve.

Example: I have timeseries data and would like to calculate indicators Y correlation to forward period changes of my X values (multiple X). (dput is in the end).

My solution:

str(data.dt)
Classes ‘data.table’ and 'data.frame':  210 obs. of  3 variables:
 $ id     : chr  "X1" "X1" "X1" "X1" ...
 $ date   : Date, format: "2016-11-18" "2016-11-25" "2016-12-02" "2016-12-09" ...
 $ PX_LAST: num  2.72 2.76 2.86 2.81 2.83 ...
 - attr(*, ".internal.selfref")=<externalptr>

#separate indicator value
y.dt <- data.dt[id=="Y"]

#add indicator as own column for each X
step1.dt <- y.dt[data.dt, on="date"]
#rename
correl.dt <-  step1.dt[, .(date=date, x_id=i.id, x_value=i.PX_LAST, y_id = id,  y_value=PX_LAST)]
#discard NAs and Y from x_id
correl.dt <- na.omit(correl.dt[x_id != "Y"])
#calculate change for each X
correl.dt[, x.chg := c(rep(NA, 1), diff(x_value, 1)), by=list(x_id)]
#create forward change by leading changes
correl.dt[, fwd.xchg := shift(x.chg, type='lead', 1), by = list(x_id)]

#create multiple Y changes to test correlations
correl.dt[, y.chg1 := c(rep(NA, 1), diff(y_value, 1)), by=list(x_id)]
correl.dt[, y.chg2 := c(rep(NA, 2), diff(y_value, 2)), by=list(x_id)]
correl.dt[, y.chg3 := c(rep(NA, 3), diff(y_value, 3)), by=list(x_id)]
correl.dt[, y.chg4 := c(rep(NA, 4), diff(y_value, 4)), by=list(x_id)]
correl.dt[, y.chg5 := c(rep(NA, 5), diff(y_value, 5)), by=list(x_id)]
correl.dt[, y.chg6 := c(rep(NA, 6), diff(y_value, 6)), by=list(x_id)]

#cbind results together
cbind(correl.dt[, cor(fwd.xchg, y.chg1, method='spearman', use='pairwise'), by=.(x_id)],
      correl.dt[, cor(fwd.xchg, y.chg2, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg3, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg4, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg5, method='spearman', use='pairwise'), by=.(x_id)][,2],
      correl.dt[, cor(fwd.xchg, y.chg6, method='spearman', use='pairwise'), by=.(x_id)][,2])

Result, don't make sense as I have very small subset. Also I have chosen short periods of correlations to fit my subset. Help is appreciated, what is best method to test forward correlations. I'm in love with datatable, not very good at it yet, but improving. I have about 100-200 indicators to test.

Here is dput:

structure(list(id = c("X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1", "X1",
"X1", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2",
"X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2",
"X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X2", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3", "X3",
"X3", "X3", "X3", "X3", "X3", "X3", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4", "X4",
"X4", "X4", "X4", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5", "X5",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6",
"X6", "X6", "X6", "X6", "X6", "X6", "X6", "X6", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y"), date = structure(c(17123L, 17130L, 17137L, 17144L, 17151L,
17158L, 17165L, 17172L, 17179L, 17186L, 17193L, 17200L, 17207L,
17214L, 17221L, 17228L, 17235L, 17242L, 17249L, 17256L, 17263L,
17270L, 17277L, 17284L, 17291L, 17298L, 17305L, 17312L, 17319L,
17326L, 17123L, 17130L, 17137L, 17144L, 17151L, 17158L, 17165L,
17172L, 17179L, 17186L, 17193L, 17200L, 17207L, 17214L, 17221L,
17228L, 17235L, 17242L, 17249L, 17256L, 17263L, 17270L, 17277L,
17284L, 17291L, 17298L, 17305L, 17312L, 17319L, 17326L, 17123L,
17130L, 17137L, 17144L, 17151L, 17158L, 17165L, 17172L, 17179L,
17186L, 17193L, 17200L, 17207L, 17214L, 17221L, 17228L, 17235L,
17242L, 17249L, 17256L, 17263L, 17270L, 17277L, 17284L, 17291L,
17298L, 17305L, 17312L, 17319L, 17326L, 17123L, 17130L, 17137L,
17144L, 17151L, 17158L, 17165L, 17172L, 17179L, 17186L, 17193L,
17200L, 17207L, 17214L, 17221L, 17228L, 17235L, 17242L, 17249L,
17256L, 17263L, 17270L, 17277L, 17284L, 17291L, 17298L, 17305L,
17312L, 17319L, 17326L, 17123L, 17130L, 17137L, 17144L, 17151L,
17158L, 17165L, 17172L, 17179L, 17186L, 17193L, 17200L, 17207L,
17214L, 17221L, 17228L, 17235L, 17242L, 17249L, 17256L, 17263L,
17270L, 17277L, 17284L, 17291L, 17298L, 17305L, 17312L, 17319L,
17326L, 17123L, 17130L, 17137L, 17144L, 17151L, 17158L, 17165L,
17172L, 17179L, 17186L, 17193L, 17200L, 17207L, 17214L, 17221L,
17228L, 17235L, 17242L, 17249L, 17256L, 17263L, 17270L, 17277L,
17284L, 17291L, 17298L, 17305L, 17312L, 17319L, 17326L, 17123L,
17130L, 17137L, 17144L, 17151L, 17158L, 17165L, 17172L, 17179L,
17186L, 17193L, 17200L, 17207L, 17214L, 17221L, 17228L, 17235L,
17242L, 17249L, 17256L, 17263L, 17270L, 17277L, 17284L, 17291L,
17298L, 17305L, 17312L, 17319L, 17326L), class = "Date"), PX_LAST = c(2.719,
2.761, 2.863, 2.815, 2.831, 2.872, 2.765, 2.681, 2.692, 2.783,
2.779, 2.795, 2.696, 2.803, 2.73, 2.807, 2.977, 2.861, 2.75,
2.701, 2.551, 2.474, 2.538, 2.575, 2.648, 2.635, 2.475, 2.41,
2.412, 2.373, 1.579, 1.56, 1.619, 1.73, 1.833, 1.796, 1.721,
1.731, 1.715, 1.751, 1.782, 1.766, 1.697, 1.711, 1.607, 1.702,
1.811, 1.761, 1.642, 1.625, 1.596, 1.494, 1.47, 1.547, 1.542,
1.571, 1.475, 1.445, 1.4, 1.413, 1.455, 1.417, 1.38, 1.453, 1.438,
1.345, 1.239, 1.383, 1.364, 1.431, 1.471, 1.352, 1.256, 1.211,
1.078, 1.185, 1.231, 1.244, 1.196, 1.139, 1.075, 1.043, 1.034,
1.085, 1.117, 1.086, 1.093, 1.012, 1.038, 1.02, 0.272, 0.24,
0.281, 0.365, 0.314, 0.221, 0.208, 0.298, 0.338, 0.421, 0.462,
0.412, 0.32, 0.302, 0.186, 0.356, 0.485, 0.435, 0.403, 0.328,
0.228, 0.187, 0.253, 0.317, 0.418, 0.391, 0.368, 0.331, 0.274,
0.268, 2.3548, 2.3572, 2.3831, 2.4675, 2.5916, 2.5373, 2.4443,
2.4193, 2.3964, 2.4668, 2.4843, 2.4648, 2.4073, 2.4147, 2.3117,
2.478, 2.5745, 2.5005, 2.4123, 2.3874, 2.3822, 2.2374, 2.248,
2.2802, 2.3487, 2.3257, 2.2346, 2.2465, 2.1591, 2.1538, 0.517,
0.534, 0.559, 0.611, 0.64, 0.615, 0.556, 0.628, 0.628, 0.699,
0.749, 0.71, 0.665, 0.678, 0.549, 0.694, 0.774, 0.75, 0.673,
0.605, 0.548, 0.516, 0.564, 0.587, 0.653, 0.572, 0.518, 0.514,
0.425, 0.43, 0.8906, 0.895, 0.8999, 0.9062, 0.89, 0.8864, 0.8802,
0.8839, 0.8964, 0.899, 0.9145, 0.9039, 0.9054, 0.9044, 0.8934,
0.8978, 0.9041, 0.9048, 0.8979, 0.9023, 0.892, 0.8842, 0.8942,
0.9107, 0.9121, 0.9163, 0.8944, 0.8965, 0.8995, 0.8965)), row.names = c(NA,
-210L), class = c("data.table", "data.frame"), .Names = c("id",
"date", "PX_LAST"), .internal.selfref = <pointer: 0x003c24a0>)

Body:
This is something I came up with. A bit faster because a smaller number of times to assign variables, but the performance gain is not that much. Probably the simplicity of the code is the biggest advantage

library(dplyr)
lapply(as.list(1:6),
     function(x) {correl.dt[, cor(fwd.xchg, y_value - shift(y_value, x),
                                  method='spearman', use='pairwise'), by=.(x_id)][, 2]}) %>%
do.call(cbind, .)

Here is a benchmark:

my_code <- function(){
  lapply(as.list(1:6),
         function(x) {correl.dt[, cor(fwd.xchg, y_value - shift(y_value, x),
                                      method='spearman', use='pairwise'), by=.(x_id)][, 2]}) %>%
    do.call(cbind, .)

}

your_code <- function(){
  #create multiple Y changes to test correlations
  correl.dt[, y.chg1 := c(rep(NA, 1), diff(y_value, 1)), by=list(x_id)]
  correl.dt[, y.chg2 := c(rep(NA, 2), diff(y_value, 2)), by=list(x_id)]
  correl.dt[, y.chg3 := c(rep(NA, 3), diff(y_value, 3)), by=list(x_id)]
  correl.dt[, y.chg4 := c(rep(NA, 4), diff(y_value, 4)), by=list(x_id)]
  correl.dt[, y.chg5 := c(rep(NA, 5), diff(y_value, 5)), by=list(x_id)]
  correl.dt[, y.chg6 := c(rep(NA, 6), diff(y_value, 6)), by=list(x_id)]

  #cbind results together
  cbind(correl.dt[, cor(fwd.xchg, y.chg1, method='spearman', use='pairwise'), by=.(x_id)],
        correl.dt[, cor(fwd.xchg, y.chg2, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg3, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg4, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg5, method='spearman', use='pairwise'), by=.(x_id)][,2],
        correl.dt[, cor(fwd.xchg, y.chg6, method='spearman', use='pairwise'), by=.(x_id)][,2])
}

microbenchmark::microbenchmark(my_code(), your_code())
## Unit: milliseconds
##        expr       min        lq     mean    median        uq      max neval
##   my_code()  8.818589  9.160749  9.47846  9.293391  9.605331 13.12389   100
## your_code() 11.068776 11.436789 11.98425 11.600102 11.926878 16.94066   100


问:
Segmentation error in c
I am trying to execute the code below but it give back a segmentation message.
I am trying to inizialize a list and after to inlude a first node(cabecera) and print the data, but it give back a segmentation error.
Please help me, dont know whats the problem.
Thank you in advance.</p>

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

typedef struct NODO{
    float data;
    struct nodo* next;
    struct nodo* before;
} nodo;

typedef struct CABECERA{
    float data;
    struct nodo* next;
} cabecera;

void init(cabecera *L){
    L=NULL;
}

void pushBack(cabecera *L, float e){
    cabecera *newnodo;
    newnodo= (cabecera*)malloc(sizeof(cabecera));
    newnodo->next= NULL;
    newnodo->data=e;
    L=newnodo;
}

int main(){
    cabecera *milista;
    init(milista);
    pushBack(milista, 0.5);
    printf("%f\n", milista->data);

    return 0;
}
</code>```

答:
Indent your code.

To find the problem, compile your program with -g and run it in valgrind, it will tell you exactly what and where the problem is.

Always write in english, it fits with the rest of C and makes it easier for others to understand and help you.

You're not using the node struct you made, but you're referencing it anyway.

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

typedef struct NODO{
    float data;
    struct nodo* next;
    struct nodo* before;
} nodo;

    typedef struct CABECERA{
    float data;
    struct nodo* next;
} cabecera;

void init(cabecera **L){
    *L=NULL;
}

void pushBack(cabecera **L, float e){ //You want to take a pointer to your pointer
    cabecera *newnodo;
    newnodo= (cabecera*)malloc(sizeof(cabecera));
    newnodo->next= NULL;
    newnodo->data=e;
    *L=newnodo; // Here you want to modify the VALUE of your pointer.
}

int main(){
    cabecera *milista;

    init(&milista); // For init (and pushBack) to modify the value of the pointer, pass a pointer to it.

    pushBack(&milista, 0.5);

    printf("%f\n", milista->data);

    return 0;
}
</code>```

Here's a toy implementation I did 2 years ago, which can iterate both ways, access element by index (using shortest-path) and convert to/from array. https://github.com/DusteDdk/list

Title: Segmentation error in c

Body:
I am trying to execute the code below but it give back a segmentation message.
I am trying to inizialize a list and after to inlude a first node(cabecera) and print the data, but it give back a segmentation error.
Please help me, dont know whats the problem.
Thank you in advance.

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

typedef struct NODO{
    float data;
    struct nodo* next;
    struct nodo* before;
} nodo;

typedef struct CABECERA{
    float data;
    struct nodo* next;
} cabecera;

void init(cabecera *L){
    L=NULL;
}

void pushBack(cabecera *L, float e){
    cabecera *newnodo;
    newnodo= (cabecera*)malloc(sizeof(cabecera));
    newnodo->next= NULL;
    newnodo->data=e;
    L=newnodo;
}

int main(){
    cabecera *milista;
    init(milista);
    pushBack(milista, 0.5);
    printf("%f\n", milista->data);

    return 0;
}

Body:
Indent your code.

To find the problem, compile your program with -g and run it in valgrind, it will tell you exactly what and where the problem is.

Always write in english, it fits with the rest of C and makes it easier for others to understand and help you.

You're not using the node struct you made, but you're referencing it anyway.

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

typedef struct NODO{
    float data;
    struct nodo* next;
    struct nodo* before;
} nodo;

    typedef struct CABECERA{
    float data;
    struct nodo* next;
} cabecera;

void init(cabecera **L){
    *L=NULL;
}

void pushBack(cabecera **L, float e){ //You want to take a pointer to your pointer
    cabecera *newnodo;
    newnodo= (cabecera*)malloc(sizeof(cabecera));
    newnodo->next= NULL;
    newnodo->data=e;
    *L=newnodo; // Here you want to modify the VALUE of your pointer.
}

int main(){
    cabecera *milista;

    init(&milista); // For init (and pushBack) to modify the value of the pointer, pass a pointer to it.

    pushBack(&milista, 0.5);

    printf("%f\n", milista->data);

    return 0;
}

Here's a toy implementation I did 2 years ago, which can iterate both ways, access element by index (using shortest-path) and convert to/from array. https://github.com/DusteDdk/list


问:
for in loop in IE11
console in IE 11

console in Chrome

If I change word 'item' in the loop to 'anotherItem' like this

```<code>var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'
};
for (anotherItem in obj){
    console.log(anotherItem);
}
</code>```

The cycle works fine

Why IE 11 does not process word 'item'

答:
item is defined as a native function in IE, and is probably read-only, and therefore is the reason you cannot change it's value.

Prior to Edge, Microsoft didn't like adhering to standards, and introduced all sorts of features that aren't in the standards. The item function is not present in Edge.

Also, you haven't declared anotherItem, try this:

Try this:

```<code>var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'
};

for (var anotherItem in obj){
    console.log(anotherItem);
}
</code>```

If you don't declare a variable with the var keywork, and you're not in strict-mode, it will be defined as a global variable (which is not what you want). Global variables are essentially properties on the global object, and in the context of a web browser, that'd be the window object.

Add the following to the top of your JS file to enable strict mode, and then you won't be able to make these mistakes in the first place as an exception will be thrown.

```<code>"use strict";
</code>```

You can also choose to enable strict mode for specific functions, like this:

```<code>(function() {
    "use strict";
    // code here is in strict mode
})()
</code>```

Title: for in loop in IE11

Body:
console in IE 11

console in Chrome

If I change word 'item' in the loop to 'anotherItem' like this

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'
};
for (anotherItem in obj){
    console.log(anotherItem);
}

The cycle works fine

Why IE 11 does not process word 'item'

Body:
item is defined as a native function in IE, and is probably read-only, and therefore is the reason you cannot change it's value.

Prior to Edge, Microsoft didn't like adhering to standards, and introduced all sorts of features that aren't in the standards. The item function is not present in Edge.

Also, you haven't declared anotherItem, try this:

Try this:

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'
};

for (var anotherItem in obj){
    console.log(anotherItem);
}

If you don't declare a variable with the var keywork, and you're not in strict-mode, it will be defined as a global variable (which is not what you want). Global variables are essentially properties on the global object, and in the context of a web browser, that'd be the window object.

Add the following to the top of your JS file to enable strict mode, and then you won't be able to make these mistakes in the first place as an exception will be thrown.

"use strict";

You can also choose to enable strict mode for specific functions, like this:

(function() {
    "use strict";
    // code here is in strict mode
})()

ContentLicense: CC BY-SA 4.0


问:
What is a "reference edge" in TensorBoard?
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

```<code>cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')
</code>```

or to

```<code>tf.add([4],[3], name='opA')
</code>```

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.

答:
This is a source of confusion, even to DeepMind developers and is being fixed in future releases so that:

All reference edges will be a distinct color (and dataflow edges the
same grey as before).

Arrows to all dataflow edges no matter where
they point (instead of only appearing in cases where data flowed
"downward").

Body:
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')

or to

tf.add([4],[3], name='opA')

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.


问:
w3wp process not found
I use Visual Studio 2010 to debug a asp.net MVC project in my local machine. The steps are:

Click Debug and try to attch process "w3wp.exe". However it is not in the list.

I am sure "Show processes in all sessions" is clicked.

答:
In my case, I needed to connect from one Visual Studio to the process which running from another VS studio window.

The problem was next: one VS was launched with Administrator permissions. For resolving that issue you should launch both VS with Admin perm.

Title: w3wp process not found


问:
Better null-management try-catch with Java 8
Given the following code:

```<code>StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}
</code>```

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.

答:
What your code does is:

invoke some methods

if it throws an exception, log (or whatever) the error and return null

otherwise return what it returns

The cleanest way to do this -- and this is not new -- is:

```<code>try {
    return someMethod(...);
} catch (SomeException e) {
    logOrWhatever(e);
    return null;
}
</code>```

Some people object to multiple returns -- but in a short block like this, it's the clearest way (and if your block isn't this short, do the extract-method refactoring until it is).

The alternative with just one return is longer and messier, and involves declaring a mutable variable in a wider scope than necessary:

```<code>Foo response = null;
try {
   response = someMethod(...);
} catch (SomeException e) {
   logOrWhatever(e);
}
return response;
</code>```

It has more clutter. Think about how much reading you have to do to answer the question "What does this method return if someMethod() throws an exception?". In the first example it's right there in the catch block. In the second you have to follow the code up through all possible state changes to response.

response can't be declared final -- I don't think you should use final everywhere, but I do think it's good to have as many variables as possibly that could be declared final.

The scope of response is outside the try block. The tidier method keeps that data in a narrower scope, which is always good.

By putting the return in a finally block, your code does something else -- if any other type of exception is thrown, null will be returned without any logging or other exception-handling. This is unlikely to be a good idea -- it just makes bugs hard to diagnose: Try-catch-finally-return clarification

However, more generally, returning null is something you should try to avoid. Your question title mentions "null-management", but it's you that has introduced a null to proceedings. If you didn't choose to return null, you wouldn't have to deal with its problems:

If null means "something went wrong", don't do that. Handle the exception higher up (if you like, re-throw it as a different exception type)

If the semantics of the method are "This might return a response, or there may not be a response", consider:

Making the method return Optional<Response> -- now the method signature is honest

Using the "Null object" pattern. That is, instead of returning null return new EmptyResponse()

This way more of your code can be much simpler and cleaner, because it doesn't have to be full of if(x==null) guards.

Body:
Given the following code:

StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.

Body:
What your code does is:

invoke some methods

if it throws an exception, log (or whatever) the error and return null

otherwise return what it returns

The cleanest way to do this -- and this is not new -- is:

try {
    return someMethod(...);
} catch (SomeException e) {
    logOrWhatever(e);
    return null;
}

Some people object to multiple returns -- but in a short block like this, it's the clearest way (and if your block isn't this short, do the extract-method refactoring until it is).

The alternative with just one return is longer and messier, and involves declaring a mutable variable in a wider scope than necessary:

Foo response = null;
try {
   response = someMethod(...);
} catch (SomeException e) {
   logOrWhatever(e);
}
return response;

It has more clutter. Think about how much reading you have to do to answer the question "What does this method return if someMethod() throws an exception?". In the first example it's right there in the catch block. In the second you have to follow the code up through all possible state changes to response.

response can't be declared final -- I don't think you should use final everywhere, but I do think it's good to have as many variables as possibly that could be declared final.

The scope of response is outside the try block. The tidier method keeps that data in a narrower scope, which is always good.

By putting the return in a finally block, your code does something else -- if any other type of exception is thrown, null will be returned without any logging or other exception-handling. This is unlikely to be a good idea -- it just makes bugs hard to diagnose: Try-catch-finally-return clarification

However, more generally, returning null is something you should try to avoid. Your question title mentions "null-management", but it's you that has introduced a null to proceedings. If you didn't choose to return null, you wouldn't have to deal with its problems:

If null means "something went wrong", don't do that. Handle the exception higher up (if you like, re-throw it as a different exception type)

If the semantics of the method are "This might return a response, or there may not be a response", consider:

Making the method return Optional<Response> -- now the method signature is honest

Using the "Null object" pattern. That is, instead of returning null return new EmptyResponse()

This way more of your code can be much simpler and cleaner, because it doesn't have to be full of if(x==null) guards.


问:
Reading text from file into string dynamically and remove odd character in c
When I'm reading the string I want to replace every char which is not a-z or A-Z or 0-9 by ' ' but I also not to put two spaces in a row.

I created the following code to read a text from file and clean it a bit like I described:

```<code>char *getText (FILE *file) {
    bool lastWasLegal = true;
    char *text, *q;
    int textLength = 0;
    char token;
    int i = 0;
    text = malloc(sizeof(char));
    while ((token = getc(file)) != EOF) {
        if (isLegalChar(token))
        {
            lastWasLegal = true;
            text[i] = token;
            i++;
            q = realloc(text, (strlen(text) + 2) * sizeof(char));
            if (!q) {
                printf("Out of memory\n");
                exit(1);
            }
            text = q;
        }
        else {
            if (lastWasLegal)
            {
                text[i] = ' ';
                i++;
                q = realloc(text, (strlen(text) + 2) * sizeof(char));
                if (!q) {
                    printf("Out of memory\n");
                    exit(1);
                }
                text = q;
                lastWasLegal = false;
            }
        }
    }
    return text;
}
</code>```

The isLegalChar function is:

```<code>bool isLegalChar (char a) {
    if (a <= 90 && a >= 65) {
        return true;
    }
    else if (a <= 122 && a >= 97) {
        return true;
    }
    else if (isdigit(a)) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

Now it's got a problem I can't find - when my file is:

hello, world

  bye

The output is:

hello world bye?

but the expected output is:

hello world bye

(which means without the question mark).

But if the file is just:

hello world

The output is ok:

hello world

To be specific I'm trying to replace all the characters which are not digits or numbers and replace them with ' ' but without having double spaces.

I think it's a memory problem but I still can't find it.

答: From the look of it you're not appending a '\0' when you are finished composing the string, so that whatever is using the return value of getText doesn't know where the string ends and may (or may not) print garbage at the end of the string.</p>

Body:
When I'm reading the string I want to replace every char which is not a-z or A-Z or 0-9 by ' ' but I also not to put two spaces in a row.

I created the following code to read a text from file and clean it a bit like I described:

char *getText (FILE *file) {
    bool lastWasLegal = true;
    char *text, *q;
    int textLength = 0;
    char token;
    int i = 0;
    text = malloc(sizeof(char));
    while ((token = getc(file)) != EOF) {
        if (isLegalChar(token))
        {
            lastWasLegal = true;
            text[i] = token;
            i++;
            q = realloc(text, (strlen(text) + 2) * sizeof(char));
            if (!q) {
                printf("Out of memory\n");
                exit(1);
            }
            text = q;
        }
        else {
            if (lastWasLegal)
            {
                text[i] = ' ';
                i++;
                q = realloc(text, (strlen(text) + 2) * sizeof(char));
                if (!q) {
                    printf("Out of memory\n");
                    exit(1);
                }
                text = q;
                lastWasLegal = false;
            }
        }
    }
    return text;
}

The isLegalChar function is:

bool isLegalChar (char a) {
    if (a <= 90 && a >= 65) {
        return true;
    }
    else if (a <= 122 && a >= 97) {
        return true;
    }
    else if (isdigit(a)) {
        return true;
    }
    else {
        return false;
    }
}

Now it's got a problem I can't find - when my file is:

hello, world

  bye

The output is:

hello world bye?

but the expected output is:

hello world bye

(which means without the question mark).

But if the file is just:

hello world

The output is ok:

hello world

To be specific I'm trying to replace all the characters which are not digits or numbers and replace them with ' ' but without having double spaces.

I think it's a memory problem but I still can't find it.


问:
golang separation of concerns vs usability
I have always struggled keeping go modules neatly separated and avoiding cyclic dependencies.

Right now I have code like this:

```<code>    package chain

type Block struct{
    Content []byte
    Number int
}

var Chain []Block = make([]Block, 10)

func AddBlockToChain(block Block){
    // do some checks
    //...
    // add to chain
    Chain[block.Number] = block
}

func GetBlock(number int) Block {
    // do some checks
    //  ...
    // get from chain
    return Chain[number]
}
</code>```

To achieve consensus I need some extra info on the block. The info may be different depending on which consensus algorithm I use. I want the consensus algorithm to be interchangeable (e.g. by flag on start up).

It would be convenient to store the info as fields in the block, so that when I call GetBlock(3) or get a block from anywhere else I can not only access the block but also the info on what state of consensus this block is in at the moment.

On the other hand I wanted to keep data that is only relevant for a certain consensus algorithm separate from basic block data - maybe even in a separate package.

How should I design my program? Where should I keep data relevant for a certain consensus algorithm?

Some background info:

I am trying to build a block chain application from scratch. I have a "chain" module responsible for storing blocks of data and a "consensus" module responsible for creating consensus between multiple peers running an instance of my program on what that data is.

答:
For completeness I want to add a solution that keeps the code and data of the consensus algorithm in a different package than the block and chain code:

Add an extra field to the block like this:

```<code>Extra []byte
</code>```

Then keep the extra data needed for a consensus algorithm in that algorithms package in a struct and encode it to json or some other format to store it in the extra field.

This solution keeps separate concerns separate. The chain would not make sense without a consensus algorithm, but they can look very different and might need different data. This way different algorithms can store different data.

I did not go with this solution however, because it just seemed simpler to keep all the code in one package as @syntagma suggested.

Body:
I have always struggled keeping go modules neatly separated and avoiding cyclic dependencies.

Right now I have code like this:

    package chain

type Block struct{
    Content []byte
    Number int
}

var Chain []Block = make([]Block, 10)

func AddBlockToChain(block Block){
    // do some checks
    //...
    // add to chain
    Chain[block.Number] = block
}

func GetBlock(number int) Block {
    // do some checks
    //  ...
    // get from chain
    return Chain[number]
}

To achieve consensus I need some extra info on the block. The info may be different depending on which consensus algorithm I use. I want the consensus algorithm to be interchangeable (e.g. by flag on start up).

It would be convenient to store the info as fields in the block, so that when I call GetBlock(3) or get a block from anywhere else I can not only access the block but also the info on what state of consensus this block is in at the moment.

On the other hand I wanted to keep data that is only relevant for a certain consensus algorithm separate from basic block data - maybe even in a separate package.

How should I design my program? Where should I keep data relevant for a certain consensus algorithm?

Some background info:

I am trying to build a block chain application from scratch. I have a "chain" module responsible for storing blocks of data and a "consensus" module responsible for creating consensus between multiple peers running an instance of my program on what that data is.

Body:
For completeness I want to add a solution that keeps the code and data of the consensus algorithm in a different package than the block and chain code:

Add an extra field to the block like this:

Extra []byte

Then keep the extra data needed for a consensus algorithm in that algorithms package in a struct and encode it to json or some other format to store it in the extra field.

This solution keeps separate concerns separate. The chain would not make sense without a consensus algorithm, but they can look very different and might need different data. This way different algorithms can store different data.

I did not go with this solution however, because it just seemed simpler to keep all the code in one package as @syntagma suggested.


问:
Can we pass two annotation(IRetryAnalyzer and priority) type as one in TestNG
I have a situation where want to use IRetryAnalyzer and priority at a single time for testcase as an example. I want to use/apply below two parameter to a single testcase

```<code>@Test(retryAnalyzer = test1.Retry.class)
@Test(priority=0)
</code>```

Example :-

```<code>@Test(retryAnalyzer = test1.Retry.class)
@Test(priority=0)
public void Test1()
{
    System.out.println("Retry attempt");
    i++;
    System.out.println("value of i ="+i);
    if(i<2)
    {
        System.out.println("I m in fail Fail");
        Assert.assertEquals(false, true);
    }
    if(i>=2) {
        System.out.println("I m in fail pass");
        Assert.assertEquals(false, false);
    }
}
</code>```

Is there any way where I can apply both to a single testcase.

答:
Combine both values into one Test annotation.

```<code>@Test(retryAnalyzer = test1.Retry.class, priority=0)
public void Test1()
</code>```

Body:
I have a situation where want to use IRetryAnalyzer and priority at a single time for testcase as an example. I want to use/apply below two parameter to a single testcase

@Test(retryAnalyzer = test1.Retry.class)
@Test(priority=0)

Example :-

@Test(retryAnalyzer = test1.Retry.class)
@Test(priority=0)
public void Test1()
{
    System.out.println("Retry attempt");
    i++;
    System.out.println("value of i ="+i);
    if(i<2)
    {
        System.out.println("I m in fail Fail");
        Assert.assertEquals(false, true);
    }
    if(i>=2) {
        System.out.println("I m in fail pass");
        Assert.assertEquals(false, false);
    }
}

Is there any way where I can apply both to a single testcase.

Body:
Combine both values into one Test annotation.

@Test(retryAnalyzer = test1.Retry.class, priority=0)
public void Test1()


问:
Persisting and accessing values globally in multiple components in Angular 2
I have a settings page where users can save some config variables, such as a Username. The user can also change the username on that page. But when I go to another Component (page) and back, the username isn't saved.

I also want to show the username in the other components. How do I do that? With a global variable?

Structure:
- App
    - app.ts (main)
    - setting.ts
    - someOtherComponent.ts

答:
This might be an overkill in your current situation, but if you are going to grow your application into a larger one, this might save you a lot of troubles down the line. That said, I believe Angular with Redux-like store is a really powerful combination. My suggestion is to use ngrx/store module.

RxJS powered state management for Angular applications, inspired by Redux

Source: ngrx/store GitHub repo

The code below should outline all steps you need to follow to integrate the ngrx/store into your application. For the sake of brevity, I have omitted any existing code you might have and all imports which you will need to add.

Install the Module

```<code>npm install --save ngrx/core ngrx/store
</code>```

Create a Reducer

export const SETTINGS_UPDATE = 'SETTINGS_UPDATE';

const initialState = {
    username: ''
};

export function settingsReducer(state: Object = initialState, action: Action) {
    switch (action.type) {
        case SETTINGS_UPDATE:
            return Object.assign({}, state, action.payload);
        default:
            return state;
    }
};
```

<p><strong>Import the StoreModule</strong></p>

<pre class="lang-ts prettyprint-override"><code>@NgModule({
    imports: [
        // your other imports
        StoreModule.provideStore({
            settings: settingsReducer
        })
    ]
})
export class AppModule {
    //
}
</code>```

Create Interface for Settings Reducer

export interface SettingsStore {
    username: string;
}
```

<p><strong>Create a Store Interface</strong></p>

<pre class="lang-ts prettyprint-override"><code>export interface AppStore {
    settings: SettingsStore;
}
</code>```

Create Settings Service

@Injectable()
export class SettingsService {

    settings$: Observable<SettingsStore>;

    constructor(private store: Store<AppStore>) {
        this.settings$ = this.store.select('settings');
    }

    public update(payload) {
        this.store.dispatch({ type: SETTINGS_UPDATE, payload });
    }

}
```

<p><strong>Settings Component Controller</strong></p>

<pre class="lang-ts prettyprint-override"><code>@Component({
    ...
})
export class SettingsComponent implements OnInit {

    settings$: Observable<SettingsStore>;

    constructor(private settingsService: SettingsService) {
        //
    }

    ngOnInit() {
        this.settings$ = this.settingsService.settings$;
    }

    public updateUsername() {
        this.settingsService.update({ username: 'newUsername' });
    }

}
</code>```

Settings Component Template

    Username:
    {{ (settings$ | async)?.username }}

<button (click)="updateUsername()">Update Username</button>
```

With the setup outlined above you can then inject the SettingsService into any component and display the value in its template.

The same way you can also update the value of the store from any component by using this.settingsService.update({ ... }); and the change will be reflected on all places which are using that value - be it a component via an async pipe or another service via .subscribe().

Body:
This might be an overkill in your current situation, but if you are going to grow your application into a larger one, this might save you a lot of troubles down the line. That said, I believe Angular with Redux-like store is a really powerful combination. My suggestion is to use ngrx/store module.

RxJS powered state management for Angular applications, inspired by Redux

Source: ngrx/store GitHub repo

The code below should outline all steps you need to follow to integrate the ngrx/store into your application. For the sake of brevity, I have omitted any existing code you might have and all imports which you will need to add.

Install the Module

npm install --save ngrx/core ngrx/store

Create a Reducer

export const SETTINGS_UPDATE = 'SETTINGS_UPDATE';

const initialState = {
    username: ''
};

export function settingsReducer(state: Object = initialState, action: Action) {
    switch (action.type) {
        case SETTINGS_UPDATE:
            return Object.assign({}, state, action.payload);
        default:
            return state;
    }
};

Import the StoreModule

@NgModule({
    imports: [
        // your other imports
        StoreModule.provideStore({
            settings: settingsReducer
        })
    ]
})
export class AppModule {
    //
}

Create Interface for Settings Reducer

export interface SettingsStore {
    username: string;
}

Create a Store Interface

export interface AppStore {
    settings: SettingsStore;
}

Create Settings Service

@Injectable()
export class SettingsService {

    settings$: Observable<SettingsStore>;

    constructor(private store: Store<AppStore>) {
        this.settings$ = this.store.select('settings');
    }

    public update(payload) {
        this.store.dispatch({ type: SETTINGS_UPDATE, payload });
    }

}

Settings Component Controller

@Component({
    ...
})
export class SettingsComponent implements OnInit {

    settings$: Observable<SettingsStore>;

    constructor(private settingsService: SettingsService) {
        //
    }

    ngOnInit() {
        this.settings$ = this.settingsService.settings$;
    }

    public updateUsername() {
        this.settingsService.update({ username: 'newUsername' });
    }

}

Settings Component Template

<p *ngIf="(settings$ | async)?.username">
    <strong>Username:</strong>
    <span>{{ (settings$ | async)?.username }}</span>
</p>

<button (click)="updateUsername()">Update Username</button>

With the setup outlined above you can then inject the SettingsService into any component and display the value in its template.

The same way you can also update the value of the store from any component by using this.settingsService.update({ ... }); and the change will be reflected on all places which are using that value - be it a component via an async pipe or another service via .subscribe().


问:
Kotlin : Interface Queue does not have constructors
I'm trying to instantiate an object of Queue using below code

var queue: Queue<Int> = Queue()

But I get this

Interface Queue does not have constructors

No idea what's going on, while searching I found this link.

But I don't understand anything.
Please help.

答:
You trying to create instance of interface but don`t override methods for it. You should use something like this: </p>

```<code>val queueA = LinkedList<Int>()
val queueB = PriorityQueue<Int>()
</code>```

<p>Also you can read more about queue implementations here </p>

Body:
You trying to create instance of interface but don`t override methods for it. You should use something like this:

val queueA = LinkedList<Int>()
val queueB = PriorityQueue<Int>()

Also you can read more about queue implementations here


问:
Electron <webview> back using backspace
I'm writing an electron app. I used webview to show a website inside my app. I want the website inside the webview to go back when I press the backspace key. The Official documentary on webview was not helpful for me. How do I make the webview content go back when the backspace is pressed,please?</p>

答:
If you want to have it not go back when you type backspace in a <textarea> or a <input>, than try this:

```<code>const webview = document.querySelector('webview')
webview.addEventListener('keydown', (e)=>{
        if(e.keyCode === 8 && e.target.nodeName.toLowerCase() !== 'textarea' && e.target.nodeName.toLowerCase() !== 'input' && e.target.contentEditable !== 'true') webview.goBack();
});
</code>```

(If this worked for you, remember you can mark it as accepted by clicking the green check mark.)

Title: Electron <webview> back using backspace

Body:
If you want to have it not go back when you type backspace in a <textarea> or a <input>, than try this:

const webview = document.querySelector('webview')
webview.addEventListener('keydown', (e)=>{
        if(e.keyCode === 8 && e.target.nodeName.toLowerCase() !== 'textarea' && e.target.nodeName.toLowerCase() !== 'input' && e.target.contentEditable !== 'true') webview.goBack();
});

(If this worked for you, remember you can mark it as accepted by clicking the green check mark.)


问:
Download and install apk (without publishing in playstore) from the Instant App
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);
</code>```

答:
If you want to download and install .apk file then you don't need to host .apk file on Dropbox instead you can publish it on playstore and from instant app you can redirect your users to playstore to download the app by following this

First add this dependency in your feature module

```<code>api "com.google.android.instantapps:instantapps:1.0.0"
</code>```

Then match you project level build.gradle with this`

```<code>buildscript {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
  }...
}

allprojects {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
 }
}
</code>```

Finally on click of install button in instant app you can call this

```<code>InstantApps.showInstallPrompt(MainActivity.this,0,"Install app")
</code>```

So on this will open your app on playstore that you have published before.

NOTE: You must have app published on playstore before you develop your instant version of app

Body:
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);

Body:
If you want to download and install .apk file then you don't need to host .apk file on Dropbox instead you can publish it on playstore and from instant app you can redirect your users to playstore to download the app by following this

First add this dependency in your feature module

api "com.google.android.instantapps:instantapps:1.0.0"

Then match you project level build.gradle with this`

buildscript {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
  }...
}

allprojects {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
 }
}

Finally on click of install button in instant app you can call this

InstantApps.showInstallPrompt(MainActivity.this,0,"Install app")

So on this will open your app on playstore that you have published before.

NOTE: You must have app published on playstore before you develop your instant version of app


问:
rJava - method with signature not found
My problem is similar to this one :
Even with adding the semicolon didn't work for me this is my method when i call .jmethod to display it for me :

[10] "public java.util.Set utils.Rinterface.getPhones()"

when I call the method, Like this

rJava::.jcall(rinterface,"Ljava.util.Set;","getPhones")

I got this error :

rJava::.jcall(rinterface, "Ljava.util.Set;", "getPhones") :    method
  getPhones with signature ()Ljava.util.Set; not found it gives that
  error, still don't know whats wrong ?!

答:
You can try with this sample tree structure:

```<code>.
└── utils
    └── Rinterface.java
</code>```

and with super simple class

```<code>package utils;

import java.util.Set;

public class Rinterface {
    public java.util.Set getPhones() {
        return new java.util.HashSet();
    }
}
</code>```

make sure to compile it with the same Java version you are using with rJava.

Set up Java env

```<code>library(rJava)
.jinit()
# note that you have to point to place where utils directory is
.jaddClassPath(dir("place_where_your_package_is",full.names=TRUE))
obj <- .jnew("utils.Rinterface")
# call method
result=.jcall(obj, returnSig="Ljava/util/Set;", method="getPhones")
</code>```

you can always get the signature of method with

```<code>Compiled from "Rinterface.java"
public class utils.Rinterface {
  public utils.Rinterface();
    descriptor: ()V

  public java.util.Set getPhones();
    descriptor: ()Ljava/util/Set;
}
</code>```

In my case, it works as expected.

Update:

in your case, you use:

Ljava.util.Set;

replace it with

Ljava/util/Set;

Update:

Updated to reflect proper package layout

Title: rJava - method with signature not found

Body:
You can try with this sample tree structure:

.
└── utils
    └── Rinterface.java

and with super simple class

package utils;

import java.util.Set;

public class Rinterface {
    public java.util.Set getPhones() {
        return new java.util.HashSet();
    }
}

make sure to compile it with the same Java version you are using with rJava.

Set up Java env

library(rJava)
.jinit()
# note that you have to point to place where utils directory is
.jaddClassPath(dir("place_where_your_package_is",full.names=TRUE))
obj <- .jnew("utils.Rinterface")
# call method
result=.jcall(obj, returnSig="Ljava/util/Set;", method="getPhones")

you can always get the signature of method with

Compiled from "Rinterface.java"
public class utils.Rinterface {
  public utils.Rinterface();
    descriptor: ()V

  public java.util.Set getPhones();
    descriptor: ()Ljava/util/Set;
}

In my case, it works as expected.

Update:

in your case, you use:

Ljava.util.Set;

replace it with

Ljava/util/Set;

Update:

Updated to reflect proper package layout