答:
Simple map:

let names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
const res = names.map(({ firstname, lastname }) => ({ name: firstname + " " + lastname }));
console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

ES5 syntax:

var names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
var res = names.map(function(e) {
  return { name: e.firstname + " " + e.lastname };
});
console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Title: How do I push a field of an object into another array of object

Body:
I know how to operate on array of objects but never had the necessity to populate an array data into another. I need to populate firstname + lastname field into name field of birth array

let birth = [
    {name: '' }
]

firstly my array is empty and i want to poplulate it with these datas

let names = [
   {firstname: "Julien", lastname: "DEHAIS"},
   {firstname: "Cyril", lastname: "GUIGUIAN"},
   {firstname: "Pascal", lastname: "BOUTRIN"},
   {firstname: "Franck", lastname: "BORDERIE"},
   {firstname: "Arnold", lastname: "GIRARD"}
]

to get something like this

let birth = [
    {name: 'Julien DEHAIS' },
    {name: 'Cyril GUIGUIAN' },
    {name: 'Pascal BOUTRIN' },
    {name: 'Franck BORDERIE' },
    {name: 'Arnold GIRARD' }
]

Kindly someone help me in this please

Body:
Simple map:

let names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
const res = names.map(({ firstname, lastname }) => ({ name: firstname + " " + lastname }));
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
var res = names.map(function(e) {
  return { name: e.firstname + " " + e.lastname };
});
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }


来源: stackexchange

问:
Proper way to integrate JS in Angular
I want to include a JS library in my Angular app. I have searched for this and I found many approaches. In my case I will include this https://mauriciopoppe.github.io/function-plot/ library. My expectation was that I can create a module e.g. 'plot-function' that provides a function tag that takes the options the library needed.

As example:

    <ng-function [options]="options" [function]="function"></ng-function>

```

But I can't find an approache that will work like this.
Do you have any ideas, or is it not possible?

答:
There are a few considerations & different answers depending on what kind of library you are trying to integrate...

The library is an NPM module

If so, import it in to your code using the most up-to-date module
syntax the library supports - ideally using some kind of ES6/TypeScript import syntax covered here. If the library doesn't support one of these modern import syntaxes, you can still use ES5 require syntax:

```<code>const myModule = require('myModule');
</code>```

The library is not an NPM module

See this official guide

ContentLicense: CC BY-SA 4.0

Title: Proper way to integrate JS in Angular

Body:
I want to include a JS library in my Angular app. I have searched for this and I found many approaches. In my case I will include this https://mauriciopoppe.github.io/function-plot/ library. My expectation was that I can create a module e.g. 'plot-function' that provides a function tag that takes the options the library needed.

As example:

    <ng-function [options]="options" [function]="function"></ng-function>

But I can't find an approache that will work like this.
Do you have any ideas, or is it not possible?

Body:
There are a few considerations & different answers depending on what kind of library you are trying to integrate...

The library is an NPM module

If so, import it in to your code using the most up-to-date module
syntax the library supports - ideally using some kind of ES6/TypeScript import syntax covered here. If the library doesn't support one of these modern import syntaxes, you can still use ES5 require syntax:

const myModule = require('myModule');

The library is not an NPM module

See this official guide


问:
How to connect React Native and PostgreSQL?
Hey guys I have a question regarding React Native and PostgreSQL.

I've build a rn App where you can save data like hours, project and a comment and another screen where you can load it. It is a project for my workplace where we have an intern timemanagement system. Our database is a PostgreSQL database.

My question is how do I connect to our database ?
- I have a test DB running locally on my pc, I would like to connect to it first.

I did some research and found that I need to use fetch request.
Then I found out that there are two approaches (kinda):

1.node-postgres npm package (my Q: Do I need to know how to write in NodeJS?)

2.postgraphile GraphQL (my Q: Is it easier to do it with GraphQL? Do I need to be a GraphQL expert?)

I really appreciate any response or tipps you can give me.
Sincerly Faded.

答: The best way is to expose your data with an API, with nodejs and node-postgres for example.</p>


问:
asset path doesn't work with "/android_asset/" path
I am trying to use this library, like this:

```<code>        val imageUrl = "file:///android_asset/error_apng.png"
        val animator = ApngAnimator(this@MainActivity).loadInto(iv_circle)
        animator.load(imageUrl)
        animator.play()
</code>```

But it shows nothing. However, the sample url with https://works fine.

I tried with the followings:

file://android_asset/error_apng

file:///android_asset/apng/error_apng

asset://error_apng.pn

assets://error_apng.png

assets://error_apng.png

The README.md says I can use url or file path. What's wrong with it?

答:
You can try using this

```<code>val file = File("file:///android_asset/error_apng.png")
val animator = ApngAnimator(this@MainActivity).loadInto(iv_circle)
animator.load(file)
animator.play()
</code>```

If it doesn't work then try hosting your image in a image hosting website and use the url.

Body:
I am trying to use this library, like this:

        val imageUrl = "file:///android_asset/error_apng.png"
        val animator = ApngAnimator(this@MainActivity).loadInto(iv_circle)
        animator.load(imageUrl)
        animator.play()

But it shows nothing. However, the sample url with https://works fine.

I tried with the followings:

file://android_asset/error_apng

file:///android_asset/apng/error_apng

asset://error_apng.pn

assets://error_apng.png

assets://error_apng.png

The README.md says I can use url or file path. What's wrong with it?

Body:
You can try using this

val file = File("file:///android_asset/error_apng.png")
val animator = ApngAnimator(this@MainActivity).loadInto(iv_circle)
animator.load(file)
animator.play()

If it doesn't work then try hosting your image in a image hosting website and use the url.


问:
Pyinstaller executable fails importing torchvision
This is my main.py:

import torchvision
input("Press key")
```

<p>It runs correctly in the command line: <code>python main.py</code></p>

<p>I need an executable for windows. So I did : <code>pyinstaller main.py</code></p>

<p>But when I launched the <strong>main.exe</strong>, inside <code>/dist/main</code> I got this error:</p>

```Traceback (most recent call last):
  File "main.py", line 1, in <module>

  ... (omitted)

  File "site-packages\torchvision\ops\misc.py", line 135, in <module>
  File "site-packages\torchvision\ops\misc.py", line 148, in FrozenBatchNorm2d
  File "site-packages\torch\jit\__init__.py", line 850, in script_method
  File "site-packages\torch\jit\frontend.py", line 152, in get_jit_def
  File "inspect.py", line 973, in getsource
  File "inspect.py", line 955, in getsourcelines
  File "inspect.py", line 786, in findsource
OSError: could not get source code
[2836] Failed to execute script main
```

<p>It seems that some source code is not correctly imported from pyinstaller. I am not sure if the problems is the <strong>torch</strong> module or <strong>torchvision</strong>.</p>

<p>Additional info:</p>

<ul>
<li>I recently installed Visual Studio 2019</li>
</ul>

<p>System info:</p>

<ul>
<li>Window 10   </li>
<li>Python 3.7  </li>
<li>torch-1.1.0   </li>
<li>torchvision-0.3.0</li>
</ul>

<p>[EDIT]</p>

<p>I found that the problem is in the definition of the class <strong>FrozenBatchNorm2d</strong> inside torchvision. The following script produce the same error as the one before posted:</p>

<p><strong>main.py</strong></p>

```import torch

class FrozenBatchNorm2d(torch.jit.ScriptModule):

    def __init__(self, n):
        super(FrozenBatchNorm2d, self).__init__()

    @torch.jit.script_method

    def forward(self):
        pass
```

I copied all the torch source file. But I still got the error...

答:
Downgrade torchvision to the previous version fix the error.

```<code>pip uninstall torchvision
pip install torchvision==0.2.2.post3
</code>```

Body:
This is my main.py:

import torchvision
input("Press key")

It runs correctly in the command line: python main.py

I need an executable for windows. So I did : pyinstaller main.py

But when I launched the main.exe, inside /dist/main I got this error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>

  ... (omitted)

  File "site-packages\torchvision\ops\misc.py", line 135, in <module>
  File "site-packages\torchvision\ops\misc.py", line 148, in FrozenBatchNorm2d
  File "site-packages\torch\jit\__init__.py", line 850, in script_method
  File "site-packages\torch\jit\frontend.py", line 152, in get_jit_def
  File "inspect.py", line 973, in getsource
  File "inspect.py", line 955, in getsourcelines
  File "inspect.py", line 786, in findsource
OSError: could not get source code
[2836] Failed to execute script main

It seems that some source code is not correctly imported from pyinstaller. I am not sure if the problems is the torch module or torchvision.

