问:
How do I access a value of a Blob?
I have a Blob object.  When I console.log it, the result is:

```<code>Blob {
  [Symbol(type)]: 'image/jpeg',
  [Symbol(buffer)]: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 01 0e 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 08 01 06 00 03 00 00 00 01 00 02 ... 956836 more bytes>
}
</code>```

How do I access that buffer?

答:
You can use stream, arrayBuffer or text.

See https://developer.mozilla.org/en-US/docs/Web/API/Blob#Methods

Example

```<code>blob.text().then(x => console.log(x));
</code>```

Title: How do I access a value of a Blob?

Body:
I have a Blob object.  When I console.log it, the result is:

Blob {
  [Symbol(type)]: 'image/jpeg',
  [Symbol(buffer)]: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 01 0e 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 08 01 06 00 03 00 00 00 01 00 02 ... 956836 more bytes>
}

How do I access that buffer?

Body:
You can use stream, arrayBuffer or text.

See https://developer.mozilla.org/en-US/docs/Web/API/Blob#Methods

Example

blob.text().then(x => console.log(x));


来源: stackexchange

问:
Cannot Connect subdomain of route 53 to ec2 node js app

But It's working fine with public IP as below

And I have created a subdomain with route 53 and then assigned A record with instance public IP
But when I ping the domain and IP it's getting request time out and all packets were lost. My application is node express app.So please it's a huge favor if anyone can solve this issue.

答:
From your screenshot, I found that you're using Nginx as a Reverse proxy. So it might be because of your Nginx config

example your Nginx config may look like this,

```<code>server {
    listen 80;
    server_name 192.168.1.21;
    ...
}
</code>```

you've to update it to:

```<code>server {
     listen 80;
     server_name subdomain.domain.com;
     ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
From your screenshot, I found that you're using Nginx as a Reverse proxy. So it might be because of your Nginx config

example your Nginx config may look like this,

server {
    listen 80;
    server_name 192.168.1.21;
    ...
}

you've to update it to:

server {
     listen 80;
     server_name subdomain.domain.com;
     ...
}


问:
Selecting one row from MySQL using mysql_* API
I have the following query:

```<code>$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
print_r ($row);
</code>```

and the output I am getting is:

Resource id #2

Ultimately, I want to be able to echo out a single field like so:

```<code>$row['option_value']
</code>```

Without having to use a while loop, as since I am only trying to get one field I do not see the point.

I have tried using mysql_result with no luck either.

Where am I going wrong?

答:
Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended  method now. You should consider PDO with better security solutions.

```<code>$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];
</code>```

Body:
I have the following query:

$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
print_r ($row);

and the output I am getting is:

Resource id #2

Ultimately, I want to be able to echo out a single field like so:

$row['option_value']

Without having to use a while loop, as since I am only trying to get one field I do not see the point.

I have tried using mysql_result with no luck either.

Where am I going wrong?

Body:
Functions mysql_ are not supported any longer and have been removed in PHP 7. You must use mysqli_ instead. However it's not recommended  method now. You should consider PDO with better security solutions.

$result = mysqli_query($con, "SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysqli_fetch_assoc($result);
echo $row['option_value'];


问:
Last Modified Date of a file on a web site
Is there a way to get the Last-Modified-Date of a file on a Web Site?

i.e. Here is an example file I have out there:
http://www.ymcadetroit.org/atf/cf/%7B2101903E-A11A-4532-A64D-9D823368A605%7D/Birmingham_Youth_Sports_Parent_Manual.pdf

答:
In php:</p>

```<code>print getlastmod();
print gmdate('D, d M Y H:i:s', getlastmod());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In php:

print getlastmod();
print gmdate('D, d M Y H:i:s', getlastmod());


问:
What to pass to aggfunc in pandas pivot table for summing up counters
I have a data table with two columns "A" and "B", and the elements in column "B" are counters. For example,

```<code>c = Counter(a=4, b=2)
df = pd.DataFrame({"A": ["group1", "group1", "group1", "group2", "group2"],
                   "B": [c, c, c, c, c]})
</code>```

I would like to create a pivot table, where I group over element values in column "A" and aggregate over column "B" by adding up the counters. I wonder what should I pass to aggfunc?

This is what I have tried, but sadly it does not work:

```<code>pt = pd.pivot_table(df, index = ['A'], values = ['B'], aggfunc = ['+'])
</code>```

Any suggestions?

My expected output is

```<code>table
  group1  Counter(a=12, b=6)   # i.e., c+c+c
  group2  Counter(a=8, b=4)    # i.e., c+c
</code>```

答:
It's just sum.

```<code>>>> df.groupby('A')['B'].sum()
A
group1    {'a': 12, 'b': 6}
group2     {'a': 8, 'b': 4}
Name: B, dtype: object
</code>```

Two notes:

Putting dictionaries into dataframe columns is usually not a good practice. I would use two columns to hold the value for 'a' and 'b' respectively.

"B": [c, c, c, c, c] initializes each element of column 'B' with the same counter object.

Demo:

```<code>>>> df.loc[0, 'B']['a'] = 100
>>> df
Out[9]:
        A                   B
0  group1  {'a': 100, 'b': 2}
1  group1  {'a': 100, 'b': 2}
2  group1  {'a': 100, 'b': 2}
3  group2  {'a': 100, 'b': 2}
4  group2  {'a': 100, 'b': 2}
</code>```

You might want "B": [c.copy() for _ in range(5)] - if you want to keep your original design at all, that is.

Body:
I have a data table with two columns "A" and "B", and the elements in column "B" are counters. For example,

c = Counter(a=4, b=2)
df = pd.DataFrame({"A": ["group1", "group1", "group1", "group2", "group2"],
                   "B": [c, c, c, c, c]})

I would like to create a pivot table, where I group over element values in column "A" and aggregate over column "B" by adding up the counters. I wonder what should I pass to aggfunc?

This is what I have tried, but sadly it does not work:

pt = pd.pivot_table(df, index = ['A'], values = ['B'], aggfunc = ['+'])

Any suggestions?

My expected output is

table
  group1  Counter(a=12, b=6)   # i.e., c+c+c
  group2  Counter(a=8, b=4)    # i.e., c+c

Body:
It's just sum.

>>> df.groupby('A')['B'].sum()
A
group1    {'a': 12, 'b': 6}
group2     {'a': 8, 'b': 4}
Name: B, dtype: object

Two notes:

Putting dictionaries into dataframe columns is usually not a good practice. I would use two columns to hold the value for 'a' and 'b' respectively.

"B": [c, c, c, c, c] initializes each element of column 'B' with the same counter object.

Demo:

>>> df.loc[0, 'B']['a'] = 100
>>> df
Out[9]:
        A                   B
0  group1  {'a': 100, 'b': 2}
1  group1  {'a': 100, 'b': 2}
2  group1  {'a': 100, 'b': 2}
3  group2  {'a': 100, 'b': 2}
4  group2  {'a': 100, 'b': 2}

You might want "B": [c.copy() for _ in range(5)] - if you want to keep your original design at all, that is.


问:
Why does my apps icon disappear after an ad hoc install (iPhone)
I have an app that I'm trying to install via standard OTA ad hoc. On iOS 4.1 The app installs ok. On newer versions (4.3.1 and 4.3.3 tested) the app installs without error, but the icon disappears from Springboard when the install is done. If I restart the device the icon is back.

I have two questions:

Does anyone know what causes this behaviour?

Is this a problem when it comes to App
Store submission?

Edit: It's the whole icon that disappears, not just the graphics. It is not possible to start the app from Springboard.

答:
I think this question is similar to this one:

In-House App Disappears After Install

Give it a try, maybe it helps...

ContentLicense: CC BY-SA 3.0


问:
Android Studio - How to use getExternalFilesDir
Since google killed the perfectly fine method getExternalStoragePublicDirectory, I have to try to get getExternalFilesDir to work.

This is one of the things I've tried:

```<code>private Context context = this.getApplicationContext();
private static final String test = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
</code>```

error message:

```<code>Non-static field 'context' cannot be referenced from a static context
</code>```

I am not allowed to make context a static field though.

答:
what is this reference to your activity, if yes then use:

```<code>this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
</code>```

Body:
Since google killed the perfectly fine method getExternalStoragePublicDirectory, I have to try to get getExternalFilesDir to work.

This is one of the things I've tried:

private Context context = this.getApplicationContext();
private static final String test = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);

error message:

Non-static field 'context' cannot be referenced from a static context

I am not allowed to make context a static field though.

Body:
what is this reference to your activity, if yes then use:

this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);


问:
<ng-select>:MouseEvent.target.select() is not working when fire element.nativeElement.click()
I am not understanding why with mouseclick event ng-select dropdown input text is getting selected but while doing this.elementRef.nativeElement.click() not getting selected input text.()

