问:
Sort by price not working in Magento Product List
I am unable to sort product by price in product list page.

Sort by name works fine there.

Any idea guys?

I googled and tried some solution but they didn't solve my problem.

I tried: System->Cache Management->Layered Navigation Indices->Refresh now

Also tried this link: http://www.miromedia.co.uk/blog/300/fixing-the-magento-price-sort-issue.htm

Magento version: 1.3.2.4

答:
You need to configure the price attribute correctly in Magento admin.

Go to attribute management, find the price attribute and ensure that you tick the box on "sortable in frontend"

that should resolve this for you.


来源: stackexchange

问:
ERROR: Attribute '2017-02-28' not found
I have the following query which runs in SAS using proc sql where I have an automated variable which contains the month end date but it results in the following error

```<code>ERROR: Prepare error: ICommandPrepare::Prepare failed. : ERROR:  Attribute '2017-02-28' not found
</code>```

Query:

```<code>proc sql;
 connect to oledb (datasource='10.1.0.105'  provider=nzoledb
    user=&user_id password=&pwd properties=('initial catalog'=ODS));
 create table &user..Pers_test as select * from connection to oledb
 (SELECT  a.ID from  DBO.Table1
   where a.SOURCE_SYSTEM_CREATED_DTM <= "&monthend."
Group by a.SWID order by a.SWID
 );
%let _sql_xrc=&sqlxrc;
disconnect from oledb;
quit;
</code>```

However the query runs when the timestamp is hardcoded.

```<code>proc sql;
 connect to oledb (datasource='10.1.0.105'  provider=nzoledb
    user=&user_id password=&pwd properties=('initial catalog'=ODS));
 create table &user..Pers_test as select * from connection to oledb
 (SELECT  a.ID from  DBO.Table1
   where a.SOURCE_SYSTEM_CREATED_DTM <= '2017-02-28 00:00:00'
Group by a.SWID order by a.SWID
 );
%let _sql_xrc=&sqlxrc;
disconnect from oledb;
quit;
</code>```

I have tried casting, substring but it all results in the same error. Any help is appreciated to work around with the automated variable.

答:
I modified Karan Pappala's answer to make it work for me:</p>

```<code>%unquote(%str(%')&execution_method.%str(%'))
</code>```

ContentLicense: CC BY-SA 3.0

Title: ERROR: Attribute '2017-02-28' not found

Body:
I have the following query which runs in SAS using proc sql where I have an automated variable which contains the month end date but it results in the following error

ERROR: Prepare error: ICommandPrepare::Prepare failed. : ERROR:  Attribute '2017-02-28' not found

Query:

proc sql;
 connect to oledb (datasource='10.1.0.105'  provider=nzoledb
    user=&user_id password=&pwd properties=('initial catalog'=ODS));
 create table &user..Pers_test as select * from connection to oledb
 (SELECT  a.ID from  DBO.Table1
   where a.SOURCE_SYSTEM_CREATED_DTM <= "&monthend."
Group by a.SWID order by a.SWID
 );
%let _sql_xrc=&sqlxrc;
disconnect from oledb;
quit;

However the query runs when the timestamp is hardcoded.

proc sql;
 connect to oledb (datasource='10.1.0.105'  provider=nzoledb
    user=&user_id password=&pwd properties=('initial catalog'=ODS));
 create table &user..Pers_test as select * from connection to oledb
 (SELECT  a.ID from  DBO.Table1
   where a.SOURCE_SYSTEM_CREATED_DTM <= '2017-02-28 00:00:00'
Group by a.SWID order by a.SWID
 );
%let _sql_xrc=&sqlxrc;
disconnect from oledb;
quit;

I have tried casting, substring but it all results in the same error. Any help is appreciated to work around with the automated variable.

Body:
I modified Karan Pappala's answer to make it work for me:

%unquote(%str(%')&execution_method.%str(%'))

ContentLicense: CC BY-SA 4.0


问:
"Expression Expected" error on line 1. How to fix it?
I am getting the "In line 1, expression expected" error and I am not sure why.

I am using the CPU Emulator from nand2tetris. I tried changing line 1 to 5, but it did not solve the problem. I just do not get what is the problem in the first place.

```<code>@j
D=5;
@i;
M=1;
@5
@i
D=M
D=D-A;
@END
D;JGT
@j
@1
M=M-A
@i
@1
M=M+A
@LOOP
0;JMP
</code>```

What I am trying to recreate is this loop:
    J=5
    for(i=1; i<5; i++) {
                    j--
    }

答:
There are several issues that pop out at first glance.

First, D=5 is not a valid Hack operation. If you want to load 5 into D, you have to first load it into A and then move to D:

```<code>@5
D=A
</code>```

Second, ; is the jump delimiter, and should be followed by a jump condition (such as JEQ, or JMP for an unconditional jump). You have several lines (including line 1) where you have a ; but no jump condition. These should be removed.

Finally, you should probably review the book pages on the Hack assembly language syntax to make sure you are clear on how it works. In particular, in the above code, you haven't specified your jump targets like END and LOOP. This is done with the (LABEL) construct.

Body:
I am getting the "In line 1, expression expected" error and I am not sure why.

I am using the CPU Emulator from nand2tetris. I tried changing line 1 to 5, but it did not solve the problem. I just do not get what is the problem in the first place.

@j
D=5;
@i;
M=1;
@5
@i
D=M
D=D-A;
@END
D;JGT
@j
@1
M=M-A
@i
@1
M=M+A
@LOOP
0;JMP

What I am trying to recreate is this loop:
    J=5
    for(i=1; i<5; i++) {
                    j--
    }

Body:
There are several issues that pop out at first glance.

First, D=5 is not a valid Hack operation. If you want to load 5 into D, you have to first load it into A and then move to D:

@5
D=A

Second, ; is the jump delimiter, and should be followed by a jump condition (such as JEQ, or JMP for an unconditional jump). You have several lines (including line 1) where you have a ; but no jump condition. These should be removed.

Finally, you should probably review the book pages on the Hack assembly language syntax to make sure you are clear on how it works. In particular, in the above code, you haven't specified your jump targets like END and LOOP. This is done with the (LABEL) construct.


问:
using python: How can I convert given UT time to LST time Such that the function automatically increments day after 24 Hr check
I want to convert given Universal Time (UT)  to  Local Time (LT) . Such that the function automatically increments day after 24 Hr check. I tried various codes. I successfully converted time but unable to increment it by certain duration in a loop.</p>

答:
Try the below code:</p>

```<code>>>> from datetime import datetime
>>> import pytz
>>> dt = datetime.utcnow()
>>> dt.astimezone(pytz.timezone('Europe/Paris'))
datetime.datetime(2019, 5, 28, 4, 44, 12, 778393, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> print(dt.astimezone(pytz.timezone('Europe/Paris')))
2019-05-28 04:44:12.778393+02:00
>>>
</code>```

Body:
Try the below code:

>>> from datetime import datetime
>>> import pytz
>>> dt = datetime.utcnow()
>>> dt.astimezone(pytz.timezone('Europe/Paris'))
datetime.datetime(2019, 5, 28, 4, 44, 12, 778393, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> print(dt.astimezone(pytz.timezone('Europe/Paris')))
2019-05-28 04:44:12.778393+02:00
>>>


问:
Make radio buttons checked /unchecked

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css('background', 'blue');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool"></code>```

My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:

1 and 2 radio buttons are selected, it  should be only 2 :checked

答:
The issue with your JS is that you never remove the class from any of the unselected checkboxes. Also note that each() only runs when the page loads (assuming you've not placed it in an event handler, but the question doesn't show that), so you need to instead run your logic in a change event handler:

```<code>var $radio = $("input[type='radio']").on('change', function() {
  $radio.removeClass('blue');
  $(this).toggleClass('blue', this.checked);
});
</code>```

That being said, what you're trying to do can be achieved more simply by using CSS:

input {
  visibility: hidden;
}
input:before {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #CCC;
  visibility: visible;
}

input:checked:before {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool"></code>```

Title: Make radio buttons checked /unchecked

Body:
$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css('background', 'blue');
  }
});

<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">

My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:

1 and 2 radio buttons are selected, it  should be only 2 :checked

Body:
The issue with your JS is that you never remove the class from any of the unselected checkboxes. Also note that each() only runs when the page loads (assuming you've not placed it in an event handler, but the question doesn't show that), so you need to instead run your logic in a change event handler:

