问:
Pandas DataFrame to List of Lists
It's easy to turn a list of lists into a pandas dataframe:

```<code>import pandas as pd
df = pd.DataFrame([[1,2,3],[3,4,5]])
</code>```

But how do I turn df back into a list of lists?

```<code>lol = df.what_to_do_now?
print lol
# [[1,2,3],[3,4,5]]
</code>```

答:
If the data has column and index labels that you want to preserve, there are a few options.

Example data:

```<code>>>> df = pd.DataFrame([[1,2,3],[3,4,5]], \
       columns=('first', 'second', 'third'), \
       index=('alpha', 'beta'))
>>> df
       first  second  third
alpha      1       2      3
beta       3       4      5
</code>```

The tolist() method described in other answers is useful but yields only the core data - which may not be enough, depending on your needs.

```<code>>>> df.values.tolist()
[[1, 2, 3], [3, 4, 5]]
</code>```

One approach is to convert the DataFrame to json using df.to_json() and then parse it again. This is cumbersome but does have some advantages, because the to_json() method has some useful options.

```<code>>>> df.to_json()
{
  "first":{"alpha":1,"beta":3},
  "second":{"alpha":2,"beta":4},"third":{"alpha":3,"beta":5}
}

>>> df.to_json(orient='split')
{
 "columns":["first","second","third"],
 "index":["alpha","beta"],
 "data":[[1,2,3],[3,4,5]]
}
</code>```

Cumbersome but may be useful.

The good news is that it's pretty straightforward to build lists for the columns and rows:

```<code>>>> columns = [df.index.name] + [i for i in df.columns]
>>> rows = [[i for i in row] for row in df.itertuples()]
</code>```

This yields:

```<code>>>> print(f"columns: {columns}\nrows: {rows}")
columns: [None, 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]
</code>```

If the None as the name of the index is bothersome, rename it:

```<code>df = df.rename_axis('stage')
</code>```

Then:

```<code>>>> columns = [df.index.name] + [i for i in df.columns]
>>> print(f"columns: {columns}\nrows: {rows}")

columns: ['stage', 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]
</code>```

Title: Pandas DataFrame to List of Lists

Body:
It's easy to turn a list of lists into a pandas dataframe:

import pandas as pd
df = pd.DataFrame([[1,2,3],[3,4,5]])

But how do I turn df back into a list of lists?

lol = df.what_to_do_now?
print lol
# [[1,2,3],[3,4,5]]

Body:
If the data has column and index labels that you want to preserve, there are a few options.

Example data:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]], \
       columns=('first', 'second', 'third'), \
       index=('alpha', 'beta'))
>>> df
       first  second  third
alpha      1       2      3
beta       3       4      5

The tolist() method described in other answers is useful but yields only the core data - which may not be enough, depending on your needs.

>>> df.values.tolist()
[[1, 2, 3], [3, 4, 5]]

One approach is to convert the DataFrame to json using df.to_json() and then parse it again. This is cumbersome but does have some advantages, because the to_json() method has some useful options.

>>> df.to_json()
{
  "first":{"alpha":1,"beta":3},
  "second":{"alpha":2,"beta":4},"third":{"alpha":3,"beta":5}
}

>>> df.to_json(orient='split')
{
 "columns":["first","second","third"],
 "index":["alpha","beta"],
 "data":[[1,2,3],[3,4,5]]
}

Cumbersome but may be useful.

The good news is that it's pretty straightforward to build lists for the columns and rows:

>>> columns = [df.index.name] + [i for i in df.columns]
>>> rows = [[i for i in row] for row in df.itertuples()]

This yields:

>>> print(f"columns: {columns}\nrows: {rows}")
columns: [None, 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]

If the None as the name of the index is bothersome, rename it:

df = df.rename_axis('stage')

Then:

>>> columns = [df.index.name] + [i for i in df.columns]
>>> print(f"columns: {columns}\nrows: {rows}")

columns: ['stage', 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]


来源: stackexchange

问:
How to print <DummyText> inside html tag using javascript?
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do</p>

```<code><p><a href='' title='Survey Link'><DummyText></a></p>
</code>```

答:
Use < to display < and > to display > in HTML

document.getElementById('anc').innerHTML="<Dummy Text>";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p></p></code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do

<DummyText>

Body:
Use &lt; to display < and &gt; to display > in HTML

document.getElementById('anc').innerHTML="&lt;Dummy Text&gt;";

<p><a id="anc" href='' title='Survey Link'></a></p>


问:
400 Bad Request Error When trying to Pass object with image to Server
In my application, I am trying to pass an object that contains an image to the web api but it throws a 400 bad request error and picks out the scanImage property as the culprit. I have tried so many workarounds and googled a lot but no help found yet.

DTO

```<code>    public class CreateTaxMapDto
    {
        [Required(ErrorMessage = "Tax Type is required")]
        public int TaxTypeId { get; set; }

        public int? BranchId { get; set; }

        [Required(ErrorMessage = "Date of receipt is required")]
        public DateTime DateOfReceipt { get; set; }

        public decimal Amount { get; set; }

        public IFormFile ScanImage { get; set; }

        [StringLength(150)]
        public string Remark { get; set; }
    }
</code>```

ApplicationService

```<code>        public async Task SaveTax(CreateTaxMapDto input)
        {
            // Code to save the input to the database
        }
</code>```

CreateTaxMap.ts

```<code>export class CreateTaxMapDto {
    taxTypeId: number;
    branchId: number;
    dateOfReceipt: Date;
    amount: number;
    scanImage: any;
    constructor(data?: any) {
        if (data !== undefined) {
            this.taxTypeId = data['taxTypeId'] !== undefined ? data['taxTypeId'] : null;
            this.branchId = data['branchId'] !== undefined ? data['branchId'] : null;
            this.dateOfReceipt = data['dateOfReceipt'] !== undefined ? data['dateOfReceipt'] : null;
            this.amount = data['amount'] !== undefined ? data['amount'] : null;
            this.scanImage = data['scanImage'] !== undefined ? data['scanImage'] : null;
        }
    }

    static fromJS(data: any): CreateTaxMapDto {
        return new CreateTaxMapDto(data);
    }

    toJS(data?: any) {
        data = data === undefined ? {} : data;
        data['taxTypeId'] = this.taxTypeId !== undefined ? this.taxTypeId : null;
        data['branchId'] = this.branchId !== undefined ? this.branchId : null;
        data['dateOfReceipt'] = this.dateOfReceipt !== undefined ? this.dateOfReceipt : null;
        data['amount'] = this.amount !== undefined ? this.amount : null;
        data['scanImage'] = this.scanImage !== undefined ? this.scanImage : null;

        return data;
    }

    toJSON() {
        return JSON.stringify(this.toJS());
    }

clone() {
    const json = this.toJSON();
    return new CreateTaxMapDto(JSON.parse(json));
}
</code>```

}

Create-Tax.Component.Html

```<code><input #imageInput type="file" class="form-control" (change)="onImageChange()" />
</code>```

Component.ts

```<code>  onImageChange() {
    let imgInput = this.imageInput.nativeElement;
    if (imgInput.files && imgInput.files[0]) {
      this.file = imgInput.files[0];
    }
  }

save(): void {
    this.saving = true;
    this.tax.branchId = this.appSession.user.branchId;
    const custFile = <MyFile>(this.file); // MyFile is an interface that extends File
    let originalFile = {
      'lastModified': custFile.lastModified,
      'lastModifiedDate': custFile.lastModifiedDate,
      'name': custFile.name,
      'size': custFile.size,
      'type': custFile.type,
      'webkitRelativePath': custFile.webkitRelativePath
    };
    this.tax.scanImage = originalFile;
    console.log(this.tax.scanImage);
    this._taxService.create(this.tax)
        .finally(() => { this.saving = false; })
        .subscribe(() => {
            this.notify.success(this.l('SavedSuccessfully'), 'Tax Saved');
            this.close();
            this.modalSave.emit(null);
        });
  }
</code>```

Service.ts

```<code>create(input: CreateTaxMapDto): Observable<TaxDto> {
        let url_ = this.baseUrl + '/api/services/app/Tax/SaveTax';

        const content_ = JSON.stringify(input ? input.toJS() : null);
        console.log('Inputt: ' + content_);

        return this.http.request(url_, {
            body: content_,
            method: 'post',
            headers: new Headers({
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/json; charset=UTF-8'
            })
        }).map((response) => {
            return this.processCreate(response);
        }).catch((response: any, caught: any) => {
            if (response instanceof Response) {
                try {
                    return Observable.of(this.processCreate(response));
                } catch (e) {
                    return <Observable<TaxDto>><any>Observable.throw(e);
                }
            } else
                return <Observable<TaxDto>><any>Observable.throw(response);
        });
    }
</code>```

The error on the console is as follows