1.working one

```<code><ng-select (click)="onClick($event)"></ng-select>
</code>```

2.Not working

```<code>constructor(public element:ElementRef){}

triggetClickEvent(){
   this.element.nativeElement.click();
}
</code>```

click event method:

```<code>onClick($event){
   $event.target.select();//while triggetClickEvent exception:$event.target.select is not a function
}
</code>```

Any help.

Thanks.

答:
Argument $event is a MouseEvent and onClick method is called after you click on dropdown not before that.

Changes to be done:

1.Add id, local ref and open event handler function.

```<code><ng-select id="element" #element (open)="onOpen()"...></ng-select>
</code>```

2.Use ViewChild to get element reference.

```<code>@ViewChild('element') element;
</code>```

3.code inside triggetClickEvent() and onOpen() functions.

```<code>triggetClickEvent(){
   let el = document.getElementById("element");
   el.classList.add("customCSSClass");
   this.element.focus();
}

onOpen() {
    let el = document.getElementById("element");
    el.classList.remove("customCSSClass");
}
</code>```

Note: I know it is not good practice to directly access DOM and I tried to use Renderer2 but focus event is not working with it somehow.

3.Add below css Refer Custom styles section of ng-select

```<code>.ng-select.ng-select-focused.customCSSClass  ::ng-deep .ng-value {
    background-color: blue;
}
.ng-select.ng-select-focused.customCSSClass ::ng-deep .ng-placeholder {
    background-color: blue ;
}
</code>```

You can find working code snippet here

Body:
I am not understanding why with mouseclick event ng-select dropdown input text is getting selected but while doing this.elementRef.nativeElement.click() not getting selected input text.()

1.working one

<ng-select (click)="onClick($event)"></ng-select>

2.Not working

constructor(public element:ElementRef){}

triggetClickEvent(){
   this.element.nativeElement.click();
}

click event method:

onClick($event){
   $event.target.select();//while triggetClickEvent exception:$event.target.select is not a function
}

Any help.

Thanks.

Body:
Argument $event is a MouseEvent and onClick method is called after you click on dropdown not before that.

Changes to be done:

1.Add id, local ref and open event handler function.

<ng-select id="element" #element (open)="onOpen()"...></ng-select>

2.Use ViewChild to get element reference.

@ViewChild('element') element;

3.code inside triggetClickEvent() and onOpen() functions.

triggetClickEvent(){
   let el = document.getElementById("element");
   el.classList.add("customCSSClass");
   this.element.focus();
}

onOpen() {
    let el = document.getElementById("element");
    el.classList.remove("customCSSClass");
}

Note: I know it is not good practice to directly access DOM and I tried to use Renderer2 but focus event is not working with it somehow.

3.Add below css Refer Custom styles section of ng-select

.ng-select.ng-select-focused.customCSSClass  ::ng-deep .ng-value {
    background-color: blue;
}
.ng-select.ng-select-focused.customCSSClass ::ng-deep .ng-placeholder {
    background-color: blue ;
}

You can find working code snippet here


答:
You can use from the following options

Using FileReader

var blobReader = new FileReader();

blobReader.onload = function() {
    alert(blobReader.result);
}

blobReader.readAsText(blob);

(OR)

const blobText = await new Response(blob).text();

Title: How do I access a value of a Blob?


问:
How to style angular material?
I want to use ngx-mat-intl-tel-input,  but I cannot set any style. . The button is taking 100% heigh everything gx-mat-intl-tel-input take 100% heigh.
here is my code:

.main {
    width: 400px;
    height: 500px;
    border: 1px solid blue;
    margin: 0 auto;
}

.phone {
    border: 1px solid black;
    margin: 300px;
}

ngx-mat-intl-tel-input>div>button {
    margin: 100px;
    background-color: green;
}

form {
    border: 1px solid black;
    width: 100%;
    background-color: green;
}

::ng-deep.mat-menu-panel {
    max-height: calc(100vh - 70vh);
}

.mat-button.mat-blue {
    color: blue;
}

.tp-button-row button,
.tp-button-row a {
    margin-right: 68px;
}

::ng-deep.mat-menu-panel {
    max-width: none !important;
}

::ng-deep ngx-mat-tel-input-container {
    width: 20px;
    border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<form #f=ngForm [formGroup]="phoneForm">
    <div>
        <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>
    </div>
</form></code>```

// app.component file

```<code>import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  phoneForm = new FormGroup({
    phone: new FormControl('', Validators.required)

  });

  get f() {
    return this.phoneForm.errors;
  }

  ngOnInit() {
    // initialization logic goes here

  }

}
</code>```

答:
Styling components don't work that way in Angular, as you have added.

```<code> <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>
</code>```

If you want to style the element, target first internal div or whatever parent element inside your ngx-mat-intl-tel-input, try to apply the styles to those classes.

If it still doesn't work, you can try setting encapsulation as ViewEncapsulation.None. But it has other side effects.
You can read more about it here.

Title: How to style angular material?

Body:
I want to use ngx-mat-intl-tel-input,  but I cannot set any style. . The button is taking 100% heigh everything gx-mat-intl-tel-input take 100% heigh.
here is my code:

.main {
    width: 400px;
    height: 500px;
    border: 1px solid blue;
    margin: 0 auto;
}

.phone {
    border: 1px solid black;
    margin: 300px;
}

ngx-mat-intl-tel-input>div>button {
    margin: 100px;
    background-color: green;
}

form {
    border: 1px solid black;
    width: 100%;
    background-color: green;
}

::ng-deep.mat-menu-panel {
    max-height: calc(100vh - 70vh);
}

.mat-button.mat-blue {
    color: blue;
}

.tp-button-row button,
.tp-button-row a {
    margin-right: 68px;
}

::ng-deep.mat-menu-panel {
    max-width: none !important;
}

::ng-deep ngx-mat-tel-input-container {
    width: 20px;
    border: 1px solid blue;
}

<form #f=ngForm [formGroup]="phoneForm">

        <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>

</form>

// app.component file

import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  phoneForm = new FormGroup({
    phone: new FormControl('', Validators.required)

  });

  get f() {
    return this.phoneForm.errors;
  }

  ngOnInit() {
    // initialization logic goes here

  }

}

Body:
Styling components don't work that way in Angular, as you have added.

 <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>

If you want to style the element, target first internal div or whatever parent element inside your ngx-mat-intl-tel-input, try to apply the styles to those classes.

If it still doesn't work, you can try setting encapsulation as ViewEncapsulation.None. But it has other side effects.
You can read more about it here.


问:
Calling stored procedure with return value
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

```<code>ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end
</code>```

Code calling the stored procedure:

```<code>SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();
</code>```

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.

答:
You need to add a ReturnValue-direction parameter to the command:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    // @ReturnVal could be any name
    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}
```

Setting the parameter's direction to ParameterDirection.ReturnValue instructs the SqlCommand to declare it as a variable and assign the stored procedure's return value to it (exec @ReturnValue = spMyProcedure...), exactly like you would write it in SQL.

Body:
I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.

Stored procedure code:

ALTER procedure [dbo].[usp_GetNewSeqVal]
      @SeqName nvarchar(255)
as
begin
      declare @NewSeqVal int
      set NOCOUNT ON
      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
print 'Sequence does not exist'
            return
      end

      return @NewSeqVal
end

Code calling the stored procedure:

SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();

SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter param = new SqlParameter();

param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";

SqlDataReader reader = cmd.ExecuteReader();

I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.

Body:
You need to add a ReturnValue-direction parameter to the command:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    // @ReturnVal could be any name
    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

Setting the parameter's direction to ParameterDirection.ReturnValue instructs the SqlCommand to declare it as a variable and assign the stored procedure's return value to it (exec @ReturnValue = spMyProcedure...), exactly like you would write it in SQL.


问:
Recursion sum numbers *with rule* - Recursion only
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

```<code>int[] a = {5,4,2,1,3};
</code>```

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

```<code>public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}
</code>```

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,

答:
First thing you can add is a check to see not 3 numbers in a row being added. Also replacing a number in the array with -1 would have unintended side effects within recursive calls. Below is something I have. You can ignore the index param I have used to see the values used.

Explanation:
The recursive sumRule method divides the problem into two parts:

First part takes the value of current index and adds with the sum of values starting from next index.

Second part assumes, current value can’t be taken for the sum. It only checks if there is a sum within the subset starting from next value of the array.

In the method, lastIndex is keeping track of the index of last value picked up for the sum. So, in the first call the value is 0, 1 in second and so on.

(start - lastIndex <= 1 ? consecutive + 1 : 1) is to check whether value of consecutive should be increased or not. consecutive = 1 means, current value is added to the sum.