var $radio = $("input[type='radio']").on('change', function() {
  $radio.removeClass('blue');
  $(this).toggleClass('blue', this.checked);
});

That being said, what you're trying to do can be achieved more simply by using CSS:

input {
  visibility: hidden;
}
input:before {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #CCC;
  visibility: visible;
}

input:checked:before {
  background-color: blue;
}

<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">


问:
How to perform Join between multiple tables in LINQ lambda
I am trying to perform a Join between multiple tables in LINQ. I have the following classes:

```<code>Product {Id, ProdName, ProdQty}

Category {Id, CatName}

ProductCategory{ProdId, CatId} //association table
</code>```

And I use the following code (where product, category and productcategory are instances of the above classes):

```<code>var query = product.Join(productcategory, p => p.Id, pc => pc.ProdID, (p, pc) => new {product = p, productcategory = pc})
                   .Join(category, ppc => ppc.productcategory.CatId, c => c.Id, (ppc, c) => new { productproductcategory = ppc, category = c});
</code>```

With this code I obtain an object from the following class:

```<code>QueryClass { productproductcategory, category}
</code>```

Where producproductcategory is of type:

```<code>ProductProductCategoryClass {product, productcategory}
</code>```

I do not understand where the joined "table" is, I was expecting a single class that contains all the properties from the involved classes.

My aim is to populate another object with some properties resulting from the query:

```<code>CategorizedProducts catProducts = query.Select(m => new { m.ProdId = ???, m.CatId = ???, //other assignments });
</code>```

how can I achieve this goal?

答:
it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

```<code>        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();
</code>```

Body:
I am trying to perform a Join between multiple tables in LINQ. I have the following classes:

Product {Id, ProdName, ProdQty}

Category {Id, CatName}

ProductCategory{ProdId, CatId} //association table

And I use the following code (where product, category and productcategory are instances of the above classes):

var query = product.Join(productcategory, p => p.Id, pc => pc.ProdID, (p, pc) => new {product = p, productcategory = pc})
                   .Join(category, ppc => ppc.productcategory.CatId, c => c.Id, (ppc, c) => new { productproductcategory = ppc, category = c});

With this code I obtain an object from the following class:

QueryClass { productproductcategory, category}

Where producproductcategory is of type:

ProductProductCategoryClass {product, productcategory}

I do not understand where the joined "table" is, I was expecting a single class that contains all the properties from the involved classes.

My aim is to populate another object with some properties resulting from the query:

CategorizedProducts catProducts = query.Select(m => new { m.ProdId = ???, m.CatId = ???, //other assignments });

how can I achieve this goal?

Body:
it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();


问:
Angular 7 - How to limit event trigger to specific component where event occurs?
I have a list of text areas:

text-area.component.html

<textarea [ngClass]="generateTextAreaClass()" (keypress)="onKeyPress($event)">{{ value }}</textarea>
```

<p>The textarea has a <code>keypress</code> event.</p>

<p>When I press a key in one of the textareas, it triggers the <code>keypress</code> event for all instances of this component.</p>

<p>As a result, I get 5 events being triggered. This obviously doesn't represent the action I just made as a user.</p>

```{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
```

<p>How can I limit the event to only be triggered for the textarea that I'm currently typing in so that only one event gets triggered?</p>

<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-utility-textarea',
  templateUrl: './text-area.component.html',
  styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements AfterViewInit {

  constructor(private eventBus: EventBusService) {
  }

  @Input() value: string;
  @Input() id: string;
  public textAreaClassPrefix = 'app-utility-textarea';

  ...

  generateTextAreaClass(): string {
    return `${this.textAreaClassPrefix}-${this.id}`;
  }

  onKeyPress(event: KeyboardEvent) {
    event.stopPropagation();
    if (event.key === 'Enter' && event.shiftKey) {
      event.preventDefault();
      const textAreaKeyPressEvent: TextAreaKeyPressEvent = {
        textareaSelector: this.generateTextAreaClassCSSSelector(),
        keypressType: TextAreaKeyPressType.SHIFT_ENTER
      };
      this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
    }
  }
}
</code>```

event-bus.service.ts

@Injectable()
export class EventBusService {

  public navbarSubject$ = new BehaviorSubject(DashboardNavbarEvent.SIDEBAR_MENU_CLOSED);
  public textAreaKeyPressSubject$ = new Subject<TextAreaKeyPressEvent>();

  constructor() {
  }

}
```

<p><strong>subscriber.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-subscriber',
  templateUrl: './subscriber.component.html',
  styleUrls: ['./subscriber.component.scss']
})
export class SubscriberComponent implements OnInit {

  @Input() public block: any;
  @Input() public index: number;

  constructor(private eventBus: EventBusService) {
  }

  ngOnInit() {
    this.eventBus.textAreaKeyPressSubject$.subscribe((event: TextAreaKeyPressEvent) => {
      console.log(event);
    });
  }

}
</code>```

答:
Turns out this was a design problem. I was subscribing to the textAreaKeyPressSubject$ inside another component that had 5 instances. Every instance ended up subscribing to the textAreaKeyPressSubject$ on init and logged the event 1 time each.

The keypress event was only triggered once in the textarea.component.ts where I was typing.

When I moved the subscription to this subject to a parent component that only had one instance, this issue was resolved.

Body:
I have a list of text areas:

text-area.component.html

<textarea [ngClass]="generateTextAreaClass()" (keypress)="onKeyPress($event)">{{ value }}</textarea>

The textarea has a keypress event.

When I press a key in one of the textareas, it triggers the keypress event for all instances of this component.

As a result, I get 5 events being triggered. This obviously doesn't represent the action I just made as a user.

{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}

How can I limit the event to only be triggered for the textarea that I'm currently typing in so that only one event gets triggered?

@Component({
  selector: 'app-utility-textarea',
  templateUrl: './text-area.component.html',
  styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements AfterViewInit {

  constructor(private eventBus: EventBusService) {
  }

  @Input() value: string;
  @Input() id: string;
  public textAreaClassPrefix = 'app-utility-textarea';

  ...

  generateTextAreaClass(): string {
    return `${this.textAreaClassPrefix}-${this.id}`;
  }

  onKeyPress(event: KeyboardEvent) {
    event.stopPropagation();
    if (event.key === 'Enter' && event.shiftKey) {
      event.preventDefault();
      const textAreaKeyPressEvent: TextAreaKeyPressEvent = {
        textareaSelector: this.generateTextAreaClassCSSSelector(),
        keypressType: TextAreaKeyPressType.SHIFT_ENTER
      };
      this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
    }
  }
}

event-bus.service.ts

@Injectable()
export class EventBusService {

  public navbarSubject$ = new BehaviorSubject(DashboardNavbarEvent.SIDEBAR_MENU_CLOSED);
  public textAreaKeyPressSubject$ = new Subject<TextAreaKeyPressEvent>();

  constructor() {
  }

}

subscriber.component.ts

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

  @Input() public block: any;
  @Input() public index: number;

  constructor(private eventBus: EventBusService) {
  }

  ngOnInit() {
    this.eventBus.textAreaKeyPressSubject$.subscribe((event: TextAreaKeyPressEvent) => {
      console.log(event);
    });
  }

}


问:
Getting undefined error while setting a state
I am using API to extract data from Amazon API and I am using react js for it.

The problem is when I extract them and save it in the state it gives me an error of undefined, however, I am getting the result from the API. The function takes time to get data from API, I am using a method of extracting data which is suitable in node js but also working in react and I am getting a result, but unable to save it in a state. Here's the code below:

```<code>    let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, function(e, result) {
        temp=result;
        this.setState({amazon_data:result})  // gives undefined error
    });
</code>```

I think the reason is the function execution takes time and it runs the setstate line which makes the result null, any suggestions on how to fix this?

答:
That happens because this.setState is not part of the this scope inside your function.

```<code> let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;
    const _this = this;
    mws.request(getReport, function(e, result) {
        temp=result;
        _this.setState({amazon_data:result})  // this works because _this references the outer this
    });
</code>```

That should work or you can use arrow functions like below.

```<code> let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, (e, result) => {
        temp=result;
        this.setState({amazon_data:result})  // this works because the arrow function binds the outer this to the function
    });
</code>```

Body:
I am using API to extract data from Amazon API and I am using react js for it.

The problem is when I extract them and save it in the state it gives me an error of undefined, however, I am getting the result from the API. The function takes time to get data from API, I am using a method of extracting data which is suitable in node js but also working in react and I am getting a result, but unable to save it in a state. Here's the code below:

    let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, function(e, result) {
        temp=result;
        this.setState({amazon_data:result})  // gives undefined error
    });

I think the reason is the function execution takes time and it runs the setstate line which makes the result null, any suggestions on how to fix this?

Body:
That happens because this.setState is not part of the this scope inside your function.

 let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;
    const _this = this;
    mws.request(getReport, function(e, result) {
        temp=result;
        _this.setState({amazon_data:result})  // this works because _this references the outer this
    });

That should work or you can use arrow functions like below.

 let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, (e, result) => {
        temp=result;
        this.setState({amazon_data:result})  // this works because the arrow function binds the outer this to the function
    });


问:
How to debug this error on Pycharm and Django
I'm trying to make a website using Django, and my next step is run manage.py, to create superuser, but when I input Username, Email address, password, then press Enter, the IDE (Pycharm) feedback an Commanderror:

```<code>manage.py@education > createsuperuser
"D:\PyCharm 2019.1\bin\runnerw64.exe" E:\pythonproject\education\Scripts\python.exe "D:\PyCharm 2019.1\helpers\pycharm\django_manage.py" createsuperuser E:/pythonproject/education
Tracking file by folder pattern:  migrations
Username:  admin
Email address:  976413993@qq.com
Warning: Password input may be echoed.
Password:  12345678
Warning: Password input may be echoed.
Password (again):  12345678
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]:  y
CommandError: '' value has an invalid date format. It must be in YYYY-MM-DD format.
</code>```

This is UserProfile:

```<code># -*- encoding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime

# Create your models here.

class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, default="", verbose_name=u"昵称")
    birday = models.DateField(verbose_name=u"生日", default="")
    gender = models.CharField(choices=(("male", u"男"), ("female", u"女")), default="male", max_length=10)
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username

class EmailVerifyRecord(models.Model):
    code = models.CharField(max_length=20, verbose_name=u"验证码")
    email = models.EmailField(max_length=50, verbose_name=u"邮箱")
    send_type = models.CharField(choices=(("register", u"注册"), ("forget", u"找回密码")), max_length=10)
    send_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name = u"邮箱验证码"
        verbose_name_plural = verbose_name

class Banner(models.Model):
    title = models.CharField(max_length=100, verbose_name=u"标题")
    image = models.ImageField(upload_to="banner/%Y/%m", verbose_name=u"轮播图", max_length=100)
    url = models.URLField(max_length=100, verbose_name=u"访问地址")
    index = models.IntegerField(default=100, verbose_name=u"顺序")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"轮播图"
        verbose_name_plural = verbose_name
</code>```

I try to Google this problem, but I didn't find any useful information.

答:
you cannot give default="" to a DateField, either change it to CharField or else

do this

```<code>birday = models.DateField(verbose_name=u"生日", null=True)
</code>```

after changing make sure to run makemigrations and migrate then create superuser

Body:
I'm trying to make a website using Django, and my next step is run manage.py, to create superuser, but when I input Username, Email address, password, then press Enter, the IDE (Pycharm) feedback an Commanderror:

manage.py@education > createsuperuser
"D:\PyCharm 2019.1\bin\runnerw64.exe" E:\pythonproject\education\Scripts\python.exe "D:\PyCharm 2019.1\helpers\pycharm\django_manage.py" createsuperuser E:/pythonproject/education
Tracking file by folder pattern:  migrations
Username:  admin
Email address:  976413993@qq.com
Warning: Password input may be echoed.
Password:  12345678
Warning: Password input may be echoed.
Password (again):  12345678
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]:  y
CommandError: '' value has an invalid date format. It must be in YYYY-MM-DD format.

This is UserProfile:

# -*- encoding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime

# Create your models here.

class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, default="", verbose_name=u"昵称")
    birday = models.DateField(verbose_name=u"生日", default="")
    gender = models.CharField(choices=(("male", u"男"), ("female", u"女")), default="male", max_length=10)
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username