```<code>> {code: 0, message: "Your request is not valid!", details: "The
> following errors were detected during validation. ↵ -  ↵",
> validationErrors: Array(1)} code : 0 details : "The following errors
> were detected during validation. ↵ -  ↵" message : "Your request is
> not valid!" validationErrors : Array(1) 0 : members : ["scanImage"]
> message : ""
> __proto__ : Object length : 1
> __proto__ : Array(0)
> __proto__ : Object
</code>```

Iam using aspnetboilerplate v3.0.0 .NET Core + Angular4. Please help me. I have been on this for days now.

答:
I advice you to create a controller based on AbpController.
Then upload your image via this controller and return the image unique filename. Then use that unique filename in CreateTaxMapDto.

Ref => Uploading Image in Aspnet boilerplate

Body:
In my application, I am trying to pass an object that contains an image to the web api but it throws a 400 bad request error and picks out the scanImage property as the culprit. I have tried so many workarounds and googled a lot but no help found yet.

DTO

    public class CreateTaxMapDto
    {
        [Required(ErrorMessage = "Tax Type is required")]
        public int TaxTypeId { get; set; }

        public int? BranchId { get; set; }

        [Required(ErrorMessage = "Date of receipt is required")]
        public DateTime DateOfReceipt { get; set; }

        public decimal Amount { get; set; }

        public IFormFile ScanImage { get; set; }

        [StringLength(150)]
        public string Remark { get; set; }
    }

ApplicationService

        public async Task SaveTax(CreateTaxMapDto input)
        {
            // Code to save the input to the database
        }

CreateTaxMap.ts

export class CreateTaxMapDto {
    taxTypeId: number;
    branchId: number;
    dateOfReceipt: Date;
    amount: number;
    scanImage: any;
    constructor(data?: any) {
        if (data !== undefined) {
            this.taxTypeId = data['taxTypeId'] !== undefined ? data['taxTypeId'] : null;
            this.branchId = data['branchId'] !== undefined ? data['branchId'] : null;
            this.dateOfReceipt = data['dateOfReceipt'] !== undefined ? data['dateOfReceipt'] : null;
            this.amount = data['amount'] !== undefined ? data['amount'] : null;
            this.scanImage = data['scanImage'] !== undefined ? data['scanImage'] : null;
        }
    }

    static fromJS(data: any): CreateTaxMapDto {
        return new CreateTaxMapDto(data);
    }

    toJS(data?: any) {
        data = data === undefined ? {} : data;
        data['taxTypeId'] = this.taxTypeId !== undefined ? this.taxTypeId : null;
        data['branchId'] = this.branchId !== undefined ? this.branchId : null;
        data['dateOfReceipt'] = this.dateOfReceipt !== undefined ? this.dateOfReceipt : null;
        data['amount'] = this.amount !== undefined ? this.amount : null;
        data['scanImage'] = this.scanImage !== undefined ? this.scanImage : null;

        return data;
    }

    toJSON() {
        return JSON.stringify(this.toJS());
    }

clone() {
    const json = this.toJSON();
    return new CreateTaxMapDto(JSON.parse(json));
}

}

Create-Tax.Component.Html

<input #imageInput type="file" class="form-control" (change)="onImageChange()" />

Component.ts

  onImageChange() {
    let imgInput = this.imageInput.nativeElement;
    if (imgInput.files && imgInput.files[0]) {
      this.file = imgInput.files[0];
    }
  }

save(): void {
    this.saving = true;
    this.tax.branchId = this.appSession.user.branchId;
    const custFile = <MyFile>(this.file); // MyFile is an interface that extends File
    let originalFile = {
      'lastModified': custFile.lastModified,
      'lastModifiedDate': custFile.lastModifiedDate,
      'name': custFile.name,
      'size': custFile.size,
      'type': custFile.type,
      'webkitRelativePath': custFile.webkitRelativePath
    };
    this.tax.scanImage = originalFile;
    console.log(this.tax.scanImage);
    this._taxService.create(this.tax)
        .finally(() => { this.saving = false; })
        .subscribe(() => {
            this.notify.success(this.l('SavedSuccessfully'), 'Tax Saved');
            this.close();
            this.modalSave.emit(null);
        });
  }

Service.ts

create(input: CreateTaxMapDto): Observable<TaxDto> {
        let url_ = this.baseUrl + '/api/services/app/Tax/SaveTax';

        const content_ = JSON.stringify(input ? input.toJS() : null);
        console.log('Inputt: ' + content_);

        return this.http.request(url_, {
            body: content_,
            method: 'post',
            headers: new Headers({
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/json; charset=UTF-8'
            })
        }).map((response) => {
            return this.processCreate(response);
        }).catch((response: any, caught: any) => {
            if (response instanceof Response) {
                try {
                    return Observable.of(this.processCreate(response));
                } catch (e) {
                    return <Observable<TaxDto>><any>Observable.throw(e);
                }
            } else
                return <Observable<TaxDto>><any>Observable.throw(response);
        });
    }

The error on the console is as follows

> {code: 0, message: "Your request is not valid!", details: "The
> following errors were detected during validation. ↵ -  ↵",
> validationErrors: Array(1)} code : 0 details : "The following errors
> were detected during validation. ↵ -  ↵" message : "Your request is
> not valid!" validationErrors : Array(1) 0 : members : ["scanImage"]
> message : ""
> __proto__ : Object length : 1
> __proto__ : Array(0)
> __proto__ : Object

Iam using aspnetboilerplate v3.0.0 .NET Core + Angular4. Please help me. I have been on this for days now.


问:
How to auto-select the first option in a dropdown list using jquery?
I'm having trouble auto-selecting the first option in a dropdown list.

I've tried using attr and val function (see this jdfiddle link for an example) and it just wouldn't work. As a a test, my example has an  alert code that displays the .text() for the first option and this works fine. So my selector is working.

Thanks a lot!

sample HTML code:

```<code><select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>
</code>```

sample JS  code:

```<code>$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt option:first-child").attr("selected", "selected");
    //$("#rt option:first-child").val("blank");
});
</code>```

答:
Use selector val method to set the value

```<code>$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt").val($("#rt option:first-child").attr("value"));
});
</code>```

or simply

```<code>$("#rs").on("change", function() {
    $("#rt").val($("#rt option:first").val());
});
</code>```

The below snippet will do what exactly you want