```<code>  public static boolean sumRule(int[] a, int num) {
    if (num == 0) {
      return true;
    } else {
      return sumRule(a, num, 0, 0, 0, 0, "");
    }
  }

  public static boolean sumRule(final int[] a, int num, int sum, int start, int consecutive, int lastIndex,
      String index) {
    if (consecutive == 3) {
      return false;
    }

    if (sum == num) {
      System.out.println(index);
      return true;
    }

    if (start >= a.length) {
      return false;
    }

    return sumRule(a, num, sum + a[start], start + 1, (start - lastIndex <= 1 ? consecutive + 1 : 1), start,
        index + ", " + start) || sumRule(a, num, sum, start + 1, consecutive, lastIndex, index);
  }
</code>```

Body:
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

int[] a = {5,4,2,1,3};

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,

Body:
First thing you can add is a check to see not 3 numbers in a row being added. Also replacing a number in the array with -1 would have unintended side effects within recursive calls. Below is something I have. You can ignore the index param I have used to see the values used.

Explanation:
The recursive sumRule method divides the problem into two parts:

First part takes the value of current index and adds with the sum of values starting from next index.

Second part assumes, current value can’t be taken for the sum. It only checks if there is a sum within the subset starting from next value of the array.

In the method, lastIndex is keeping track of the index of last value picked up for the sum. So, in the first call the value is 0, 1 in second and so on.

(start - lastIndex <= 1 ? consecutive + 1 : 1) is to check whether value of consecutive should be increased or not. consecutive = 1 means, current value is added to the sum.

  public static boolean sumRule(int[] a, int num) {
    if (num == 0) {
      return true;
    } else {
      return sumRule(a, num, 0, 0, 0, 0, "");
    }
  }

  public static boolean sumRule(final int[] a, int num, int sum, int start, int consecutive, int lastIndex,
      String index) {
    if (consecutive == 3) {
      return false;
    }

    if (sum == num) {
      System.out.println(index);
      return true;
    }

    if (start >= a.length) {
      return false;
    }

    return sumRule(a, num, sum + a[start], start + 1, (start - lastIndex <= 1 ? consecutive + 1 : 1), start,
        index + ", " + start) || sumRule(a, num, sum, start + 1, consecutive, lastIndex, index);
  }


问:
Getting the CORS policy: No 'Access-Control-Allow-Origin' error
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

```<code>Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Here is my JavaScript,

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "<a href="+ myObj.articles[i].url +" target='blank'>";
            x += "<div style='background: linear-gradient(rgba(0,130,170,0),rgba(6,23,0,1)), url( "+ myObj.articles[i].urlToImage +" );height: 430px;margin-top: 20px;'>";
            x += "</div>";
            x += "</a>";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();
</code>```

HTML

```<code><div style="background-color: gray;height: 430px;margin-top: 20px;">
   p id="technology"></p>
</div>
</code>```

I don't understand why this is happening.

Please help me out,
Thanks in advance.

答:
The response is right in front of your eyes - You need to pay to use it outside of "localhost" domain which usually means you are develeping the site as developer thus you use the "Developer" plan. But when going live you need to pay up:

And you clearly missing the API Key (if you havent cut it out to paste here;) ) in the request ;)

Body:
I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.

Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my JavaScript,

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);

        for (i=0;i<1;i++ in myObj.articles) {

            x += "";
            x += "
";
            x += "
";
            x += "";

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();

HTML

   p id="technology">

I don't understand why this is happening.

Please help me out,
Thanks in advance.


问:
Regrouping rows containing the same column content
I have a file containing multiple rows and columns (Name, Avatar, Company). I'd like the rows having similar content in the company column to be regrouped in my file. Here is a visual example of what i have :

```<code>Name     |Avatar      |Company
-------------------------------
ZZZ      |MMM         |MMM
XXX      |PPP         |AAA
UUU      |QQQ         |MMM
YYY      |OOO         |AAA
</code>```

And what i'd like to do :

```<code>Name     |Avatar      |Company
-------------------------------
XXX      |PPP         |AAA
YYY      |OOO         |AAA

Name     |Avatar      |Company
-------------------------------
ZZZ      |MMM         |MMM
UUU      |QQQ         |MMM

</code>```

How can i achieve this in Google Sheets?

答:
You can use the following formula

```<code>={QUERY(A2:C6,"where C='AAA'",1);
QUERY(A2:C6,"where C='MMM'",1)}</code>```

OR you can take advantage of the skipping clause

```<code>={QUERY(A2:C6,"skipping 2");
QUERY({A2:C2;A2:C6},"skipping 2")}</code>```

Functions used:

QUERY

Body:
I have a file containing multiple rows and columns (Name, Avatar, Company). I'd like the rows having similar content in the company column to be regrouped in my file. Here is a visual example of what i have :

Name     |Avatar      |Company
-------------------------------
ZZZ      |MMM         |MMM
XXX      |PPP         |AAA
UUU      |QQQ         |MMM
YYY      |OOO         |AAA

And what i'd like to do :

Name     |Avatar      |Company
-------------------------------
XXX      |PPP         |AAA
YYY      |OOO         |AAA

Name     |Avatar      |Company
-------------------------------
ZZZ      |MMM         |MMM
UUU      |QQQ         |MMM

How can i achieve this in Google Sheets?

Body:
You can use the following formula

={QUERY(A2:C6,"where C='AAA'",1);
QUERY(A2:C6,"where C='MMM'",1)}

OR you can take advantage of the skipping clause

={QUERY(A2:C6,"skipping 2");
QUERY({A2:C2;A2:C6},"skipping 2")}

Functions used:

QUERY


问:
Creating a maze graph from a text file : Java
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

```<code>A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F
</code>```

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

```<code>package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}
</code>```

Can someone point me in the right direction, please?

答:
You should write additional code in a separate class to construct the maze. It will take textual input, and ouput a set of connected nodes. The nodes themselves shouldn't "construct" anything - they're just building blocks.

Here is some pseudo-code for how to connect them:

```<code>nameToNodeMap -> dictionary of string to node
for each line in the file
    previous token = null
    loop:
    try to get a token (letter, separated by commas)
    if there was no token
        break out of the loop
    else
        if nameToNodeMap contains that token
            get the node for that token
        else
            create a node
            add it to nameToNodeMap, with the token as the key
        if previous node != null
            link previous node to this node
        previous nope = current node
        goto loop
</code>```

Body:
I need to make a graph from a text file containing multiple 'mazes' represented as adjacency lists. The list is as follows:

A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F

The first line of each 'maze' contains the starting node of the maze (first letter) and the ending node of the maze (second letter).

I've parsed the text file into an ArrayList of all lines (including blank lines), then into an ArrayList of ArrayLists of lines (a list of separate mazes). I did this by splitting the complete text on blank lines. My problem is now that I cannot figure out how to use my node class to construct a graph from these 'mazes'. Here's my node class:

package algo2;

import java.util.ArrayList;

public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}

Can someone point me in the right direction, please?

Body:
You should write additional code in a separate class to construct the maze. It will take textual input, and ouput a set of connected nodes. The nodes themselves shouldn't "construct" anything - they're just building blocks.

Here is some pseudo-code for how to connect them:

nameToNodeMap -> dictionary of string to node
for each line in the file
    previous token = null
    loop:
    try to get a token (letter, separated by commas)
    if there was no token
        break out of the loop
    else
        if nameToNodeMap contains that token
            get the node for that token
        else
            create a node
            add it to nameToNodeMap, with the token as the key
        if previous node != null
            link previous node to this node
        previous nope = current node
        goto loop


问:
How to make early stopping in image classification pytorch
I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/ and use my custom dataset. Then I have same problem in this tutorial but I dont know how to make early stopping in pytorch and if do you have better without create early stopping process please tell me.</p>

答:
This is what I did in each epoch

```<code>val_loss += loss
val_loss = val_loss / len(trainloader)
if val_loss < min_val_loss:
  #Saving the model
  if min_loss > loss.item():
    min_loss = loss.item()
    best_model = copy.deepcopy(loaded_model.state_dict())
    print('Min loss %0.2f' % min_loss)
  epochs_no_improve = 0
  min_val_loss = val_loss

else:
  epochs_no_improve += 1
  # Check early stopping condition
  if epochs_no_improve == n_epochs_stop:
    print('Early stopping!' )
    loaded_model.load_state_dict(best_model)
</code>```

