问:
Get the RGB-hexadecimal values from an array and give it to an malloc-array as int
I need a method, how I can get a hexadecimal number from an array, then give it to a variable with the type int. I know that sounds easy but I need it in a "special way" - for example:

I have given a RGB hex color: 01a7ff - and I saved the value of R, G and B in extra arrays - looking like this:

```<code>char red[3];
red[0] = '0';
red[1] = '1';
red[2] = '\0';

char green[3];
green[0] = 'a';
green[1] = '7';
green[2] = '\0';

char blue[3];
blue[0] = 'f';
blue[1] = 'f';
blue[2] = '\0';
</code>```

Now I want to give the complete array of red, green and blue to a malloc reserved array so it looks like this:

```<code>char *data;
data = malloc(sizeof(char)*6);

data[0] = 01; //red array
data[1] = a7; //green array
data[2] = ff; //blue array
</code>```

I first tried using atoi() but that didn't work if the array had also de hexadecimal literals (a,b,c,d,e,f) - has anyone a solution for me?

Cheers

答:
Providing that data holds unsigned char values this should do:

```<code>data[0] = (unsigned char) strtol(red, NULL, 16);
data[1] = (unsigned char) strtol(green, NULL, 16);
data[2] = (unsigned char) strtol(blue, NULL, 16);
</code>```

Note: It is enough to use unsigned char to hold data value from 0 to 255

Body:
I need a method, how I can get a hexadecimal number from an array, then give it to a variable with the type int. I know that sounds easy but I need it in a "special way" - for example:

I have given a RGB hex color: 01a7ff - and I saved the value of R, G and B in extra arrays - looking like this:

char red[3];
red[0] = '0';
red[1] = '1';
red[2] = '\0';

char green[3];
green[0] = 'a';
green[1] = '7';
green[2] = '\0';

char blue[3];
blue[0] = 'f';
blue[1] = 'f';
blue[2] = '\0';

Now I want to give the complete array of red, green and blue to a malloc reserved array so it looks like this:

char *data;
data = malloc(sizeof(char)*6);

data[0] = 01; //red array
data[1] = a7; //green array
data[2] = ff; //blue array

I first tried using atoi() but that didn't work if the array had also de hexadecimal literals (a,b,c,d,e,f) - has anyone a solution for me?

Cheers

Body:
Providing that data holds unsigned char values this should do:

data[0] = (unsigned char) strtol(red, NULL, 16);
data[1] = (unsigned char) strtol(green, NULL, 16);
data[2] = (unsigned char) strtol(blue, NULL, 16);

Note: It is enough to use unsigned char to hold data value from 0 to 255


来源: stackexchange

问:
Allow read to only accept two lengths
I am trying to add to a script I'm writing a restriction to the input where the user can only input 9 or 10 characters I set it up like this but when I run it, it doesn't work the way I want it to. Everything I type in comes back as 10 characters even if I just put one number. What is wrong with my code?</p>

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

echo "Please input numbers only"
read inputline
if read -n10 inputline
then
    echo "10 chars"
else
    if read -n9 inputline
    then
    echo "9 chars"
else
    echo "invalid input length"