class EmailVerifyRecord(models.Model):
    code = models.CharField(max_length=20, verbose_name=u"验证码")
    email = models.EmailField(max_length=50, verbose_name=u"邮箱")
    send_type = models.CharField(choices=(("register", u"注册"), ("forget", u"找回密码")), max_length=10)
    send_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name = u"邮箱验证码"
        verbose_name_plural = verbose_name

class Banner(models.Model):
    title = models.CharField(max_length=100, verbose_name=u"标题")
    image = models.ImageField(upload_to="banner/%Y/%m", verbose_name=u"轮播图", max_length=100)
    url = models.URLField(max_length=100, verbose_name=u"访问地址")
    index = models.IntegerField(default=100, verbose_name=u"顺序")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"轮播图"
        verbose_name_plural = verbose_name

I try to Google this problem, but I didn't find any useful information.

Body:
you cannot give default="" to a DateField, either change it to CharField or else

do this

birday = models.DateField(verbose_name=u"生日", null=True)

after changing make sure to run makemigrations and migrate then create superuser


问:
Logstash authentication
I'm setting up a logstash cluster and I configured some authentication regarding the output filter.
However I can't figure out why it isn't working...

I tried brackets, no brackets, IP, FQDN...

```<code>input {
  tcp {
    port => 5000
    type => syslog
  }
  udp {
    port => 5000
    type => syslog
  }
}

filter {
  if [type] == "syslog" {
    grok {
      match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
      add_field => [ "received_at", "%{@timestamp}" ]
      add_field => [ "received_from", "%{host}" ]
    }
     date {
      match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }
  }
}

output {
  elasticsearch { hosts => ["localhost.enedis.fr:9200"] }
  user = sec-svc-log01
  password => 3N3D1S!!
  stdout { codec => rubydebug }
}
</code>```

Am I missing something ?
Thanks for your help !

答:
Try using below ouput section code,</p>

```<code>output {
  elasticsearch {
  hosts => ["localhost.enedis.fr:9200"]
  user => "sec-svc-log01"
  password => "3N3D1S!!"
 }
  stdout { codec => rubydebug }
}
</code>```

Title: Logstash authentication

Body:
I'm setting up a logstash cluster and I configured some authentication regarding the output filter.
However I can't figure out why it isn't working...

I tried brackets, no brackets, IP, FQDN...

input {
  tcp {
    port => 5000
    type => syslog
  }
  udp {
    port => 5000
    type => syslog
  }
}

filter {
  if [type] == "syslog" {
    grok {
      match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
      add_field => [ "received_at", "%{@timestamp}" ]
      add_field => [ "received_from", "%{host}" ]
    }
     date {
      match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }
  }
}

output {
  elasticsearch { hosts => ["localhost.enedis.fr:9200"] }
  user = sec-svc-log01
  password => 3N3D1S!!
  stdout { codec => rubydebug }
}

Am I missing something ?
Thanks for your help !

Body:
Try using below ouput section code,

output {
  elasticsearch {
  hosts => ["localhost.enedis.fr:9200"]
  user => "sec-svc-log01"
  password => "3N3D1S!!"
 }
  stdout { codec => rubydebug }
}


问:
Unity 3D Stop spawn particles after hit a wall
I'm doing a work for school: a game like bomberman.

My problem is when a bomb explodes, the particles should stop spawning after the wall. Here an image of the problem:

I have this code here to spawn the bomb and start the coroutine to spawn the particles in every diresction:

```<code>void Explode()
    {
        Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        StartCoroutine(CreateExplosions(Vector3.forward));
        StartCoroutine(CreateExplosions(Vector3.right));
        StartCoroutine(CreateExplosions(Vector3.back));
        StartCoroutine(CreateExplosions(Vector3.left));
        GetComponent<MeshRenderer>().enabled = false;
        exploded = true;
        GetComponent<CapsuleCollider>().enabled = false;
        Invoke("desativar_particulas", 0.4f);
        Destroy(gameObject, .45f);

      }
</code>```

And here is my coroutine to spawn the particles:

```<code> private IEnumerator CreateExplosions(Vector3 direction)
{
    for (int i = 1; i < 3; i++)
    {

        RaycastHit hit;

        Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask);

        if (!hit.collider)
        {
                Instantiate(explosionPrefab, transform.position + (i * direction * 10), explosionPrefab.transform.rotation);
        }

        else
        {
            break;
        }

        yield return new WaitForSeconds(.05f);
    }
}
</code>```