Donno how correct it is (I took most parts of this code from a post on another website, but forgot where, so I can't put the reference link. I have just modified it a bit), hope you find it useful, in case I'm wrong, kindly point out the mistake. Thank you

Body:
This is what I did in each epoch

val_loss += loss
val_loss = val_loss / len(trainloader)
if val_loss < min_val_loss:
  #Saving the model
  if min_loss > loss.item():
    min_loss = loss.item()
    best_model = copy.deepcopy(loaded_model.state_dict())
    print('Min loss %0.2f' % min_loss)
  epochs_no_improve = 0
  min_val_loss = val_loss

else:
  epochs_no_improve += 1
  # Check early stopping condition
  if epochs_no_improve == n_epochs_stop:
    print('Early stopping!' )
    loaded_model.load_state_dict(best_model)

Donno how correct it is (I took most parts of this code from a post on another website, but forgot where, so I can't put the reference link. I have just modified it a bit), hope you find it useful, in case I'm wrong, kindly point out the mistake. Thank you


问:
Can't hide column in jquery datatable shows TypeError: table.column is not a function
I am using jQuery datatables to show grid view of my records.

I took the reference of column show/hide api from here.

As defined I am trying to use it in my project with all CSS & JS files.

When I run this it shows me error as:

```<code>TypeError: table.column is not a function
</code>```

My jquery is this:

```<code>    $(document).ready(function() {
    var table = $('.dataTables-example').dataTable({"scrollX": true});

    $('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();
    var column = table.column($(this).attr('data-column') );

    column.visible( ! column.visible() );
} );
});
</code>```

Is there anything I am missing?

答:
Those who are struggling with a similar type of problem in datatable version 1.9.* can do

```<code>// column
    var ColNum = $(this).attr('data-column');

    // Define
    var bVis = table.fnSettings().aoColumns[ColNum].bVisible;

    // Toggle
    table.fnSetColumnVis(ColNum, bVis ? false : true);
</code>```

instead of

```<code>var column = table.column($(this).attr('data-column') );

column.visible( ! column.visible() );
</code>```

Body:
I am using jQuery datatables to show grid view of my records.

I took the reference of column show/hide api from here.

As defined I am trying to use it in my project with all CSS & JS files.

When I run this it shows me error as:

TypeError: table.column is not a function

My jquery is this:

    $(document).ready(function() {
    var table = $('.dataTables-example').dataTable({"scrollX": true});

    $('a.toggle-vis').on( 'click', function (e) {
    e.preventDefault();
    var column = table.column($(this).attr('data-column') );

    column.visible( ! column.visible() );
} );
});

Is there anything I am missing?

Body:
Those who are struggling with a similar type of problem in datatable version 1.9.* can do

// column
    var ColNum = $(this).attr('data-column');

    // Define
    var bVis = table.fnSettings().aoColumns[ColNum].bVisible;

    // Toggle
    table.fnSetColumnVis(ColNum, bVis ? false : true);

instead of

var column = table.column($(this).attr('data-column') );

column.visible( ! column.visible() );


问:
Using Levenberg-Marquardt optimization algorithm via opencv projectPoints() to estimate Calibration Errors
In camera calibration, i have used calibrateCamera() to find the camera parameters from several views of a calibration pattern. It precisely does two things:

1) Estimate the Initial Camera Parameters in closed form, assuming lens distortion as zero.

2) Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, which is done using projectPoints()

Now, i don't just want to compute the Minimized Reprojection Error but the fit parameters which caused it. There is currently no function which would return the error-free parameters. So, what i thought was i would use projectPoints() to get the reprojected image points and then use the reprojected image points and world points to calibrate again and obtain the error-free parameters. Problem is this is not something i am sure would give me output. Can anybody tell me whether it is? Any help would be appreciated.

答:
Levenberg-Marquardt will give you the best estimate of what your model and data are capable of. You can't get an error free parameters unless your input data is noise free and your model complexity matches the complexity of your real model.

For example, your model is:
x * 2 + y = z, with x > 0 and x is an integer number

Input data z = { 3 }

Depending on your initial value, Levenberg-Marquardt will give you:
(x = 1, y = 1) or (x=2,y=-1) or ... which are error free

However, with the same input z, if your model is:
x * 2 = z, with x > 0 and x is an integer number

There is no way that you will get an error free parameters


问:
how to get the sum of values in 2 textboxes that gets updated C#
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

```<code>value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();
</code>```

Output textbox1:

```<code>100, after sometime updates to 200, then 300
</code>```

Output textbox2:

```<code>50, after sometime updates to 100, then 150
</code>```

What I'm getting, output in textbox3:

```<code>150, after some time updates to 300, then 450
</code>```

The value I should get is

```<code>100+200+300+50+100+150
</code>```

答:
solved my own problem, ill post here in case someone else might be in the same position</p>

```<code>used two lists got the sums and added the sums
</code>```

```<code>List<double> totalvalueList = new List<double>();
totalvalueList.Add(Convert.ToDouble(value1));
            double totalval = totalvalueList.Sum();
</code>```

Body:
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();

Output textbox1:

100, after sometime updates to 200, then 300

Output textbox2:

50, after sometime updates to 100, then 150

What I'm getting, output in textbox3:

150, after some time updates to 300, then 450

The value I should get is

100+200+300+50+100+150

Body:
solved my own problem, ill post here in case someone else might be in the same position

used two lists got the sums and added the sums

List<double> totalvalueList = new List<double>();
totalvalueList.Add(Convert.ToDouble(value1));
            double totalval = totalvalueList.Sum();


问:
C++ Cross Platform MP3 Decoder?
I have searched high and low, and cannot find any decent MP3 decoders =/

I need one that will compile under gcc/linux.

The closest thing i could find was libmad, which has no documentation at all, and the only example I could find was the one on their home page, which is really complicated.

Does anyone know where I can find one?

答:
I have used MAD (MPEG Audio Decoder) in the past with great results, so I would not give up on it so quickly. MAD is specialy designed for good performance on CPUs without floating-point operations, which is desirable while developing applications for mobile devices for example.
 I would like to recommend you to take a look on the source code of this project (GSPlayer). It is an audio player for Windows CE/Windows Mobile and it uses libmad. The code is fully functional, neat, and not too large, so it may help you to get an idea on how to use libmad on your own projects.

You may have to verify the license (GPL) for libmad though, since it may not suit your needs.

Title: C++ Cross Platform MP3 Decoder?


问:
raise Value Error('Custom files must have an attribution')

This is the source code I wrote to generate maps with folium in python

```<code>import folium
map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15,
tiles='Stream Terreain')
</code>```

to put some markers in map

```<code>folium.Marker(location=[53.073635, 8.806422], popup='Ich bin verloren',
icon=folium.Icon(icon='cloud')).add_to(map3)

folium.Marker(location=[53.073600, 8.806400], popup='Hej, ich bin da',
icon=folium.Icon(icon='cloud')).add_to(map3)

print(map3.save('test3.html'))
</code>```

Unfortunately, PyCharm gives following error:

```<code>Connected to pydev debugger (build 182.4129.34 Traceback (most recent call last):

File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1664, in <module> main()

File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) .
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals)  # execute the script .
</code>```

File"/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) .

```<code>File "/Users/kuldeep/PycharmProjects/webmap/webmap_2.py", line 2, in <module> map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15, tiles='Stream Terreain') .

File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/folium.py", line 278, in __init__
subdomains=subdomains .
</code>```

File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/folium.py", line 349, in add_tile_layer
    no_wrap=no_wrap) .

```<code>File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/raster_layers.py", line 113, in __init__ .

raise ValueError('Custom tiles must have an attribution.')
</code>```

ValueError: Custom tiles must have an attribution.

Process finished with exit code 1
raise ValueError('Custom tiles must have an attribution.')
ValueError: Custom tiles must have an attribution.
Process finished with exit code 1

答:
Try this instead:

```<code>map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15, tiles='Stamen Terrain')
</code>```

It results into:

```<code>("Stream Terreain" -> "Stamen Terrain")
</code>```

Body:
This is the source code I wrote to generate maps with folium in python

import folium
map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15,
tiles='Stream Terreain')

to put some markers in map

folium.Marker(location=[53.073635, 8.806422], popup='Ich bin verloren',
icon=folium.Icon(icon='cloud')).add_to(map3)

folium.Marker(location=[53.073600, 8.806400], popup='Hej, ich bin da',
icon=folium.Icon(icon='cloud')).add_to(map3)

print(map3.save('test3.html'))

Unfortunately, PyCharm gives following error:

Connected to pydev debugger (build 182.4129.34 Traceback (most recent call last):

File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1664, in <module> main()

File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) .
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals)  # execute the script .

File"/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) .

File "/Users/kuldeep/PycharmProjects/webmap/webmap_2.py", line 2, in <module> map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15, tiles='Stream Terreain') .

File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/folium.py", line 278, in __init__
subdomains=subdomains .

File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/folium.py", line 349, in add_tile_layer
    no_wrap=no_wrap) .