$("#rs").on("change", function() {
    $("#rt").val($("#rt option:first").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select></code>```

Body:
I'm having trouble auto-selecting the first option in a dropdown list.

I've tried using attr and val function (see this jdfiddle link for an example) and it just wouldn't work. As a a test, my example has an  alert code that displays the .text() for the first option and this works fine. So my selector is working.

Thanks a lot!

sample HTML code:

<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>

<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>

sample JS  code:

$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt option:first-child").attr("selected", "selected");
    //$("#rt option:first-child").val("blank");
});

Body:
Use selector val method to set the value

$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt").val($("#rt option:first-child").attr("value"));
});

or simply

$("#rs").on("change", function() {
    $("#rt").val($("#rt option:first").val());
});

The below snippet will do what exactly you want

$("#rs").on("change", function() {
    $("#rt").val($("#rt option:first").val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>


答:
What's happening is that the reserved characters <> are being parsed as HTML. Since <Dummy Text> doesn't exist as a tag, it swallows it so that it doesn't appear on your page.

To fix this you need to use HTML character codes. Instead of inserting the symbol < use the string < and instead of > use >

Title: How to print <DummyText> inside html tag using javascript?

Body:
What's happening is that the reserved characters <> are being parsed as HTML. Since <Dummy Text> doesn't exist as a tag, it swallows it so that it doesn't appear on your page.

To fix this you need to use HTML character codes. Instead of inserting the symbol < use the string &lt; and instead of > use &gt;


问:
Unable to Apply CSS style to SVG text element
I noticed that when you append text with JS, some styling rules work and others cease to work. To be specific, consider my css style rule that creates a border-bottom on hover...

var svg = d3.select('body')
        .append('svg')
        .attr('height',200)
        .attr('width',200);

svg.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content-text-1:hover {
    border-bottom: 1px solid blue;
}</code>```

```

I don't believe this a "asynchronous" type of issue, because when I create other things, such as, svg rects or circles (just to name a few), they can be styled after the fact.

Question: What is causing the border-bottom not to show?

答:
The problem here is not the CSS, but the SVG instead. SVG does not support border-bottom property.

For instance, you can clearly see that the CSS works if you have HTML elements:

var div = d3.select('body')
  .append('div')
  .html('This is not a text.')
  .style('font-size', '14px')
  .attr('class', 'content-text-1');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content-text-1:hover {
  border-bottom: 1px solid blue;
}</code>```

```

Body:
I noticed that when you append text with JS, some styling rules work and others cease to work. To be specific, consider my css style rule that creates a border-bottom on hover...

var svg = d3.select('body')
        .append('svg')
        .attr('height',200)
        .attr('width',200);

svg.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);

.content-text-1:hover {
    border-bottom: 1px solid blue;
}

I don't believe this a "asynchronous" type of issue, because when I create other things, such as, svg rects or circles (just to name a few), they can be styled after the fact.

Question: What is causing the border-bottom not to show?

Body:
The problem here is not the CSS, but the SVG instead. SVG does not support border-bottom property.

For instance, you can clearly see that the CSS works if you have HTML elements:

var div = d3.select('body')
  .append('div')
  .html('This is not a text.')
  .style('font-size', '14px')
  .attr('class', 'content-text-1');

.content-text-1:hover {
  border-bottom: 1px solid blue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
Login Page in ASP.NET application with FormsAuthentication access denied
I've got a webapp running that needs users to login.
Webconfig:

```<code>    <!--Logging in stuff-->
    <authentication mode="Forms">
        <forms loginUrl="login.aspx" timeout="2880"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

And in the login.aspx page (doubled checked the name) I have the following logic after verifying the user credentials using my own database:

```<code>    if (checkCredentials.searchCredentials(attemptedName, passwordBox.Text) != null)
            {
                FormsAuthentication.RedirectFromLoginPage(attemptedName,false);
            }
</code>```

I know the if statement works, as it did with a previous method I used for logging in.

However, when I run the application, the login page opens up immediately with error 401.2. Help would be much appreciated :)

答:
I am posting another answer since this deals with the typical problem of using Visual Studio 2017 with forms authentication, and is an alternate to my previous answer.

Visual Studio 2017 will automatically add a NuGet package called Microsoft.AspNet.FriendlyUrls to your website or web app project. Because of this package, forms authentication will not work and even the login page will not render many times.

The solution explained in my previous answer is to remove this
package or comment the line in Application_Start event in global.asax
that says RouteConfig.RegisterRoutes(RouteTable.Routes);.  Your website will lose the benefits of friendlyUrls if you use this approach.

But, there is a third solution that is mentioned in two different CONFIGURATIONS below; you can use either of them.

CONFIGURATION 1 removes the aspx extension from login and defaultUrl

values.

CONFIGURATION 2 keeps the aspx extensions but adds special access
permissions for freindlyurl corresponding to login.aspx.

(? in access permission means all unauthenticated users and * means all users i.e. authenticated + unauthenticated users)

NOTE: I have tried and tested this solution.

CONFIGURATION 1 for Forms authentication config when using Friendly Urls

```<code><authentication mode="Forms">
<forms loginUrl="login" defaultUrl="home"
   slidingExpiration="true" timeout="20" name=".Auth" protection="All">
</forms>
</authentication>
</code>```

CONFIGURATION 2  for Forms authentication config when using Friendly Urls

```<code><system.web>
<!--keep the aspx extensions for login and default pages-->
<authentication mode="Forms">
    <forms loginUrl="login.aspx" defaultUrl="home.aspx"
       slidingExpiration="true" timeout="20" name=".Auth" protection="All">
    </forms>
    </authentication>
</system.web>

<!-- add access permissions for friendly url corresponding to login.aspx-->
<location path="login">
        <system.web>
            <authorization>
                <allow users="?" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
</configuration>
</code>```

Body:
I've got a webapp running that needs users to login.
Webconfig:

    <authentication mode="Forms">
        <forms loginUrl="login.aspx" timeout="2880"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>

And in the login.aspx page (doubled checked the name) I have the following logic after verifying the user credentials using my own database:

    if (checkCredentials.searchCredentials(attemptedName, passwordBox.Text) != null)
            {
                FormsAuthentication.RedirectFromLoginPage(attemptedName,false);
            }

I know the if statement works, as it did with a previous method I used for logging in.

However, when I run the application, the login page opens up immediately with error 401.2. Help would be much appreciated :)

Body:
I am posting another answer since this deals with the typical problem of using Visual Studio 2017 with forms authentication, and is an alternate to my previous answer.

Visual Studio 2017 will automatically add a NuGet package called Microsoft.AspNet.FriendlyUrls to your website or web app project. Because of this package, forms authentication will not work and even the login page will not render many times.

The solution explained in my previous answer is to remove this
package or comment the line in Application_Start event in global.asax
that says RouteConfig.RegisterRoutes(RouteTable.Routes);.  Your website will lose the benefits of friendlyUrls if you use this approach.

But, there is a third solution that is mentioned in two different CONFIGURATIONS below; you can use either of them.

CONFIGURATION 1 removes the aspx extension from login and defaultUrl

values.

CONFIGURATION 2 keeps the aspx extensions but adds special access
permissions for freindlyurl corresponding to login.aspx.

(? in access permission means all unauthenticated users and * means all users i.e. authenticated + unauthenticated users)

NOTE: I have tried and tested this solution.

CONFIGURATION 1 for Forms authentication config when using Friendly Urls

<authentication mode="Forms">
<forms loginUrl="login" defaultUrl="home"
   slidingExpiration="true" timeout="20" name=".Auth" protection="All">
</forms>
</authentication>

CONFIGURATION 2  for Forms authentication config when using Friendly Urls

<system.web>
<!--keep the aspx extensions for login and default pages-->
<authentication mode="Forms">
    <forms loginUrl="login.aspx" defaultUrl="home.aspx"
       slidingExpiration="true" timeout="20" name=".Auth" protection="All">
    </forms>
    </authentication>
</system.web>

<!-- add access permissions for friendly url corresponding to login.aspx-->
<location path="login">
        <system.web>
            <authorization>
                <allow users="?" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
</configuration>


问:
Unable to invoke localhost https REST service in Ballerinalang and give a timeout error?
I've implemented a Ballerina(ballerina 0.91) service to invoke https REST service which running on localhost. I used http:ClientConnector to call that service. This is my sample code.

```<code>http:ClientConnector clientConnector = create http:ClientConnector("https://localhost:9445/");
string token = "admin:admin";
string auth = utils:base64encode(token);
message request = {};
messages:setHeader(request,"Basic ",auth);
message response = clientConnector.get("bpmn/runtime/process-instances/",request);
</code>```

By the way here I interact with a business process in WSO2 EI.

The problem is when I call this service normally it didn't respond or gave an error like below.

```<code>error: ballerina.lang.errors:Error, message: failed to invoke 'get' action in ClientConnector. response was not received within sender timeout of 180 seconds
    at ballerina.net.http:ClientConnector.get(<native>:0)
    at org.wso2.ballerina.connectors.basicauth:ClientConnector.get(org/wso2/ballerina/connectors/basicauth/ClientConnector.bal:28)
    at .:main(MainFile.bal:21)
</code>```

答: I sort out my problem from adding the certificate of WSO2-EI into Ballerina client-truststore.jks file.</p>

Body:
I've implemented a Ballerina(ballerina 0.91) service to invoke https REST service which running on localhost. I used http:ClientConnector to call that service. This is my sample code.

http:ClientConnector clientConnector = create http:ClientConnector("https://localhost:9445/");
string token = "admin:admin";
string auth = utils:base64encode(token);
message request = {};
messages:setHeader(request,"Basic ",auth);
message response = clientConnector.get("bpmn/runtime/process-instances/",request);

By the way here I interact with a business process in WSO2 EI.

The problem is when I call this service normally it didn't respond or gave an error like below.

error: ballerina.lang.errors:Error, message: failed to invoke 'get' action in ClientConnector. response was not received within sender timeout of 180 seconds
    at ballerina.net.http:ClientConnector.get(<native>:0)
    at org.wso2.ballerina.connectors.basicauth:ClientConnector.get(org/wso2/ballerina/connectors/basicauth/ClientConnector.bal:28)
    at .:main(MainFile.bal:21)


问:
Unable to solve flash error 5000: The class ... must subclass 'flash.display.MovieClip'
I'm getting the following error on my flash project
5000: The class ... must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.
I looked at the class and made sure that I import flash.display.MovieClip and I do. I tried to change the base class in the linkage to flash.display.MovieClip but I got the following message: "The base class specified is a native class and will be defined in the player at runtime. It cannot be edited."

How can I fix this issue?
Thanks in advance,
Kfir

答:
Well I just had the same bug in another project and decided that I should post the solution. For some bizarre reason this error may occur when the references of the project are invalid.
In my case all I had to do is go to File->Publish Settings->Flash->Settings and update all the paths there. That solved my problem.

I hope this will help other people out there and maybe the someone from the flash team will see this and patch this bug.

ContentLicense: CC BY-SA 2.5


问:
Google Cloud Storage as file storage for multiple users
I need the following:-
I want to give access to Google Cloud Storage for multiple users.

I will create a Google project and will do the following:
I want each of them to have their-

Regional storage bucket: with 5-25 GB/user space allocation based on their location. They will store and use their data as files.

Coldline storage bucket: Each user can store approximately 1TB of archival data/files over here.

I need to provide the users to have an easy uploading environment (like Google Drive).

I want to sent storage usage alerts, if they runs out of space.

Please suggest me or connect me to the right person for this.

答: The solution is simply to set up a NAS Server (google cloud based) and tag it to the aforementioned storage.</p>


答:
Try this </p>

```<code>$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $('#rt').html($("#rt option:first-child").text());
});
</code>```

Title: How to auto-select the first option in a dropdown list using jquery?

Body:
Try this

$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $('#rt').html($("#rt option:first-child").text());
});