That if statement should do the trick: the wall have a box component collider and the particle have a box collider component as a trigger.
Am I missing something? Please help, thank you.

答: You can configure how the collisions work in a particle system in this submenu, doing it dynamically can be hard:

Body:
I'm doing a work for school: a game like bomberman.

My problem is when a bomb explodes, the particles should stop spawning after the wall. Here an image of the problem:

I have this code here to spawn the bomb and start the coroutine to spawn the particles in every diresction:

void Explode()
    {
        Instantiate(explosionPrefab, transform.position, Quaternion.identity);
        StartCoroutine(CreateExplosions(Vector3.forward));
        StartCoroutine(CreateExplosions(Vector3.right));
        StartCoroutine(CreateExplosions(Vector3.back));
        StartCoroutine(CreateExplosions(Vector3.left));
        GetComponent<MeshRenderer>().enabled = false;
        exploded = true;
        GetComponent<CapsuleCollider>().enabled = false;
        Invoke("desativar_particulas", 0.4f);
        Destroy(gameObject, .45f);

      }

And here is my coroutine to spawn the particles:

 private IEnumerator CreateExplosions(Vector3 direction)
{
    for (int i = 1; i < 3; i++)
    {

        RaycastHit hit;

        Physics.Raycast(transform.position + new Vector3(0, .5f, 0), direction * 10, out hit, i, levelMask);

        if (!hit.collider)
        {
                Instantiate(explosionPrefab, transform.position + (i * direction * 10), explosionPrefab.transform.rotation);
        }

        else
        {
            break;
        }

        yield return new WaitForSeconds(.05f);
    }
}

That if statement should do the trick: the wall have a box component collider and the particle have a box collider component as a trigger.
Am I missing something? Please help, thank you.


问:
Angular universal flickering
I'm having a flicker while the website is loading.
The HTML coming form the server is downloaded and then in the UI the view is rendered and there is a small flicker between the transition.

I managed to fix it by adding:

```<code>RouterModule.forRoot([ // ROUTES HERE ], { initialNavigation: 'enabled' })
</code>```

But I wanted to know why it happend? Because of the lazy loading of the components?
So we got a flicker between the transition while the UI (angular components) building the DOM? And let's say I had a 'light' component the flicker would be faster?

答:
@DonDaniel's answer is currect but slightly outdated.

In Angular 6+ you can use TransferHttpCacheModule.
Official docs explain how 3 lines changes do the magic.

And there is a good article that compare the old way versus the new way.

Title: Angular universal flickering

Body:
I'm having a flicker while the website is loading.
The HTML coming form the server is downloaded and then in the UI the view is rendered and there is a small flicker between the transition.

I managed to fix it by adding:

RouterModule.forRoot([ // ROUTES HERE ], { initialNavigation: 'enabled' })

But I wanted to know why it happend? Because of the lazy loading of the components?
So we got a flicker between the transition while the UI (angular components) building the DOM? And let's say I had a 'light' component the flicker would be faster?


问:
How to store string data in BIGSQL table with length greater than VARCHAR(32k)
The data beyond 32762 characters is getting truncated when I am loading the data in my BigSQL table. My table definition is as below :

CREATE hadoop TABLE schema_name.table_name
(
  column1 VARCHAR(50),
  column2 INTEGER,
  column3 STRING,
  loaddate TIMESTAMP
)
STORED AS PARQUET;

The for column3 is getting truncated.
Is there a way to store the full data?

答: Maybe the CLOB is the answer you're looking for</p>


问:
JS convert blob url to Base64 file
There is the following code:

```<code>console.log(blob);
var reader = new window.FileReader();
reader.onloadend = function() {
  console.log(reader.result);
};
reader.readAsDataURL(blob);
</code>```

blob is 'blob:http://localhost:3000/e3c23a22-75b1-4b83-b39a-75104d1909b9' and I've got the following error:

```<code>TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
</code>```

How can I fix this error and convert Blob to Base64 encoded image? Thanks in advance!

答:
I know this is an old question, but I came across this problem lately and it took me a while to fix it. So I am going to answer the question in case anyone run into it again.

First, I think the naming of variable blob is very confusing. Blob URLs and Blob Object are different things. This answer does a very good job explaining what a Blob URL is. I think you should rename it as below.

```<code>var blobUrl = 'blob:http://localhost:3000/e3c2...'
</code>```

Then, the function readAsDataURL of FileReader requires a Blob Object as its parameter. And what you give it is the variable blob, which is a Blob URL.

So what you need to do is:

Recover the Blob Object that is used to create the Blob URL

Use readAsDataURL to convert the recovered Blob Object to base64 url

Here is the code I find in this answer:

var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);

var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';

xhr.onload = function() {
   var recoveredBlob = xhr.response;

   var reader = new FileReader;

   reader.onload = function() {
     var blobAsDataUrl = reader.result;
     window.location = blobAsDataUrl;
   };

   reader.readAsDataURL(recoveredBlob);
};

xhr.open('GET', blobUrl);
xhr.send();```

Title: JS convert blob url to Base64 file

Body:
There is the following code:

console.log(blob);
var reader = new window.FileReader();
reader.onloadend = function() {
  console.log(reader.result);
};
reader.readAsDataURL(blob);

blob is 'blob:http://localhost:3000/e3c23a22-75b1-4b83-b39a-75104d1909b9' and I've got the following error:

TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

How can I fix this error and convert Blob to Base64 encoded image? Thanks in advance!

Body:
I know this is an old question, but I came across this problem lately and it took me a while to fix it. So I am going to answer the question in case anyone run into it again.

First, I think the naming of variable blob is very confusing. Blob URLs and Blob Object are different things. This answer does a very good job explaining what a Blob URL is. I think you should rename it as below.

var blobUrl = 'blob:http://localhost:3000/e3c2...'

Then, the function readAsDataURL of FileReader requires a Blob Object as its parameter. And what you give it is the variable blob, which is a Blob URL.

So what you need to do is:

Recover the Blob Object that is used to create the Blob URL

Use readAsDataURL to convert the recovered Blob Object to base64 url

Here is the code I find in this answer:

var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);

var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';

xhr.onload = function() {
   var recoveredBlob = xhr.response;

   var reader = new FileReader;

   reader.onload = function() {
     var blobAsDataUrl = reader.result;
     window.location = blobAsDataUrl;
   };

   reader.readAsDataURL(recoveredBlob);
};

xhr.open('GET', blobUrl);
xhr.send();


问:
How to get file from storage by public URL?
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

```<code>http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx
</code>```

But it does not work for me.

Also I tried to return file in backend side:

```<code>$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;
</code>```

答:
Your files are in the wrong folder if you want them publicly accessible (without controller).

Symlink

If you want your files to be public accessible.

Move your files to storage/app/public, run php artisan storage:link. This will symlink storage/app/public to public/storage. Your files will be publicly accessible now at http://localhost:8000/storage/report_27-05-19_05.xlsx

Serving file

You can also use Laravel / PHP to serve the file, trough your controller.

Retrieve files trough the controller:

$filename = "Example.docx";
return response()->download(storage_path("app/reports/{$fileName}"));
```

Body:
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx

But it does not work for me.

Also I tried to return file in backend side:

$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;


问:
How to POST data using Retrofit2?
I'm trying Retrofit 2.4.0 in my android application. Where do I have a login activity. I'm trying POST request but it return response code 404 in onResponse method. But It is working perfectly with POSTMAN and I getting correct data in log using HttpLoggingInterceptor. I have tried many methods to overcome this problem. My service code is.

```<code>@POST("user_login")
@FormUrlEncoded
Call<ResponseBody> user_login(@Field("email") String email, @Field("password") String password);

@Multipart
@POST("user_login")
Call<ResponseBody> user_login(@PartMap() Map<String, RequestBody> bodyMap);

@Multipart
@POST("user_login")
Call<Status> user_login(@Part("email") RequestBody email, @Part("password") RequestBody password);

@POST("user_login")
Call<JSONObject> user_login(@Body String credentials);

@POST("user_login")
Call<User> user_login(@Body LoginCredentials credentials);
</code>```

none of above methods aren't working.

I'm posting some other methods Which are I am using too.

```<code>@Provides
@Singleton
Cache provideOkHttpCache(TUK application) {
    int cacheSize = 10 * 1024 * 1024; // 10 MB
    return new Cache(application.getCacheDir(), cacheSize);
}

@Provides
@Singleton
Gson provideGson() {
    GsonBuilder builder = new GsonBuilder();
    // builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    return builder.create();
}

@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cache(cache);
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> Logger.wtf("AppModule", message));
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    builder.addInterceptor(interceptor);
    return builder.build();
}

@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(TUK.BASE_URL)
            .client(client)
            .build();
}
</code>```

but I'm trying other URLs too with GET method are working perfectly.

my base url is like "http://www.example.com/api/"
and my @PartMap() code is

```<code>public static Map<String, RequestBody> getMap(LoginCredentials credentials) {
    Map<String, RequestBody> map = new HashMap<>();
    map.put("email", RequestBody.create(MultipartBody.FORM, credentials.getEmail()));
    map.put("password", RequestBody.create(MultipartBody.FORM, credentials.getPassword()));
    return map;
}
</code>```

my HttpLoggingInterceptor logging data is

```<code><-- 404 https://www.example.com/api/user_login (718ms)
content-type: application/json; charset=utf-8
.
.
.
.
{"status":false,"message":"Invalid User Email Or Password."}
<-- END HTTP (60-byte body)
</code>```

and my onResponse methods logging data is

```<code>Response{protocol=h2, code=404, message=, url=https://www.example.com/api/user_login}
</code>```

At the end my question is how to POST data using Retrofit.

I have stuck at this point. I have tried other solutions from stackoverflow but no help. Please guys help me out this problem. Any help will be appreciated. Thank you.

答:
I have solved this problem by setting builder.setLenient();
complete code is

```<code>@Provides
@Singleton
Gson provideGson() {
GsonBuilder builder = new GsonBuilder();
builder.setLenient(); // this line help me to get response.
// builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return builder.create();
}
</code>```

thanks for your help guys.

Title: How to POST data using Retrofit2?

Body:
I'm trying Retrofit 2.4.0 in my android application. Where do I have a login activity. I'm trying POST request but it return response code 404 in onResponse method. But It is working perfectly with POSTMAN and I getting correct data in log using HttpLoggingInterceptor. I have tried many methods to overcome this problem. My service code is.

@POST("user_login")
@FormUrlEncoded
Call<ResponseBody> user_login(@Field("email") String email, @Field("password") String password);

@Multipart
@POST("user_login")
Call<ResponseBody> user_login(@PartMap() Map<String, RequestBody> bodyMap);

@Multipart
@POST("user_login")
Call<Status> user_login(@Part("email") RequestBody email, @Part("password") RequestBody password);

@POST("user_login")
Call<JSONObject> user_login(@Body String credentials);

@POST("user_login")
Call<User> user_login(@Body LoginCredentials credentials);

none of above methods aren't working.

I'm posting some other methods Which are I am using too.

@Provides
@Singleton
Cache provideOkHttpCache(TUK application) {
    int cacheSize = 10 * 1024 * 1024; // 10 MB
    return new Cache(application.getCacheDir(), cacheSize);
}

@Provides
@Singleton
Gson provideGson() {
    GsonBuilder builder = new GsonBuilder();
    // builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    return builder.create();
}

@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cache(cache);
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> Logger.wtf("AppModule", message));
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    builder.addInterceptor(interceptor);
    return builder.build();
}