File "/Users/kuldeep/PycharmProjects/webmap/venv/lib/python3.7/site-packages/folium/raster_layers.py", line 113, in __init__ .

raise ValueError('Custom tiles must have an attribution.')

ValueError: Custom tiles must have an attribution.

Process finished with exit code 1
raise ValueError('Custom tiles must have an attribution.')
ValueError: Custom tiles must have an attribution.
Process finished with exit code 1

Body:
Try this instead:

map3 = folium.Map(location=[53.073635, 8.806422], zoom_start=15, tiles='Stamen Terrain')

It results into:

("Stream Terreain" -> "Stamen Terrain")


问:
Combining p values using scipy
I have to combine p values and get one p value.
I'm using scipy.stats.combine_pvalues function, but it is giving very small combined p value, is it normal?

e.g.:

```<code>>>> import scipy
>>> p_values_list=[8.017444955844044e-06, 0.1067379119652372, 5.306374345615846e-05, 0.7234201655194492, 0.13050605094545614, 0.0066989543716175, 0.9541246420333787]
>>> test_statistic, combined_p_value = scipy.stats.combine_pvalues(p_values_list, method='fisher',weights=None)
>>> combined_p_value
4.331727536209026e-08
</code>```

As you see, combined_p_value is smaller than any given p value in the p_values_list?
How can it be?

Thanks in advance,
Burcak

答:
It is correct, because you are testing all of your p-values come from a random uniform distribution. The alternate hypothesis is that at least one of them is true. Which in your case is very possible.

We can simulate this, by drawing from a random uniform distribution 1000 times, the length of your p-values:

```<code>import numpy as np
from scipy.stats import combine_pvalues
from matplotlib import pyplot as plt

random_p = np.random.uniform(0,1,(1000,len(p_values_list)))
res = np.array([combine_pvalues(i,method='fisher',weights=None) for i in random_p])
plt.hist(fisher_p)
</code>```

From your results, the chi-square is 62.456 which is really huge and no where near the simulated chi-square above.

One thing to note is that the combining you did here does not take into account directionality, if that is possible in your test, you might want to consider using stouffer's Z along with weights. Also another sane way to check is to run simulation like the above, to generate list of p-values under the null hypothesis and see how they differ from what you observed.

Interesting paper but maybe a bit on the statistics side

Title: Combining p values using scipy

Body:
I have to combine p values and get one p value.
I'm using scipy.stats.combine_pvalues function, but it is giving very small combined p value, is it normal?

e.g.:

>>> import scipy
>>> p_values_list=[8.017444955844044e-06, 0.1067379119652372, 5.306374345615846e-05, 0.7234201655194492, 0.13050605094545614, 0.0066989543716175, 0.9541246420333787]
>>> test_statistic, combined_p_value = scipy.stats.combine_pvalues(p_values_list, method='fisher',weights=None)
>>> combined_p_value
4.331727536209026e-08

As you see, combined_p_value is smaller than any given p value in the p_values_list?
How can it be?

Thanks in advance,
Burcak

Body:
It is correct, because you are testing all of your p-values come from a random uniform distribution. The alternate hypothesis is that at least one of them is true. Which in your case is very possible.

We can simulate this, by drawing from a random uniform distribution 1000 times, the length of your p-values:

import numpy as np
from scipy.stats import combine_pvalues
from matplotlib import pyplot as plt

random_p = np.random.uniform(0,1,(1000,len(p_values_list)))
res = np.array([combine_pvalues(i,method='fisher',weights=None) for i in random_p])
plt.hist(fisher_p)

From your results, the chi-square is 62.456 which is really huge and no where near the simulated chi-square above.

One thing to note is that the combining you did here does not take into account directionality, if that is possible in your test, you might want to consider using stouffer's Z along with weights. Also another sane way to check is to run simulation like the above, to generate list of p-values under the null hypothesis and see how they differ from what you observed.

Interesting paper but maybe a bit on the statistics side


问:
Override claims' key names used in JWTs in ASP.NET Core
It is considered best practice not to leak implementation details to a system's clients. For example, not to respond with "Powered by foo" headers, etc.

The System.Security.Claims.ClaimTypes contains all sort of Microsoft-centric schemas which are a tipoff that one is using ASP.NET Core.

e.g., Role claim is: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role".

So:

Is there an alternative approach to encoding JWTs to avoid this problem? (without having to custom code the entire auth layer).

Specifically for the role claim, can its key be renamed somehow? The runtime provides useful auto-detection and use in Identity. I'd like to continue using this functionality, just somehow rename the claim's key.

答:
I was also faced same issue, here is my solution

```<code>var roles = await _userManager.GetRolesAsync(user);

foreach (var role in roles)
{
    claims.Add(new Claim(ClaimTypes.Role, role));
    claims.Add(new Claim("roles", role));
}
</code>```

with "ClaimTypes.Role" also add as "roles". This works for me.

Body:
I was also faced same issue, here is my solution

var roles = await _userManager.GetRolesAsync(user);

foreach (var role in roles)
{
    claims.Add(new Claim(ClaimTypes.Role, role));
    claims.Add(new Claim("roles", role));
}

with "ClaimTypes.Role" also add as "roles". This works for me.


问:
How to group by using bit column?
my table data

```<code>id  quota
1  0
1  NULL
1  1
2  0
2  NULL
3  NULL
</code>```

Result I Except

```<code>id  quota
1  1
2  0
3  NULL
</code>```

Result I am getting:

```<code>id  quota
1  1
2  0
3  0
</code>```

Query I am using:

```<code> select id,count(id) count_id,
 case when max(coalesce(quota,0)) = 1 then 1
 when max(coalesce(quota,0)) = 0 then 0
 else null
 end as quota from forbit group by i
</code>```

My data type for column quota is bit.

I want whenever the max in group is 1 give quota as 1, whenever the max in group is 0 give quota as 0 and whenever the max in group is null give quota as null.
I basically want to achieve NULL for id 3.

Similar post I saw:
Use column of type bit to differentiate group by?

答:
I think just a simple max is what you are looking for, after converting to an int because max doesn't work on a bit.

```<code>declare @Test table (id int, quota bit);

insert into @Test (id, quota)
values
(1, 0)
, (1, NULL)
, (1, 1)
, (2, 0)
, (2, NULL)
, (3, NULL);

select id, max(convert(int,quota))
from @Test
group by id;
</code>```

Returns:

```<code>id  quota
1   1
2   0
3   NULL
</code>```

Title: How to group by using bit column?

Body:
my table data

id  quota
1  0
1  NULL
1  1
2  0
2  NULL
3  NULL

Result I Except

id  quota
1  1
2  0
3  NULL

Result I am getting:

id  quota
1  1
2  0
3  0

Query I am using:

 select id,count(id) count_id,
 case when max(coalesce(quota,0)) = 1 then 1
 when max(coalesce(quota,0)) = 0 then 0
 else null
 end as quota from forbit group by i

My data type for column quota is bit.

I want whenever the max in group is 1 give quota as 1, whenever the max in group is 0 give quota as 0 and whenever the max in group is null give quota as null.
I basically want to achieve NULL for id 3.

Similar post I saw:
Use column of type bit to differentiate group by?

Body:
I think just a simple max is what you are looking for, after converting to an int because max doesn't work on a bit.

declare @Test table (id int, quota bit);

insert into @Test (id, quota)
values
(1, 0)
, (1, NULL)
, (1, 1)
, (2, 0)
, (2, NULL)
, (3, NULL);

select id, max(convert(int,quota))
from @Test
group by id;

Returns:

id  quota
1   1
2   0
3   NULL


问:
Dialogflow easy way for authorization
Does exist an easy way to connect Dialogflow agent to node.js code? When I use this code with the correct projectID taken from the Dialogflow agent's settings page, I have the following error:

Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

```<code>const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
</code>```

I visited the page, but for what I want I think is quite confused (they quotes other API and a lot of setting), how can I solve this?

I want to take informations from a file and loading all without installing third party APIs.

答:
I follow the above solutions with little changes :</p>

```<code>// A unique identifier for the given session
const sessionId = uuid.v4();

// Create a new session

const sessionClient = new dialogflow.SessionsClient({
    keyFilename: require("path").join('config/google-credential.json')
});
const sessionPath = sessionClient.sessionPath(process.env.DIALOGFLOW_PROJECTID, sessionId);
</code>```

Title: Dialogflow easy way for authorization

Body:
Does exist an easy way to connect Dialogflow agent to node.js code? When I use this code with the correct projectID taken from the Dialogflow agent's settings page, I have the following error:

Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

I visited the page, but for what I want I think is quite confused (they quotes other API and a lot of setting), how can I solve this?

I want to take informations from a file and loading all without installing third party APIs.