问:
Show Code Analysis warnings in VSTS
I've setup Static Code Analysis on my Visual Studio Team Services builds. I'm using the "MSBuild" build step for my solution and in the build logs it shows 999+ lines that start with ##[warning]:

2017-11-09T13:52:34.7970784Z ##[warning]myfilename.cs(753,17): Warning CA2200: Re-throwing caught exception changes stack information.

When building with "system.debug" set to true, we also see that vso parses these warnings, and 999+ lines in the log show up like this:

2017-11-15T12:30:40.1964968Z ##[warning]myfilename.cs(28,33): Warning CS0109: The member 'Invoice.ColumnOptions' does not hide an accessible member. The new keyword is not required.

  2017-11-15T12:30:40.1964968Z ##[debug]Processed: ##vso[task.logissue type=Warning;sourcepath=myfilename.cs;linenumber=28;columnnumber=33;code=CS0109;]The member 'XXX' does not hide an accessible member. The new keyword is not required.

I would expect that the 999+ static analysis warnings would show up somewhere in the build overview (i.e. https://MYSITE.visualstudio.com/MYPROJECT/_build/index?buildId=XXX&_a=summary&tab=details). However it only shows 11 build warnings, nothing else. See also the screenshot below. How can I display the Static Code Analysis warnings in this build overview? Maybe even a summarised overview of the types of warnings that have triggered?

答:
Yes, just part of warnings in build display in the Issues section of build summary.

The workaround is that you can upload the code analysis result file (xml) through Logging Commands (##vso[task.uploadsummary]local file path)and the content shall be added to build/release summary (Below Work items linked to associated changes section)

Add Powershell task

Call logging command to upload code analysis result

For example:

```<code>param(
[string]$p
)
Write-Host "##vso[task.uploadsummary]$p"
</code>```

Arguments:

-p $(Build.SourcesDirectory)\WebAppAzureProfile\bin\WebAppAzureProfile.dll.CodeAnalysisLog.xml

Title: Show Code Analysis warnings in VSTS

Body:
Yes, just part of warnings in build display in the Issues section of build summary.

The workaround is that you can upload the code analysis result file (xml) through Logging Commands (##vso[task.uploadsummary]local file path)and the content shall be added to build/release summary (Below Work items linked to associated changes section)

Add Powershell task

Call logging command to upload code analysis result

For example:

param(
[string]$p
)
Write-Host "##vso[task.uploadsummary]$p"

Arguments:

-p $(Build.SourcesDirectory)\WebAppAzureProfile\bin\WebAppAzureProfile.dll.CodeAnalysisLog.xml


问:
By returning a pointer that points to a node, is the rest of the list returned as well? c++
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

```<code>Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }
</code>```

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

答:
Yes, your code is correct for your question "not to create new nodes for a function called rest(), where the rest list is returned without the head."

But you need to delete the head node in case your professor want. But he not mention it so I assume that he just want to return the rest without head.

```<code>template<typename T>
struct ListNode{
    T value;
    ListNode<T>* next;
    ListNode(const T &v) : value(v), next(nullptr) {}
};

ListNode<int>* rest(ListNode<int> *head)
{
    if (head) // head is not nullptr
        return nullptr;
    else
        return head->next;
}
</code>```

You could imagine like below:

In example, we have a list with a few elements and a head pointer which point to the first element:

```<code>0x1             0x2                    0x3
-------         --------------
|head |     --> |value1| next|    -->  .....
-------         --------------
</code>```

so that mean :

&head = 0x1;  // the address of pointer head is 0x1

head  = 0x2;  // head pointer will point to the block memory which have address 0x2, i mean, the first element of list

next  = 0x3;  // next pointer will point to the block memory which have address 0x3, the second element of list

So when we call "return head->next", you can easy see that it will return 0x3, the address of the second element.

Body:
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

Body:
Yes, your code is correct for your question "not to create new nodes for a function called rest(), where the rest list is returned without the head."

But you need to delete the head node in case your professor want. But he not mention it so I assume that he just want to return the rest without head.

template<typename T>
struct ListNode{
    T value;
    ListNode<T>* next;
    ListNode(const T &v) : value(v), next(nullptr) {}
};

ListNode<int>* rest(ListNode<int> *head)
{
    if (head) // head is not nullptr
        return nullptr;
    else
        return head->next;
}

You could imagine like below:

In example, we have a list with a few elements and a head pointer which point to the first element:

0x1             0x2                    0x3
-------         --------------
|head |     --> |value1| next|    -->  .....
-------         --------------

so that mean :

&head = 0x1;  // the address of pointer head is 0x1

head  = 0x2;  // head pointer will point to the block memory which have address 0x2, i mean, the first element of list

next  = 0x3;  // next pointer will point to the block memory which have address 0x3, the second element of list

So when we call "return head->next", you can easy see that it will return 0x3, the address of the second element.


答:
```<code>$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt").val("blank");
});
</code>```


问:
Command to open file with git

I have sublime text as the default editor in git (and it works)

git config --edit opens the config file in sublime text (Awesome)

My Question:

What is the command to open say index.html or style.css from inside the project directory?

Basically when I'm working on a project I would like to be able to open a file from git.  How to do this.  Every tutorial seems to go over merge, clone, commit yes we all know these, how to do this simple command.  Or is this not possible from within git?

windows 7

msysgit version 1.8.0

I understand git is not a launcher and is strictly for version control. Just want to know what options I have with the tools at hand.

The question came up while i was commiting a project and realized i needed to make a small edit to a css file i had closed already and was wondering if i could open to edit the file from within git since i had it up.

Seems this is not possible (not the end of the world) I just like to understand all of my options with the tools i use is all

答:
You can use the git command line as a terminal my dude you just know the commands are bash
To create a file

```<code>touch file.txt
</code>```

To open a file

```<code>code file.py
atom file.py
start file.py
</code>```

ect

To open your current folder and everything inside of it in your text editor

```<code>code .
</code>```

To make a folder

```<code>mkdir folder1 folder2 folder3
</code>```

You can make as many as you want at once this works with touch to

ContentLicense: CC BY-SA 4.0

Title: Command to open file with git

Body:
You can use the git command line as a terminal my dude you just know the commands are bash
To create a file

touch file.txt

To open a file

code file.py
atom file.py
start file.py

ect

To open your current folder and everything inside of it in your text editor

code .

To make a folder

mkdir folder1 folder2 folder3

You can make as many as you want at once this works with touch to


问:
Android: ListView can't click items
I created a ListView with a new adapter. Each item in a row contains a photo and a subtitle. When I click on an item, I need to turn to another class and then show the details. And I generate data using a java class called XMLPeopleParser which get data from the raw xml file which is already put data.
I am defining a setOnItemClickListener but when clicking an item, nothing happens.
Also, the photo in each row couldn't be added.
Any help will be appreciated!

MainActivity.class

```<code>import android.app.Activity;
import android.content.Intent;
import android.provider.Contacts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class List_Activity extends AppCompatActivity {

    private ListView list = null;
    private TextView mselection = null;
    private ArrayAdapter<String> adapter = null;

    private XMLPeopleParser parser = null;
    private String [] names = null;
    private String [] addresses = null;
    private String [] images = null;

    private Person [] data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_);
        list = (ListView) findViewById(R.id.listview);
        mselection = (TextView) findViewById(R.id.selection);

        parser = new XMLPeopleParser(getApplicationContext());
        names = parser.getNames();
        addresses = parser.getAddresses();
        images = parser.getImages();
        data = parser.getData();

        list.setAdapter(new IconicAdapter(this));

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });
    }

    private class IconicAdapter extends ArrayAdapter {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.list_row, data);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View row = inflater.inflate(R.layout.list_row, null);
            ImageView icon = (ImageView) row.findViewById(R.id.icon);
            TextView name_title = (TextView) row.findViewById(R.id.name_title);
            TextView address_title = (TextView) row.findViewById(R.id.address_title);

            name_title.setText(names[position]);
            address_title.setText(addresses[position]);

            int[] ImageIds = new int[images.length];
            String[] ImageNames = new String[images.length];

            ImageNames[position] = images[position].substring(0, images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);

            return (row);

        }
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.custom_list_a.List_Activity">

    <TextView
        android:id="@+id/selection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/selection"
        />

</RelativeLayout>
</code>```

list_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <ImageButton
        android:id="@+id/icon"
        android:src="@android:drawable/btn_star"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/address_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>
</code>```

XMLPeopleParser.class

```<code>public class XMLPeopleParser {

    private Person [] data = null;
    private Context context = null;

    public XMLPeopleParser(Context c){

        this.context = c;

        // grab the data from the xml
        // get the doc parser ready for people.xml
        InputStream is = this.context.getResources().openRawResource(R.raw.people);
        DocumentBuilder builder = null;
        Document doc = null;

        try{
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = builder.parse(is);
        }catch (Exception e){}

        NodeList nameList = doc.getElementsByTagName("name");
        NodeList addressList = doc.getElementsByTagName("address");
        NodeList dobList = doc.getElementsByTagName("dob");
        NodeList colourList = doc.getElementsByTagName("color");
        NodeList imageList = doc.getElementsByTagName("image");
        NodeList urlList = doc.getElementsByTagName("url");

        data = new Person[nameList.getLength()];

        for (int i = 0; i < data.length; i++){

            String name = nameList.item(i).getFirstChild().getNodeValue();
            String address = addressList.item(i).getFirstChild().getNodeValue();
            String dob = dobList.item(i).getFirstChild().getNodeValue();
            String colour = colourList.item(i).getFirstChild().getNodeValue();
            String image = imageList.item(i).getFirstChild().getNodeValue();
            String url = urlList.item(i).getFirstChild().getNodeValue();

            data[i] = new Person(name, address, dob, colour, image, url);

        }
    }

    public Person [] getData(){return data;}

    public Person getData(int i) {return data[i];}

    public String[] getNames(){
        String[] names = new String[data.length];

        for (int i = 0; i < names.length; i ++){

            names[i] = getData(i).getName();
        }
        return names;
    }

    public String[] getAddresses() {
        String[] addresses = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            addresses[i] = getData(i).getAddress();
        }
        return  addresses;
    }

    public String[] getDobs() {
        String[] dobs = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            dobs[i] = getData(i).getDob();
        }
        return  dobs;
    }

    public String[] getColours() {
        String[] colours = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            colours[i] = getData(i).getColour();
        }
        return  colours;
    }

    public String[] getImages() {
        String[] images = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            images[i] = getData(i).getImage();

        }
        return  images;
    }

    public String[] geturls() {
        String[] urls = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            urls[i] = getData(i).getUrl();
        }
        return  urls;
    }

}
</code>```

R.raw.people xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="people.xsd" generated="2011-11-05T23:09:59">

    <person>
        <name>ANDY</name>
        <address>USA</address>
        <color>BLACK</color>
        <dob>2020/2/2</dob>
        <image>andy.jpeg</image>
        <url>https://en.wikipedia.org/wiki/andy</url>
    </person>

    <person>
        <name>Bill</name>
        <address>UK</address>
        <dob>2020/1/1</dob>
        <color>white</color>
        <image>bill.jpeg</image>
        <url>https://en.wikipedia.org/wiki/bill</url>
    </person>
</code>```