@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(TUK.BASE_URL)
            .client(client)
            .build();
}

but I'm trying other URLs too with GET method are working perfectly.

my base url is like "http://www.example.com/api/"
and my @PartMap() code is

public static Map<String, RequestBody> getMap(LoginCredentials credentials) {
    Map<String, RequestBody> map = new HashMap<>();
    map.put("email", RequestBody.create(MultipartBody.FORM, credentials.getEmail()));
    map.put("password", RequestBody.create(MultipartBody.FORM, credentials.getPassword()));
    return map;
}

my HttpLoggingInterceptor logging data is

<-- 404 https://www.example.com/api/user_login (718ms)
content-type: application/json; charset=utf-8
.
.
.
.
{"status":false,"message":"Invalid User Email Or Password."}
<-- END HTTP (60-byte body)

and my onResponse methods logging data is

Response{protocol=h2, code=404, message=, url=https://www.example.com/api/user_login}

At the end my question is how to POST data using Retrofit.

I have stuck at this point. I have tried other solutions from stackoverflow but no help. Please guys help me out this problem. Any help will be appreciated. Thank you.

Body:
I have solved this problem by setting builder.setLenient();
complete code is

@Provides
@Singleton
Gson provideGson() {
GsonBuilder builder = new GsonBuilder();
builder.setLenient(); // this line help me to get response.
// builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return builder.create();
}

thanks for your help guys.


问:
Memory Leaks tutorial in iphone
is there is any good tutorial link that can help me in the memory leaks of iphone,, b/c I am facing some problem whenever I allocate a memeory , in the dealloc I am releasing that memeory, but the problem is that when I run application in the (Run-> Run With Performance Tools -> Leaks) but I got the leaks through there.. how can I resolve it...

reply me plz

答:
In XCode, you can run Build and Analyze. XCode shows memory leaks with arrows of you bad memory management.

This is a good tutorial : iphone-memory-management-tips

Title: Memory Leaks tutorial in iphone


问:
Ngrx store - delay tap after emitting action
Using Ngrx store, I have the following 2 effects:

```<code>@Effect({ dispatch: false })
    toastSuccess$ = this.actions$
        .pipe(
            ofType(TOAST_SUCCESS),
            map((action: any) => this.toastr.success(action.payload, 'Success'))
        );

@Effect()
    appContextChanged$ = this.actions$
        .pipe(
            ofType(UPDATE_USER_APP_CONTEXT_SUCCESS),
            mergeMap(() => of(
                { type: TOAST_SUCCESS, payload: 'App context updated successfully!' })),
            tap(() => location.reload()),
            catchError(() => of({ type: UPDATE_USER_APP_CONTEXT_FAILED }))
        )
</code>```

What I'd like to do is delay the tap location.reload() by a 1000ms (so the toast show for a second, then the page is refreshed), but I've tried using delay everywhere with no success. How can I delay the refreshing of the page, i.e. location.reload() after the toast effect?

答:
Create a different effect for that, soappContextChanged$ can finish and notify your toastSuccess effect:

```<code>@Effect({dispatch: false})
reload$ = this.actions$
  .pipe(
    ofType(TOAST_SUCCESS),
    tap(() => location.reload())
</code>```

It seems toastr.success returns an action, is that true? In that case, you can listen to that action instead of Toast_sucess in the ofType operator.

Body:
Using Ngrx store, I have the following 2 effects:

@Effect({ dispatch: false })
    toastSuccess$ = this.actions$
        .pipe(
            ofType(TOAST_SUCCESS),
            map((action: any) => this.toastr.success(action.payload, 'Success'))
        );

@Effect()
    appContextChanged$ = this.actions$
        .pipe(
            ofType(UPDATE_USER_APP_CONTEXT_SUCCESS),
            mergeMap(() => of(
                { type: TOAST_SUCCESS, payload: 'App context updated successfully!' })),
            tap(() => location.reload()),
            catchError(() => of({ type: UPDATE_USER_APP_CONTEXT_FAILED }))
        )

What I'd like to do is delay the tap location.reload() by a 1000ms (so the toast show for a second, then the page is refreshed), but I've tried using delay everywhere with no success. How can I delay the refreshing of the page, i.e. location.reload() after the toast effect?

Body:
Create a different effect for that, soappContextChanged$ can finish and notify your toastSuccess effect:

@Effect({dispatch: false})
reload$ = this.actions$
  .pipe(
    ofType(TOAST_SUCCESS),
    tap(() => location.reload())

It seems toastr.success returns an action, is that true? In that case, you can listen to that action instead of Toast_sucess in the ofType operator.


问:
Error while importing neurokit in jupyter notebook
In Jupyter notebook, I have to import neurokit.

There was this error:

ImportError: No module named neurokit

So I tried:

```<code>!pip install neurokit
</code>```

but there was another error:

IOError: [Errno 2] No such file or directory: 'README.md'

Can anyone help me with this?

This is the error:

```<code>!pip install neurokit

Collecting neurokit
  Using cached https://files.pythonhosted.org/packages/aa/e4/aac4c53fb12d52c292988897bff3d003a5798ec582b267f57057bfdf6c31/neurokit-0.2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\dell\appdata\local\temp\pip-install-i17inb\neurokit\setup.py", line 39, in <module>
        long_description = open('README.md').read(),
    IOError: [Errno 2] No such file or directory: 'README.md'
</code>```

答:
This is definitely a bug in installation package — they have forgotten to include README.md into the package. Overall, their installation packages at PyPI are quite old, the latest one is from 2017 year.

Install directly from the repository:

```<code>pip install numpy
pip install git+https://github.com/neuropsychology/NeuroKit.py#egg=neurokit
</code>```

Body:
In Jupyter notebook, I have to import neurokit.

There was this error:

ImportError: No module named neurokit

So I tried:

!pip install neurokit

but there was another error:

IOError: [Errno 2] No such file or directory: 'README.md'

Can anyone help me with this?

This is the error:

!pip install neurokit

Collecting neurokit
  Using cached https://files.pythonhosted.org/packages/aa/e4/aac4c53fb12d52c292988897bff3d003a5798ec582b267f57057bfdf6c31/neurokit-0.2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\dell\appdata\local\temp\pip-install-i17inb\neurokit\setup.py", line 39, in <module>
        long_description = open('README.md').read(),
    IOError: [Errno 2] No such file or directory: 'README.md'

Body:
This is definitely a bug in installation package — they have forgotten to include README.md into the package. Overall, their installation packages at PyPI are quite old, the latest one is from 2017 year.

Install directly from the repository:

pip install numpy
pip install git+https://github.com/neuropsychology/NeuroKit.py#egg=neurokit


问:
Could not find a generator for route "home-page" in the _MaterialAppState
I am getting exception when I trying to navigate from one view to another in flutter app. </p>

```<code>I/flutter ( 2199): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 2199): The following assertion was thrown while handling a gesture:
I/flutter ( 2199): Could not find a generator for route "home-page" in the _MaterialAppState.
</code>```

答: This message tells, that in route list, the route you search aren't listed. So, check if in your MaterialApp->routes have your specified route.</p>

Body:
I am getting exception when I trying to navigate from one view to another in flutter app.

I/flutter ( 2199): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 2199): The following assertion was thrown while handling a gesture:
I/flutter ( 2199): Could not find a generator for route "home-page" in the _MaterialAppState.


问:
T-SQL Create a view in a stored procedure using dynamic sql
I have a stored procedure which pivots query results and creates corresponding views. I'm stuck at the point where it actually creates views. Please see the code below

I've already tried with execute(), sp_executesql().

If in an initial @query we don't have any variables then the following code works:

```<code>execute ('create view  AzureDataCatalog.temp AS ' + @query).
</code>```

I have to make it work with variables.

```<code>DECLARE @iterator INT = 0

declare @n int = (
                SELECT COUNT(DISTINCT c.name)  AS [ColumnName]
                FROM    sys.views  v
                        INNER JOIN sys.all_columns c ON v.object_id = c.object_id
                        INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
                )

WHILE @iterator< @n
BEGIN

Declare @cols nvarchar(max)
Declare @query nvarchar(max)

Select @cols = stuff((select ','+QuoteName([ColumnName]) from
(
    SELECT  DISTINCT c.name  AS [ColumnName]
    FROM    sys.views  v
            INNER JOIN sys.all_columns c ON v.object_id = c.object_id
            INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
    ORDER BY [ColumnName]
    OFFSET @iterator ROWS
    FETCH NEXT 1000 ROWS ONLY
) tb

    for xml path('')),1,1,'')
Select @query = N' Select * from (
    Select [ColumnName], RowN = Row_Number() over (order by [ColumnName])
    FROM
        (
            SELECT  DISTINCT c.name  AS [ColumnName]
            FROM    sys.views  v
                INNER JOIN sys.all_columns c ON v.object_id = c.object_id
                INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
            ORDER BY [ColumnName]
            OFFSET @iterator ROWS
            FETCH NEXT 1000 ROWS ONLY
        ) tb
    ) a
    pivot (MAX([RowN]) for [ColumnName] in (' + @cols + ')) p '

Exec sp_executesql @query, N'@iterator INT', @iterator

DECLARE @iteratorName NVARCHAR(20)
SET @iteratorName = CONVERT(NVARCHAR(20), @iterator)

DECLARE @viewName VARCHAR(100)
DECLARE @sqlCommand NVARCHAR(100)
SET @viewName = 'temp' + @iteratorName

-- Check if the view exists
IF EXISTS(SELECT 1 FROM sys.views WHERE name = @viewName)
BEGIN
    SET @sqlCommand = 'SELECT ''Yes'''
    EXEC(@sqlCommand)

    execute ('drop view  AzureDataCatalog.temp' + @iteratorName)

    -- This code works, if there aren't any variables inside @query
    execute ('create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query)
END
ELSE
BEGIN
    SET @sqlCommand = 'SELECT ''No'''
    EXEC(@sqlCommand)

    SET @sqlCommand = 'create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query

    Exec sp_executesql @query, N'@iterator INT', @iterator
END

SET @iterator += 1024

/*Execute a Stored Procedure*/
END
</code>```

Basically, I need to get the following code working:

```<code>DECLARE @sqlCommand NVARCHAR(100)
SET @sqlCommand = 'create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query

Exec sp_executesql @query, N'@iterator INT', @iterator
</code>```

But instead I get a following error

```<code>Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'view'.
</code>```

答:
To change identifiers, you need to munge the query string, which you seem to basically be doing.  Just to be clear, store the view name you want in a string and use that in your code:</p>

```<code>DECLARE @iteratorName NVARCHAR(20);
SET @iteratorName = CONVERT(NVARCHAR(20), @iterator);

DECLARE @viewName VARCHAR(100);
DECLARE @sqlCommand NVARCHAR(100);
SET @viewName = 'temp' + @iteratorName;

SET @sqlCommand = 'create view ' + @viewName + ' AS ' + @query;

EXEC sp_executesql @query;
</code>```

Body:
I have a stored procedure which pivots query results and creates corresponding views. I'm stuck at the point where it actually creates views. Please see the code below

I've already tried with execute(), sp_executesql().

If in an initial @query we don't have any variables then the following code works:

execute ('create view  AzureDataCatalog.temp AS ' + @query).

I have to make it work with variables.

DECLARE @iterator INT = 0

declare @n int = (
                SELECT COUNT(DISTINCT c.name)  AS [ColumnName]
                FROM    sys.views  v
                        INNER JOIN sys.all_columns c ON v.object_id = c.object_id
                        INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
                )

WHILE @iterator< @n
BEGIN

Declare @cols nvarchar(max)
Declare @query nvarchar(max)

Select @cols = stuff((select ','+QuoteName([ColumnName]) from
(
    SELECT  DISTINCT c.name  AS [ColumnName]
    FROM    sys.views  v
            INNER JOIN sys.all_columns c ON v.object_id = c.object_id
            INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
    ORDER BY [ColumnName]
    OFFSET @iterator ROWS
    FETCH NEXT 1000 ROWS ONLY
) tb

    for xml path('')),1,1,'')
Select @query = N' Select * from (
    Select [ColumnName], RowN = Row_Number() over (order by [ColumnName])
    FROM
        (
            SELECT  DISTINCT c.name  AS [ColumnName]
            FROM    sys.views  v
                INNER JOIN sys.all_columns c ON v.object_id = c.object_id
                INNER JOIN sys.schemas s ON v.schema_id = s.schema_id
            ORDER BY [ColumnName]
            OFFSET @iterator ROWS
            FETCH NEXT 1000 ROWS ONLY
        ) tb
    ) a
    pivot (MAX([RowN]) for [ColumnName] in (' + @cols + ')) p '