Body:
I follow the above solutions with little changes :

// A unique identifier for the given session
const sessionId = uuid.v4();

// Create a new session

const sessionClient = new dialogflow.SessionsClient({
    keyFilename: require("path").join('config/google-credential.json')
});
const sessionPath = sessionClient.sessionPath(process.env.DIALOGFLOW_PROJECTID, sessionId);


问:
Fetch data for the entire app without depending on component logic
There are X routes in the frontend made with React-router and each of them drives to a component.

No matter which route is visited, I need to use some data from an api.

This data is constant through the application. Using Redux I could dispatch an action FETCH_DATA in each React component and manage the logic of fetching in Redux actions.

However, this looks repetitive to me because I would be writing the same logic through all the React components that need data: look for the the data in the store. If it's there take it. If it's not there, dispatch FETCH_DATA.

What is another approach?

答:
You can call that api in the App.tsx i.e. your first component to be rendered in the application. This is the component which actually holds the Routes also.

Consider the following code as an example and change it according to the need of your application:

```<code>class App extends React.Component {
  ComponentDidMount() {
    this.props.callTheApiHere()
  }

  render() {
    return (
      <Routes history={this.props.history} />
    )
  }
}

export default App;
</code>```

Now each component that any of your Route render have to just get the data from the redux store using mapStateToProps in react-redux Connect

Body:
You can call that api in the App.tsx i.e. your first component to be rendered in the application. This is the component which actually holds the Routes also.

Consider the following code as an example and change it according to the need of your application:

class App extends React.Component {
  ComponentDidMount() {
    this.props.callTheApiHere()
  }

  render() {
    return (
      <Routes history={this.props.history} />
    )
  }
}

export default App;

Now each component that any of your Route render have to just get the data from the redux store using mapStateToProps in react-redux Connect


问:
why `sh -c "export a=1&&echo $a"` returns nothing?
A)
 first I run export a=1&&echo $a in linux terminal and I get 1.

```<code>[root@ip-172-31-16-92 ec2-user]# export a=1&&echo $a
1
</code>```

B)
But when I run  sh -c "export a=2&&echo $a" and I still get 1 instead of 2.

```<code>[root@ip-172-31-16-92 ec2-user]# sh -c "export a=2&&echo $a"
1
</code>```

What happend? If sh -c "export a=2&&echo $a" itself is a child process of the terminal,it should have its own environment, first it should make a copy of his father environment,so a=1,but when it execute export a=2 ,environment a should be set to 2,then echo $a should be 2.But it returns 1,what happend?

答:
Try this one and and you'll see it works.

```<code>sh -c 'export a=2&&echo $a'
</code>```

When enclosed in double-quotes, $a is expanded to its current value by the shell before invoking sh.

Body:
A)
 first I run export a=1&&echo $a in linux terminal and I get 1.

[root@ip-172-31-16-92 ec2-user]# export a=1&&echo $a
1

B)
But when I run  sh -c "export a=2&&echo $a" and I still get 1 instead of 2.

[root@ip-172-31-16-92 ec2-user]# sh -c "export a=2&&echo $a"
1

What happend? If sh -c "export a=2&&echo $a" itself is a child process of the terminal,it should have its own environment, first it should make a copy of his father environment,so a=1,but when it execute export a=2 ,environment a should be set to 2,then echo $a should be 2.But it returns 1,what happend?

Body:
Try this one and and you'll see it works.

sh -c 'export a=2&&echo $a'

When enclosed in double-quotes, $a is expanded to its current value by the shell before invoking sh.


问:
Issue with writing htaccess rules
Please guys I need help; I am having a little issue routing my URL using .htaccess.

I want a situation where I can route the url Localhost/project_folder/test/learn-the-basic-of-computing to a script on my server. Like Localhost/project_folder/test/learn-the-basic-of-computing should be routed to script.php where the slug "learn-the-basic-of-computing" will be use as a URL parameter.

So I want Localhost/project_folder/test/learn-the-basic-of-computing to be routed to script.php?slug="learn-the-basic-of-computing".

Please can someone recommend solutions on how I will construct the .htaccess rules to achieve the above explained situation

答:
Could you please try following. Please place .htaccess inside project_folder/test/ directory.

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$  script.php?slug=$1 [NC,QSA,L]
</code>```

Brief explanation: By using (.*) save matched regex value into buffer where it will match learn-the-basic-of-computing and later using in redirection as query string by using $1.

Title: Issue with writing htaccess rules

Body:
Could you please try following. Please place .htaccess inside project_folder/test/ directory.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$  script.php?slug=$1 [NC,QSA,L]

Brief explanation: By using (.*) save matched regex value into buffer where it will match learn-the-basic-of-computing and later using in redirection as query string by using $1.


问:
Will the compiler optimize the for loop to match the bus width?
Let's say that I want to set a char array with different values, but for the sake of simplicity:

```<code>char buff[1024];
...
for (int i = 0; i < 1024; i++) buff[i] = NULL;
</code>```

Is the compiler going to optimize this to match the bus width? Or should I manually do this:

```<code>char buff[1024];
...
size_t empty = NULL;
for (int i = 0; i < 1024 / sizeof(size_t); i++)
    memcpy(buff + i * sizeof(size_t), &empty, sizeof(size_t));
</code>```

In the supposed case that sizeof(size_t) is the bus width.

I made some measurements, I think it just proves the points stated:

```<code>#define TIMES 512
#define SIZE 4194304

int main(void) {

    char *buff = new char[SIZE];

    int times = TIMES;

    clock_t begin = clock();

    void *pattern = (void*)0xffeeddcc;

    while (times--) {

        ... some for loop ...
    };

    clock_t end = clock();

    delete[] buff;

    std::cout << ((float)(end - begin) / CLOCKS_PER_SEC) << " s elapsed.\n";

    return 0;
};
</code>```

Set char by char:

```<code>for (int i = 0; i < SIZE; i++) buff[i] = i % 0xff;
</code>```

Average elapsed time: 13.6284 s

Set fixed size at a time (bus width):

```<code>for (int i = 0; i < SIZE / sizeof(void*); i++) {
    void* sub = (void*)(((i * sizeof(void*)) % 0xff) + (((i * sizeof(size_t) + 1) % 0xff) << 8) + (((i * sizeof(void*) + 2) % 0xff) << 16) + (((i * sizeof(void*) + 3) % 0xff) << 24));

    memcpy(buff + i * sizeof(void*), &sub, sizeof(void*));
};
</code>```

Average elapsed time: 19.4352 s

Pattern char by char:

```<code>for (int i = 0; i < SIZE; i++) buff[i] = ((char*)&pattern)[i % sizeof(void*)];
</code>```

Average elapsed time: 17.1696 s

Pattern fixed size (bus width):

```<code>for (int i = 0; i < SIZE / sizeof(void*); i++) memcpy(buff + i * sizeof(void*), &pattern, sizeof(void*));
</code>```

Average elapsed time: 5.6976 s

I don't know if all this measurement was necessary XD

Done with a 2 GHz, 2 cores CPU (Intel Core i3-5005U CPU @ 2.00 GHz).

答:
If you're setting each char to the same value, just call memset.

Compilers (namely gcc and clang) do recognize loops like

```<code>for (int i = 0; i < 1024; i++) buff[i] = 0xff;
</code>```

Clang turns it into a memset call; gcc uses instructions setting one word at a time: https://gcc.godbolt.org/z/ovRTPU. But you get the same assembly output from making a call to memset (it's generally a compiler-recognized function (like memcpy)).

If you're setting a buffer with static storage duration to 0, you don't need to do anything because it already will have been zeroed by the time the program is loaded.

(BTW, using NULL for 0 isn't a good idea. At least in C, NULL can be (void*)0 which won't get assigned to an integer type without warnings/errors.)

Body:
Let's say that I want to set a char array with different values, but for the sake of simplicity:

char buff[1024];
...
for (int i = 0; i < 1024; i++) buff[i] = NULL;

Is the compiler going to optimize this to match the bus width? Or should I manually do this:

char buff[1024];
...
size_t empty = NULL;
for (int i = 0; i < 1024 / sizeof(size_t); i++)
    memcpy(buff + i * sizeof(size_t), &empty, sizeof(size_t));

In the supposed case that sizeof(size_t) is the bus width.

I made some measurements, I think it just proves the points stated:

#define TIMES 512
#define SIZE 4194304

int main(void) {

    char *buff = new char[SIZE];

    int times = TIMES;

    clock_t begin = clock();

    void *pattern = (void*)0xffeeddcc;

    while (times--) {

        ... some for loop ...
    };

    clock_t end = clock();

    delete[] buff;

    std::cout << ((float)(end - begin) / CLOCKS_PER_SEC) << " s elapsed.\n";

    return 0;
};

Set char by char:

for (int i = 0; i < SIZE; i++) buff[i] = i % 0xff;

Average elapsed time: 13.6284 s

Set fixed size at a time (bus width):

for (int i = 0; i < SIZE / sizeof(void*); i++) {
    void* sub = (void*)(((i * sizeof(void*)) % 0xff) + (((i * sizeof(size_t) + 1) % 0xff) << 8) + (((i * sizeof(void*) + 2) % 0xff) << 16) + (((i * sizeof(void*) + 3) % 0xff) << 24));

    memcpy(buff + i * sizeof(void*), &sub, sizeof(void*));
};

Average elapsed time: 19.4352 s

Pattern char by char:

for (int i = 0; i < SIZE; i++) buff[i] = ((char*)&pattern)[i % sizeof(void*)];

Average elapsed time: 17.1696 s

Pattern fixed size (bus width):

for (int i = 0; i < SIZE / sizeof(void*); i++) memcpy(buff + i * sizeof(void*), &pattern, sizeof(void*));

Average elapsed time: 5.6976 s

I don't know if all this measurement was necessary XD

Done with a 2 GHz, 2 cores CPU (Intel Core i3-5005U CPU @ 2.00 GHz).

Body:
If you're setting each char to the same value, just call memset.

Compilers (namely gcc and clang) do recognize loops like

for (int i = 0; i < 1024; i++) buff[i] = 0xff;

Clang turns it into a memset call; gcc uses instructions setting one word at a time: https://gcc.godbolt.org/z/ovRTPU. But you get the same assembly output from making a call to memset (it's generally a compiler-recognized function (like memcpy)).

If you're setting a buffer with static storage duration to 0, you don't need to do anything because it already will have been zeroed by the time the program is loaded.

(BTW, using NULL for 0 isn't a good idea. At least in C, NULL can be (void*)0 which won't get assigned to an integer type without warnings/errors.)


问:
How to bring an element to the browser's viewpoint with Nightwatchjs
I am trying the scroll down and bring an element to the browser's viewpoint. Which is at the bottom of the page and not visible unless scroll down.

With the help of this Stackoverflow post I am able to get the x and y for the element but not able to bring it to the viewpoint.

```<code>    browser.getLocationInView('#element', function (result){
        console.log ('x: '+ result.value.x);
        console.log ('y: '+ result.value.y);
    })