答:
I think your list_row.xml is not proper so it may be possible your cell hit not working. Can you please try this one.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        android:src="@android:drawable/btn_star" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="ABC" />

        <TextView
            android:id="@+id/address_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="ABC" />
    </LinearLayout>

</LinearLayout>
</code>```

Title: Android: ListView can't click items

Body:
I created a ListView with a new adapter. Each item in a row contains a photo and a subtitle. When I click on an item, I need to turn to another class and then show the details. And I generate data using a java class called XMLPeopleParser which get data from the raw xml file which is already put data.
I am defining a setOnItemClickListener but when clicking an item, nothing happens.
Also, the photo in each row couldn't be added.
Any help will be appreciated!

MainActivity.class

import android.app.Activity;
import android.content.Intent;
import android.provider.Contacts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class List_Activity extends AppCompatActivity {

    private ListView list = null;
    private TextView mselection = null;
    private ArrayAdapter<String> adapter = null;

    private XMLPeopleParser parser = null;
    private String [] names = null;
    private String [] addresses = null;
    private String [] images = null;

    private Person [] data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_);
        list = (ListView) findViewById(R.id.listview);
        mselection = (TextView) findViewById(R.id.selection);

        parser = new XMLPeopleParser(getApplicationContext());
        names = parser.getNames();
        addresses = parser.getAddresses();
        images = parser.getImages();
        data = parser.getData();

        list.setAdapter(new IconicAdapter(this));

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });
    }

    private class IconicAdapter extends ArrayAdapter {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.list_row, data);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View row = inflater.inflate(R.layout.list_row, null);
            ImageView icon = (ImageView) row.findViewById(R.id.icon);
            TextView name_title = (TextView) row.findViewById(R.id.name_title);
            TextView address_title = (TextView) row.findViewById(R.id.address_title);

            name_title.setText(names[position]);
            address_title.setText(addresses[position]);

            int[] ImageIds = new int[images.length];
            String[] ImageNames = new String[images.length];

            ImageNames[position] = images[position].substring(0, images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);

            return (row);

        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.custom_list_a.List_Activity">

    <TextView
        android:id="@+id/selection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/selection"
        />

</RelativeLayout>

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <ImageButton
        android:id="@+id/icon"
        android:src="@android:drawable/btn_star"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/address_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>

XMLPeopleParser.class

public class XMLPeopleParser {

    private Person [] data = null;
    private Context context = null;

    public XMLPeopleParser(Context c){

        this.context = c;

        // grab the data from the xml
        // get the doc parser ready for people.xml
        InputStream is = this.context.getResources().openRawResource(R.raw.people);
        DocumentBuilder builder = null;
        Document doc = null;

        try{
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = builder.parse(is);
        }catch (Exception e){}

        NodeList nameList = doc.getElementsByTagName("name");
        NodeList addressList = doc.getElementsByTagName("address");
        NodeList dobList = doc.getElementsByTagName("dob");
        NodeList colourList = doc.getElementsByTagName("color");
        NodeList imageList = doc.getElementsByTagName("image");
        NodeList urlList = doc.getElementsByTagName("url");

        data = new Person[nameList.getLength()];

        for (int i = 0; i < data.length; i++){

            String name = nameList.item(i).getFirstChild().getNodeValue();
            String address = addressList.item(i).getFirstChild().getNodeValue();
            String dob = dobList.item(i).getFirstChild().getNodeValue();
            String colour = colourList.item(i).getFirstChild().getNodeValue();
            String image = imageList.item(i).getFirstChild().getNodeValue();
            String url = urlList.item(i).getFirstChild().getNodeValue();

            data[i] = new Person(name, address, dob, colour, image, url);

        }
    }

    public Person [] getData(){return data;}

    public Person getData(int i) {return data[i];}

    public String[] getNames(){
        String[] names = new String[data.length];

        for (int i = 0; i < names.length; i ++){

            names[i] = getData(i).getName();
        }
        return names;
    }

    public String[] getAddresses() {
        String[] addresses = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            addresses[i] = getData(i).getAddress();
        }
        return  addresses;
    }

    public String[] getDobs() {
        String[] dobs = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            dobs[i] = getData(i).getDob();
        }
        return  dobs;
    }

    public String[] getColours() {
        String[] colours = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            colours[i] = getData(i).getColour();
        }
        return  colours;
    }

    public String[] getImages() {
        String[] images = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            images[i] = getData(i).getImage();

        }
        return  images;
    }

    public String[] geturls() {
        String[] urls = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            urls[i] = getData(i).getUrl();
        }
        return  urls;
    }

}

R.raw.people xml file:

<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="people.xsd" generated="2011-11-05T23:09:59">

    <person>
        <name>ANDY</name>
        <address>USA</address>
        <color>BLACK</color>
        <dob>2020/2/2</dob>
        <image>andy.jpeg</image>
        <url>https://en.wikipedia.org/wiki/andy</url>
    </person>

    <person>
        <name>Bill</name>
        <address>UK</address>
        <dob>2020/1/1</dob>
        <color>white</color>
        <image>bill.jpeg</image>
        <url>https://en.wikipedia.org/wiki/bill</url>
    </person>

Body:
I think your list_row.xml is not proper so it may be possible your cell hit not working. Can you please try this one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        android:src="@android:drawable/btn_star" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="ABC" />

        <TextView
            android:id="@+id/address_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="ABC" />
    </LinearLayout>

</LinearLayout>


问:
Validation Error: when creation/update: a mandatory field is not correctly set "[object with reference: Product Template - product.template] "
I want to create product category but have validation error

Here is my .py code:

class product_product(models.Model):
    _inherit = 'product.product'

    product_package_item_ids = fields.One2many("product.package.item", "parent_product_id", "Product Package Item")

class product_template(models.Model):
    _inherit = 'product.template'

    pack = fields.Boolean(
        'Pack?',
        help='Product Pack?',
        )
    product_package_item_ids = fields.One2many("product.package.item", "parent_product_id", "Product Package Item")
```