Exec sp_executesql @query, N'@iterator INT', @iterator

DECLARE @iteratorName NVARCHAR(20)
SET @iteratorName = CONVERT(NVARCHAR(20), @iterator)

DECLARE @viewName VARCHAR(100)
DECLARE @sqlCommand NVARCHAR(100)
SET @viewName = 'temp' + @iteratorName

-- Check if the view exists
IF EXISTS(SELECT 1 FROM sys.views WHERE name = @viewName)
BEGIN
    SET @sqlCommand = 'SELECT ''Yes'''
    EXEC(@sqlCommand)

    execute ('drop view  AzureDataCatalog.temp' + @iteratorName)

    -- This code works, if there aren't any variables inside @query
    execute ('create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query)
END
ELSE
BEGIN
    SET @sqlCommand = 'SELECT ''No'''
    EXEC(@sqlCommand)

    SET @sqlCommand = 'create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query

    Exec sp_executesql @query, N'@iterator INT', @iterator
END

SET @iterator += 1024

/*Execute a Stored Procedure*/
END

Basically, I need to get the following code working:

DECLARE @sqlCommand NVARCHAR(100)
SET @sqlCommand = 'create view  AzureDataCatalog.temp' + @iteratorName +' AS ' + @query

Exec sp_executesql @query, N'@iterator INT', @iterator

But instead I get a following error

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'view'.

Body:
To change identifiers, you need to munge the query string, which you seem to basically be doing.  Just to be clear, store the view name you want in a string and use that in your code:

DECLARE @iteratorName NVARCHAR(20);
SET @iteratorName = CONVERT(NVARCHAR(20), @iterator);

DECLARE @viewName VARCHAR(100);
DECLARE @sqlCommand NVARCHAR(100);
SET @viewName = 'temp' + @iteratorName;

SET @sqlCommand = 'create view ' + @viewName + ' AS ' + @query;

EXEC sp_executesql @query;


问:
How to remove quotes in my product description string?
I'm using OSCommerce for my online store and I'm currently optimizing my product page for rich snippets.
Some of my Google Indexed pages are being marked as "Failed" by Google due to double quotes in the description field.

I'm using an existing code which strips the html coding and truncates anything after 197 characters.

```<code><?php echo substr(trim(preg_replace('/\s\s+/', ' ', strip_tags($product_info['products_description']))), 0, 197); ?>
</code>```

How can I include the removal of quotes in that code so that the following string:

```<code><strong>This product is the perfect "fit"</strong>
</code>```

becomes:

```<code>This product is the perfect fit
</code>```

答:
Happened with me, try to use:

```<code>tep_output_string($product_info['products_description']))
</code>```

" becomes "

Body:
I'm using OSCommerce for my online store and I'm currently optimizing my product page for rich snippets.
Some of my Google Indexed pages are being marked as "Failed" by Google due to double quotes in the description field.

I'm using an existing code which strips the html coding and truncates anything after 197 characters.

<?php echo substr(trim(preg_replace('/\s\s+/', ' ', strip_tags($product_info['products_description']))), 0, 197); ?>

How can I include the removal of quotes in that code so that the following string:

This product is the perfect "fit"

becomes:

This product is the perfect fit

Body:
Happened with me, try to use:

tep_output_string($product_info['products_description']))