fi
</code>```

答:
Your script is asking for input three times. I'm assuming that the following is closer to what you intend:

```<code>#!/bin/bash
read -p "Please input numbers only " inputline
len=${#inputline}
if (( len == 9 || len == 10 ))
then
    echo "$len chars"
else
    echo "invalid input length"
fi
</code>```

The -n option to read limits the input to the specified number of characters but accepts that length without pressing enter. You can enter fewer by pressing Enter though. I've found it to be useful for -n 1 but rarely otherwise.

ContentLicense: CC BY-SA 3.0

Title: Allow read to only accept two lengths

Body:
I am trying to add to a script I'm writing a restriction to the input where the user can only input 9 or 10 characters I set it up like this but when I run it, it doesn't work the way I want it to. Everything I type in comes back as 10 characters even if I just put one number. What is wrong with my code?

#!/bin/bash
#

echo "Please input numbers only"
read inputline
if read -n10 inputline
then
    echo "10 chars"
else
    if read -n9 inputline
    then
    echo "9 chars"
else
    echo "invalid input length"
fi

Body:
Your script is asking for input three times. I'm assuming that the following is closer to what you intend:

#!/bin/bash
read -p "Please input numbers only " inputline
len=${#inputline}
if (( len == 9 || len == 10 ))
then
    echo "$len chars"
else
    echo "invalid input length"
fi

The -n option to read limits the input to the specified number of characters but accepts that length without pressing enter. You can enter fewer by pressing Enter though. I've found it to be useful for -n 1 but rarely otherwise.

ContentLicense: CC BY-SA 2.5


问:
How to reference Value instead of formula in a formula using Excel?
In Microsoft Excel 2010/2013, I have five data columns as follows :

```<code>           | A  | B |  C   | D  |  E  |
          ------------------------------
  line 1   |  12|  7|  1.71|   5| 8.57|

C1: it's a formula ==> A1/B1, and it's formatted as two decimal places.
</code>```

However, the formula of E1 (which is C1*D1) gives 8.57 instead of 8.55, I figured out that Excel uses C1's formula instead of the displayed value, which is not my expectation!

So how can I enforce Excel to use the value(displayed) of a cell instead of its formula, to calculate another formula?

Note: I can get around by using the following formula in E1:

```<code>ROUND(C1,2)*D1
</code>```

...but I want a solution which gets the displayed value directly without formatting the C1 twice.

答:
This is the access to a cell's contents, since your original question asked how to access the value rather than the formula that generates the value:</p>

```<code>=CELL("contents",$C$1)
</code>```

Body:
In Microsoft Excel 2010/2013, I have five data columns as follows :

           | A  | B |  C   | D  |  E  |
          ------------------------------
  line 1   |  12|  7|  1.71|   5| 8.57|

C1: it's a formula ==> A1/B1, and it's formatted as two decimal places.

However, the formula of E1 (which is C1*D1) gives 8.57 instead of 8.55, I figured out that Excel uses C1's formula instead of the displayed value, which is not my expectation!

So how can I enforce Excel to use the value(displayed) of a cell instead of its formula, to calculate another formula?

Note: I can get around by using the following formula in E1:

ROUND(C1,2)*D1

...but I want a solution which gets the displayed value directly without formatting the C1 twice.

Body:
This is the access to a cell's contents, since your original question asked how to access the value rather than the formula that generates the value:

=CELL("contents",$C$1)


问:
How is "void()" useful?
You cannot declare a void variable:

```<code>void fn() {
    void a; // ill-formed
}
</code>```

Yet this compiles:

```<code>void fn() {
    void(); // a void object?
}
</code>```

What does void() mean? How is it useful? Why is void a; ill-formed, while void() OK?

```<code>void fn() {
    void a = void(); // ill-formed
}
</code>```

答:
Syntactically void() is an explict type conversion written in functional notation (see 5.2.3).

Note that even in "classic" C (C89/90) explicit conversions to void were already allowed. Of course, in C one has to use "classic" C-style cast notation and supply an argument. Any expression can be cast to void in C, including expressions that are already void. This functionality migrated unchanged to cast notation of explicit type conversion in C++ (it is handled by static_cast branch of its functionality, i.e. you can static_cast to void in C++).

Taking the above into account, it is not surprising that conversion to void is also consistently supported by the alternative C++ cast syntax - functional notation. And once you understand that, it is no surprise that it was extended to support the "argument-less" version - void().

The usefulness of this in C++ will include such contexts as generic functions

```<code>template <typename T>
T foo() {
  ...;
  return T(); // remains valid even when `T == void`
}
</code>```

Note that in C++ it is perfectly legal to return void pseudo-values from void functions. The ability to create such void() pseudo-values eliminates the need to write dedicated void specializations for functions like the one above.

As a side note, void() stands for explicit type conversion only if the context forces it to be interpreted as an expression, as in your example. When context calls for a type  name (e.g. int foo(void()) or using T = void();) it actually declares a nameless function that returns void and takes no arguments.

Title: How is "void()" useful?

Body:
You cannot declare a void variable:

void fn() {
    void a; // ill-formed
}

Yet this compiles:

void fn() {
    void(); // a void object?
}

What does void() mean? How is it useful? Why is void a; ill-formed, while void() OK?

void fn() {
    void a = void(); // ill-formed
}

Body:
Syntactically void() is an explict type conversion written in functional notation (see 5.2.3).

Note that even in "classic" C (C89/90) explicit conversions to void were already allowed. Of course, in C one has to use "classic" C-style cast notation and supply an argument. Any expression can be cast to void in C, including expressions that are already void. This functionality migrated unchanged to cast notation of explicit type conversion in C++ (it is handled by static_cast branch of its functionality, i.e. you can static_cast to void in C++).

Taking the above into account, it is not surprising that conversion to void is also consistently supported by the alternative C++ cast syntax - functional notation. And once you understand that, it is no surprise that it was extended to support the "argument-less" version - void().

The usefulness of this in C++ will include such contexts as generic functions

template <typename T>
T foo() {
  ...;
  return T(); // remains valid even when `T == void`
}

Note that in C++ it is perfectly legal to return void pseudo-values from void functions. The ability to create such void() pseudo-values eliminates the need to write dedicated void specializations for functions like the one above.

As a side note, void() stands for explicit type conversion only if the context forces it to be interpreted as an expression, as in your example. When context calls for a type  name (e.g. int foo(void()) or using T = void();) it actually declares a nameless function that returns void and takes no arguments.


问:
Jquery - Store Ajax jSON response as variable
I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer remains undefined outside the $.getJSON and $.ajax functions (I tried both).

Here is my code and where I am able to see the results from the console.log(beer).

```<code>var beer;
$.getJSON(jsonUrl, function (json) {
    beer = json;
    console.log(beer); // returns beer
});
console.log(beer); // returns undefined

var beer = (function () {
    var result;

    $.ajax({
        url: jsonUrl,
        success: function (data) {
            result = data;
            console.log(beer); // returns beer

        }
    });
    console.log(result); // returns undefined
    if (result) return result;
})();
console.log(beer); // returns undefined
</code>```

答:
The problem is that you're trying to access the data before it actually comes back from the server, the 'success' function is actually a callback that gets called when the ajax call finishes successfully. The $.ajax (or $.get) functions return inmediatly...

You would need to somehow signal to the interested functions that you got the data into the 'beer' var inside your success callback

Body:
I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer remains undefined outside the $.getJSON and $.ajax functions (I tried both).

Here is my code and where I am able to see the results from the console.log(beer).

var beer;
$.getJSON(jsonUrl, function (json) {
    beer = json;
    console.log(beer); // returns beer
});
console.log(beer); // returns undefined

var beer = (function () {
    var result;

    $.ajax({
        url: jsonUrl,
        success: function (data) {
            result = data;
            console.log(beer); // returns beer

        }
    });
    console.log(result); // returns undefined
    if (result) return result;
})();
console.log(beer); // returns undefined


问:
Angular 4 - html input element change event triggers @Input() setter with OnPush strategy
I have a simple component:

```<code>@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {

  private _items: string[];

  @Input()
  set items(items) {
    console.log('setter of items: ', items); // verify call
    this._items = items;
  }

  onChangeValue(event) {
    console.log('on change value', event);
  }
}
</code>```

It's template:

```<code><div *ngFor="let item of _items">
  {{item}}
</div>

<input type='text' (change)='onChangeValue($event)'>
</code>```

Question:

Why the setter @Input() set items(..) is being called after the text has been changed in the input element and the onChangeValue function is called.

I thought Angular's change detection strategy OnPush will trigger the @Input() set items(..) function if and only if the parent component passes in a new reference of items to this component.

However, @Input() set items(..) is also triggered when the input text has changed.

Why??

答:
As explained in this S.O. post:

OnPush is defined this way.

It triggers change detection

when a DOM event the component listens to was received

when the |async pipe receives a new event

when an @Input() was updated by change detection.

when explicitly registering the component to be checked the next change detection turn using ChangeDetectorRef::markForCheck

ChangeDetectionStrategy.Default triggers change detection for every
  async callback called within Angulars zone (every DOM even listened to
  within the Angular application, every Observable event or completed
  Promise, setTimeout, ...)

So, in your case, change detection is being triggered by a DOM event the component listens to.

Body:
I have a simple component:

@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {

  private _items: string[];

  @Input()
  set items(items) {
    console.log('setter of items: ', items); // verify call
    this._items = items;
  }

  onChangeValue(event) {
    console.log('on change value', event);
  }
}

It's template:

  {{item}}

<input type='text' (change)='onChangeValue($event)'>

Question:

Why the setter @Input() set items(..) is being called after the text has been changed in the input element and the onChangeValue function is called.

I thought Angular's change detection strategy OnPush will trigger the @Input() set items(..) function if and only if the parent component passes in a new reference of items to this component.

However, @Input() set items(..) is also triggered when the input text has changed.

Why??


问:
SSRS How to Get Report Cache Options With Powershell?
In SSRS web interface, after clicking on a report and going to Manage --> Caching if a report is configured to "Always run this report against pregenerated snapshots" there is a Cache snapshots section with an option "Create cache snapshots on a schedule"

I have been messing around with PowerShell and trying to create a scriptthe finds all of the reports where this option is set, and output the schedule.

I have this script that iterates over each report with "Execution Type" of "Snapshot", but I believe I'm calling the wrong method (GetCacheOptions), as all it returns is False for each item:

```<code>Clear-Host

$webServiceUrl = 'http://myReportServer.domain.com/reportserver/reportservice2010.asmx?WSDL'

$rs = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $webServiceUrl -UseDefaultCredential

$reports = $rs.ListChildren("/Some Folder", $true) | Where-Object { $_.TypeName -eq "Report" }

$schedDef = New-Object RS.ScheduleDefinition
$expDef = New-Object RS.ExpirationDefinition

foreach ($report in $reports) {

    $execType = $rs.GetExecutionOptions($report.Path, [ref]$schedDef.Item)

    if($execType -eq "Snapshot") {
        $rs.GetCacheOptions($report.Path, [ref]$expDef.Item)
    }

}
</code>```

Does anyone know what method needs to be called to get this information and how to call this method (i.e. what parameters needs to be supplied)?

EDIT:

Per guidance from accepted answer, I was able to make some edits (below) and I'm not getting the schedule information I desire:

```<code>.......
....
foreach ($report in $reports) {

    $execResult = $rs.GetExecutionOptions($report.Path,
        [ref]$ScheduleDefinitionOrReference)

    if ($execResult -eq "Snapshot") {
        if($ScheduleDefinitionOrReference.Item -is [RS.DailyRecurrence]) {
            Write-Host "$($report.Name):" -f Green
            Write-Host "`tSchedule Information:" -f Yellow
            Write-Host "`t`tEvery $($ScheduleDefinitionOrReference.Item.Daysinterval) Day(s)"
            Write-Host "`t`tStart Time: $($ScheduleDefinitionOrReference.StartDateTime)`n"
        }

    }
</code>```

答:
You can use ReportingService2010.GetItemHistoryOptions and pass the ItemPath, and out bool KeepExecutionSnapshots, and out ScheduleDefinitionOrReference to the method.

ScheduleDefinitionOrReference will contain the ScheduleDefinition if you check Create cache snapshots on a schedule, otherwise its value will be NoSchedule.

Example

```<code>$svcUrl = 'http://the-host-name/ReportServer/reportservice2010.asmx'
$svc = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $svcUrl -UseDefaultCredential
$reports = $svc.ListChildren("/", $true) | Where-Object { $_.TypeName -eq "Report" }

$KeepExecutionSnapshots = $false
$ScheduleDefinitionOrReference = New-Object RS.ScheduleDefinitionOrReference

foreach ($report in $reports) {
    $svc.GetItemHistoryOptions($report.Path,
        [ref]$KeepExecutionSnapshots,
        [ref]$ScheduleDefinitionOrReference)
    $report.Path
    $ScheduleDefinitionOrReference
}
</code>```

Body:
In SSRS web interface, after clicking on a report and going to Manage --> Caching if a report is configured to "Always run this report against pregenerated snapshots" there is a Cache snapshots section with an option "Create cache snapshots on a schedule"

I have been messing around with PowerShell and trying to create a scriptthe finds all of the reports where this option is set, and output the schedule.

I have this script that iterates over each report with "Execution Type" of "Snapshot", but I believe I'm calling the wrong method (GetCacheOptions), as all it returns is False for each item:

Clear-Host

$webServiceUrl = 'http://myReportServer.domain.com/reportserver/reportservice2010.asmx?WSDL'

$rs = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $webServiceUrl -UseDefaultCredential

$reports = $rs.ListChildren("/Some Folder", $true) | Where-Object { $_.TypeName -eq "Report" }

$schedDef = New-Object RS.ScheduleDefinition
$expDef = New-Object RS.ExpirationDefinition

foreach ($report in $reports) {

    $execType = $rs.GetExecutionOptions($report.Path, [ref]$schedDef.Item)

    if($execType -eq "Snapshot") {
        $rs.GetCacheOptions($report.Path, [ref]$expDef.Item)
    }

}

Does anyone know what method needs to be called to get this information and how to call this method (i.e. what parameters needs to be supplied)?

EDIT:

Per guidance from accepted answer, I was able to make some edits (below) and I'm not getting the schedule information I desire:

.......
....
foreach ($report in $reports) {

    $execResult = $rs.GetExecutionOptions($report.Path,
        [ref]$ScheduleDefinitionOrReference)

    if ($execResult -eq "Snapshot") {
        if($ScheduleDefinitionOrReference.Item -is [RS.DailyRecurrence]) {
            Write-Host "$($report.Name):" -f Green
            Write-Host "`tSchedule Information:" -f Yellow
            Write-Host "`t`tEvery $($ScheduleDefinitionOrReference.Item.Daysinterval) Day(s)"
            Write-Host "`t`tStart Time: $($ScheduleDefinitionOrReference.StartDateTime)`n"
        }

    }

Body:
You can use ReportingService2010.GetItemHistoryOptions and pass the ItemPath, and out bool KeepExecutionSnapshots, and out ScheduleDefinitionOrReference to the method.

ScheduleDefinitionOrReference will contain the ScheduleDefinition if you check Create cache snapshots on a schedule, otherwise its value will be NoSchedule.

Example

$svcUrl = 'http://the-host-name/ReportServer/reportservice2010.asmx'
$svc = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $svcUrl -UseDefaultCredential
$reports = $svc.ListChildren("/", $true) | Where-Object { $_.TypeName -eq "Report" }

$KeepExecutionSnapshots = $false
$ScheduleDefinitionOrReference = New-Object RS.ScheduleDefinitionOrReference

foreach ($report in $reports) {
    $svc.GetItemHistoryOptions($report.Path,
        [ref]$KeepExecutionSnapshots,
        [ref]$ScheduleDefinitionOrReference)
    $report.Path
    $ScheduleDefinitionOrReference
}


问:
Reinstalling intero using stack
I deleted intero from ~/Users/amir/.stack/snapshots/x86_64-osx/lts-9.14/8.0.2/bin/. Now if i run stack install intero. I get the following error:

```<code>Couldn't find executable intero in directory ~/.stack/snapshots/x86_64-osx/lts-9.14/8.0.2/bin/
</code>```

Is there any way to force reinstalling? I tried --force-dirty as well.