<p>Here is my <strong>xml</strong> code:</p>

<pre class="lang-xml prettyprint-override"><code><record model="ir.ui.view" id="product_template_only_form_view">
        <field name="name">product.template.pack.form</field>
        <field name="model">product.template</field>
        <field name="inherit_id" ref="product.product_template_only_form_view" />
        <field name="arch" type="xml">
            <field name="type" position="after">
                <field name="pack"/>
            </field>
            <notebook position="inside">
                <page string="Pack" attrs="{'invisible': ['|', ('product_variant_count', '>', 1), ('pack', '=', False)]}">
                    <field name="product_package_item_ids">
                        <tree editable="bottom">
                            <field name="product_categ_id"/>
                            <field name="quantity"/>
                        </tree>
                    </field>
                </page>
            </notebook>
        </field>
    </record>

    <record model="ir.ui.view" id="nan_product_pack_form">
        <field name="name">product.product.pack.form</field>
        <field name="model">product.product</field>
        <field name="inherit_id" ref="product.product_normal_form_view" />
        <field name="arch" type="xml">
            <field name="type" position="after">
                <field name="pack"/>
            </field>
            <notebook position="inside">
                <page string="Pack" attrs="{'invisible':[('pack', '=', False)]}">
                <!-- <page string="Pack" attrs="{'required': [('pack','=', True)]}"> -->
                    <field name="product_package_item_ids">
                    <!-- <field name="product_package_item_ids" attrs="{'required': [('attribute_value_ids','=', True)]}"> -->
                    <!-- <field name="product_package_item_ids" attrs="{'required':[('pack', '=', 'attribute_value_ids')]}"> -->
                        <tree editable="bottom">
                            <field name="product_categ_id"/>
                            <field name="quantity"/>
                        </tree>
                    </field>
                </page>
            </notebook>
        </field>
    </record>
</code>```

This is error

The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set

[object with reference: Product Template - product.template]

How to fix it? any ideas?

答: You don't want to create a product_package_item_ids in both product.template and product.product. Because product.product inherits product.template model. Remove product_package_item_ids from product.product model. And try again.

Body:
I want to create product category but have validation error

Here is my .py code:

class product_product(models.Model):
    _inherit = 'product.product'

    product_package_item_ids = fields.One2many("product.package.item", "parent_product_id", "Product Package Item")

class product_template(models.Model):
    _inherit = 'product.template'

    pack = fields.Boolean(
        'Pack?',
        help='Product Pack?',
        )
    product_package_item_ids = fields.One2many("product.package.item", "parent_product_id", "Product Package Item")

Here is my xml code:

<record model="ir.ui.view" id="product_template_only_form_view">
        <field name="name">product.template.pack.form</field>
        <field name="model">product.template</field>
        <field name="inherit_id" ref="product.product_template_only_form_view" />
        <field name="arch" type="xml">
            <field name="type" position="after">
                <field name="pack"/>
            </field>
            <notebook position="inside">
                <page string="Pack" attrs="{'invisible': ['|', ('product_variant_count', '>', 1), ('pack', '=', False)]}">
                    <field name="product_package_item_ids">
                        <tree editable="bottom">
                            <field name="product_categ_id"/>
                            <field name="quantity"/>
                        </tree>
                    </field>
                </page>
            </notebook>
        </field>
    </record>

    <record model="ir.ui.view" id="nan_product_pack_form">
        <field name="name">product.product.pack.form</field>
        <field name="model">product.product</field>
        <field name="inherit_id" ref="product.product_normal_form_view" />
        <field name="arch" type="xml">
            <field name="type" position="after">
                <field name="pack"/>
            </field>
            <notebook position="inside">
                <page string="Pack" attrs="{'invisible':[('pack', '=', False)]}">

                    <field name="product_package_item_ids">

                        <tree editable="bottom">
                            <field name="product_categ_id"/>
                            <field name="quantity"/>
                        </tree>
                    </field>
                </page>
            </notebook>
        </field>
    </record>

This is error

The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set

[object with reference: Product Template - product.template]

How to fix it? any ideas?


问:
java.lang.IllegalStateException: The driver executable does not exist: C:\Users\jagrelot\workspace\AntBuildExample\chromedriver.exe with ChromeDriver
When I try to run Selenium within Eclipse, I get a The driver executable does not exist: error. I've ensured that the path to the exe is correct and that the environment PATH variable is set. The error is referencing an older location of the driver which was located in the workspace of the Java project. It seems to be working when I run it through the command line. Are there any suggestions to get the code to run in Eclipse properly?</p>

```<code>public WebDriver chromeDriver;