Additional info:

I recently installed Visual Studio 2019

System info:

Window 10

Python 3.7

torch-1.1.0

torchvision-0.3.0

[EDIT]

I found that the problem is in the definition of the class FrozenBatchNorm2d inside torchvision. The following script produce the same error as the one before posted:

main.py

import torch

class FrozenBatchNorm2d(torch.jit.ScriptModule):

    def __init__(self, n):
        super(FrozenBatchNorm2d, self).__init__()

    @torch.jit.script_method

    def forward(self):
        pass

I copied all the torch source file. But I still got the error...

Body:
Downgrade torchvision to the previous version fix the error.

pip uninstall torchvision
pip install torchvision==0.2.2.post3


问:
How can I set a click listener only for Button in angular application
I just want to implement a event (click) listner into my angular application, which is only for button. buttons will be created dynamically.

the code looks like this:

```<code>  constructor(
    private companyService: CompanyService,
    elementRef: ElementRef,
    renderer: Renderer,
    private router: Router
  ) {
    renderer.listen(elementRef.nativeElement, "onclick", event => {
      // if (event.target.innerHTML) {
      //   this.searchByVin(event.target.innerHTML);
      // }
    });
  }

private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = `<div class="gridster-item-content"><button (click)="searchByVin(${elemValue})">${elemValue}</button></div>`;
      }
      if (elemKey === "status") {
        elemValue = `
        <mat-icon>done</mat-icon>`;
      }
      return elemValue;
    };
  }

</code>```

this 2 functions, which can create a button dynamically and in constructor will set a click event listner, but this listner is for all click event, the question is, how can I set this listner only for buttons.

Best Regards,

Leo

答:
I had a similar requiremrnt and I used Componetn to achive this.
Try Following this.

1. Create Component with your button

```<code><div nxRow *ngIf="editMode">
<div nxCol="12,12,6">
  <button nxButton='secondary' (click)='save()'>save</button>
</div>
<div nxCol="12,12,6">
  <button nxButton='secondary' (click)='cancel()'>cancel</button>
</div>
</div>
<div nxRow *ngIf="!editMode">
<div nxCol="12,12,12">
<button nxButton='secondary' (click)='edit()'>edit</button>
</div>
</div>
</code>```

TS:

```<code>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
// tslint:disable-next-line: component-selector
selector: 'az-save-edit-button',
templateUrl: './save-edit-button.component.html',
styleUrls: ['./save-edit-button.component.css']
})
export class SaveEditButtonComponent implements OnInit {

@Input() divId = null;
@Output() btnClick = new EventEmitter();
editMode = false;

constructor() { }

ngOnInit() {
}

save() {
this.editMode = false;
this.btnClick.emit({divId: this.divId, action: 'save'});
}

edit() {
this.editMode = true;
this.btnClick.emit({divId: this.divId, action: 'edit'});
}

cancel() {
this.editMode = false;
this.btnClick.emit({divId: this.divId, action: 'cancel'});
}

}
</code>```

2. create dynamically from parent component(pass your id)

```<code><az-save-edit-button [divId]="3" (btnClick)="functionCall($event)"></az-save-edit-button>
</code>```

on clik you will get the button id. Modify this to suit your requirement

Body:
I just want to implement a event (click) listner into my angular application, which is only for button. buttons will be created dynamically.

the code looks like this:

  constructor(
    private companyService: CompanyService,
    elementRef: ElementRef,
    renderer: Renderer,
    private router: Router
  ) {
    renderer.listen(elementRef.nativeElement, "onclick", event => {
      // if (event.target.innerHTML) {
      //   this.searchByVin(event.target.innerHTML);
      // }
    });
  }

private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = `<div class="gridster-item-content"><button (click)="searchByVin(${elemValue})">${elemValue}</button></div>`;
      }
      if (elemKey === "status") {
        elemValue = `
        <mat-icon>done</mat-icon>`;
      }
      return elemValue;
    };
  }

this 2 functions, which can create a button dynamically and in constructor will set a click event listner, but this listner is for all click event, the question is, how can I set this listner only for buttons.

Best Regards,

Leo

Body:
I had a similar requiremrnt and I used Componetn to achive this.
Try Following this.

1. Create Component with your button

<div nxRow *ngIf="editMode">
<div nxCol="12,12,6">
  <button nxButton='secondary' (click)='save()'>save</button>
</div>
<div nxCol="12,12,6">
  <button nxButton='secondary' (click)='cancel()'>cancel</button>
</div>
</div>
<div nxRow *ngIf="!editMode">
<div nxCol="12,12,12">
<button nxButton='secondary' (click)='edit()'>edit</button>
</div>
</div>

TS:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
// tslint:disable-next-line: component-selector
selector: 'az-save-edit-button',
templateUrl: './save-edit-button.component.html',
styleUrls: ['./save-edit-button.component.css']
})
export class SaveEditButtonComponent implements OnInit {

@Input() divId = null;
@Output() btnClick = new EventEmitter();
editMode = false;

constructor() { }

ngOnInit() {
}

save() {
this.editMode = false;
this.btnClick.emit({divId: this.divId, action: 'save'});
}

edit() {
this.editMode = true;
this.btnClick.emit({divId: this.divId, action: 'edit'});
}

cancel() {
this.editMode = false;
this.btnClick.emit({divId: this.divId, action: 'cancel'});
}

}

2. create dynamically from parent component(pass your id)

<az-save-edit-button [divId]="3" (btnClick)="functionCall($event)"></az-save-edit-button>

on clik you will get the button id. Modify this to suit your requirement


问:
JMeter HTML report - HTTP requests named <name>-0, <name>-1 <name>-2 etc - Why?
I have two thread groups in my project, and on of them has two HTTP request samplers. It's set up like the following

Thread group

   Timer: Random between 1 and 5 minutes: ${__Random(60000,300000)}

   HTTP request: A basic GET web service call

   HTTP request: A basic GET web service call

Here's the Thread group setup.

That's it. Here's an example of the web service call setup

And here's what the "Statistics" portion of the HTML report looks like. Note the -1, -2 after the HTTP Request names. I'm trying to figure out why that's happening.

My other thread group / samplers are not displaying that way, but they're set up the same way, as far as I can tell.

答:
In your example, HTTP requests Get Locations-0, Get Locations-1 are sub requests of Get Locations which appeared since you have selected the check box - Follow Redirects.

In case, you don't want HTTP requests Get Locations-0, Get Locations-1 to appear in your HTML report:
In the listener page(where you have saved the result file; which is the source file of HTML report) -> click on configure button -> uncheck the Save Sub Result option

You can also refer :Configure result file to customize HTML report


问:
How to add value of mean in number in violin plot using base R
I have data

```<code>Name    V1
M1      50
M2      10
M1      30
M1      45
M2      5
M2      7
</code>```

With my code, I was able to produce a violin plot. But I don't know how to put the value of mean in each violin plot in number using base R (not ggplot)?

Here is an example of my code.

```<code>with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="gray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

</code>```

Thanks a lot

答:
You could use the following code:

Your data:

```<code>Data <- read.table(header = TRUE,
            text = "Name    V1
                    M1      50
                    M2      10
                    M1      30
                    M1      45
                    M2      5
                    M2      7")
</code>```

Code

```<code>library(vioplot)
library(dplyr)

## calculate the mean per group
DataMean <- Data %>%
  group_by(Name) %>%
  summarize(mean = mean(V1))

## your plotting code
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="gray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

## use base r 'text' to add the calculated means
## at position 1 and 2 on the X-axis, and
## at height of the Y-axis of 60 (2 times)
text(x = c(1, 2), y = c(60,60), labels = round(DataMean$mean, 2))
</code>```

yielding the following plot:

Of course, we can play around with the position of the text. If we want the means to appear inside the violin plots, we use the mean values as Y-coordinates, and change the color to make it more visible (and shift the X-coordinates a little to the right, in combination with a lighter grey).

```<code>### playing with position and color
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="lightgray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
text(x = c(1.1, 2.1), y = DataMean$mean, labels = round(DataMean$mean, 2), col = "blue")
</code>```

yielding this plot:

Please, let me know whether this is what you want.

Body:
I have data

Name    V1
M1      50
M2      10
M1      30
M1      45
M2      5
M2      7

With my code, I was able to produce a violin plot. But I don't know how to put the value of mean in each violin plot in number using base R (not ggplot)?

Here is an example of my code.

with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="gray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

Thanks a lot

Body:
You could use the following code:

Your data:

Data <- read.table(header = TRUE,
            text = "Name    V1
                    M1      50
                    M2      10
                    M1      30
                    M1      45
                    M2      5
                    M2      7")

Code

library(vioplot)
library(dplyr)

## calculate the mean per group
DataMean <- Data %>%
  group_by(Name) %>%
  summarize(mean = mean(V1))

## your plotting code
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="gray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")

## use base r 'text' to add the calculated means
## at position 1 and 2 on the X-axis, and
## at height of the Y-axis of 60 (2 times)
text(x = c(1, 2), y = c(60,60), labels = round(DataMean$mean, 2))

yielding the following plot:

Of course, we can play around with the position of the text. If we want the means to appear inside the violin plots, we use the mean values as Y-coordinates, and change the color to make it more visible (and shift the X-coordinates a little to the right, in combination with a lighter grey).

### playing with position and color
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
                   plotCentre="line", rectCol="white", col="lightgray", ylab="",
                   ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
text(x = c(1.1, 2.1), y = DataMean$mean, labels = round(DataMean$mean, 2), col = "blue")

yielding this plot:

Please, let me know whether this is what you want.


问:
Heroku transfer db from one app to another
I need to transfer db from app_1 to app_2

I created backup on app_1

Then ran:

heroku pg:backups restore HEROKU_POSTGRESQL_COLOR --app app_2 heroku pgbackups:url --app app_1

HEROKU_POSTGRESQL_COLOR = database URL for app_2

Then I get:

```<code> !    `pg:backups` is not a heroku command.
 !    Perhaps you meant `pgbackups`.
 !    See `heroku help` for a list of available commands.
</code>```

So I ran:

heroku pgbackups:restore HEROKU_POSTGRESQL_COLOR --app app_2 heroku pgbackups:url --app app_1

Then I get the following:

```<code>!    WARNING: Destructive Action
!    This command will affect the app: app_2
!    To proceed, type "app_2" or re-run this command with --confirm app_2
</code>```

So I confirmed with:

```<code>> app_2
 !    Please add the pgbackups addon first via:
 !    heroku addons:add pgbackups
</code>```

So then I ran: heroku addons:add pgbackups --app app_2

```<code>Adding pgbackups on app_2... failed
 !    Add-on plan not found.
</code>```

Is there a way around this issue? any help would be greatly appreciated!

* Solution *

I ended up emailing Heroku, they advised that I need to heroku update; heroku plugins:update but heroku update is only available to heroku toolbelt only and I had the gem installed.

Solution:

Install Heroku toolbelt here

Then uninstall the gem:

```<code>gem uninstall heroku --all
</code>```

run the following to get the version and it should output heroku-toolbelt, instead of the gem, more info here

```<code>$ heroku --version
  heroku-toolbelt/2.39.0 (x86_64-darwin10.8.0) ruby/1.9.3
</code>```

To copy the databases over:

```<code>heroku pg:backups restore `heroku pgbackups:url --app app_1` HEROKU_POSTGRESQL_COLOR --app app_2
</code>```

But even better—you can copy directly from one database to another without needing the backup:

Assuming app_2 database url is: HEROKU_POSTGRESQL_GOLD

```<code>heroku pg:copy app_1::DATABASE_URL GOLD -a app_2
</code>```

That will copy the main database from app_1 to the GOLd database on app_2

答:
There are simple ways to do this, and there is a fast way to do it

The simple ways generally involve using a backup/restore methodology (including pg:copy, which is a backup that streams the data directly to a pg_restore process), but these are slow in creating the new database because you are restoring a logical definition of tables, loading the data, and creating indexes on the data.

That's a lot of work, and for my 30GB standard-2 databases it can literally take hours.

The fast way to do it is to provision a follower of the database to be copied (e.g. production) on the application you want the data on (e.g. test). On the same 30GB databases that take hours to do a restore, this last took about 15 minutes.

The methodology I use is:

```<code># Get the name of the source database addon (e.g. postgresql-clean-12345)
heroku pg:info -a production-app

# Create a follower on the destination app (choose your own plan)
# You create the follower on the new app because otherwise it is
# perpetually associated with the source as it's "billing app"
heroku addons:create heroku-postgresql:standard-2 --follow postgresql-clean-12345 -a test-app
heroku pg:wait -a test-app

# Quiesce the destination app
heroku scale web=0 worker=0 -a test-app
heroku maintenance:on -a test-app

# Get the colour of the new database (e.g. HEROKU_POSTGRESQL_GRAY_URL)
heroku pg:info -a test-app

# Unfollow the source database.
# If you want to upgrade the database, do that now instead of the
# unfollow.
heroku pg:unfollow HEROKU_POSTGRESQL_GRAY_URL -a test-app

# Promote the new database on the destination app
heroku pg:promote HEROKU_POSTGRESQL_GRAY_URL -a test-app

# Get the colour of the old database, if any(e.g. HEROKU_POSTGRESQL_MAROON_URL)
heroku pg:info -a test-app

# Destroy the old database (if any)
heroku addons:destroy HEROKU_POSTGRESQL_MAROON_URL -a test-app

# Bring the test app back up
heroku scale web=1 worker=1 -a test-app
heroku maintenance:off -a test-app
</code>```

Why is this faster?

I believe that when creating a follower, Heroku creates the new database by either copying data files or restoring from a physical (file) backup, then replaying the logs to bring it up to date.

ContentLicense: CC BY-SA 3.0

Body:
I need to transfer db from app_1 to app_2

I created backup on app_1

Then ran:

heroku pg:backups restore HEROKU_POSTGRESQL_COLOR --app app_2 heroku pgbackups:url --app app_1

HEROKU_POSTGRESQL_COLOR = database URL for app_2

Then I get:

 !    `pg:backups` is not a heroku command.
 !    Perhaps you meant `pgbackups`.
 !    See `heroku help` for a list of available commands.

So I ran:

heroku pgbackups:restore HEROKU_POSTGRESQL_COLOR --app app_2 heroku pgbackups:url --app app_1

Then I get the following:

!    WARNING: Destructive Action
!    This command will affect the app: app_2
!    To proceed, type "app_2" or re-run this command with --confirm app_2

So I confirmed with:

> app_2
 !    Please add the pgbackups addon first via:
 !    heroku addons:add pgbackups

So then I ran: heroku addons:add pgbackups --app app_2

Adding pgbackups on app_2... failed
 !    Add-on plan not found.

Is there a way around this issue? any help would be greatly appreciated!

* Solution *

I ended up emailing Heroku, they advised that I need to heroku update; heroku plugins:update but heroku update is only available to heroku toolbelt only and I had the gem installed.

Solution:

Install Heroku toolbelt here

Then uninstall the gem:

gem uninstall heroku --all

run the following to get the version and it should output heroku-toolbelt, instead of the gem, more info here

$ heroku --version
  heroku-toolbelt/2.39.0 (x86_64-darwin10.8.0) ruby/1.9.3

To copy the databases over:

heroku pg:backups restore `heroku pgbackups:url --app app_1` HEROKU_POSTGRESQL_COLOR --app app_2

But even better—you can copy directly from one database to another without needing the backup:

Assuming app_2 database url is: HEROKU_POSTGRESQL_GOLD

heroku pg:copy app_1::DATABASE_URL GOLD -a app_2

That will copy the main database from app_1 to the GOLd database on app_2

Body:
There are simple ways to do this, and there is a fast way to do it

The simple ways generally involve using a backup/restore methodology (including pg:copy, which is a backup that streams the data directly to a pg_restore process), but these are slow in creating the new database because you are restoring a logical definition of tables, loading the data, and creating indexes on the data.

That's a lot of work, and for my 30GB standard-2 databases it can literally take hours.

The fast way to do it is to provision a follower of the database to be copied (e.g. production) on the application you want the data on (e.g. test). On the same 30GB databases that take hours to do a restore, this last took about 15 minutes.

The methodology I use is:

# Get the name of the source database addon (e.g. postgresql-clean-12345)
heroku pg:info -a production-app

# Create a follower on the destination app (choose your own plan)
# You create the follower on the new app because otherwise it is
# perpetually associated with the source as it's "billing app"
heroku addons:create heroku-postgresql:standard-2 --follow postgresql-clean-12345 -a test-app
heroku pg:wait -a test-app

# Quiesce the destination app
heroku scale web=0 worker=0 -a test-app
heroku maintenance:on -a test-app

# Get the colour of the new database (e.g. HEROKU_POSTGRESQL_GRAY_URL)
heroku pg:info -a test-app