答: There is an issue about this here.  Workaround for now is to also do rm ~/Users/amir/.stack/snapshots/x86_64-osx/lts-9.14/8.0.2/installed-packages/intero-*

Title: Reinstalling intero using stack

Body:
I deleted intero from ~/Users/amir/.stack/snapshots/x86_64-osx/lts-9.14/8.0.2/bin/. Now if i run stack install intero. I get the following error:

Couldn't find executable intero in directory ~/.stack/snapshots/x86_64-osx/lts-9.14/8.0.2/bin/

Is there any way to force reinstalling? I tried --force-dirty as well.


问:
Returning/Passing Variables in Java
I am a beginning programmer and we were assigned to implement methods into a code. I had this grade average code working fine, but once I broke it up into methods, I could not get the return functions to work. I have tried moving brackets and rearranging the code but to no avail. I believe it may have to do with the scope of my variables... Thanks in advance :)

```<code>package milsteadgrades;
import java.util.Scanner;

public class MilsteadGrades {

public static void main(String[] args)

{
//Call methods to execute program.
displayInfo();
double numOfgrades = getInput();
double average = getAverage(numOfgrades);
char letgrade = determineLetterGrade(average);
displayGrades(average, letgrade);
}

public static void displayInfo()

{
System.out.println("Mallory Milstead");
System.out.println("This program will prompt the user for a number of
grades"
+ " and each grade. Then the program calculates and displays the average and
letter"+" grade.");
}

 public static double getInput()

{
//Prompt user to enter number of grades and assign that number to
numOfgrades.
System.out.print("How many grades would you like to average? ");
Scanner keyboard = new Scanner(System.in);
double numOfgrades = keyboard.nextDouble();
return numOfgrades;
}

public static double getAverage(numOfgrades)

{
//Prompt the user to enter grades.
System.out.println("Enter exam scores : ");
Scanner keyboard = new Scanner(System.in);
double total = 0;
for (double i = 0; i < numOfgrades; i++) {
double grade = keyboard.nextDouble();
total+=grade;}
double average = total/numOfgrades;
return average;
}

public static char determineLetterGrade(average)

{ double testscore = average;
    char letgrade;

    if (testscore >= 90)
    {
        letgrade = 'A';
    } else if (testscore >= 80)
    {
        letgrade = 'B';
    } else if (testscore >= 70)
    {
        letgrade = 'C';
    } else if (testscore >= 60)
    {
        letgrade = 'D';
    } else
    {
        letgrade = 'F';
    }
    return letgrade;
    }

public static void displayGrades(average, letgrade)

{
System.out.println("The average of the grades is "+average+ " and the
letter grade"+ " is " + letgrade+".");}

}
</code>```

Beginning with the line -public static double getAverage(numOfgrades)-, I continuously get "cannot find symbol" error message. None of my variables is being recognized.

答:
You need to declare the type of the argument of getAverage. Like

public static double getAverage(double numOfgrades)

Similiarly for your other methods(not modules). Have a read of this or this for tips.

Title: Returning/Passing Variables in Java

Body:
I am a beginning programmer and we were assigned to implement methods into a code. I had this grade average code working fine, but once I broke it up into methods, I could not get the return functions to work. I have tried moving brackets and rearranging the code but to no avail. I believe it may have to do with the scope of my variables... Thanks in advance :)

package milsteadgrades;
import java.util.Scanner;

public class MilsteadGrades {

public static void main(String[] args)

{
//Call methods to execute program.
displayInfo();
double numOfgrades = getInput();
double average = getAverage(numOfgrades);
char letgrade = determineLetterGrade(average);
displayGrades(average, letgrade);
}

public static void displayInfo()

{
System.out.println("Mallory Milstead");
System.out.println("This program will prompt the user for a number of
grades"
+ " and each grade. Then the program calculates and displays the average and
letter"+" grade.");
}

 public static double getInput()

{
//Prompt user to enter number of grades and assign that number to
numOfgrades.
System.out.print("How many grades would you like to average? ");
Scanner keyboard = new Scanner(System.in);
double numOfgrades = keyboard.nextDouble();
return numOfgrades;
}

public static double getAverage(numOfgrades)

{
//Prompt the user to enter grades.
System.out.println("Enter exam scores : ");
Scanner keyboard = new Scanner(System.in);
double total = 0;
for (double i = 0; i < numOfgrades; i++) {
double grade = keyboard.nextDouble();
total+=grade;}
double average = total/numOfgrades;
return average;
}

public static char determineLetterGrade(average)

{ double testscore = average;
    char letgrade;

    if (testscore >= 90)
    {
        letgrade = 'A';
    } else if (testscore >= 80)
    {
        letgrade = 'B';
    } else if (testscore >= 70)
    {
        letgrade = 'C';
    } else if (testscore >= 60)
    {
        letgrade = 'D';
    } else
    {
        letgrade = 'F';
    }
    return letgrade;
    }

public static void displayGrades(average, letgrade)

{
System.out.println("The average of the grades is "+average+ " and the
letter grade"+ " is " + letgrade+".");}

}

Beginning with the line -public static double getAverage(numOfgrades)-, I continuously get "cannot find symbol" error message. None of my variables is being recognized.


问:
How to replace default SortArgumentResolver
I need to add private static final Sort sortById = new Sort(Sort.Direction.DESC, ID); to each Pageable. I guess, the best way to do that is to create decorator/adapter for SortArgumentResolver.

I've created class:

```<code>public class IdSortArgumentResolver implements SortArgumentResolver {

private static final String ID = "id";
private static final Sort sortById = new Sort(Sort.Direction.DESC, ID);
private final SortArgumentResolver delegate;

public IdSortArgumentResolverAdapter(SortArgumentResolver delegate) {
    this.delegate = delegate;
}

@Override
public boolean supportsParameter(MethodParameter methodParameter) {
    return delegate.supportsParameter(methodParameter);
}

@Override
public Sort resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
    Sort sort = delegate.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    if (isNull(sort)) {
        return sortById;
    }
    if (containsSortById(sort)) {
        return sort;
    }
    return sort.and(sortById);
}

private static boolean containsSortById(Sort currentSort) {
    return StreamSupport.stream(currentSort.spliterator(), false)
                        .anyMatch(order -> ID.equalsIgnoreCase(order.getProperty()));
}
</code>```

}

How can I change default SortArgumentResolver to IdSortArgumentResolver ? Is it possible? or maybe there is a better way to do that...

P.S It's spring-boot 1.5.2 RELEASE and current SortHandlerMethodArgumentResolver is configured in SpringDataWebConfiguration

答:
Starting in spring-data-commons version 2.0, there is are 2 new classes that will make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version of Spring Boot, so replace at your own risk.

```<code>@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    // s is SortHandlerMethodArgumentResolver
    return s -> s.setPropertyDelimiter("<-->");
}
</code>```

In this case, one would probably call resolveArgument to manipulate it.

Spring Data Web Support

Body:
I need to add private static final Sort sortById = new Sort(Sort.Direction.DESC, ID); to each Pageable. I guess, the best way to do that is to create decorator/adapter for SortArgumentResolver.

I've created class:

public class IdSortArgumentResolver implements SortArgumentResolver {

private static final String ID = "id";
private static final Sort sortById = new Sort(Sort.Direction.DESC, ID);
private final SortArgumentResolver delegate;

public IdSortArgumentResolverAdapter(SortArgumentResolver delegate) {
    this.delegate = delegate;
}

@Override
public boolean supportsParameter(MethodParameter methodParameter) {
    return delegate.supportsParameter(methodParameter);
}

@Override
public Sort resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
    Sort sort = delegate.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    if (isNull(sort)) {
        return sortById;
    }
    if (containsSortById(sort)) {
        return sort;
    }
    return sort.and(sortById);
}

private static boolean containsSortById(Sort currentSort) {
    return StreamSupport.stream(currentSort.spliterator(), false)
                        .anyMatch(order -> ID.equalsIgnoreCase(order.getProperty()));
}

}

How can I change default SortArgumentResolver to IdSortArgumentResolver ? Is it possible? or maybe there is a better way to do that...

P.S It's spring-boot 1.5.2 RELEASE and current SortHandlerMethodArgumentResolver is configured in SpringDataWebConfiguration

Body:
Starting in spring-data-commons version 2.0, there is are 2 new classes that will make this kind of thing easier:

SortHandlerMethodArgumentResolverCustomizer

PageableHandlerMethodArgumentResolverCustomizer

Unfortunately that's not the version that ships with the current version of Spring Boot, so replace at your own risk.

@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    // s is SortHandlerMethodArgumentResolver
    return s -> s.setPropertyDelimiter("<-->");
}

In this case, one would probably call resolveArgument to manipulate it.

Spring Data Web Support


问:
Force Refresh on Dialog before showing it with react-native-dialog-component
I am using https://github.com/jacklam718/react-native-dialog-component for my Dialogs and I am having some problems with async functions not refreshing the dialog. I am using it like in the example with

```<code> render() {
    return (
        ...
        <Button onItemPressed={(item) => {
                    this.completeMovementDialog.show()
                }}/>}
        ...
        <CompleteMovementDialog onRefresh={() => this.getStationsNearToPlayer()}
                        ref={(completeMovementDialog) => {
                                this.completeMovementDialog = completeMovementDialog;
                            }}/>
</code>```

The CompleteMovementDialog uses the onRefresh Method in componentDidMount() and is a wrapper for a DialogComponent. It works fine, when i refresh the list, that is retrieved from the backend by this.getStationsNearToPlayer(). The problem is, that the CompleteMovementDialog component gets loaded, as soon as the component around it gets loaded. So when i call this.startMovementDialog.show() it does not go into componentDidMount anymore and the list is never refreshed unless you refresh it manually. Does anybody have a tip, how i can achieve to forecefully refresh the list before show()? Or is there a better library to show dialogs? I heard ref is not a good practice...