</code>```

This gives me x: 16, y: 519

After that I tried

browser.execute('scrollTo(16, 519)')
```

This does not scroll it to the viewpoint. What is the way to do this?

Well, perhaps I did not understood the use of these apis in right way.

答:
There are Nightwatch APIs that work fine if you have to scroll an element into the viewport.

moveToElement is my first choice always as it takes element selector as param and brings the element to top of the viewport.

moveTo is a great choice if you have to use the element's location. The docs are available here.

Below is the syntax.

```<code>.moveToElement(selector, xoffset, yoffset, [callback])
.moveToElement(using, selector, xoffset, yoffset, [callback])

.moveTo([webElementId], xoffset, yoffset, [callback])
.moveTo(null, xoffset, yoffset, [callback])
</code>```

Body:
I am trying the scroll down and bring an element to the browser's viewpoint. Which is at the bottom of the page and not visible unless scroll down.

With the help of this Stackoverflow post I am able to get the x and y for the element but not able to bring it to the viewpoint.

    browser.getLocationInView('#element', function (result){
        console.log ('x: '+ result.value.x);
        console.log ('y: '+ result.value.y);
    })

This gives me x: 16, y: 519

After that I tried

browser.execute('scrollTo(16, 519)')

This does not scroll it to the viewpoint. What is the way to do this?

Well, perhaps I did not understood the use of these apis in right way.

Body:
There are Nightwatch APIs that work fine if you have to scroll an element into the viewport.

moveToElement is my first choice always as it takes element selector as param and brings the element to top of the viewport.

moveTo is a great choice if you have to use the element's location. The docs are available here.

Below is the syntax.

.moveToElement(selector, xoffset, yoffset, [callback])
.moveToElement(using, selector, xoffset, yoffset, [callback])

.moveTo([webElementId], xoffset, yoffset, [callback])
.moveTo(null, xoffset, yoffset, [callback])


问:
How to put assert into release builds in C/C++
I need to only run ship build and I need to assert on certain condition in release build to see if the problem is fixed. How do I do it?</p>

答:
Why not just define your own assert:</p>

```<code>#define assert(x) MessageBox(...);
</code>```

OwnerDisplayName: pra che

Body:
Why not just define your own assert:

#define assert(x) MessageBox(...);

OwnerDisplayName: Baiyan Huang


问:
objective c leaking NSNumber being retained
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit of testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.

```<code>latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];
</code>```

This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.

I understand the alloc-release paradigm, but I'm still not sure how to fix this.

答:
Without seeing the rest of your code its tough to say exactly how you should fix this, but a good first approach might be to try autoreleasing it like:

```<code>latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] autorelease];
</code>```

The other thing to consider is making latitude a @property and set it to retain.  This way, when you set it, it will release the previous value.  Again, without knowing how you're using latitude its hard to point you in a solid direction.

Body:
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit of testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.

latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];

This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.

I understand the alloc-release paradigm, but I'm still not sure how to fix this.

Body:
Without seeing the rest of your code its tough to say exactly how you should fix this, but a good first approach might be to try autoreleasing it like:

latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] autorelease];

The other thing to consider is making latitude a @property and set it to retain.  This way, when you set it, it will release the previous value.  Again, without knowing how you're using latitude its hard to point you in a solid direction.


问:
Mocking Repositories to test Service in Spring
I occurred some failures after trying to mock repositories to unit test my services in Spring-Boot
Thats what I have (simplified)

@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserTest{

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepostiory userRepository;

    @Before
    public void setUp() {
       User user = new User(1L, "email@email", "name");
        when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
    }

    @Test
    public void findUserByIdReturnsUser() {

        User user = userService.getById(1L); => always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
        assertEquals(1L,user.getId());

    }
}
```

But I never get the User returned when the service calls the repo. I am kinda new to Unit Testing, and I am pretty sure, that I miss something here.

答:
In the setUp you do:

```<code>when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
</code>```

But in the Test you call

```<code>User user = userService.getById(1L);
</code>```

Either mock getById or call findById

Body:
I occurred some failures after trying to mock repositories to unit test my services in Spring-Boot
Thats what I have (simplified)

@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles("test")
public class UserTest{

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepostiory userRepository;

    @Before
    public void setUp() {
       User user = new User(1L, "email@email", "name");
        when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
    }

    @Test
    public void findUserByIdReturnsUser() {

        User user = userService.getById(1L); => always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
        assertEquals(1L,user.getId());

    }
}

But I never get the User returned when the service calls the repo. I am kinda new to Unit Testing, and I am pretty sure, that I miss something here.

Body:
In the setUp you do:

when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));

But in the Test you call

User user = userService.getById(1L);

Either mock getById or call findById


问:
Apache - exposing webapp on port using subdomain / route with SSL
I'm trying to expose web app via subdomain with SSL or via route.

Subdomain Method:

The webapp I'm running is on port: http://localhost:4567/

With the following configuration, the web browser tells me the app is "not secure" (non-https).

The app is generally working fine, but is non-https.

What am I doing wrong?
Are there alternative configurations?

```<code><IfModule mod_ssl.c>
    Listen 443
    NameVirtualHost *:443
</IfModule>

<VirtualHost *:80>
  ServerName blast.example.com
  Redirect permanent / https://blast.example.com/
</VirtualHost>

<IfModule mod_ssl.c>

<VirtualHost *:443>
    ServerAdmin me@gmail.com
    ServerName blast.example.com
    # ProxyPreserveHost On
    ProxyRequests off

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
#    ProxyPass / http://localhost:4567/
#    ProxyPassReverse / http://localhost:4567/

  <Location />
    ProxyPass http://localhost:4567/
    ProxyPassReverse http://localhost:4567/
  </Location>

  SSLEngine on
  SSLProtocol all -SSLv2 -SSLv3
  SSLCipherSuite ALL:!DH:!EXPORT:!RC4:+HIGH:+MEDIUM:!LOW:!aNULL:!eNULL

  SSLCertificateFile ...
  SSLCertificateKeyFile ...
  Include /etc/letsencrypt/options-ssl-apache.conf

</VirtualHost>
</code>```

I had been following the prescription given at How to configure multiple subdomain with SSL in Apache?

Path/Route Method

I had also tried exposing the app as a route path (ie https://example.com/blast)

```<code>  <Location /blast/ >
    ProxyPass http://localhost:4567/
    ProxyPassReverse http://localhost:4567/
  </Location>