# Unfollow the source database.
# If you want to upgrade the database, do that now instead of the
# unfollow.
heroku pg:unfollow HEROKU_POSTGRESQL_GRAY_URL -a test-app

# Promote the new database on the destination app
heroku pg:promote HEROKU_POSTGRESQL_GRAY_URL -a test-app

# Get the colour of the old database, if any(e.g. HEROKU_POSTGRESQL_MAROON_URL)
heroku pg:info -a test-app

# Destroy the old database (if any)
heroku addons:destroy HEROKU_POSTGRESQL_MAROON_URL -a test-app

# Bring the test app back up
heroku scale web=1 worker=1 -a test-app
heroku maintenance:off -a test-app

Why is this faster?

I believe that when creating a follower, Heroku creates the new database by either copying data files or restoring from a physical (file) backup, then replaying the logs to bring it up to date.


问:
Check if devices has biometric enabled with androidx biometric prompt
In Android BiometricPrompt prompt has replaced the deprecated FingerprintManager.
FingerPrintManager has two functions hasEnrolledFingerprints() and isHardwareDetected() to check if the device supports fingerprints and if the user has enrolled any fingerprint authentication.

With the new BiometricPrompt it seems there are no functions to check this without trying to prompt the BiometricPrompt. There is a BiometricPrompt.AuthenticationCallback.onAuthenticationError( that is called with an error code indicating if the device supports biometric and if the user has biometric authentication enrolled.

So I can only get this information if I try to authenticate from the user. Is there a way to check without trying to prompt the authentication to check if the device supports biometrics and the user has enrolled them?

答:
FingerPrintManager has the data regarding fingerpint authentication only, hence it has hasEnrolledFringers(). But BiometricPrompt is used for face unlock, finerprint, iris. It's like a common manager class.
Google has added canAuthenticate which supports from Android Q.
But you can check it for lower API using

```<code>if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
       val hasBiometricFeature :Boolean = context.packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)
</code>```

Anyway, Google has also added it to androidx components androidx.biometric:biometric

```<code>implementation 'androidx.biometric:biometric:1.0.0-alpha04'
</code>```

uses permission

```<code><uses-permission android:name="android.permission.USE_BIOMETRIC" />
</code>```

on `AuthenticationCallback'

```<code>public void onAuthenticationError(int errorCode, CharSequence errString) {}
</code>```

you can check the error codes with the ones

```<code>/**
 * The user does not have any biometrics enrolled.
 */
int BIOMETRIC_ERROR_NO_BIOMETRICS = 11;
</code>```

Body:
FingerPrintManager has the data regarding fingerpint authentication only, hence it has hasEnrolledFringers(). But BiometricPrompt is used for face unlock, finerprint, iris. It's like a common manager class.
Google has added canAuthenticate which supports from Android Q.
But you can check it for lower API using

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
       val hasBiometricFeature :Boolean = context.packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)

Anyway, Google has also added it to androidx components androidx.biometric:biometric

implementation 'androidx.biometric:biometric:1.0.0-alpha04'

uses permission

<uses-permission android:name="android.permission.USE_BIOMETRIC" />

on `AuthenticationCallback'

public void onAuthenticationError(int errorCode, CharSequence errString) {}

you can check the error codes with the ones

/**
 * The user does not have any biometrics enrolled.
 */
int BIOMETRIC_ERROR_NO_BIOMETRICS = 11;


问:
How to plot scatter pie chart using matplotlib
I find the code example for drawing scatter pie chat

In this example, the size of each pie slices is identical across all three scatters. I would like to know if it is possible to make each pie chart unique (different number of slices and different pie proportions)

答:
you could implement it like this:

```<code>import numpy as np
import matplotlib.pyplot as plt

def drawPieMarker(xs, ys, ratios, sizes, colors):
    assert sum(ratios) <= 1, 'sum of ratios needs to be < 1'

    markers = []
    previous = 0
    # calculate the points of the pie pieces
    for color, ratio in zip(colors, ratios):
        this = 2 * np.pi * ratio + previous
        x  = [0] + np.cos(np.linspace(previous, this, 10)).tolist() + [0]
        y  = [0] + np.sin(np.linspace(previous, this, 10)).tolist() + [0]
        xy = np.column_stack([x, y])
        previous = this
        markers.append({'marker':xy, 's':np.abs(xy).max()**2*np.array(sizes), 'facecolor':color})

    # scatter each of the pie pieces to create pies
    for marker in markers:
        ax.scatter(xs, ys, **marker)

fig, ax = plt.subplots()
drawPieMarker(xs=np.random.rand(3),
              ys=np.random.rand(3),
              ratios=[.3, .2, .5],
              sizes=[80, 60, 100],
              colors=['cyan', 'orange', 'teal'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .66],
              sizes=[100, 120],
              colors=['blue', 'yellow'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .25],
              sizes=[50, 75],
              colors=['maroon', 'brown'])
plt.show()
</code>```

Body:
you could implement it like this:

import numpy as np
import matplotlib.pyplot as plt

def drawPieMarker(xs, ys, ratios, sizes, colors):
    assert sum(ratios) <= 1, 'sum of ratios needs to be < 1'

    markers = []
    previous = 0
    # calculate the points of the pie pieces
    for color, ratio in zip(colors, ratios):
        this = 2 * np.pi * ratio + previous
        x  = [0] + np.cos(np.linspace(previous, this, 10)).tolist() + [0]
        y  = [0] + np.sin(np.linspace(previous, this, 10)).tolist() + [0]
        xy = np.column_stack([x, y])
        previous = this
        markers.append({'marker':xy, 's':np.abs(xy).max()**2*np.array(sizes), 'facecolor':color})

    # scatter each of the pie pieces to create pies
    for marker in markers:
        ax.scatter(xs, ys, **marker)

fig, ax = plt.subplots()
drawPieMarker(xs=np.random.rand(3),
              ys=np.random.rand(3),
              ratios=[.3, .2, .5],
              sizes=[80, 60, 100],
              colors=['cyan', 'orange', 'teal'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .66],
              sizes=[100, 120],
              colors=['blue', 'yellow'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .25],
              sizes=[50, 75],
              colors=['maroon', 'brown'])
plt.show()


问:
Return series from specific value within pandas df
I am trying to return a series that contains some addition from specific values in a pandas df. Specifically, for the df below. I want to add all the X's with all the Y's. These aren't in any specific order though.

```<code>import pandas as pd

d = ({
    'Item' : ['X','Y','Z','X','Z','Y','Z'],
    'Value' : [10,11,20,21,10,30,31],
     })

df = pd.DataFrame(data=d)

Xs = df.loc[df['Item'] == 'X', 'Value']
Ys = df.loc[df['Item'] == 'Y', 'Value']

Out = Xs + Ys
</code>```

Intended Output:

```<code>21
51
</code>```

答:
Here is problem different indices, so need same by Series.reset_index with drop=True:

```<code>Out = Xs.reset_index(drop=True) + Ys.reset_index(drop=True)
print (Out)
0    21
1    51
Name: Value, dtype: int64
</code>```

Or if possible different length of Series use Series.add:

```<code>Out = Xs.reset_index(drop=True).add(Ys.reset_index(drop=True), fill_value=0)
</code>```

Or if always same length of Series is possible sum 1d numpy arrays:

```<code>Out = pd.Series(Xs.values + Ys.values)
print (Out)
0    21
1    51
dtype: int64
</code>```

Body:
I am trying to return a series that contains some addition from specific values in a pandas df. Specifically, for the df below. I want to add all the X's with all the Y's. These aren't in any specific order though.

import pandas as pd

d = ({
    'Item' : ['X','Y','Z','X','Z','Y','Z'],
    'Value' : [10,11,20,21,10,30,31],
     })

df = pd.DataFrame(data=d)

Xs = df.loc[df['Item'] == 'X', 'Value']
Ys = df.loc[df['Item'] == 'Y', 'Value']

Out = Xs + Ys

Intended Output:

21
51

Body:
Here is problem different indices, so need same by Series.reset_index with drop=True:

Out = Xs.reset_index(drop=True) + Ys.reset_index(drop=True)
print (Out)
0    21
1    51
Name: Value, dtype: int64

Or if possible different length of Series use Series.add:

Out = Xs.reset_index(drop=True).add(Ys.reset_index(drop=True), fill_value=0)

Or if always same length of Series is possible sum 1d numpy arrays:

Out = pd.Series(Xs.values + Ys.values)
print (Out)
0    21
1    51
dtype: int64


问:
How to pass values from html to python
I have a 4 buttons on first page which put me through to another page(All those 'buttons' are connected to database in mysql) and on this second page I have some data from mysql tables which I wanna display depending on what I have chosen in the first page. Right now I just display everything I have and I don't really know how to change that. I was looking for solutions but none worked.

views.py

```<code>def kategorie_list(request):

    obj = Kategorie.objects.all()
    context ={'obj': obj}
    return render(request, "kategorie/lista.html", context)

def uslugodawcy_list(request):

    obj = Uslugodawcy.objects.all()
    context ={'obj': obj}
    return render(request, "uslugodawcy/uslugodawcy_lista.html", context)
</code>```

first html page

```<code>{% for Kategorie in obj %}

     <p> <a class="btn btn-primary" href="/uslugodawcy"><button type="nw" style="height: 65px; width: 170px"> <font size="4">{{Kategorie.idkategorie}} . {{Kategorie.nazwakategorii}}</font> </button> </a> </p>

{% endfor %}
</code>```

second

```<code>{% for Uslugodawcy in obj %}

     <p> <a class="btn btn-primary" href="/promocje"><button type="nw" style="height: 65px; width: 170px"> <font size="4">{{Uslugodawcy.iduslugodawcy}} . {{Uslugodawcy.nazwa_uslugodawcy}} </font> </button> </a> </p>

{% endfor %}
</code>```

答:
There are many approaches. In outline:

Style a link as a button. . If the href is http://djangoserver/url?foo=bar then request.GET['foo'] will be available and equal to "bar".

Make all the buttons relate to a form that you are displaying and POSTing, so all of them do a SUBMIT but have diffferent values that you can find in request.POST. <button form="form-id" type="submit" ...>

Use Javascript to cause clicking the button to fill in fields on the form (which may be hidden fields, so the user has no other way of changing them.

Title: How to pass values from html to python

Body:
I have a 4 buttons on first page which put me through to another page(All those 'buttons' are connected to database in mysql) and on this second page I have some data from mysql tables which I wanna display depending on what I have chosen in the first page. Right now I just display everything I have and I don't really know how to change that. I was looking for solutions but none worked.

views.py

def kategorie_list(request):

    obj = Kategorie.objects.all()
    context ={'obj': obj}
    return render(request, "kategorie/lista.html", context)

def uslugodawcy_list(request):

    obj = Uslugodawcy.objects.all()
    context ={'obj': obj}
    return render(request, "uslugodawcy/uslugodawcy_lista.html", context)

first html page

{% for Kategorie in obj %}

 <button type="nw" style="height: 65px; width: 170px"> {{Kategorie.idkategorie}} . {{Kategorie.nazwakategorii}} </button>

{% endfor %}

second

{% for Uslugodawcy in obj %}

 <button type="nw" style="height: 65px; width: 170px"> {{Uslugodawcy.iduslugodawcy}} . {{Uslugodawcy.nazwa_uslugodawcy}}  </button>

{% endfor %}


问:
Repeat function itself without setInterval based on its finish
I need my program to repeat itself continuously. My program starts to fetch proxies from servers and saves them to a database and then send those saved proxies to another server again. So I don't know how long it takes for my program to do this task.

I wanna know what happens if any problem happens that makes this startJob() function take more than 30 seconds.

Does setInterval call it again or waits for function to finish?
What's the best approach for my program to repeat itself after it's done without setInterval?
(for exmaple startJob() being called again after it's done.)

I was wondering if it is ok to put this function in a loop with a big number like:

```<code>for ( let i = 0 ; i < 999999999 ; i ++ ) {
    await startJob()
}
</code>```

Here is my code:

```<code>
const startJob = async () => {
  await postProxyToChannel()
  grabProxies()
}

setInterval(function(){
  startJob()
}, (30000))

</code>```

grabProxies() takes about 10 seconds and postProxyToChannel() takes about 5 seconds on my server.

答:
Yup an infinite loop sounds good, that can be compared with a timer to pause the loop:

```<code>   const timer = ms => new Promise(resolve => setTimeout(resolve, ms));

  (async function() {
     while(true) {
        await postProxyToChannel();
        await grabProxies();
        await timer(30000);
     }
  })();
</code>```

Now that loop will run the task, wait 30secs, then do that again. Therefore the loop will not run every 30secs but will usually take longer. To adjust that, you could measure the time the task took, then await the rest of the time:

```<code>  const start = Date.now();

  await postProxyToChannel();
  await grabProxies();

  await timer(30000 - (Date.now() - start));
</code>```

Body:
I need my program to repeat itself continuously. My program starts to fetch proxies from servers and saves them to a database and then send those saved proxies to another server again. So I don't know how long it takes for my program to do this task.

I wanna know what happens if any problem happens that makes this startJob() function take more than 30 seconds.

Does setInterval call it again or waits for function to finish?
What's the best approach for my program to repeat itself after it's done without setInterval?
(for exmaple startJob() being called again after it's done.)

I was wondering if it is ok to put this function in a loop with a big number like:

for ( let i = 0 ; i < 999999999 ; i ++ ) {
    await startJob()
}

Here is my code:

const startJob = async () => {
  await postProxyToChannel()
  grabProxies()
}

setInterval(function(){
  startJob()
}, (30000))

grabProxies() takes about 10 seconds and postProxyToChannel() takes about 5 seconds on my server.

Body:
Yup an infinite loop sounds good, that can be compared with a timer to pause the loop:

   const timer = ms => new Promise(resolve => setTimeout(resolve, ms));

  (async function() {
     while(true) {
        await postProxyToChannel();
        await grabProxies();
        await timer(30000);
     }
  })();

Now that loop will run the task, wait 30secs, then do that again. Therefore the loop will not run every 30secs but will usually take longer. To adjust that, you could measure the time the task took, then await the rest of the time:

  const start = Date.now();

  await postProxyToChannel();
  await grabProxies();

  await timer(30000 - (Date.now() - start));


问:
Learning Python: Changing value in list based on condition
Sorry for the very basic question, but this is actually a 2-part question:

Given a list, I need to replace the values of '?' with 'i' and the 'x' with an integer, 10. The list does not always have the same number of elements, so I need a loop that permits me to do this.

```<code>a = ['1', '7', '?', '8', '5', 'x']
</code>```

How do I grab the index of where the value is equal to '?'. It'd be nice if this show me how I could grab all the index and values in a list as well.

答:
You can now use lambda</p>

```<code># replace occurrences of ?
a = map(lambda x: i if x == '?' else x, a)
# replace occurrences of x
a = list(map(lambda x: 10 if x == 'x' else x, a))
</code>```

Body:
Sorry for the very basic question, but this is actually a 2-part question:

Given a list, I need to replace the values of '?' with 'i' and the 'x' with an integer, 10. The list does not always have the same number of elements, so I need a loop that permits me to do this.

a = ['1', '7', '?', '8', '5', 'x']

How do I grab the index of where the value is equal to '?'. It'd be nice if this show me how I could grab all the index and values in a list as well.

Body:
You can now use lambda

# replace occurrences of ?
a = map(lambda x: i if x == '?' else x, a)
# replace occurrences of x
a = list(map(lambda x: 10 if x == 'x' else x, a))


问:
Yii2: How to set db console migration parameter as array
I want to migrate my test database using the command migrate/fresh --db=array as stated by the help:

```<code>--db: Connection|array|string
  the DB connection object or the application component ID of the DB connection to use
  when applying migrations. Starting from version 2.0.3, this can also be a configuration array
  for creating the object.
</code>```

but I don't know how to specify an array in the command line.

I have tried the following command:

```<code>  php yii migrate/fresh --db="dns=sqlite:@app/runtime/test.db"
</code>```

but I get

```<code>Exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\db\Connection::0'
</code>```

Having a look at console/Controller/runAction:

```<code>                if (in_array($name, $options, true)) {
                    $default = $this->$name;
                    if (is_array($default)) {
                        $this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
                    } elseif ($default !== null) {
                        settype($value, gettype($default));
                        $this->$name = $value;
                    } else {
                        $this->$name = $value;
                    }
</code>```

It looks like $this->db should be initaliced as an array if I want to be able to pass an array from the command line.

However, even if I set it as an array, the preg_split command indexes the configuracion array for the connection by number, not by an string key, so this array can not create a db connection.

答:
You can't configure it from console in this way. This description comes from $db property documentation, which is valid (MigrateController will handle array with configuration or Connection instance), but it is possible to define these formats only from PHP - from console you can pass only string.

If you really need to define connection dynamically from PHP, you can override MigrateController::beforeAction() and parse string in $db and convert it to array with Connection configuration - MigrateController will be able to handle it.

Body:
I want to migrate my test database using the command migrate/fresh --db=array as stated by the help:

--db: Connection|array|string
  the DB connection object or the application component ID of the DB connection to use
  when applying migrations. Starting from version 2.0.3, this can also be a configuration array
  for creating the object.

but I don't know how to specify an array in the command line.

I have tried the following command:

  php yii migrate/fresh --db="dns=sqlite:@app/runtime/test.db"

but I get

Exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\db\Connection::0'

Having a look at console/Controller/runAction:

                if (in_array($name, $options, true)) {
                    $default = $this->$name;
                    if (is_array($default)) {
                        $this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
                    } elseif ($default !== null) {
                        settype($value, gettype($default));
                        $this->$name = $value;
                    } else {
                        $this->$name = $value;
                    }

It looks like $this->db should be initaliced as an array if I want to be able to pass an array from the command line.

However, even if I set it as an array, the preg_split command indexes the configuracion array for the connection by number, not by an string key, so this array can not create a db connection.


问:
Twilio Sends transactional and promotional SMS
By using twilio Service provider and twilio sdk , I want to send transactional sms and  promotional sms from single account.

How can i achieve this ?

Any help would be appreciated!

答:
Do you have a specific Question?
Otherwise I would refer to the Twilio docs, there are a lot Step by Step guides to set up your Twilio sdk. </p>


问:
restore a factor variable original values
I have factor variable (Accuracy w/2 levels: "0", "1"). However, I have mistakenly converted to a numeric using the

Task_df_Acc_Exp$Accuracy <- as.numeric(Task_df_Acc_Exp$Accuracy)

Now when look up the variable, it looks like that the underlying internal coding  (1, 2) has overwritten the factor original values.

```<code>Accuracy: Factor w/ 2 levels "1","2": 1 1 1 2 1 2 2 2 2 1 ...
</code>```

I have tried to converted back to a factor variable, but the variable still the internal coding of (1, 2). Is there anyway I could converted to  factor and restored the original values back?
Do you think that this might affect any subsequent logistic analysis?

dput

```<code>Accuracy = structure(c(1L, 1L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor")
</code>```

答:
Here is a way to do it, juste decrease levels by one :</p>

```<code>levels(Task_df_Acc_Exp$Accuracy) <- as.numeric(levels(Task_df_Acc_Exp$Accuracy)) - 1
</code>```

Body:
I have factor variable (Accuracy w/2 levels: "0", "1"). However, I have mistakenly converted to a numeric using the

Task_df_Acc_Exp$Accuracy <- as.numeric(Task_df_Acc_Exp$Accuracy)

Now when look up the variable, it looks like that the underlying internal coding  (1, 2) has overwritten the factor original values.

Accuracy: Factor w/ 2 levels "1","2": 1 1 1 2 1 2 2 2 2 1 ...

I have tried to converted back to a factor variable, but the variable still the internal coding of (1, 2). Is there anyway I could converted to  factor and restored the original values back?
Do you think that this might affect any subsequent logistic analysis?

dput

Accuracy = structure(c(1L, 1L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor")

Body:
Here is a way to do it, juste decrease levels by one :

levels(Task_df_Acc_Exp$Accuracy) <- as.numeric(levels(Task_df_Acc_Exp$Accuracy)) - 1


问:
Using pure TNSNAMES rather than host-based database connections in Oracle JDeveloper
I'm using Oracle JDeveloper 11.1.1.4.0, and I can create database connections (with a type of Oracle (JDBC)) using the thin driver without any problems as long as I'm specifying a host.

For instance, I can connect to a locally-running Oracle XE database by specifying:

```<code>Driver: thin
Host Name: localhost
JDBC Port: 1521
Service Name: XE
</code>```

For connecting to remote databases, I use TNS, and my tnsnames.ora file is set up as below, where MYDATABASE.EXAMPLE.COM is the Oracle Service Identifier I want to use.

```<code>MYDATABASE.EXAMPLE.COM=
  (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=testdb.example.com)
      (PORT=1234)
    )
    (CONNECT_DATA=
      (SERVICE_NAME=MYDATABASE.example.com)
    )
  )
</code>```

Connections to the MYDATABASE.EXAMPLE.COM service work with SQL Developer, SQL Plus, TNSPING etc. from this machine but I can't find a way of specifying this in a JDeveloper database connection without being forced to specify a host.

The reason I don't want to specify a host is the same reason we're using TNS in the first place - the testdb.example.com host will change over time, but the MYDATABASE.EXAMPLE.COM TNS service identifier will not.

If I specify the host testdb.example.com along with the correct TNS alias, the connection works. If I specify the wrong identifier, it fails - it's definitely aware of the contents of my tnsnames.ora file.

Posts like this one seem to suggest that if JDeveloper is aware of TNS_ADMIN, it will use tnsnames.ora, but even using the "Enter Custom JDBC URL" doesn't work, using a string like:

```<code>jdbc:oracle:thin:MYDATABASE.EXAMPLE.COM
</code>```

It still gives the "Please enter a valid value for Host Name" error.

Does anybody know how to create a database connection in JDeveloper without specifying the host?

答:
According to the Oracle JDBC developer's guide, you need to specify the location of the tnsnames.ora file through a (JVM) system property in order to be able to use tnsnames with the thin driver:

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDIJCE

You will need to start SQL Developer in such a way that the system property oracle.net.tns_admin is defined.

Adding

AddVMOption  -Doracle.net.tns_admin=/path/to/tnsnames.ora

to ide.conf should do the trick (although I have not tried it).

Body:
I'm using Oracle JDeveloper 11.1.1.4.0, and I can create database connections (with a type of Oracle (JDBC)) using the thin driver without any problems as long as I'm specifying a host.

For instance, I can connect to a locally-running Oracle XE database by specifying:

Driver: thin
Host Name: localhost
JDBC Port: 1521
Service Name: XE

For connecting to remote databases, I use TNS, and my tnsnames.ora file is set up as below, where MYDATABASE.EXAMPLE.COM is the Oracle Service Identifier I want to use.

MYDATABASE.EXAMPLE.COM=
  (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=testdb.example.com)
      (PORT=1234)
    )
    (CONNECT_DATA=
      (SERVICE_NAME=MYDATABASE.example.com)
    )
  )

Connections to the MYDATABASE.EXAMPLE.COM service work with SQL Developer, SQL Plus, TNSPING etc. from this machine but I can't find a way of specifying this in a JDeveloper database connection without being forced to specify a host.

The reason I don't want to specify a host is the same reason we're using TNS in the first place - the testdb.example.com host will change over time, but the MYDATABASE.EXAMPLE.COM TNS service identifier will not.

If I specify the host testdb.example.com along with the correct TNS alias, the connection works. If I specify the wrong identifier, it fails - it's definitely aware of the contents of my tnsnames.ora file.

Posts like this one seem to suggest that if JDeveloper is aware of TNS_ADMIN, it will use tnsnames.ora, but even using the "Enter Custom JDBC URL" doesn't work, using a string like:

jdbc:oracle:thin:MYDATABASE.EXAMPLE.COM

It still gives the "Please enter a valid value for Host Name" error.

Does anybody know how to create a database connection in JDeveloper without specifying the host?


答:
No matter what happens inside startJob, setInterval will call it every 30 seconds. This means that postProxyToChannel will be called every 30 seconds. If that function throws, you'll get an unhandled Promise rejection, but the interval will continue.

Even if postProxyToChannel takes, say, 45 seconds, that won't prevent startJob from being called again before the prior startJob has completed.

If you want to make sure that startJob is only called 30 seconds after it finishes, you could await it in your for loop, then await a Promise that resolves every 30 seconds:

```<code>(async () => {
  for ( let i = 0 ; i < 999999999 ; i ++ ) {
    await startJob();
    await new Promise(resolve => setTimeout(resolve, 30000));
  }
})()
  .catch((err) => {
    console.log('There was an error', err);
  });
</code>```

But it would probably make more sense just to have a recursive call of startJob, eg:

```<code>const startJob = async () => {
  try {
    await postProxyToChannel();
  } catch(e) {
    // handle error
  }
  grabProxies();
  setTimeout(startJob, 30000);
};
startJob();
</code>```

Title: Repeat function itself without setInterval based on its finish

Body:
No matter what happens inside startJob, setInterval will call it every 30 seconds. This means that postProxyToChannel will be called every 30 seconds. If that function throws, you'll get an unhandled Promise rejection, but the interval will continue.

Even if postProxyToChannel takes, say, 45 seconds, that won't prevent startJob from being called again before the prior startJob has completed.

If you want to make sure that startJob is only called 30 seconds after it finishes, you could await it in your for loop, then await a Promise that resolves every 30 seconds:

(async () => {
  for ( let i = 0 ; i < 999999999 ; i ++ ) {
    await startJob();
    await new Promise(resolve => setTimeout(resolve, 30000));
  }
})()
  .catch((err) => {
    console.log('There was an error', err);
  });

But it would probably make more sense just to have a recursive call of startJob, eg:

const startJob = async () => {
  try {
    await postProxyToChannel();
  } catch(e) {
    // handle error
  }
  grabProxies();
  setTimeout(startJob, 30000);
};
startJob();


问:
Find duplicate for a combination of rows - Oracle SQL
I have a table:

table1

```<code>unique_id       user_id   user_seq      col_name            value_val    position
1               100       1             test1               100          1
1               100       1             test2               123          1
1               100       1             test1               a            2
1               100       1             test2               text         2
1               100       1             test3               1Rw          2
1               100       1             test4               1Tes         2

2               101       1             test1               1            1
2               101       1             test2               1            1
2               101       1             test3               1            1
2               101       1             test4               1            1
2               101       1             test5               1            1

3               100       1             test1               100          1
3               100       1             test2               123          1
3               100       1             test1               a            2
3               100       1             test2               text         2
3               100       1             test3               1Rw          2
3               100       1             test4               1Tes         2

4               101       1             test1               1            1
4               101       1             test2               1            1
4               101       1             test3               1            1
4               101       1             test4               1            1
</code>```

I need to find duplicate based on the following:

user_id, user_seq, col_name, value_val and position should be exactly same for different unique_id.

In the above example, unique_id - 1 and 3 are EXACTLY same, so they should be returned as output.

For unique_id = 2 and 4, there is a difference of test5 not available for unique_id = 4, so it won't be captured.

Output would be:

```<code>unique_id
1
3
</code>```

Also, my dataset is huge, around 50 million records, so need an optimized solution. Any help?

EDIT

My table structure:

```<code>Name        Null? Type
----------- ----- --------------
UNIQUE_ID          NUMBER
USER_SEQ           VARCHAR2(100)
COL_NAME           VARCHAR2(263)
VALUE_VAL          VARCHAR2(4000)
POSITION           NUMBER
USER_ID            NUMBER
</code>```

No indexes available.

答:
If performance is not an issue, what about a self join?</p>

```<code>select a.unique_id as unique_id
from table1 a join table1 b
on a.user_id = b.user_id
and a.user_seq = b.user_seq
and a.col_name = b.col_name
and a.value_val = b.value_val
and a.position = b.position
and a.unique_id <> b.unique_id
</code>```

Body:
I have a table:

table1

unique_id       user_id   user_seq      col_name            value_val    position
1               100       1             test1               100          1
1               100       1             test2               123          1
1               100       1             test1               a            2
1               100       1             test2               text         2
1               100       1             test3               1Rw          2
1               100       1             test4               1Tes         2

2               101       1             test1               1            1
2               101       1             test2               1            1
2               101       1             test3               1            1
2               101       1             test4               1            1
2               101       1             test5               1            1

3               100       1             test1               100          1
3               100       1             test2               123          1
3               100       1             test1               a            2
3               100       1             test2               text         2
3               100       1             test3               1Rw          2
3               100       1             test4               1Tes         2

4               101       1             test1               1            1
4               101       1             test2               1            1
4               101       1             test3               1            1
4               101       1             test4               1            1

I need to find duplicate based on the following:

user_id, user_seq, col_name, value_val and position should be exactly same for different unique_id.

In the above example, unique_id - 1 and 3 are EXACTLY same, so they should be returned as output.

For unique_id = 2 and 4, there is a difference of test5 not available for unique_id = 4, so it won't be captured.

Output would be:

unique_id
1
3

Also, my dataset is huge, around 50 million records, so need an optimized solution. Any help?

EDIT

My table structure:

Name        Null? Type
----------- ----- --------------
UNIQUE_ID          NUMBER
USER_SEQ           VARCHAR2(100)
COL_NAME           VARCHAR2(263)
VALUE_VAL          VARCHAR2(4000)
POSITION           NUMBER
USER_ID            NUMBER

No indexes available.

Body:
If performance is not an issue, what about a self join?

select a.unique_id as unique_id
from table1 a join table1 b
on a.user_id = b.user_id
and a.user_seq = b.user_seq
and a.col_name = b.col_name
and a.value_val = b.value_val
and a.position = b.position
and a.unique_id <> b.unique_id


问:
route not found on ajax post
I'm trying to create a dependent select using ajax, here is my JS

```<code>$("#make").change(function(){
    $.ajax({
        url: "{{ url('chauffeur/ajax_vehicle_model') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});
</code>```

My routing looks like this

```<code>Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('chauffeur/ajax_vehicle_model','Admin\ChauffeurController@get_vehicle_model');
});
</code>```

And in my controller I have this

```<code>public function get_vehicle_model(Request $request)
{
    ....
}
</code>```

But I get a 404 error, any idea what I'm doing wrong here?

答:
As you see, you have an argument in your route group prefix, with the value admin.

This prefixes your routes inside that route group with admin. This way, your url in JS should look like:

```<code>url(“admin/chauffeur/ajax_vehicle_model”)
</code>```

Title: route not found on ajax post

Body:
I'm trying to create a dependent select using ajax, here is my JS

$("#make").change(function(){
    $.ajax({
        url: "{{ url('chauffeur/ajax_vehicle_model') }}?make=" + $(this).val(),
        method: 'GET',
        success: function(data) {
            $('#model').html(data.html);
        }
    });
});

My routing looks like this

Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('chauffeur/ajax_vehicle_model','Admin\ChauffeurController@get_vehicle_model');
});

And in my controller I have this

public function get_vehicle_model(Request $request)
{
    ....
}

But I get a 404 error, any idea what I'm doing wrong here?

Body:
As you see, you have an argument in your route group prefix, with the value admin.

This prefixes your routes inside that route group with admin. This way, your url in JS should look like:

url(“admin/chauffeur/ajax_vehicle_model”)


问:
SignalR Websocket Exception when closing client
When starting and stopping a SignalR client that is connected to a basic self hosted server like this:

```<code>async public void Start(string url)
{
    _connection = new HubConnection(url);
    _proxy = _connection.CreateHubProxy("hubname");
    await _connection.Start().ContinueWith((task) => IsRunning = true);
}
public void Stop()
{
    _connection.Stop();
}
</code>```

I get the following exception when calling the "Stop" method (including trace messages):

```<code>SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)
SignalR.Transports.TransportHeartBeat Information: 0 : Connection 1bdabc19-e0a7-4649-aabb-bade071ad6d0 is New.
SignalR.Transports.WebSocketTransport Information: 0 : Abort(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.TransportHeartBeat Information: 0 : Removing connection 1bdabc19-e0a7-4649-aabb-bade071ad6d0
SignalR.Transports.WebSocketTransport Information: 0 : End(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.WebSocketTransport Verbose: 0 : DrainWrites(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.WebSocketTransport Information: 0 : CloseSocket(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
App.vshost.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<<CloseAsync>b__6>d__8.MoveNext()
App.vshost.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<<CloseAsync>b__6>d__8.MoveNext()
SignalR.Transports.WebSocketTransport Information: 0 : CompleteRequest (1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)
</code>```

The setups itself seem to work fine and devices can connect, send, receive, and disconnect. But with every disconnect I get the ugly above exception. Any idea what the problem could be? I am using SignalR 2.2.0 and Owin 1.2.2.

答:
I solved this problem with

```<code>connection.Reconnecting += connection.Stop;
</code>```

Because I found the connection state is always reconnecting

Body:
When starting and stopping a SignalR client that is connected to a basic self hosted server like this:

async public void Start(string url)
{
    _connection = new HubConnection(url);
    _proxy = _connection.CreateHubProxy("hubname");
    await _connection.Start().ContinueWith((task) => IsRunning = true);
}
public void Stop()
{
    _connection.Stop();
}

I get the following exception when calling the "Stop" method (including trace messages):

SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)
SignalR.Transports.TransportHeartBeat Information: 0 : Connection 1bdabc19-e0a7-4649-aabb-bade071ad6d0 is New.
SignalR.Transports.WebSocketTransport Information: 0 : Abort(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.TransportHeartBeat Information: 0 : Removing connection 1bdabc19-e0a7-4649-aabb-bade071ad6d0
SignalR.Transports.WebSocketTransport Information: 0 : End(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.WebSocketTransport Verbose: 0 : DrainWrites(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.WebSocketTransport Information: 0 : CloseSocket(1bdabc19-e0a7-4649-aabb-bade071ad6d0)
App.vshost.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<<CloseAsync>b__6>d__8.MoveNext()
App.vshost.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<<CloseAsync>b__6>d__8.MoveNext()
SignalR.Transports.WebSocketTransport Information: 0 : CompleteRequest (1bdabc19-e0a7-4649-aabb-bade071ad6d0)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(c75fe282-a86d-406a-935b-5981b47bd472)

The setups itself seem to work fine and devices can connect, send, receive, and disconnect. But with every disconnect I get the ugly above exception. Any idea what the problem could be? I am using SignalR 2.2.0 and Owin 1.2.2.

Body:
I solved this problem with

connection.Reconnecting += connection.Stop;

Because I found the connection state is always reconnecting


问:
How can I set session timeout for 2-3 days in PHP?
I would like to set my sessions to last for 2-3 days so that my users will not have to login to get data after days of being idle.

Please help me with the code to achieve this.

答:
You could try:</p>

```<code>ini_set('session.gc_maxlifetime', 2*60*60*24); // 2*60*60*24 = 2 days
</code>```

Body:
You could try:

ini_set('session.gc_maxlifetime', 2*60*60*24); // 2*60*60*24 = 2 days


问:
How to navigate to detail page using Flatlist
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

```<code>import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});
</code>```

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.

答:
make the renderRow ({ item }) function an arrow function
like renderRow = ({ item })=>{} , or try binding the function,

Body:
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.


问:
Change Double format - dot to comma
I must change Double format from dot to comma. I try this:

```<code>DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));
</code>```

but it`s not working. Have you got any ideas how you can change a dot to a comma?

答:
Code :

```<code>double value = 123.12345;
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
decimalFormatSymbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("#.###", decimalFormatSymbols);
System.out.println(df.format(value));
selectedSheet.addCell(new Number(selectedCellColumn, selectedCellRow, Double.valueOf(df.format(value)));
</code>```

Output :

```<code>123,123
</code>```

Title: Change Double format - dot to comma

Body:
I must change Double format from dot to comma. I try this:

DecimalFormat df = new DecimalFormat("#,00",
                   DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
                                 selectedCellRow,
                                 Double.valueOf(df.format(value)));

but it`s not working. Have you got any ideas how you can change a dot to a comma?

Body:
Code :

double value = 123.12345;
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
decimalFormatSymbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("#.###", decimalFormatSymbols);
System.out.println(df.format(value));
selectedSheet.addCell(new Number(selectedCellColumn, selectedCellRow, Double.valueOf(df.format(value)));

Output :

123,123


问:
How do you interpret "java.lang.NoSuchMethodError: No direct method"?
We decided, perhaps naively, that we should update many of our libraries from two-year-old 1.12.0-betas to nice new versions 1.20.0. For example: we updated google-http-client-1.12.0-beta.jar to google-http-client-android-1.20.0.jar.

When we execute this code:

```<code>  List<String> scopes = Lists.newArrayList(SendToGoogleUtils.FUSION_TABLES_SCOPE);
  GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(
      context, account.name, scopes );
  if (credential == null) {
    return false;
  }
  Fusiontables fusiontables = new Fusiontables.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
</code>```

we get this amazing error report:

```<code>FATAL EXCEPTION Caused by: java.lang.NoSuchMethodError: No direct method <init>(Lcom/google/api/client/http/HttpTransport;Lcom/google/api/client/http/HttpRequestInitializer;Ljava/lang/String;Ljava/lang/String;Lcom/google/api/client/json/JsonObjectParser;Lcom/google/api/client/googleapis/services/GoogleClientRequestInitializer;Ljava/lang/String;Z)V in class Lcom/google/api/client/googleapis/services/json/AbstractGoogleJsonClient; or its super classes (declaration of 'com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient' appears in /data/app/dkr.ajijic.apps.tm-1/base.apk)
</code>```

Does anybody know how to interpret it? We sure don't!

答:
This issue is happened because of Proguard is applied via Proguard this class name and methods name changes that why NoSuchMethod exception is occurring.

To resolve this error please add below line into you Proguard rules.

-keep class com.google.** { *; }

Hopefully this will resolve your issue.

Body:
We decided, perhaps naively, that we should update many of our libraries from two-year-old 1.12.0-betas to nice new versions 1.20.0. For example: we updated google-http-client-1.12.0-beta.jar to google-http-client-android-1.20.0.jar.

When we execute this code:

  List<String> scopes = Lists.newArrayList(SendToGoogleUtils.FUSION_TABLES_SCOPE);
  GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(
      context, account.name, scopes );
  if (credential == null) {
    return false;
  }
  Fusiontables fusiontables = new Fusiontables.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();

we get this amazing error report:

FATAL EXCEPTION Caused by: java.lang.NoSuchMethodError: No direct method <init>(Lcom/google/api/client/http/HttpTransport;Lcom/google/api/client/http/HttpRequestInitializer;Ljava/lang/String;Ljava/lang/String;Lcom/google/api/client/json/JsonObjectParser;Lcom/google/api/client/googleapis/services/GoogleClientRequestInitializer;Ljava/lang/String;Z)V in class Lcom/google/api/client/googleapis/services/json/AbstractGoogleJsonClient; or its super classes (declaration of 'com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient' appears in /data/app/dkr.ajijic.apps.tm-1/base.apk)

Does anybody know how to interpret it? We sure don't!


答:
Do not increase session time for a huge amount of time.

Instead you can use the remember me cookies for your purpose.

You can create a cookie to store user name and password set the time for cookies life time to 2 or 3 days.

Whenever user enter your site check for existence of these cookie if they exists log in them backgroundly and redirect them on landing page.

Whenever the logout delete these cookies as well.

Title: How can I set session timeout for 2-3 days in PHP?

Body:
I would like to set my sessions to last for 2-3 days so that my users will not have to login to get data after days of being idle.

Please help me with the code to achieve this.


问:
How to format textbox field in Access form to show data the same as in imported file to the table
I have a textbox, which is presenting data from one field in selected recordset. This field contains comments made by user in Excel file, which is later imported to Access table. Each comment is made in separete line and in each it looks ok. Textbox present it as one line, but when I export it to Excel again it looks ok in that new excel.

I have tried changing textbox into rich text format. I have also create other textbox, in which I am able to insert comments and then it looks good.

Textbox source code:

```<code>sSql = SELECT LogID, 1Comment, 2Comment, Author
sSql = sSql & " FROM tblGeneralLog"
sSql = sSql & " WHERE LogID= " & Me.ID &

Forms![frmMain_CommentAdd]![txtboxComment2].Value = CurrentDb.OpenRecordset(sSql).Fields(2).Value
</code>```

答:
Probably, in Excel you don't have a "full new line" (CR + LF). Thus, try:

```<code>Forms![frmMain_CommentAdd]![txtboxComment2].Value = Replace(CurrentDb.OpenRecordset(sSql).Fields(2).Value, vbCr, vbCrLf)
</code>```

or:

```<code>Forms![frmMain_CommentAdd]![txtboxComment2].Value = Replace(CurrentDb.OpenRecordset(sSql).Fields(2).Value, vbLf, vbCrLf)
</code>```

Body:
I have a textbox, which is presenting data from one field in selected recordset. This field contains comments made by user in Excel file, which is later imported to Access table. Each comment is made in separete line and in each it looks ok. Textbox present it as one line, but when I export it to Excel again it looks ok in that new excel.

I have tried changing textbox into rich text format. I have also create other textbox, in which I am able to insert comments and then it looks good.

Textbox source code:

sSql = SELECT LogID, 1Comment, 2Comment, Author
sSql = sSql & " FROM tblGeneralLog"
sSql = sSql & " WHERE LogID= " & Me.ID &

Forms![frmMain_CommentAdd]![txtboxComment2].Value = CurrentDb.OpenRecordset(sSql).Fields(2).Value

Body:
Probably, in Excel you don't have a "full new line" (CR + LF). Thus, try:

Forms![frmMain_CommentAdd]![txtboxComment2].Value = Replace(CurrentDb.OpenRecordset(sSql).Fields(2).Value, vbCr, vbCrLf)

or:

Forms![frmMain_CommentAdd]![txtboxComment2].Value = Replace(CurrentDb.OpenRecordset(sSql).Fields(2).Value, vbLf, vbCrLf)