@BeforeTest
public void beforeTestsetUp(){

    System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe");
    chromeDriver = new ChromeDriver();

    [RemoteTestNG] detected TestNG version 6.12.0
    FAILED CONFIGURATION: @BeforeTest beforeTestsetUp
    java.lang.IllegalStateException: The driver executable does not exist: C:\Users\jagrelot\workspace\AntBuildExample\chromedriver.exe
</code>```

答:
The code block you have provided is not sufficient to analyze the root cause. How ever the following points are pretty much evident :

The initialization of ChromeDriver is error prone, it should have been :

```<code>ChromeDriver driver = new ChromeDriver();
</code>```

As per best practices we should use the WebDriver interface instead of the ChromeDriver implementation :

```<code>WebDriver driver = new ChromeDriver();
</code>```

As you are seeing the error as IllegalStateException: The driver executable does not exist: C:\Users\jagrelot\workspace\AntBuildExample\chromedriver.exe which clearly indicates your script is looking for the chromedriver binary in a different location other than the mentioned one. Probably its due to error prone code of setProperty.

Body:
When I try to run Selenium within Eclipse, I get a The driver executable does not exist: error. I've ensured that the path to the exe is correct and that the environment PATH variable is set. The error is referencing an older location of the driver which was located in the workspace of the Java project. It seems to be working when I run it through the command line. Are there any suggestions to get the code to run in Eclipse properly?

public WebDriver chromeDriver;

@BeforeTest
public void beforeTestsetUp(){

    System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe");
    chromeDriver = new ChromeDriver();

    [RemoteTestNG] detected TestNG version 6.12.0
    FAILED CONFIGURATION: @BeforeTest beforeTestsetUp
    java.lang.IllegalStateException: The driver executable does not exist: C:\Users\jagrelot\workspace\AntBuildExample\chromedriver.exe

Body:
The code block you have provided is not sufficient to analyze the root cause. How ever the following points are pretty much evident :

The initialization of ChromeDriver is error prone, it should have been :

ChromeDriver driver = new ChromeDriver();

As per best practices we should use the WebDriver interface instead of the ChromeDriver implementation :

WebDriver driver = new ChromeDriver();

As you are seeing the error as IllegalStateException: The driver executable does not exist: C:\Users\jagrelot\workspace\AntBuildExample\chromedriver.exe which clearly indicates your script is looking for the chromedriver binary in a different location other than the mentioned one. Probably its due to error prone code of setProperty.


问:
Printing fabricjs canvas?
I've been struggling for a few weeks on creating functionality to allow me to print my fabricjs canvas. I've tried the methods mentioned here without luck. I'm able to get to the print dialog, however, it's blank aside from the title and page info. Can anyone point me in the right direction?

I'm currently using:

```<code>// Trying to print
function printCanvas()
{
    var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '">';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('','','width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
    printWin.document.close();
    printWin.focus();
    printWin.print();
    printWin.close();
}
</code>```

```<code><button onclick="printCanvas()">Print</button>
</code>```

答:
You need to do the print operation after the content is loaded. The following code should work</p>

```<code>function printCanvas() {
    var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('', '', 'width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
}
</code>```

Title: Printing fabricjs canvas?

Body:
I've been struggling for a few weeks on creating functionality to allow me to print my fabricjs canvas. I've tried the methods mentioned here without luck. I'm able to get to the print dialog, however, it's blank aside from the title and page info. Can anyone point me in the right direction?

I'm currently using:

// Trying to print
function printCanvas()
{
    var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
    var windowContent = '<!DOCTYPE html>';
    windowContent += ''
    windowContent += '<title>Print canvas</title>';
    windowContent += ''
    windowContent += '';
    windowContent += '';
    windowContent += '';
    var printWin = window.open('','','width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
    printWin.document.close();
    printWin.focus();
    printWin.print();
    printWin.close();
}

<button onclick="printCanvas()">Print</button>

Body:
You need to do the print operation after the content is loaded. The following code should work

function printCanvas() {
    var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('', '', 'width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
}


问:
Confused with homebrew version mysql and official mysql preferences pane on mac
I downloaded mysql for my Mac from official website 'mysql.com', then launched it on my server using preferences pane and as well as from command line using

sudo /usr/local/etc/mysql/support-files/mysql.server start

Its working good, but during my development process i want to change the sql_mode,because i am getting below error

sql_mode=only_full_group_by

Many of them said to change sql mode config in /usr/mysql/my.cnf, but unfortunately i don't see that directory on my mac, So i installed Homebrew version mysql ,this also not working.

My Problem is where I can find my.cnf file on my mac? now i am not using homebrew version of mysql, I'm using official mysql downloaded from mysql.com/downloads.

答:
Finally i got solution, i created new file inside /etc called my.cnf and set this as

```<code>[mysqld]
# Default : STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
sql_mode = ""
</code>```

Now its working great :) Thanks for your responses!

Body:
Finally i got solution, i created new file inside /etc called my.cnf and set this as

[mysqld]
# Default : STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
sql_mode = ""

Now its working great :) Thanks for your responses!


问:
How can I pause a C# Console application (only when being run by a user)
How can I pause a C# console application only while being run by a user?

I've searched similar issues on stack overflow which recommend learning to debug properly, using readline, etc, but none of them cover the instance where your process might be being run by an automated system that needs to continue straight past (i.e. not pause, to let user read screen).

How can I determine whether the console is being run interactively or by a script?

If this were bash on a linux system, I could do something like

https://www.gnu.org/software/bash/manual/html_node/Is-this-Shell-Interactive_003f.html

答:
Using some command line argument would be the easiest solution. For example if program is run with command line parameter "-automatic" it could just run without stopping. Without such parameter program would run in interactive mode and would expect user input.

It is pretty standard approach used by many command line utilities.


问:
Codeigniter-how to foreach and echo project name by id in my view page
```<code>$data['posts'] = $this->whiteboard_model->u_getTSrowsindex(array('limit'=>$this->perPage));
$data['postsexp'] = $this->whiteboard_model->u_getTSrowsexp(array('limit'=>$this->perPage));
//print_r($data['postsexp']); exit;
foreach($data['posts']  as $post)
{
    $project_id =$post['project_name'];
    $data['projectName'] = $this->whiteboard_model->get_project_name($project_id);
    print_r($data['projectName']);
}
//This is my controller

public function get_project_name($project_id) {
    $this->db->select('project_name');
    $this->db->from('project_list');
    $this->db->where('project_id',$project_id);
    $query = $this->db->get();
    //echo $this->db->last_query();
    //return fetched data
    return ($query->num_rows() > 0)?$query->result_array():FALSE;
}
//my model

<?php if(!empty($posts)): foreach($posts as $post):

//print_r($post);?>

<tr>
    <td>  <?php echo $post['advisor']; ?></td>
    <td>  <?php echo $post['spentdate']; ?></td>
    <td><?php echo $post['project_name']; ?>
    <?php if(!empty($projectName)){
        foreach($projectName as $prj_name){                     //print_r($projectName);
            echo $prj_name['project_name'];
        }
    }    ?>
    </td>
    <td>  <?php echo $post['activity']; ?></td>
    <td>  <?php echo $post['billtype']; ?></td>
    <td>  <?php echo $post['timespent']; ?></td>
    <td>  <?php if($post['status']  == 1){?>
    <b style = "color:blue;">Pending</b>
    <?php }else if($post['status']  == 2){?>
    <b style = "color:green;">Approved</b>
    <?php }else{?>                                      <b style = "color:red;">Rejected</b>
    <?php } ?>                           </td>
</tr>
<?php endforeach; else: ?>`enter code here`

//my view file
</code>```

Finally iam not getting proper values from projectName array ..its giving only one name

答:
It seems like you are fetching data using the project_id

```<code>$this->db->select('project_name');
$this->db->from('project_list');
$this->db->where('project_id',$project_id);
$query = $this->db->get();
</code>```

Here you may be getting only the details of one project where the project_id = $project_id

Comment out that line and see if you get all the project names. Additionally use a print_r($query->result()); to verify your data.

So that it would look like:

```<code>$this->db->select('project_name');
$this->db->from('project_list');
//$this->db->where('project_id',$project_id);
$query = $this->db->get();
print_r($query->result());
</code>```

You can refer more here.

Body:
$data['posts'] = $this->whiteboard_model->u_getTSrowsindex(array('limit'=>$this->perPage));
$data['postsexp'] = $this->whiteboard_model->u_getTSrowsexp(array('limit'=>$this->perPage));
//print_r($data['postsexp']); exit;
foreach($data['posts']  as $post)
{
    $project_id =$post['project_name'];
    $data['projectName'] = $this->whiteboard_model->get_project_name($project_id);
    print_r($data['projectName']);
}
//This is my controller

public function get_project_name($project_id) {
    $this->db->select('project_name');
    $this->db->from('project_list');
    $this->db->where('project_id',$project_id);
    $query = $this->db->get();
    //echo $this->db->last_query();
    //return fetched data
    return ($query->num_rows() > 0)?$query->result_array():FALSE;
}
//my model

<?php if(!empty($posts)): foreach($posts as $post):

//print_r($post);?>

      <?php echo $post['advisor']; ?>
      <?php echo $post['spentdate']; ?>
    <?php echo $post['project_name']; ?>
    <?php if(!empty($projectName)){
        foreach($projectName as $prj_name){                     //print_r($projectName);
            echo $prj_name['project_name'];
        }
    }    ?>

      <?php echo $post['activity']; ?>
      <?php echo $post['billtype']; ?>
      <?php echo $post['timespent']; ?>
      <?php if($post['status']  == 1){?>
    Pending
    <?php }else if($post['status']  == 2){?>
    Approved
    <?php }else{?>                                      Rejected
    <?php } ?>

<?php endforeach; else: ?>`enter code here`

//my view file

Finally iam not getting proper values from projectName array ..its giving only one name

Body:
It seems like you are fetching data using the project_id

$this->db->select('project_name');
$this->db->from('project_list');
$this->db->where('project_id',$project_id);
$query = $this->db->get();

Here you may be getting only the details of one project where the project_id = $project_id

Comment out that line and see if you get all the project names. Additionally use a print_r($query->result()); to verify your data.

So that it would look like:

$this->db->select('project_name');
$this->db->from('project_list');
//$this->db->where('project_id',$project_id);
$query = $this->db->get();
print_r($query->result());

You can refer more here.


问:
Build label_image tensorflow example with Windows10
I built tensorflow following every bit of instruction here.
 The build with VS2015 x64 looks fine, but when compiling the tensorflow\examples\label_image sample I have many errors:

```<code>\tensorflow\third_party\eigen3\unsupported\eigen\cxx11\tensor(1): fatal error C1014: too many include files: depth = 1024
</code>```

Fixing it with a #pragma once, then I got that this (and many like this)

```<code>template <>
struct NumTraits<QInt8> : GenericNumTraits<int8_t> {};
</code>```

gives this error:

\tensorflow\third_party\eigen3\unsupported\eigen\cxx11\src\fixedpoint\fixedpointtypes.h(27): error C2988: unrecognizable template declaration/definition

I also miss the file

```<code>#include "tensorflow/cc/ops/image_ops.h"
</code>```

Did anyone succeed to built (and link...) this sample?

答: may be your include path is wrong. in my project i copy all incloud path in _beam_search_ops project to my project. then the problem is solved</p>

Body:
I built tensorflow following every bit of instruction here.
 The build with VS2015 x64 looks fine, but when compiling the tensorflow\examples\label_image sample I have many errors:

\tensorflow\third_party\eigen3\unsupported\eigen\cxx11\tensor(1): fatal error C1014: too many include files: depth = 1024

Fixing it with a #pragma once, then I got that this (and many like this)

template <>
struct NumTraits<QInt8> : GenericNumTraits<int8_t> {};

gives this error:

\tensorflow\third_party\eigen3\unsupported\eigen\cxx11\src\fixedpoint\fixedpointtypes.h(27): error C2988: unrecognizable template declaration/definition

I also miss the file

#include "tensorflow/cc/ops/image_ops.h"

Did anyone succeed to built (and link...) this sample?


问:
Submitting form via Vue JS to Laravel getting error 419/500 deployed on Google Cloud
I was trying to submit a form using Vue JS with vue-resource to backend running Laravel 5.5 deployed on Google Cloud - App Engine (GAE) with SQL. In my local environment, everything was working fine. But when I deploy on GAE, I could not post the form through /api/rsvp and show error Failed to load resource: the server responded with a status of 419 (Internal Server Error).

Below are the code:

welcome.html

```<code><div class="container-fluid text-center full-height" id="rsvp" style="padding-top: 10em;">
      <div class="row justify-content-center">
        <div class="col-sm col-md-8 col-lg-6 col-xl-6">

          <h1 class="title">RSVP</h1>

          <div id="app" style="padding-top: 5em;">
            <form v-on:submit.prevent="addRSVP()" v-if="!sendRSVP">

              <div class="form-group">
                <div class="row justify-content-center">
                  <div class="col-8">
                    <input v-model="rsvpName" type="text" placeholder="Your name" class="form-control text-center" required>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <div class="radio">
                  <input type="radio" id="one" value="Yeayy!!! See you there, " v-model="rsvp" required>
                  <label for="one">I am coming!</label>
                </div>
                <div class="radio">
                  <input type="radio" id="two" value="It'okay, " v-model="rsvp" required>
                  <label for="two">Sorry, can't make it.</label>
                </div>
              </div>

              <div class="form-group">
                <label for="">@{{ rsvp }} @{{ rsvpName }}</label>
              </div>
              <div class="form-group">
                <div class="row justify-content-center">
                  <div class="col-6" style="background-color: #05341f;">
                    <input type="submit" name="buttonAccept" v-bind:value="rsvpStatus" style="color: white; background-color: transparent;" class="btn btn-block">
                  </div>
                </div>
              </div>
            </form>

            <div class="alert alert-success" v-if="sendRSVP">
              <p>Thank you for your response, @{{ rsvpName }}.</p>
              <p>Would you like to send wedding wishes to us?</p>
              <div class="form-group">
                <div class="row justify-content-center">
                  <div class="col-6" style="background-color: #05341f;">
                    <a href="#wishes" class="btn btn-block" style="background-color: transparent; color: white;">Send Wedding Wishes</a>
                  </div>
                </div>
              </div>
            </div>

          </div>

        </div>
      </div>
    </div>
</code>```

vue-main.js

```<code>Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector("meta[name=csrf-token] ").getAttribute('content');

 var app = new Vue({
     el: '#app',

     data: {
            rsvp: '',
            rsvpName: '',
            sendRSVP: false,
            rsvpStatus: "Send"
     },

     methods: {
             addRSVP(){
                 this.rsvpStatus = "Loading...";
                 var postData = {name: this.rsvpName, rsvp: this.rsvp};

                 this.$http.post('/api/rsvp', postData).then((response)=>{
                   console.log(response);
                   if(response.status = 200){
                     this.rsvpStatus = "Sent!";
                     this.sendRSVP = true;
                   }
                 });
              }
      }
  });
</code>```

web.php

```<code>Route::post('/api/rsvp', 'RSVPController@save');
</code>```

RSVPController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\RSVP;
use Session;

class RSVPController extends Controller
{
  public function save(Request $request)
  {
    $this->validate(request(),[
      'name' => 'required',
      'rsvp' => 'required'
    ]);

    $rsvp = RSVP::create([
      'name' => request('name'),
      'rsvp' => request('rsvp')
    ]);

    return $rsvp;
  }
}
</code>```

app.yaml

```<code>runtime: php
env: flex

runtime_config:
document_root: public

# Ensure we skip ".env", which is only for local development
skip_files:
  - .env

env_variables:
 # Put production environment variables here.
 APP_KEY: [app-key]
 APP_LOG: errorlog
 ## Set these environment variables according to your CloudSQL configuration.
 DB_HOST: localhost
 DB_DATABASE: [db-name]
 DB_USERNAME: [db-acc]
 DB_PASSWORD: [db-password]
 DB_SOCKET: "[my-db-socket-name]"

beta_settings:
# for Cloud SQL, set this value to the Cloud SQL connection name,
# e.g. "project:region:cloudsql-instance"
cloud_sql_instances: "[my-db-instance-name]"
</code>```

app.yaml file above is the configuration to deploy on GAE, am I missing anything out? I have been looking for the solution but still could find it.

答:
I finally managed to solve this by changing the content in app.yaml file for configuration to deploy on Google Cloud Platform - Google Application Engine (GAE).

I need to specify these in the app.yaml

```<code>STORAGE_DIR: /tmp
CACHE_DRIVER: database
SESSION_DRIVER: database
</code>```

Below is the updated app.yaml.

```<code>runtime: php
env: flex

runtime_config:
   document_root: public

# Ensure we skip ".env", which is only for local development
skip_files:
 - .env

env_variables:
# Put production environment variables here.
APP_KEY: [app-key]
APP_LOG: errorlog
   #here i missed out
STORAGE_DIR: /tmp
CACHE_DRIVER: database
SESSION_DRIVER: database
   #until here
## Set these environment variables according to your CloudSQL configuration.
DB_HOST: localhost
DB_DATABASE: [db-name]
DB_USERNAME: [db-acc]
DB_PASSWORD: [db-password]
DB_SOCKET: "[my-db-socket-name]"

beta_settings:
# for Cloud SQL, set this value to the Cloud SQL connection name,
# e.g. "project:region:cloudsql-instance"
cloud_sql_instances: "[my-db-instance-name]"
</code>```

The error happened because the application session is not set to database and it is not able to send the request with the correct session.

Body:
I was trying to submit a form using Vue JS with vue-resource to backend running Laravel 5.5 deployed on Google Cloud - App Engine (GAE) with SQL. In my local environment, everything was working fine. But when I deploy on GAE, I could not post the form through /api/rsvp and show error Failed to load resource: the server responded with a status of 419 (Internal Server Error).

Below are the code:

welcome.html

RSVP

            <form v-on:submit.prevent="addRSVP()" v-if="!sendRSVP">

                    <input v-model="rsvpName" type="text" placeholder="Your name" class="form-control text-center" required>

                  <input type="radio" id="one" value="Yeayy!!! See you there, " v-model="rsvp" required>
                  I am coming!

                  <input type="radio" id="two" value="It'okay, " v-model="rsvp" required>
                  Sorry, can't make it.

                @{{ rsvp }} @{{ rsvpName }}

                    <input type="submit" name="buttonAccept" v-bind:value="rsvpStatus" style="color: white; background-color: transparent;" class="btn btn-block">

            </form>

Thank you for your response, @{{ rsvpName }}.

Would you like to send wedding wishes to us?

                    Send Wedding Wishes

vue-main.js

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector("meta[name=csrf-token] ").getAttribute('content');

 var app = new Vue({
     el: '#app',

     data: {
            rsvp: '',
            rsvpName: '',
            sendRSVP: false,
            rsvpStatus: "Send"
     },

     methods: {
             addRSVP(){
                 this.rsvpStatus = "Loading...";
                 var postData = {name: this.rsvpName, rsvp: this.rsvp};

                 this.$http.post('/api/rsvp', postData).then((response)=>{
                   console.log(response);
                   if(response.status = 200){
                     this.rsvpStatus = "Sent!";
                     this.sendRSVP = true;
                   }
                 });
              }
      }
  });

web.php

Route::post('/api/rsvp', 'RSVPController@save');

RSVPController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\RSVP;
use Session;

class RSVPController extends Controller
{
  public function save(Request $request)
  {
    $this->validate(request(),[
      'name' => 'required',
      'rsvp' => 'required'
    ]);

    $rsvp = RSVP::create([
      'name' => request('name'),
      'rsvp' => request('rsvp')
    ]);

    return $rsvp;
  }
}

app.yaml

runtime: php
env: flex

runtime_config:
document_root: public

# Ensure we skip ".env", which is only for local development
skip_files:
  - .env

env_variables:
 # Put production environment variables here.
 APP_KEY: [app-key]
 APP_LOG: errorlog
 ## Set these environment variables according to your CloudSQL configuration.
 DB_HOST: localhost
 DB_DATABASE: [db-name]
 DB_USERNAME: [db-acc]
 DB_PASSWORD: [db-password]
 DB_SOCKET: "[my-db-socket-name]"

beta_settings:
# for Cloud SQL, set this value to the Cloud SQL connection name,
# e.g. "project:region:cloudsql-instance"
cloud_sql_instances: "[my-db-instance-name]"

app.yaml file above is the configuration to deploy on GAE, am I missing anything out? I have been looking for the solution but still could find it.

Body:
I finally managed to solve this by changing the content in app.yaml file for configuration to deploy on Google Cloud Platform - Google Application Engine (GAE).

I need to specify these in the app.yaml

STORAGE_DIR: /tmp
CACHE_DRIVER: database
SESSION_DRIVER: database

Below is the updated app.yaml.

runtime: php
env: flex

runtime_config:
   document_root: public

# Ensure we skip ".env", which is only for local development
skip_files:
 - .env

env_variables:
# Put production environment variables here.
APP_KEY: [app-key]
APP_LOG: errorlog
   #here i missed out
STORAGE_DIR: /tmp
CACHE_DRIVER: database
SESSION_DRIVER: database
   #until here
## Set these environment variables according to your CloudSQL configuration.
DB_HOST: localhost
DB_DATABASE: [db-name]
DB_USERNAME: [db-acc]
DB_PASSWORD: [db-password]
DB_SOCKET: "[my-db-socket-name]"

beta_settings:
# for Cloud SQL, set this value to the Cloud SQL connection name,
# e.g. "project:region:cloudsql-instance"
cloud_sql_instances: "[my-db-instance-name]"

The error happened because the application session is not set to database and it is not able to send the request with the correct session.