" becomes &quot;


问:
Testing User Input - Python
I am having troubles with testing my input for my code in Python. I tried a couple of solutions, but there is something that I am missing, so I would appreciate it if you could give me some tips.

First here is a snippet from my main file of code that I want to test:

```<code>if __name__ == '__main__':

    n = int(input())
    m = int(input())

    grid = []

    for _ in range(n):
        grid.append(list(map(str, input().rstrip().split())))

    calculate(grid)
</code>```

When I run my code, I input "n", then "m", then a grid is created according to the user input (each row on a new row..), and a function is executed that calculates something on the grid and the function returns the result. It all works great, but now I need to create a couple of test cases for it (that test different inputs against expected outputs).

First, I tried this: (on a separate .py file)

```<code>from unittest import mock
from unittest import TestCase
import main_file

class DictCreateTests(TestCase):
    @mock.patch('main_file.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['2', '2', 'R G B\nR G B'] #this is the input I need for my color grid
        self.assertEqual(calculate(grid), 2)

if __name__ == '__main__':
    unittest.main()
</code>```

I then researched for some more options and I tried this option, which got me the closest:

```<code>import unittest
import os

class Test1(unittest.TestCase):

    def test_case1(self):
        input = "2\n2\nR G B\nR G B"
        expected_output = '2'
        with os.popen("echo " + input + "' | python main_file.py") as o:
            output = o.read()
        output = output.strip() # Remove leading spaces and LFs
        self.assertEqual(output, expected_output)

if __name__ == '__main__':
    unittest.main()
</code>```

Unfortunately, even though it passed the test, I discovered that it always accepts the first letter/number of input as a result, when it compares it out to the expected output. So, I am thinking it has something to do with the multiple values I need to input. I tried separating them on different inputs (input1 + input2+ input3), but it still didn't work.

I would very much appreciate it if anyone could give me some tips on how to do it! Thank you in advance!

答:
I suggest to refactor the code, so that you can test a function:

```<code>def create_grid_and_calculate(n, m):
    grid = []

    for _ in range(n):
        grid.append(list(map(str, input().rstrip().split())))

    return calculate(grid)

if __name__ == '__main__':

    n = int(input())
    m = int(input())

    create_grid_and_calculate(n, m)
</code>```

Then

```<code>import unittest
import os
from main_file import create_grid_and_calculate

class Test1(unittest.TestCase):

    def test_case1(self):
        expected_output = '2'
        self.assertEqual(create_grid_and_calculate(2, 2), expected_output)
        self.assertEqual(create_grid_and_calculate(int("R G B"), int("R G B")), expected_output)

if __name__ == '__main__':
    unittest.main()
</code>```

You could also replace your inputs with arguments passed on the command line, parsed with a dedicated module (argparse is standard for instance), to have a better control on your inputs.

```<code>import argparse

def create_grid_and_calculate(n, m):
    ...

def main(argv: list = None):
    parser = argparse.ArgumentParser(description="My script...")
    parser.add_argument(
        "-m",
        dest="m",
        action="store",
        type=int,
        help="parameter m",
    )
    parser.add_argument(
        "-n",
        dest="n",
        action="store",
        type=int,
        help="parameter n",
    )
    args = parser.parse_args(argv or [])

    create_grid_and_calculate(args.n, args.m)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv[1:]))
</code>```

So you can also test the main function with different inputs (int, strings...).

Finally, pytest is a great unitary test framework build on top of unittest, maybe you can have a look.

EDIT:
To define your grid, you do not need to input the sizes (n and m), and you do not need to input each row separately. Choose 1 separator for line (here the comma), another for columns (here the space), and you get:

```<code>import argparse

def main(argv: list = None):
    parser = argparse.ArgumentParser(description="My script...")
    parser.add_argument(
        "-g",
        "--grid",
        dest="grid",
        action="store",
        type=str,
        help="The grid, defined as 'x11 x12 ... x1n, x21 x22 ... x2n, ...'",
    )
    args = parser.parse_args(argv or [])

    # first we split on comma, then on space
    grid = [x.split() for x in args.grid.split(',')]
    print(grid)
    calculate(grid)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv[1:]))
</code>```

and you run it like that: main_file.py -g '1 2 3, 4 5 6, 7 8 9'

```<code>[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
</code>```

To get a list of list of int, use:

```<code>grid = [[int(val) for val in row.split()] for row in args.grid.split(',')]
</code>```

or perhaps more clearly:

```<code>grid = []
for row in args.grid.split(','):
    grid.append([])
    for val in row.split():
        grid[-1].append(int(val))
</code>```

Title: Testing User Input - Python

Body:
I am having troubles with testing my input for my code in Python. I tried a couple of solutions, but there is something that I am missing, so I would appreciate it if you could give me some tips.

First here is a snippet from my main file of code that I want to test:

if __name__ == '__main__':

    n = int(input())
    m = int(input())

    grid = []

    for _ in range(n):
        grid.append(list(map(str, input().rstrip().split())))

    calculate(grid)

When I run my code, I input "n", then "m", then a grid is created according to the user input (each row on a new row..), and a function is executed that calculates something on the grid and the function returns the result. It all works great, but now I need to create a couple of test cases for it (that test different inputs against expected outputs).

First, I tried this: (on a separate .py file)

from unittest import mock
from unittest import TestCase
import main_file