答:
For somebody stumbling across this:

The DialogComponent offers a onShown and onDismissed property, where you can pass a function, that can be an api call. I solved it by loading the data in the onShown callback and set the view to loading mode again, when the dialog was dismissed and the onDismissed callback occured.

Body:
I am using https://github.com/jacklam718/react-native-dialog-component for my Dialogs and I am having some problems with async functions not refreshing the dialog. I am using it like in the example with

 render() {
    return (
        ...
        <Button onItemPressed={(item) => {
                    this.completeMovementDialog.show()
                }}/>}
        ...
        <CompleteMovementDialog onRefresh={() => this.getStationsNearToPlayer()}
                        ref={(completeMovementDialog) => {
                                this.completeMovementDialog = completeMovementDialog;
                            }}/>

The CompleteMovementDialog uses the onRefresh Method in componentDidMount() and is a wrapper for a DialogComponent. It works fine, when i refresh the list, that is retrieved from the backend by this.getStationsNearToPlayer(). The problem is, that the CompleteMovementDialog component gets loaded, as soon as the component around it gets loaded. So when i call this.startMovementDialog.show() it does not go into componentDidMount anymore and the list is never refreshed unless you refresh it manually. Does anybody have a tip, how i can achieve to forecefully refresh the list before show()? Or is there a better library to show dialogs? I heard ref is not a good practice...


问:
Relationship between dpi and figure size
I have created a figure using matplotlib but I have realized the plot axis and the drawn line gets zoomed out.

Reading this earlier discussion thread, it explains how to set the figure size.

```<code>fig, ax = plt.subplots()
fig.set_size_inches(3, 1.5)
plt.savefig(file.jpeg, edgecolor='black', dpi=400, facecolor='black', transparent=True)
</code>```

With the above code (other configurations removed for brevity), I do get a resulting image file with 1200 X 600 desired dimensions(should we say resolution too?) and desired file size.

The projected image is scaled out in an unusual way, annotations for example are enlarged. While I can set the size of the labels on the axis, the figure doesn't look proportional with respect to the scale since the bottom and right spines are large and so are the plotted lines.

The question, therefore, is, what configurations are going wrong?

答:
Figure size (figsize) determines the size of the figure in inches. This gives the amount of space the axes (and other elements) have inside the figure. The default figure size is (6.4, 4.8) inches in matplotlib 2. A larger figure size will allow for longer texts, more axes or more ticklabels to be shown.

Dots per inches (dpi) determines how many pixels the figure comprises. The default dpi in matplotlib is 100. A figure of figsize=(w,h) will have

```<code>px, py = w*dpi, h*dpi  # pixels
# e.g.
# 6.4 inches * 100 dpi = 640 pixels
</code>```

So in order to obtain a figure with a pixel size of e.g. (1200,600) you may chose several combinations of figure size and dpi, e.g.

```<code>figsize=(15,7.5), dpi= 80
figsize=(12,6)  , dpi=100
figsize=( 8,4)  , dpi=150
figsize=( 6,3)  , dpi=200
etc.
</code>```

Now, what is the difference? This is determined by the size of the elements inside the figure. Most elements like lines, markers, texts have a size given in points.

Matplotlib figures use Points per inch (ppi) of 72. A line with thickness 1 point will be 1./72. inch wide. A text with fontsize 12 points will be 12./72. inch heigh.

Of course if you change the figure size in inches, points will not change, so a larger figure in inches still has the same size of the elements. Changing the figure size is thus like taking a piece of paper of a different size. Doing so, would of course not change the width of the line drawn with the same pen.

On the other hand, changing the dpi scales those elements. At 72 dpi, a line of 1 point size is one pixel strong. At 144 dpi, this line is 2 pixels strong. A larger dpi will therefore act like a magnifying glass. All elements are scaled by the magnifying power of the lens.

A comparisson for constant figure size and varying dpi is shown in the image below on the left. On the right you see a constant dpi and varying figure size. Figures in each row have the same pixel size.

Code to reproduce:

```<code>import matplotlib.pyplot as plt
%matplotlib inline

def plot(fs,dpi):
    fig, ax=plt.subplots(figsize=fs, dpi=dpi)
    ax.set_title("Figsize: {}, dpi: {}".format(fs,dpi))
    ax.plot([2,4,1,5], label="Label")
    ax.legend()

figsize=(2,2)
for i in range(1,4):
    plot(figsize, i*72)

dpi=72
for i in [2,4,6]:
    plot((i,i), dpi)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a figure using matplotlib but I have realized the plot axis and the drawn line gets zoomed out.

Reading this earlier discussion thread, it explains how to set the figure size.

fig, ax = plt.subplots()
fig.set_size_inches(3, 1.5)
plt.savefig(file.jpeg, edgecolor='black', dpi=400, facecolor='black', transparent=True)

With the above code (other configurations removed for brevity), I do get a resulting image file with 1200 X 600 desired dimensions(should we say resolution too?) and desired file size.

The projected image is scaled out in an unusual way, annotations for example are enlarged. While I can set the size of the labels on the axis, the figure doesn't look proportional with respect to the scale since the bottom and right spines are large and so are the plotted lines.

The question, therefore, is, what configurations are going wrong?

Body:
Figure size (figsize) determines the size of the figure in inches. This gives the amount of space the axes (and other elements) have inside the figure. The default figure size is (6.4, 4.8) inches in matplotlib 2. A larger figure size will allow for longer texts, more axes or more ticklabels to be shown.

Dots per inches (dpi) determines how many pixels the figure comprises. The default dpi in matplotlib is 100. A figure of figsize=(w,h) will have

px, py = w*dpi, h*dpi  # pixels
# e.g.
# 6.4 inches * 100 dpi = 640 pixels

So in order to obtain a figure with a pixel size of e.g. (1200,600) you may chose several combinations of figure size and dpi, e.g.

figsize=(15,7.5), dpi= 80
figsize=(12,6)  , dpi=100
figsize=( 8,4)  , dpi=150
figsize=( 6,3)  , dpi=200
etc.

Now, what is the difference? This is determined by the size of the elements inside the figure. Most elements like lines, markers, texts have a size given in points.

Matplotlib figures use Points per inch (ppi) of 72. A line with thickness 1 point will be 1./72. inch wide. A text with fontsize 12 points will be 12./72. inch heigh.

Of course if you change the figure size in inches, points will not change, so a larger figure in inches still has the same size of the elements. Changing the figure size is thus like taking a piece of paper of a different size. Doing so, would of course not change the width of the line drawn with the same pen.

On the other hand, changing the dpi scales those elements. At 72 dpi, a line of 1 point size is one pixel strong. At 144 dpi, this line is 2 pixels strong. A larger dpi will therefore act like a magnifying glass. All elements are scaled by the magnifying power of the lens.

A comparisson for constant figure size and varying dpi is shown in the image below on the left. On the right you see a constant dpi and varying figure size. Figures in each row have the same pixel size.

Code to reproduce:

import matplotlib.pyplot as plt
%matplotlib inline

def plot(fs,dpi):
    fig, ax=plt.subplots(figsize=fs, dpi=dpi)
    ax.set_title("Figsize: {}, dpi: {}".format(fs,dpi))
    ax.plot([2,4,1,5], label="Label")
    ax.legend()

figsize=(2,2)
for i in range(1,4):
    plot(figsize, i*72)

dpi=72
for i in [2,4,6]:
    plot((i,i), dpi)


问:
In Akka, when a message is sent to an Actor Pool, does 'self' hold a reference to the Actor instance or to the entire Pool?
What is the behavior if I send a message to an Actor pool whose Actors then, upon receiving that message, send a message to self?  In this case, is sending to self going to send messages to the pool, or to the specific Actor instance that sent the message?

Pseudocode of this scenario would look like the following

```<code>...
val system: ActorSystem = ActorSystem()
val actorPool: ActorRef = system.actorOf(
  Props(new SomeActor(someDependency))
    .withRouter(RoundRobinPool(conf.someActorPoolSize))
actorPool ! "hello"

class SomeActor(someDependency: SomeDependency) extends Actor {
  def receive = {
    case hello @ "hello" => self ! hello + " world"
    // ^Does the above send to the entire Pool, or does this specific
    // Actor just send the message directly to itself?
    case msg @ "hello world" => println(msg)
    // ^Do I know that the same Actor insntance that sent me "hello world"
    // is also going to execute "println(msg)", or could any Actor in the
    // Pool have sent the "hello world" message?
  }
}
</code>```

答:
self always points to an actor's own ActorRef:

```<code>def receive = {
  case hello @ "hello" =>
    self ! hello + " world" // sends "hello world" to itself
  case msg @ "hello world" =>
    println(msg)
</code>```

When the routee sends "hello world" to self, it's sending that string to itself. This "hello world" string will then be captured in the case msg @ "hello world" => clause, and the actor will print the message.

Do I know that the same Actor insntance that sent me "hello world"
  is also going to execute "println(msg)"...

An external actor could send either "hello" or "hello world" to the router. The router would then forward the message to one of the routees. For a routee to determine whether a "hello world" message was from itself or an external actor, the routee would have to inspect the value of sender (e.g., it could check whether sender was equal to self).

...or could any Actor in the Pool have sent the "hello world" message?

It's unclear what you're asking here. Routees typically don't communicate with each other.

How would I send a message back to the Pool, instead of to 'self'? Would I need to pass the reference to the Actor Pool as a dependency, even though my Actor is a member of the Pool it wants to send messages to?

A routee doesn't need to know about other routees or the router. If you want to send a message back to the pool, let the original sender (i.e., the actor that sent the message to the router) do this. In other words, have your routee send the message to sender, and let that actor send the message back to the router. To emphasize this point, sender in this context is not the router/pool, but the original sender (there are a few exceptions to this, as described in the documentation):

```<code>client            --> router --> [routee1, routee2, etc.]
(original sender)                // sender in a routee is a reference to client, because
                                 // the router forwards the messages to the routees
</code>```

You can read more about routing here.

Body:
What is the behavior if I send a message to an Actor pool whose Actors then, upon receiving that message, send a message to self?  In this case, is sending to self going to send messages to the pool, or to the specific Actor instance that sent the message?

Pseudocode of this scenario would look like the following

...
val system: ActorSystem = ActorSystem()
val actorPool: ActorRef = system.actorOf(
  Props(new SomeActor(someDependency))
    .withRouter(RoundRobinPool(conf.someActorPoolSize))
actorPool ! "hello"

class SomeActor(someDependency: SomeDependency) extends Actor {
  def receive = {
    case hello @ "hello" => self ! hello + " world"
    // ^Does the above send to the entire Pool, or does this specific
    // Actor just send the message directly to itself?
    case msg @ "hello world" => println(msg)
    // ^Do I know that the same Actor insntance that sent me "hello world"
    // is also going to execute "println(msg)", or could any Actor in the
    // Pool have sent the "hello world" message?
  }
}

Body:
self always points to an actor's own ActorRef:

def receive = {
  case hello @ "hello" =>
    self ! hello + " world" // sends "hello world" to itself
  case msg @ "hello world" =>
    println(msg)

When the routee sends "hello world" to self, it's sending that string to itself. This "hello world" string will then be captured in the case msg @ "hello world" => clause, and the actor will print the message.

Do I know that the same Actor insntance that sent me "hello world"
  is also going to execute "println(msg)"...

An external actor could send either "hello" or "hello world" to the router. The router would then forward the message to one of the routees. For a routee to determine whether a "hello world" message was from itself or an external actor, the routee would have to inspect the value of sender (e.g., it could check whether sender was equal to self).

...or could any Actor in the Pool have sent the "hello world" message?

It's unclear what you're asking here. Routees typically don't communicate with each other.

How would I send a message back to the Pool, instead of to 'self'? Would I need to pass the reference to the Actor Pool as a dependency, even though my Actor is a member of the Pool it wants to send messages to?

A routee doesn't need to know about other routees or the router. If you want to send a message back to the pool, let the original sender (i.e., the actor that sent the message to the router) do this. In other words, have your routee send the message to sender, and let that actor send the message back to the router. To emphasize this point, sender in this context is not the router/pool, but the original sender (there are a few exceptions to this, as described in the documentation):

client            --> router --> [routee1, routee2, etc.]
(original sender)                // sender in a routee is a reference to client, because
                                 // the router forwards the messages to the routees

You can read more about routing here.


问:
get the min value from a count subquery
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

```<code>  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id
</code>```

I get:

```<code>banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2
</code>```

So I then try and wrap it up as a sub query:

```<code>SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
</code>```

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

```<code>SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id
</code>```

but I am getting an invalid group function error

答:
Looks to me like you don't need a subquery, you just need to add an ORDER BY num_of_individual_sales and maybe a limit if you only want, say, the 3 items with the least number of sales.

But your query is not going to include items with no sales; is that what you want?

That said, you are receiving only one answer because there is no GROUP BY in your outer query, so MIN() is finding the minimum from all the results (but name is an arbitrary one of the names).  Just adding a GROUP BY ans.name would fix it, but, as I said, the subquery isn't actually needed.

Update (for updated question):

You still have an unnecessary level of subquery that you can avoid with an order by and limit, and you can use grouping functions such as COUNT() in HAVING instead of WHERE (HAVING applies after grouping, not before as WHERE does), though you still need to tell the outer query what to group on to avoid it grouping all rows:

```<code>SELECT st.name, st.price, s.sales_id
FROM stock AS st
JOIN sales AS s
ON st.sid = s.stock_id
GROUP BY st.sid
HAVING COUNT(s.stock_id)=(
    SELECT COUNT(s.stock_id) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id
    ORDER BY 1
    LIMIT 1
)
</code>```

(untested)

Title: get the min value from a count subquery

Body:
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id

I get:

banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2

So I then try and wrap it up as a sub query:

SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id

but I am getting an invalid group function error

Body:
Looks to me like you don't need a subquery, you just need to add an ORDER BY num_of_individual_sales and maybe a limit if you only want, say, the 3 items with the least number of sales.

But your query is not going to include items with no sales; is that what you want?

That said, you are receiving only one answer because there is no GROUP BY in your outer query, so MIN() is finding the minimum from all the results (but name is an arbitrary one of the names).  Just adding a GROUP BY ans.name would fix it, but, as I said, the subquery isn't actually needed.

Update (for updated question):

You still have an unnecessary level of subquery that you can avoid with an order by and limit, and you can use grouping functions such as COUNT() in HAVING instead of WHERE (HAVING applies after grouping, not before as WHERE does), though you still need to tell the outer query what to group on to avoid it grouping all rows:

SELECT st.name, st.price, s.sales_id
FROM stock AS st
JOIN sales AS s
ON st.sid = s.stock_id
GROUP BY st.sid
HAVING COUNT(s.stock_id)=(
    SELECT COUNT(s.stock_id) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id
    ORDER BY 1
    LIMIT 1
)

(untested)


问:
rails- convert time to utc based on browser time zone and start_date
I have browser time zone in a cookie variable and date in start_date variable as string .
say cookie['browser_zone']="Asia/kolkata"
& start_date = "2017/12/31 03:00:00"
how can I convert above date to with this time zone to UTC time zone.</p>

答:
Use ActiveSupport::TimeZone to parse the time into the correct time zone, then convert it to UTC

```<code>ActiveSupport::TimeZone["Asia/Kolkata"].parse("2017/12/31 03:00:00").utc
=> 2017-12-30 21:30:00 UTC
</code>```

Body:
Use ActiveSupport::TimeZone to parse the time into the correct time zone, then convert it to UTC

ActiveSupport::TimeZone["Asia/Kolkata"].parse("2017/12/31 03:00:00").utc
=> 2017-12-30 21:30:00 UTC


问:
Using an array of longitudes and latitudes to plot on mapbox
i am trying to implement Mapbox api into my web application however i have reached a snag. My objective is to grab the longitudes and latitudes from my array and insert them into the coordinates. I have tried using a loop that loops through but it does not seem to work. If anyone has any solution it be greatly appreciated! note i took out my access token</p>

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Draw GeoJSON points</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.2/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.2/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<div id='map'></div>
<script>

var longLat = [
 [53.515333, -6.190796],
 [53.342686, -6.403656],
 [51.678091, -9.624023],
 [52.768293, -1.560059]
 ];

mapboxgl.accessToken = 'undefined';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [-96, 37.8],
    zoom: 3
});

map.on('load', function () {

    map.addLayer({
        "id": "points",
        "type": "symbol",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": [{
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [-77.03238901390978, 38.913188059745586]
                    },
                    "properties": {
                        "title": "Mapbox DC",
                        "icon": "monument"
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [-122.414, 37.776]
                    },
                    "properties": {
                        "title": "Mapbox SF",
                        "icon": "harbor"
                    }
                }]
            }
        },
        "layout": {
            "icon-image": "{icon}-15",
            "text-field": "{title}",
            "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
            "text-offset": [0, 0.6],
            "text-anchor": "top"
        }
    });
});
</script>

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

答:
I've got no mapbox experience, but basing on this documentation page, i came up with following;

You need to create your features collection (array) within for loop, like that:

```<code>var featureCollection = []; // Initialize empty collection

// Your longLat collection
var longLat = [
  [53.515333, -6.190796],
  [53.342686, -6.403656],
  [51.678091, -9.624023],
  [52.768293, -1.560059]
];

// for every item object within longLat
for(var itemIndex in longLat) {
  // push new feature to the collection
  featureCollection.push({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": longLat[itemIndex]
    },
    "properties": {
      "title": "Mapbox DC",
      "icon": "monument"
    }
  });
}
</code>```

Try if you can skip the properties (icon and title). For now they are hardcoded.

Then, you pass them to the map itself this way:

```<code>map.on('load', function () {
  map.addLayer({
    "id": "points",
    "type": "symbol",
    "source": {
    "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": featureCollection
      }
    },
    "layout": {
      "icon-image": "{icon}-15",
      "text-field": "{title}",
      "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
      "text-offset": [0, 0.6],
      "text-anchor": "top"
    }
  });
});
</code>```

I'm not sure what all of the things mean (like layout with all icons for example), but that's just taken from the mentioned example, so it should not break anything.

Body:
i am trying to implement Mapbox api into my web application however i have reached a snag. My objective is to grab the longitudes and latitudes from my array and insert them into the coordinates. I have tried using a loop that loops through but it does not seem to work. If anyone has any solution it be greatly appreciated! note i took out my access token

<!DOCTYPE html>

    <meta charset='utf-8' />
    <title>Draw GeoJSON points</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.2/mapbox-gl.css' rel='stylesheet' />

Body:
I've got no mapbox experience, but basing on this documentation page, i came up with following;

You need to create your features collection (array) within for loop, like that:

var featureCollection = []; // Initialize empty collection

// Your longLat collection
var longLat = [
  [53.515333, -6.190796],
  [53.342686, -6.403656],
  [51.678091, -9.624023],
  [52.768293, -1.560059]
];

// for every item object within longLat
for(var itemIndex in longLat) {
  // push new feature to the collection
  featureCollection.push({
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": longLat[itemIndex]
    },
    "properties": {
      "title": "Mapbox DC",
      "icon": "monument"
    }
  });
}

Try if you can skip the properties (icon and title). For now they are hardcoded.

Then, you pass them to the map itself this way:

map.on('load', function () {
  map.addLayer({
    "id": "points",
    "type": "symbol",
    "source": {
    "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": featureCollection
      }
    },
    "layout": {
      "icon-image": "{icon}-15",
      "text-field": "{title}",
      "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
      "text-offset": [0, 0.6],
      "text-anchor": "top"
    }
  });
});

I'm not sure what all of the things mean (like layout with all icons for example), but that's just taken from the mentioned example, so it should not break anything.


问:
Is it possible to have scala Future execute a mapping action in the same thread, like Java CompletableFuture?
In Java it is possible to do:

```<code>CompletableFuture<Integer> e = new CompletableFuture<Integer>();
e = e.thenApply(x -> x * 2);
e.complete(12);
</code>```

in this scenario the function in thenApply will run in the thread that is calling e.complete see thenApply

In Scala I noticed that all manipulation functions for the future have an ExecutionContext as argument, so I assume map (that does the same as thenApply) will send another task to the execution context.

How can I get the same behaviour of a Java CompletableFuture with non Async methods?

答:
Yes, this is possible in priciple. In fact, scala's ExecutionContext -- as opposed to java's thread pools -- abstracts over where you code is run and doesn't force you to schedule it on a thread of a certain thread pool. Instead, it could as well be the current thread. This is typically referred to as a tramplined execution context.

For example the play framework defines one: https://github.com/playframework/playframework/blob/38abd1ca6d17237950c82b1483057c5c39929cb4/framework/src/play-streams/src/main/scala/play/api/libs/streams/Execution.scala#L31

However, before implementing this, you should really be sure you know what you're doing and you really need this. In fact, the play framework has decided not to expose it, because it's too easy to shoot in one's foot with it:

So... given that trampoline is not widely known and won't lead to performance advantages for users, closing.

Source: https://github.com/playframework/playframework/issues/6390

A similar discussion happened on the scala-interals mailing list, where the debate was whether to add one to the scala standard library. In the end, the reservations were similar:

We have hesitated in exposing it as a general thing since it can very easily wreak having for synchronous implementations.

Source: https://groups.google.com/forum/#!msg/scala-internals/QgtKugpqUlk/llVXveEuFAAJ

Also note that there are alternative implementations that might help if you're writing performance-sensitive / concurrent code, such as monix: https://monix.io/api/3.0/

Body:
In Java it is possible to do:

CompletableFuture<Integer> e = new CompletableFuture<Integer>();
e = e.thenApply(x -> x * 2);
e.complete(12);

in this scenario the function in thenApply will run in the thread that is calling e.complete see thenApply

In Scala I noticed that all manipulation functions for the future have an ExecutionContext as argument, so I assume map (that does the same as thenApply) will send another task to the execution context.

How can I get the same behaviour of a Java CompletableFuture with non Async methods?


问:
Validate html form with javascript after html automatic validation
I have to make a little form with some fields like name, age or email. For example:

```<code><input id="name" type="text" required/>
</code>```

I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:

```<code><input type="submit" value="Submit" onclick="form.validate()" />
</code>```

The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:

```<code>"use strict";
class Form {
    constructor(){}
    validate(){
        alert("validate");
    }
}
var form = new Form();
</code>```

The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?

答:
You need to use the directive ng-submit in your form:

```<code><form ng-submit="form.validate()" ng-controller="YourController">
   <input type="text" ng-model="text" name="text" />
   <input type="submit" id="submit" value="Submit" />
</form>
</code>```

https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action

Keep Rocking!

Body:
I have to make a little form with some fields like name, age or email. For example:

<input id="name" type="text" required/>

I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:

<input type="submit" value="Submit" onclick="form.validate()" />

The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:

"use strict";
class Form {
    constructor(){}
    validate(){
        alert("validate");
    }
}
var form = new Form();

The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?

Body:
You need to use the directive ng-submit in your form:

<form ng-submit="form.validate()" ng-controller="YourController">
   <input type="text" ng-model="text" name="text" />
   <input type="submit" id="submit" value="Submit" />
</form>

https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action

Keep Rocking!


问:
What file does FromFile pull from?
This is my first time trying to use images in my code. I cannot figure out what file the FromFile command pulls from.

```<code>firstDice.Image = Image.FromFile(fDice.ToString() + ".png");
</code>```

I am trying to get the image to correspond with whatever the random number fDice is.

Here is my error message:

System.IO.FileNotFoundException: '5.png'

答:
Environment.CurrentDirectory

As Steve says in his comment, you must specify the full path otherwise.

You can use Path.Combine to create a path based on the current working directory. Such as:

```<code>Path.Combine(Environment.CurrentDirectory, "Images");
</code>```

Title: What file does FromFile pull from?

Body:
This is my first time trying to use images in my code. I cannot figure out what file the FromFile command pulls from.

firstDice.Image = Image.FromFile(fDice.ToString() + ".png");

I am trying to get the image to correspond with whatever the random number fDice is.

Here is my error message:

System.IO.FileNotFoundException: '5.png'

Body:
Environment.CurrentDirectory

As Steve says in his comment, you must specify the full path otherwise.

You can use Path.Combine to create a path based on the current working directory. Such as:

Path.Combine(Environment.CurrentDirectory, "Images");


问:
cobalt: When StorageManager calling destructor , there is task in last_change_timer_ or change_max_delay_timer_ ,it maybe be discarded
I found that StorageManager would call FinishIO and OnDestroy when it call destructor. It will wait sql_message_loop and savegame_thread_ completed in  FinishIO, and reset resources include flush_on_last_change_timer_ and flush_on_change_max_delay_timer_. So if there is a task in flush_on_last_change_timer_ or flush_on_change_max_delay_timer_ when iStorageManager calling destructor, it maybe discard this task and lead to last savegame operate miss. Is it a problem or I don`t understand right.</p>

答: Thanks for pointing this out. I believe that you are correct; it does appear that the last save can fail to occur if the StorageManager is destructed before the timer goes off. This will be fixed in later versions of Cobalt.</p>


问:
split columns into multiple columns
i have been struggled with how to split multiple columns into multiple columns using R but with no result, i have tried many tricks on Stackoverflow and it doesn't work. here is my probleme :

```<code>reactions__001 reactions__002 reactions__003
25 Like        23 Love
15 Like        5 Love         3 Haha
20 Haha        3 Sad          2 Angry
</code>```

now what i am looking for is to split this data frame like this one

```<code>Like Love Haha Sad Angry
25   23   0    0   0
15   5    3    0   0
0    0    20   3   2
</code>```

i have tried the str_split_fixed(df$reactions__001, " ", 2)   but it gives me something like :

```<code> [26,] "1"  "Angry"
 [27,] "3"  "Like"
 [28,] "0"  ""
 [29,] ""   ""
 [30,] "1"  "Like"
 [31,] "10" "Like"
</code>```

答:
```<code>xx$id = 1:nrow(xx)
library(tidyr)
library(dplyr)
xxlong = gather(xx, key = "key", value = "value",-id)
xxlong = separate(xxlong, value, into = c("num", "attr"))
xxlong %>% na.omit %>% select(-key) %>%
    spread(key = attr, value = num, fill = 0)
#   id Angry Haha Like Love Sad
# 1  1     0    0   25   23   0
# 2  2     0    3   15    5   0
# 3  3     2   20    0    0   3
</code>```

I'll leave the reordering of the columns to you.

Using this data:

```<code>xx = read.table(text = "reactions__001 reactions__002 reactions__003
'25 Like'        '23 Love'
'15 Like'        '5 Love'         '3 Haha'
'20 Haha'        '3 Sad'          '2 Angry'  ", header = T, fill = T)
</code>```

Title: split columns into multiple columns

Body:
i have been struggled with how to split multiple columns into multiple columns using R but with no result, i have tried many tricks on Stackoverflow and it doesn't work. here is my probleme :

reactions__001 reactions__002 reactions__003
25 Like        23 Love
15 Like        5 Love         3 Haha
20 Haha        3 Sad          2 Angry

now what i am looking for is to split this data frame like this one

Like Love Haha Sad Angry
25   23   0    0   0
15   5    3    0   0
0    0    20   3   2

i have tried the str_split_fixed(df$reactions__001, " ", 2)   but it gives me something like :

 [26,] "1"  "Angry"
 [27,] "3"  "Like"
 [28,] "0"  ""
 [29,] ""   ""
 [30,] "1"  "Like"
 [31,] "10" "Like"

Body:
xx$id = 1:nrow(xx)
library(tidyr)
library(dplyr)
xxlong = gather(xx, key = "key", value = "value",-id)
xxlong = separate(xxlong, value, into = c("num", "attr"))
xxlong %>% na.omit %>% select(-key) %>%
    spread(key = attr, value = num, fill = 0)
#   id Angry Haha Like Love Sad
# 1  1     0    0   25   23   0
# 2  2     0    3   15    5   0
# 3  3     2   20    0    0   3

I'll leave the reordering of the columns to you.

Using this data:

xx = read.table(text = "reactions__001 reactions__002 reactions__003
'25 Like'        '23 Love'
'15 Like'        '5 Love'         '3 Haha'
'20 Haha'        '3 Sad'          '2 Angry'  ", header = T, fill = T)


问:
add watch on a non scope variable in angularjs
Is there a way to add watch to a non scope variable. I want to add a watch to local variable. I have something like this

```<code> function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
        var vm = this;
        vm.manufacturers = [];
        vm.projects = [];
        vm.asset_types = [];
        vm.ch_group_uniq = 'none';
}
</code>```

here is there a way to add watch to vm.ch_group_uniq?
I know how it will be done with scope variable but I have scenarios where I have to check many complex variables.

答:
A cleaner syntax using ES6</p>

```<code>$scope.$watch(() => {
    return this.thingToWatch;
}, (newVal, oldVal) => {
    // Your code here...
});
</code>```

Body:
Is there a way to add watch to a non scope variable. I want to add a watch to local variable. I have something like this

 function EditAssetRegistryController(assetregistryService, manufacturerService, assettypeService, projectService, $localStorage, $routeParams) {
        var vm = this;
        vm.manufacturers = [];
        vm.projects = [];
        vm.asset_types = [];
        vm.ch_group_uniq = 'none';
}

here is there a way to add watch to vm.ch_group_uniq?
I know how it will be done with scope variable but I have scenarios where I have to check many complex variables.

Body:
A cleaner syntax using ES6

$scope.$watch(() => {
    return this.thingToWatch;
}, (newVal, oldVal) => {
    // Your code here...
});


问:
General Android Memory leaks and specifically google analytics tracker
I have a couple quick questions. They all deal with 1 general topic, and one strategy may take care of everything, so I hope that its ok I put them under the same topic.

I have had trouble finding solid info on garbage collection, so would appreciate any help, I think perhaps I don't fully understand what I am reading in the MAT. Even if you can answer 1 question I would be super happy

What is the best strategy for finding memory leaks in Android? As best I can tell it is to get the Eclipse MAT, picking an object that isn't getting garbage collected (using the dominator tree, or whatever is easiest for you to find it with), and displaying the shortest merged paths to the gc of that object and find the furthest incoming reference to that object that you can control and killing that reference on destroy. This works to kill the references, but sometimes the object still doesn't get garbage collected

Is it good practice to null all of your handlers/runnables/threads/listeners on destroy? Some of these seem to stick around indefinitely if I don't, and sometimes even if I do.

What is the best way to ensure that a thread gets garbage collected, even if the reference is nulled (they seem to stick around sometimes)?

Why oh why can't I get the google analytics tracker to get garbage collected, even though it has no reference from my application at all. It seems to maintain a reference to my activity, so I think that might have something to do with my GC problems.

Thanks you!

答:
The best strategy is to fully understand the implications of what you are doing from the beginning, and thus avoid memory leaks in the first place.  See, for example, handling memory leaks in Java.  Otherwise, that seems like a fine approach along with code inspection.  Are you forcing a GC to prove that the object still isn't collected?

In general, no.  This article has a good explanation as to why.

Don't hold any references to it?  Follow standard coding practices as described above.

Don't know.  But wouldn't you be using it throughout your application, so it doesn't really matter?  Eventually Android will kill your whole process and reclaim the memory anyways.


问:
How to load Table View in Main View Controller before segueing
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

```<code>public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}
</code>```

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.

答: Try putting the API call in the ViewDidAppear Method of the Table View Controller Class. That way the app will segue to the View Controller then call the data. The app will appear faster but take the same amount of time. This way you can also manage timeouts and default data for the ViewDidLoad.</p>

Body:
Working on Swift 3 Xcode 9.1

I have two view controllers (one MainView and one Table View)

Problem: The Table View loads data from an API and displays it, however it take too long. I'm trying to have the load occur on the Main Controller.

I tried creating a custom method How to instantiate and load a view controller before segueing to it using swift

However the Table View has too many functions and I'm not sure how to call it.

Table View Code:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cell
}

func loadData(){
 //loads data
 DispatchQueue.main.sync(execute:{
    self.tableView.reloadData()
}

Question: Is creating a custom method the best way or is there another way? Please note I'm trying to do all this is the Main View Controller so the data can load once I segue to the Table View.


问:
Firebase Analytics not working with Instant App or Normal App
I have an app that is modularized to support instant-apps.

App modules:

app

instantapp

base

main

detail

search

I tried to add Firebase by adding:

classpath 'com.google.gms:google-services:3.1.1' → to the Project Level build.gradle

api "com.google.firebase:firebase-core:${versions.firebase}" → to the Base Module

apply plugin: 'com.google.gms.google-services' → to the bottom of the Base Module

google-services.json → to the base module folder

When I run the non-instant app I receive the following errors:

I/FirebaseInitProvider: FirebaseApp initialization unsuccessful

E/FA: GoogleService failed to initialize, status: 10, Missing google app id value from from string resources with name google_app_id.

I/FA: App measurement is starting up, version: 11720

I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE

I/FA: To enable faster debug mode event logging run:
          adb shell setprop debug.firebase.analytics.app com.punpuf.chacaraselazer.app

E/FA: Missing google_app_id. Firebase Analytics disabled. See https://goo(...)

E/FA: Uploading is not possible. App measurement disabled

I/FA: Tag Manager is not found and thus will not be used

And when I run the instant app I receive the following error:

V/FA: Cancelling job. JobID: 1799580119

E/FirebaseApp: Firebase API initialization failure. (...) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void android.app.job.IJobScheduler.cancel(int)' on a null object reference

I/FirebaseInitProvider: FirebaseApp initialization successful

If I add the following line: "FirebaseAnalytics.getInstance(this)", not only does it receive the previous errors, it also crashes:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.punpuf.chacaraselazer.app, PID: 11273 java.lang.RuntimeException: Unable to start activity ComponentInfo{(...)}: java.lang.NullPointerException: Attempt to invoke interface method 'void android.app.job.IJobScheduler.cancel(int)' on a null object reference

So my question is how can I get Firebase Analytics to work, and not crash on both my instant and non-instant version of my app.

Although this question is a bit similar to FirebaseApp initialization unsuccessful in Android Instant apps , mine not contain the same type of errors.

Update:
I've created a new Firebase Project, and updated my google-services.json, but still didn't work.

Here are my gradle files:

project: https://gist.github.com/Punpuf/8582fa3610a1c3dea13627e1207a6064

app: https://gist.github.com/Punpuf/2104ffe0c90927cb79944860a7cb6c46

instantapp: https://gist.github.com/Punpuf/233d96e91293a2a14e8fdf50092edd2d

base: https://gist.github.com/Punpuf/e1646f67d8a6094773c390d2df209eae

main: https://gist.github.com/Punpuf/f8bdd8789b11d274afdb1c51f490ed25

detail: https://gist.github.com/Punpuf/0a4f87b4fb512557ffe6cd110ce667de

search: https://gist.github.com/Punpuf/455e28b38baad23294dda6c9592586a2

I've also tried replacing firebase analytics dependency with firebase messaging and I still received the "FirebaseApp initialization unsuccessful" error.

答: I've had the same problem, I solved it adding the google-services.json to both base and app module and applying the google services plugin in both build.gradle files</p>


问:
javascript post request not seen by server
I am trying to do a simple post from javascript to php, and am not getting data to transfer.  I'm using Apache2 on Ubuntu.  If I run the php code in Mozilla, it does what I've asked, but when called from javascript php does not seem to get the info to php on the server side.  I've tried to simplify the code to focus on just the post function.  Here is the html code:

```<code><!doctype html>
<html>
<head>
<title>Post Test </title>
</head>
<body>

<p id="demo"></p>

<script>
    var http = new XMLHttpRequest();
    var url = "post_test.php";
    var file_data = "text string";
    http.open("POST", url, true);
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200){
          document.getElementById('demo').innerHTML=this.responseText
        };
    }
http.send(file_data);
</script>
</body>
</html>
</code>```

Here is the php:

```<code><?php
var_dump(isset($_POST['file_data']));
?>
</code>```

I get a bool(false) message on the screen.
I checked the file access.  Both files are set rwx for all.
I am trying to learn html,javascript, and php.  I'd like to hold off on jQuery until I can do more.

答:
You should indicate in the data which field name it should go under. In your case it is file_data.

```<code>var myData = "file_data=foo";
http.send(myData);
</code>```

Then your php

```<code><?php
   var_dump(isset($_POST['file_data']));
?>
</code>```

Body:
I am trying to do a simple post from javascript to php, and am not getting data to transfer.  I'm using Apache2 on Ubuntu.  If I run the php code in Mozilla, it does what I've asked, but when called from javascript php does not seem to get the info to php on the server side.  I've tried to simplify the code to focus on just the post function.  Here is the html code:

<!doctype html>

<title>Post Test </title>

Here is the php:

<?php
var_dump(isset($_POST['file_data']));
?>

I get a bool(false) message on the screen.
I checked the file access.  Both files are set rwx for all.
I am trying to learn html,javascript, and php.  I'd like to hold off on jQuery until I can do more.

Body:
You should indicate in the data which field name it should go under. In your case it is file_data.

var myData = "file_data=foo";
http.send(myData);

Then your php

<?php
   var_dump(isset($_POST['file_data']));
?>


问:
cannot find -lgtest when setting up Google Test
I'm using Google Test for C++ and trying to set it up on my linux machine.
My make file has the following code:

```<code>CC=g++
CFLAGS=-I $(GOOGLETESTDIR)/include -L $(GOOGLETESTDIR)/lib -lgtest -lpthread -Wall
DEPS=fib.h
OBJS=fib.o main.o

all: | r6

clean:
    -rm -f r6 $(OBJS)

%.o: %.cpp $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

r6: $(OBJS)
    $(CC) -o $@ $^ $(CFLAGS)
.PHONY: all clean
</code>```

I get the error when I run make:

```<code>/usr/bin/ld: cannot find -lgtest
</code>```

How do I fix this? I'm new to this kind of testing and rather new to linux so I'm really lost.

答:
I had this issue on Ubuntu 17.10 and basically what Alexander says is true.

Someone wrote a nice tutorial with explicit commands that can be found at https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/

It boils down to:

```<code>sudo apt install libgtest-dev cmake
cd /usr/src/gtest
sudo cmake CMakeLists.txt
sudo make
sudo cp *.a /usr/lib
</code>```

Personally, I would appreciate a solution that did not manually move files into /usr/lib, but on the plus side this works as-is.

Body:
I'm using Google Test for C++ and trying to set it up on my linux machine.
My make file has the following code:

CC=g++
CFLAGS=-I $(GOOGLETESTDIR)/include -L $(GOOGLETESTDIR)/lib -lgtest -lpthread -Wall
DEPS=fib.h
OBJS=fib.o main.o

all: | r6

clean:
    -rm -f r6 $(OBJS)

%.o: %.cpp $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

r6: $(OBJS)
    $(CC) -o $@ $^ $(CFLAGS)
.PHONY: all clean

I get the error when I run make:

/usr/bin/ld: cannot find -lgtest

How do I fix this? I'm new to this kind of testing and rather new to linux so I'm really lost.

Body:
I had this issue on Ubuntu 17.10 and basically what Alexander says is true.

Someone wrote a nice tutorial with explicit commands that can be found at https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/

It boils down to:

sudo apt install libgtest-dev cmake
cd /usr/src/gtest
sudo cmake CMakeLists.txt
sudo make
sudo cp *.a /usr/lib

Personally, I would appreciate a solution that did not manually move files into /usr/lib, but on the plus side this works as-is.


问:
React - Child Components as Behaviors?
I'm trying to inject capabilities into a parent component via child decorators.  For example,

```<code><OpenLayers>
    <GeoJsonLayer url="https://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</OpenLayers>
</code>```

I'm having to use a context to do it, but I'm interpreting that as a warning sign, since there are many places that say, 'if you're using context you're probably doing something wrong'.  It seems like child.props.parent should already exist but, again, the fact that I'm looking for that must be another warning sign.

Perhaps it's the parent's responsibility to iterate through it's children and invoke methods on them that modify themselves?  But where would that be done?
 How to get access to the component instance?

How can a child modify its parent without the parent having explicit knowledge of the child?  I'm looking for existing pattern that allows child components to modify the behavior of the parent component that don't invoke using "context".

Here are the two approaches I've tried so far.  The first seems to be better design but the second allows me to extend the  capabilities via introducing child components (e.g. ):

```<code>    // one alternative is to not use child components but properties...
    this.props.geoJsonUrl && GeoJsonLayer.addGeoJsonLayer(map, this.props.geoJsonUrl);

    // another is to use child components and pass parent to a handler..
    Children.forEach(this.props.children, c => {
        c;
        if (typeof c === "string") return;
        if (typeof c === "number") return;
        let child: any = c;
        if (child.type === GeoJsonLayer) {
            GeoJsonLayer.addGeoJsonLayer(map, c.props.url);
        }
    });

    // I would prefer that the child trigger a cascading event that the parent could receive
    // and process
</code>```

Using props only:

```<code>        <OpenLayers
            orientation={orientation}
            controls={{ mousePosition: true }}
            bingImagerySet="AerialWithLabels"
            labels={true}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            geoJsonUrl="http://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</code>```

Using child:

```<code>        <OpenLayers
            orientation={orientation}
            controls={{ zoom: true, zoomToExtent: true }}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            osm={false}>
            <GeoJsonLayer url="http://openlayers.org/en/master/examples/data/geojson/countries.geojson" />
        </OpenLayers>
</code>```

答:
You could pass a prop onMount to the child component that takes a function. Then, in the child's componentDidMount() you could call this function. This basic principal stands for any communication from child to parent. You implement a property that receives a handler for some event, then call that handler when the event occurs.

Edit: After looking again, I think I understand the desired use case better.

You want to allow users of the OpenLayers component the ability to pick and choose layers in a compositional way, and not have to worry about the wiring up of the actual layers in the parent.

You could transparently pass an interface-like object to the children that is implemented by the parent. This property would get added when rendering the child component.

```<code>class OpenLayers extends React.Component {
  constructor(props) {
    super(props);
    this.state = { };
    this.layerApi = {
      setupGeoJsonLayer: ({ url }) => // do something with state etc.
    };
  }

  render() {
    const { layerApi } = this;
    const { children } = this.props;
    return (
      <div>
        {
          !children ? null : React.Children(children, child =>
            React.cloneElement(child, { layerApi }))
        }
      </div>
    )
  }
}

class GeoJsonLayer extends React.Component {
  componentDidMount() {
    this.props.layerApi.setupGeoJsonLayer(this.props);
  }

  componentWillReceiveProps(next) {
    if (next.props.url !== this.props.url)
      this.props.layerApi.setupGeoJsonLayer(next.props);
  }

  render() {
    // what is rendered here?
  }
}
</code>```

Now each layer would have the means of manipulating the parent according to the parent's API passed down in the props.

You would have to make sure the parent OpenLayers triggers its render cycle accordingly. Also, each layer would most likely have an empty render() method because they rely on the parent to render content and are only there to modify the render output of the parent. For these reasons, I think the props only approach might be better.

Title: React - Child Components as Behaviors?

Body:
I'm trying to inject capabilities into a parent component via child decorators.  For example,

<OpenLayers>
    <GeoJsonLayer url="https://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>
</OpenLayers>

I'm having to use a context to do it, but I'm interpreting that as a warning sign, since there are many places that say, 'if you're using context you're probably doing something wrong'.  It seems like child.props.parent should already exist but, again, the fact that I'm looking for that must be another warning sign.

Perhaps it's the parent's responsibility to iterate through it's children and invoke methods on them that modify themselves?  But where would that be done?
 How to get access to the component instance?

How can a child modify its parent without the parent having explicit knowledge of the child?  I'm looking for existing pattern that allows child components to modify the behavior of the parent component that don't invoke using "context".

Here are the two approaches I've tried so far.  The first seems to be better design but the second allows me to extend the  capabilities via introducing child components (e.g. ):

    // one alternative is to not use child components but properties...
    this.props.geoJsonUrl && GeoJsonLayer.addGeoJsonLayer(map, this.props.geoJsonUrl);

    // another is to use child components and pass parent to a handler..
    Children.forEach(this.props.children, c => {
        c;
        if (typeof c === "string") return;
        if (typeof c === "number") return;
        let child: any = c;
        if (child.type === GeoJsonLayer) {
            GeoJsonLayer.addGeoJsonLayer(map, c.props.url);
        }
    });

    // I would prefer that the child trigger a cascading event that the parent could receive
    // and process

Using props only:

        <OpenLayers
            orientation={orientation}
            controls={{ mousePosition: true }}
            bingImagerySet="AerialWithLabels"
            labels={true}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            geoJsonUrl="http://openlayers.org/en/master/examples/data/geojson/countries.geojson"/>

Using child:

        <OpenLayers
            orientation={orientation}
            controls={{ zoom: true, zoomToExtent: true }}
            setCenter={setCenter}
            center={this.state.center}
            zoom={this.state.zoom}
            osm={false}>
            <GeoJsonLayer url="http://openlayers.org/en/master/examples/data/geojson/countries.geojson" />
        </OpenLayers>

Body:
You could pass a prop onMount to the child component that takes a function. Then, in the child's componentDidMount() you could call this function. This basic principal stands for any communication from child to parent. You implement a property that receives a handler for some event, then call that handler when the event occurs.

Edit: After looking again, I think I understand the desired use case better.

You want to allow users of the OpenLayers component the ability to pick and choose layers in a compositional way, and not have to worry about the wiring up of the actual layers in the parent.

You could transparently pass an interface-like object to the children that is implemented by the parent. This property would get added when rendering the child component.

class OpenLayers extends React.Component {
  constructor(props) {
    super(props);
    this.state = { };
    this.layerApi = {
      setupGeoJsonLayer: ({ url }) => // do something with state etc.
    };
  }

  render() {
    const { layerApi } = this;
    const { children } = this.props;
    return (
      <div>
        {
          !children ? null : React.Children(children, child =>
            React.cloneElement(child, { layerApi }))
        }
      </div>
    )
  }
}

class GeoJsonLayer extends React.Component {
  componentDidMount() {
    this.props.layerApi.setupGeoJsonLayer(this.props);
  }

  componentWillReceiveProps(next) {
    if (next.props.url !== this.props.url)
      this.props.layerApi.setupGeoJsonLayer(next.props);
  }

  render() {
    // what is rendered here?
  }
}

Now each layer would have the means of manipulating the parent according to the parent's API passed down in the props.

You would have to make sure the parent OpenLayers triggers its render cycle accordingly. Also, each layer would most likely have an empty render() method because they rely on the parent to render content and are only there to modify the render output of the parent. For these reasons, I think the props only approach might be better.


问:
Reset random number stream
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

```<code>data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;
</code>```

Output:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586
</code>```

I would like the output to be:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
</code>```

答:
You could work around this using generated code, though, with CALL EXECUTE or perhaps DOSUBL, for example:

```<code>data _null_;
  do i = 1 to 2;
    rc=dosubl(cats("data want_",i,";
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    i=",i,";
    put _all_;
    output;
    run;
    "));
  end;
  rc = dosubl("data want; set want_1 want_2; run;");
run;
</code>```

Obviously easier/better to write a macro to do this part.

This is a limitation unfortunately of the 'new' RAND routine; the old one was much easier to work with in this regard (as it actually truly had just one seed).  The new one's seed properties are more complex, and so while you can initialize it with a single number, it's not as straightforward, hence the complications.

Title: Reset random number stream

Body:
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;

Output:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586

I would like the output to be:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207

Body:
You could work around this using generated code, though, with CALL EXECUTE or perhaps DOSUBL, for example:

data _null_;
  do i = 1 to 2;
    rc=dosubl(cats("data want_",i,";
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    i=",i,";
    put _all_;
    output;
    run;
    "));
  end;
  rc = dosubl("data want; set want_1 want_2; run;");
run;

Obviously easier/better to write a macro to do this part.

This is a limitation unfortunately of the 'new' RAND routine; the old one was much easier to work with in this regard (as it actually truly had just one seed).  The new one's seed properties are more complex, and so while you can initialize it with a single number, it's not as straightforward, hence the complications.