</code>```

but the reverse proxy didn't see to work in that, if I started with:

```<code>https://example.com/blast
</code>```

And clicked whatever on the start page.
The app would generate a internal URL without the /blast part, resulting in 404:

```<code>https://example.com/blah-blah-generated-url
(should be https://example.com/blast/blah-blah-generated-url)
</code>```

In general, the subdomain path seems to work better except for the non-https problem.

答:
Setting up a path/route:

Making the application accessible with https://example.com/blast.  If the application generates new routes, ProxyPassReverse is needed; otherwise; only ProxyPass is needed.

```<code><VirtualHost *:443>
  ...
  ProxyPass "/blast/" "http://localhost:4567/"
  ProxyPassReverse "/blast/" "/"
  ...
</code>```

Found in Example 1, here: ProxyPassReverse doesn't rewrite Location (http header)

Body:
I'm trying to expose web app via subdomain with SSL or via route.

Subdomain Method:

The webapp I'm running is on port: http://localhost:4567/

With the following configuration, the web browser tells me the app is "not secure" (non-https).

The app is generally working fine, but is non-https.

What am I doing wrong?
Are there alternative configurations?

<IfModule mod_ssl.c>
    Listen 443
    NameVirtualHost *:443
</IfModule>

<VirtualHost *:80>
  ServerName blast.example.com
  Redirect permanent / https://blast.example.com/
</VirtualHost>

<IfModule mod_ssl.c>

<VirtualHost *:443>
    ServerAdmin me@gmail.com
    ServerName blast.example.com
    # ProxyPreserveHost On
    ProxyRequests off

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
#    ProxyPass / http://localhost:4567/
#    ProxyPassReverse / http://localhost:4567/

  <Location />
    ProxyPass http://localhost:4567/
    ProxyPassReverse http://localhost:4567/
  </Location>

  SSLEngine on
  SSLProtocol all -SSLv2 -SSLv3
  SSLCipherSuite ALL:!DH:!EXPORT:!RC4:+HIGH:+MEDIUM:!LOW:!aNULL:!eNULL

  SSLCertificateFile ...
  SSLCertificateKeyFile ...
  Include /etc/letsencrypt/options-ssl-apache.conf

</VirtualHost>

I had been following the prescription given at How to configure multiple subdomain with SSL in Apache?

Path/Route Method

I had also tried exposing the app as a route path (ie https://example.com/blast)

  <Location /blast/ >
    ProxyPass http://localhost:4567/
    ProxyPassReverse http://localhost:4567/
  </Location>

but the reverse proxy didn't see to work in that, if I started with:

https://example.com/blast

And clicked whatever on the start page.
The app would generate a internal URL without the /blast part, resulting in 404:

https://example.com/blah-blah-generated-url
(should be https://example.com/blast/blah-blah-generated-url)

In general, the subdomain path seems to work better except for the non-https problem.

Body:
Setting up a path/route:

Making the application accessible with https://example.com/blast.  If the application generates new routes, ProxyPassReverse is needed; otherwise; only ProxyPass is needed.

<VirtualHost *:443>
  ...
  ProxyPass "/blast/" "http://localhost:4567/"
  ProxyPassReverse "/blast/" "/"
  ...

Found in Example 1, here: ProxyPassReverse doesn't rewrite Location (http header)


问:
Avoid duplicated code if the only diffence is a method call in a for loop
I have this two methods written in java:

```<code>public void fillRect(float x, float y, float width, float height, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++){
                // here is the difference between the other method
                setPixel(xx,yy,color);

            }
        }
    }
</code>```

```<code>public void fillRect(float x, float y, float width, float height,float transparency, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++) {
                // here is the difference between the other method
                // this Method is slower then setPixel()
                plot(xx,yy,transparency,color);
            }
        }
    }
</code>```

I'm used to write a method like this validateBoundary(float* x,float* y, float* width, float *height): void which includes the 'if-statments' and call it instead but clearly this won't be happen in Java.
What is the solution for problems like this? We could write a Methode validateBoundaryWidthf(xi, widhtf, pixelWitdth) which returns the  the new value for widthf. But something like this:

```<code>if (xi < 0) {
     widthf += xi;
     xi = 0;
}
</code>```

can't be a solved by this because there is only one return value. Sure I could create a POJO with the attributes widthf and xi an return this instead but I assume this is comes expensive in terms of cpu / memory. So what is the proper way solving this duplicated code issue?

答:
You can use consumers to handle the different handling inside the for loop. Define a new functional interface which takes the xx and yy values as arguments:

```<code>@FunctionalInterface
public interface PointConsumer {
    void accept(int x, int y);
}
</code>```

Then you add a new method performOnPoints with all the arguments needed and with one PointConsumer argument. It might look like this:

```<code>public void performOnPoints(float x, float y, float width,
                            float height, PointConsumer consumer) {
    int xi = mapX(x);
    int yi = mapY(y);

    int heightf =  mapHeight(height);
    int widthf  = mapWidth(width);

    if (xi + widthf > pixelWidth){
        widthf -= xi + widthf - pixelWidth;
    }
    if (yi + heightf > pixelHeight){
        heightf -= yi + heightf - pixelHeight;
    }

    if (xi < 0) {
        widthf += xi;
        xi = 0;

    }
    if (yi < 0) {
        heightf += yi;
        yi = 0;
    }

    for (int xx = xi; xx < xi + widthf; xx++){
        for (int yy = yi; yy < yi + heightf; yy++){
            consumer.accept(xx, yy);
        }
    }
}
</code>```

Then you can rewrite your existing fillRect methods like this:

```<code>public void fillRect(float x, float y, float width, float height, Color color) {
    performOnPoints(x, y, width, height, (xx, yy) -> setPixel(xx, yy, color));
}

public void fillRect(float x, float y, float width, float height,
        float transparency, Color color) {
    performOnPoints(x, y, width, height, (xx, yy) -> plot(xx,yy,transparency,color);
}
</code>```

As you see they both use the same looping code with all the special if() statements, but you have this code only once. For the different arguments you will use a different consumer object, one will call setPixel(), the other will call plot().

Body:
I have this two methods written in java:

public void fillRect(float x, float y, float width, float height, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++){
                // here is the difference between the other method
                setPixel(xx,yy,color);

            }
        }
    }

public void fillRect(float x, float y, float width, float height,float transparency, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++) {
                // here is the difference between the other method
                // this Method is slower then setPixel()
                plot(xx,yy,transparency,color);
            }
        }
    }

I'm used to write a method like this validateBoundary(float* x,float* y, float* width, float *height): void which includes the 'if-statments' and call it instead but clearly this won't be happen in Java.
What is the solution for problems like this? We could write a Methode validateBoundaryWidthf(xi, widhtf, pixelWitdth) which returns the  the new value for widthf. But something like this:

if (xi < 0) {
     widthf += xi;
     xi = 0;
}

can't be a solved by this because there is only one return value. Sure I could create a POJO with the attributes widthf and xi an return this instead but I assume this is comes expensive in terms of cpu / memory. So what is the proper way solving this duplicated code issue?

Body:
You can use consumers to handle the different handling inside the for loop. Define a new functional interface which takes the xx and yy values as arguments:

@FunctionalInterface
public interface PointConsumer {
    void accept(int x, int y);
}

Then you add a new method performOnPoints with all the arguments needed and with one PointConsumer argument. It might look like this:

public void performOnPoints(float x, float y, float width,
                            float height, PointConsumer consumer) {
    int xi = mapX(x);
    int yi = mapY(y);

    int heightf =  mapHeight(height);
    int widthf  = mapWidth(width);

    if (xi + widthf > pixelWidth){
        widthf -= xi + widthf - pixelWidth;
    }
    if (yi + heightf > pixelHeight){
        heightf -= yi + heightf - pixelHeight;
    }

    if (xi < 0) {
        widthf += xi;
        xi = 0;

    }
    if (yi < 0) {
        heightf += yi;
        yi = 0;
    }

    for (int xx = xi; xx < xi + widthf; xx++){
        for (int yy = yi; yy < yi + heightf; yy++){
            consumer.accept(xx, yy);
        }
    }
}

Then you can rewrite your existing fillRect methods like this:

public void fillRect(float x, float y, float width, float height, Color color) {
    performOnPoints(x, y, width, height, (xx, yy) -> setPixel(xx, yy, color));
}

public void fillRect(float x, float y, float width, float height,
        float transparency, Color color) {
    performOnPoints(x, y, width, height, (xx, yy) -> plot(xx,yy,transparency,color);
}

As you see they both use the same looping code with all the special if() statements, but you have this code only once. For the different arguments you will use a different consumer object, one will call setPixel(), the other will call plot().