class DictCreateTests(TestCase):
    @mock.patch('main_file.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['2', '2', 'R G B\nR G B'] #this is the input I need for my color grid
        self.assertEqual(calculate(grid), 2)

if __name__ == '__main__':
    unittest.main()

I then researched for some more options and I tried this option, which got me the closest:

import unittest
import os

class Test1(unittest.TestCase):

    def test_case1(self):
        input = "2\n2\nR G B\nR G B"
        expected_output = '2'
        with os.popen("echo " + input + "' | python main_file.py") as o:
            output = o.read()
        output = output.strip() # Remove leading spaces and LFs
        self.assertEqual(output, expected_output)

if __name__ == '__main__':
    unittest.main()

Unfortunately, even though it passed the test, I discovered that it always accepts the first letter/number of input as a result, when it compares it out to the expected output. So, I am thinking it has something to do with the multiple values I need to input. I tried separating them on different inputs (input1 + input2+ input3), but it still didn't work.

I would very much appreciate it if anyone could give me some tips on how to do it! Thank you in advance!

Body:
I suggest to refactor the code, so that you can test a function:

def create_grid_and_calculate(n, m):
    grid = []

    for _ in range(n):
        grid.append(list(map(str, input().rstrip().split())))

    return calculate(grid)

if __name__ == '__main__':

    n = int(input())
    m = int(input())

    create_grid_and_calculate(n, m)

Then

import unittest
import os
from main_file import create_grid_and_calculate

class Test1(unittest.TestCase):

    def test_case1(self):
        expected_output = '2'
        self.assertEqual(create_grid_and_calculate(2, 2), expected_output)
        self.assertEqual(create_grid_and_calculate(int("R G B"), int("R G B")), expected_output)

if __name__ == '__main__':
    unittest.main()

You could also replace your inputs with arguments passed on the command line, parsed with a dedicated module (argparse is standard for instance), to have a better control on your inputs.

import argparse

def create_grid_and_calculate(n, m):
    ...

def main(argv: list = None):
    parser = argparse.ArgumentParser(description="My script...")
    parser.add_argument(
        "-m",
        dest="m",
        action="store",
        type=int,
        help="parameter m",
    )
    parser.add_argument(
        "-n",
        dest="n",
        action="store",
        type=int,
        help="parameter n",
    )
    args = parser.parse_args(argv or [])

    create_grid_and_calculate(args.n, args.m)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv[1:]))

So you can also test the main function with different inputs (int, strings...).

Finally, pytest is a great unitary test framework build on top of unittest, maybe you can have a look.

EDIT:
To define your grid, you do not need to input the sizes (n and m), and you do not need to input each row separately. Choose 1 separator for line (here the comma), another for columns (here the space), and you get:

import argparse

def main(argv: list = None):
    parser = argparse.ArgumentParser(description="My script...")
    parser.add_argument(
        "-g",
        "--grid",
        dest="grid",
        action="store",
        type=str,
        help="The grid, defined as 'x11 x12 ... x1n, x21 x22 ... x2n, ...'",
    )
    args = parser.parse_args(argv or [])

    # first we split on comma, then on space
    grid = [x.split() for x in args.grid.split(',')]
    print(grid)
    calculate(grid)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv[1:]))

and you run it like that: main_file.py -g '1 2 3, 4 5 6, 7 8 9'

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

To get a list of list of int, use:

grid = [[int(val) for val in row.split()] for row in args.grid.split(',')]

or perhaps more clearly:

grid = []
for row in args.grid.split(','):
    grid.append([])
    for val in row.split():
        grid[-1].append(int(val))


问:
Convert object in JSON to map in Java
Been trying to convert an object in JSON to java using Gson but many things do not match up.
Before the object was an int, now it's converted into an object.
This is part of the JSON (I need only damage to get converted):

I've tried most of the guides online but still not helpful at all.

```<code>[
  {
    "username": "lol",
    "value": [
      "one","two"
    ],
    "Power": [
      {
        "type": "Damage",
        "damage": {"first":2, "second":0,"third":0}
}]}]
</code>```

答: The JSON you are trying to parse seems not a valid Json structure. Use this https://jsonformatter.curiousconcept.com/ to validate the JSON structure and try parsing.  </p>

Title: Convert object in JSON to map in Java

Body:
Been trying to convert an object in JSON to java using Gson but many things do not match up.
Before the object was an int, now it's converted into an object.
This is part of the JSON (I need only damage to get converted):

I've tried most of the guides online but still not helpful at all.

[
  {
    "username": "lol",
    "value": [
      "one","two"
    ],
    "Power": [
      {
        "type": "Damage",
        "damage": {"first":2, "second":0,"third":0}
}]}]


问:
authentication to oauth fails on IIS
I use oauth authentication to add contacts to google Contacts api
when I deploy to iis I get this error:

Server Error in '/' Application. Access is denied Description: An
  unhandled exception occurred during the execution of the current web
  request. Please review the stack trace for more information about the
  error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: Access is
  denied

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

```<code>[Win32Exception (0x80004005): Access is denied]
   System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +604
   System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +60
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +258

[NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=347204707806-a44e1b5q57mqr0bkvic9gd03ms52nk0c.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54450%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth2%2Fcontacts%20https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds" for authorization. See inner exception for details.]
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +832
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +701
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +572
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +426

 string clientId = xxxxxxx.apps.googleusercontent.com";
            string clientSecret = "xxxxxxxxxxxxxxxxxx";

        string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts" };     // view your basic profile info.

        // Use the current Google .net client library to get the Oauth2 stuff.
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "teste"
                                                                            , CancellationToken.None
                                                                                , new FileDataStore(Server.MapPath("/") + "Datastore", true)).Result;
        try
        {
            // Translate the Oauth permissions to something the old client libray can read
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken = credential.Token.AccessToken;
            parameters.RefreshToken = credential.Token.RefreshToken;

            RequestSettings settings = new RequestSettings("contacts-241820", parameters);
            ContactsRequest cr = new ContactsRequest(settings);
            if (User.Identity.IsAuthenticated)

                CreateContact(cr);
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <authentication mode="None" />
    <customErrors mode="Off" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>
</code>```

Title: authentication to oauth fails on IIS

Body:
I use oauth authentication to add contacts to google Contacts api
when I deploy to iis I get this error:

Server Error in '/' Application. Access is denied Description: An
  unhandled exception occurred during the execution of the current web
  request. Please review the stack trace for more information about the
  error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: Access is
  denied

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[Win32Exception (0x80004005): Access is denied]
   System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +604
   System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +60
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +258

[NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=347204707806-a44e1b5q57mqr0bkvic9gd03ms52nk0c.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54450%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth2%2Fcontacts%20https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds" for authorization. See inner exception for details.]
   Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__16.MoveNext() +832
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +701
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +572
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +426

 string clientId = xxxxxxx.apps.googleusercontent.com";
            string clientSecret = "xxxxxxxxxxxxxxxxxx";

        string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts" };     // view your basic profile info.

        // Use the current Google .net client library to get the Oauth2 stuff.
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "teste"
                                                                            , CancellationToken.None
                                                                                , new FileDataStore(Server.MapPath("/") + "Datastore", true)).Result;
        try
        {
            // Translate the Oauth permissions to something the old client libray can read
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken = credential.Token.AccessToken;
            parameters.RefreshToken = credential.Token.RefreshToken;

            RequestSettings settings = new RequestSettings("contacts-241820", parameters);
            ContactsRequest cr = new ContactsRequest(settings);
            if (User.Identity.IsAuthenticated)

                CreateContact(cr);

Body:
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <authentication mode="None" />
    <customErrors mode="Off" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>


问:
Javah tool error: Could not find class file for hellojni
I am trying to create a header file using javah tool from command line on windows 7 OS but i am failing all the time.

I have followed different ways and even read the documentation of javah tool from oracle but they didn't help to overcome with this problem.

My class file (hellojni.class) and java file (hellojni.java) both are in the root of D:\ drive.

But whenever I run javah tool it gives me an error:

could not find class file for hellojni

I tried by providing classpath as well but not getting any header file.

答:
I also faced the same problem when trying to compile and generate the C/C++ header in two steps for a Java Native Interface (JNI) implementation (I suspect that is what your trying to do from the file names). What solved it for me was to merge the two steps into one using the following command:

```<code>javac YOUR_CLASS_FILE_NAME.java -h .
</code>```

The dot (.) includes the current path. This command can only be run as of Java 8.

Body:
I also faced the same problem when trying to compile and generate the C/C++ header in two steps for a Java Native Interface (JNI) implementation (I suspect that is what your trying to do from the file names). What solved it for me was to merge the two steps into one using the following command:

javac YOUR_CLASS_FILE_NAME.java -h .

The dot (.) includes the current path. This command can only be run as of Java 8.