问:
Problem with inserting curdate to database
I keep getting an error when trying to insert the current date to MySQL Database. I got table pictures with different columns. One of them, picture_upload, is supposed to have the date, when picture is uploaded.

I keep getting an error

```<code>PDOException: SQLSTATE[21S01]: Insert value list does not match column list:
1136 Column count doesn't match value count at row 1 in
/Applications/MAMP/htdocs/pinterest/profile.php:57 Stack trace: #0
/Applications/MAMP/htdocs/pinterest/profile.php(57): PDOStatement->execute() #1 {main}Success
</code>```

See my pictures table

```<code>{
    $sName = $_POST['name'];
    $img = $_FILES['image']['name'];
    $sUserId = $_SESSION['txtUsername'];

    try{
        $stmt = $db->prepare("INSERT INTO pictures VALUES (null, :sName, :sImage, 'curdate()', :sUserId, 0, 0)");
        $stmt->bindValue(':sName', $sName);
        $stmt->bindValue(':sImage', $img);
        $stmt->bindValue(':sUserId', $aRow->user_id);

        $stmt->execute();

    }catch (PDOEXception $ex){
        echo $ex;
    }
    move_uploaded_file($_FILES['image']['tmp_name'], "images/$img");
    echo 'Success';
}
</code>```

Thanks for any help!

答:
You should always explicitly list out the columns being targeted by the insert:

```<code>try {
    $sql = "INSERT INTO pictures (picture_name, picture_path, upload_date, use_rid, pic_like, pic_dislike) ";
    $sql .= "VALUES (:sName, :sImage, CURDATE(), :sUserId, 0, 0)";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':sName', $sName);
    $stmt->bindValue(':sImage', $img);
    $stmt->bindValue(':sUserId', $aRow->user_id);

    $stmt->execute();
} catch (PDOEXception $ex) {
    echo $ex;
}
</code>```

Notes:

As picture_id is an auto increment column, if you want MySQL to automatically assign a sequence value, you should omit this column from the insert.  Then, MySQL will handle choosing the value.

CURDATE() does not take single quotes, as it is a function call.

Body:
I keep getting an error when trying to insert the current date to MySQL Database. I got table pictures with different columns. One of them, picture_upload, is supposed to have the date, when picture is uploaded.

I keep getting an error

PDOException: SQLSTATE[21S01]: Insert value list does not match column list:
1136 Column count doesn't match value count at row 1 in
/Applications/MAMP/htdocs/pinterest/profile.php:57 Stack trace: #0
/Applications/MAMP/htdocs/pinterest/profile.php(57): PDOStatement->execute() #1 {main}Success

See my pictures table

{
    $sName = $_POST['name'];
    $img = $_FILES['image']['name'];
    $sUserId = $_SESSION['txtUsername'];

    try{
        $stmt = $db->prepare("INSERT INTO pictures VALUES (null, :sName, :sImage, 'curdate()', :sUserId, 0, 0)");
        $stmt->bindValue(':sName', $sName);
        $stmt->bindValue(':sImage', $img);
        $stmt->bindValue(':sUserId', $aRow->user_id);

        $stmt->execute();

    }catch (PDOEXception $ex){
        echo $ex;
    }
    move_uploaded_file($_FILES['image']['tmp_name'], "images/$img");
    echo 'Success';
}

Thanks for any help!

Body:
You should always explicitly list out the columns being targeted by the insert:

try {
    $sql = "INSERT INTO pictures (picture_name, picture_path, upload_date, use_rid, pic_like, pic_dislike) ";
    $sql .= "VALUES (:sName, :sImage, CURDATE(), :sUserId, 0, 0)";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':sName', $sName);
    $stmt->bindValue(':sImage', $img);
    $stmt->bindValue(':sUserId', $aRow->user_id);

    $stmt->execute();
} catch (PDOEXception $ex) {
    echo $ex;
}

Notes:

As picture_id is an auto increment column, if you want MySQL to automatically assign a sequence value, you should omit this column from the insert.  Then, MySQL will handle choosing the value.

CURDATE() does not take single quotes, as it is a function call.


来源: stackexchange

问:
How to make queries from multiple models in a single view
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

```<code>class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username
</code>```

This is my result upload model

```<code>class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)
</code>```

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

```<code>class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)
</code>```

And this is my views.py for placement.

```<code>def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")
</code>```

Here is my placement.html file

```<code><div class="container">
<p id="success">
    Placement Here.
</p>
{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}<br>
    Stdudent username: {{ placement.student.user }}<br>
    Stdudent gender: {{ placement.student.gender }}<br>
    School: {{ placement.school }}<br><br>

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

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

答:
On these two lines

```<code>for candidate in profile:
    if profile.student_ID == place.student_ID:
</code>```

you are indicating you want to use candidate as the variable name inside the loop, so the second line should probably read if candidate.student_ID instead of if profile.student_ID.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username

This is my result upload model

class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

And this is my views.py for placement.

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")

Here is my placement.html file

    Placement Here.

{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}

    Stdudent username: {{ placement.student.user }}

    Stdudent gender: {{ placement.student.gender }}

    School: {{ placement.school }}

{% endfor %}

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

Body:
On these two lines

for candidate in profile:
    if profile.student_ID == place.student_ID:

you are indicating you want to use candidate as the variable name inside the loop, so the second line should probably read if candidate.student_ID instead of if profile.student_ID.


问:
Convert string[][] to int[][]
I am trying to simply convert the type of jagged arrays:

I would like to do it using something like:

```<code>int[][] jaggedArray = Array.ConvertAll(jaggedArrayString, int.Parse)
</code>```

or

```<code>int[][] jaggedArray = Array.ConvertAll(jaggedArrayString, delegate(string s) { return int.Parse(s); }
</code>```

With Linq, I can't do it that way either

```<code>int[][] jaggedArray = jaggedArrayString.Select(int.Parse).ToArray();
</code>```

I didn't find any solution, is there any easy way to do it?

答:
If you want to use LINQ, you need to Select the strings in each sub array, so you need nested Selects:

```<code>int[][] result = arr.Select(x =>
                     x.Select(int.Parse).ToArray()
                 ).ToArray();
</code>```

Title: Convert string[][] to int[][]

Body:
I am trying to simply convert the type of jagged arrays:

I would like to do it using something like:

int[][] jaggedArray = Array.ConvertAll(jaggedArrayString, int.Parse)

or

int[][] jaggedArray = Array.ConvertAll(jaggedArrayString, delegate(string s) { return int.Parse(s); }

With Linq, I can't do it that way either

int[][] jaggedArray = jaggedArrayString.Select(int.Parse).ToArray();

I didn't find any solution, is there any easy way to do it?

Body:
If you want to use LINQ, you need to Select the strings in each sub array, so you need nested Selects:

int[][] result = arr.Select(x =>
                     x.Select(int.Parse).ToArray()
                 ).ToArray();


问:
Include a module with or without send, is there any difference?
```<code>SomeClass.include(SomeModule)
</code>```

vs.

```<code>SomeClass.send :include, SomeModule
</code>```

Is there any differences between them? Why is the second way preferred? (At least I've found it more frequently in other people's code).

答:
They are almost identical.

The difference is that if SomeClass#include is private, the latter will still be able to call it due to the nature of Object#send

If SomeClass#include was private and you went with the former, it would raise an error.

So the advantage of using the latter is that you can include a module no matter what the visibility is. (Whether or not you actually believe accessing private methods is the "right" thing to do is another story. It certainly gives you tremendous power).

ContentLicense: CC BY-SA 3.0

Body:
SomeClass.include(SomeModule)

vs.

SomeClass.send :include, SomeModule

Is there any differences between them? Why is the second way preferred? (At least I've found it more frequently in other people's code).


问:
How do I remove the global flag from a regular expression?
Given a user (developer) provided regular expression, I need to remove the global flag if it exists, on Firefox 38 and above you can just set it:

```<code>the_regex.global = false;
</code>```

However that is not supported elsewhere.  So, I have created this pair of functions:

```<code>function deGlobal(regex) {
  if (!regex instanceof RegExp) return regex;
  if (!regex.global) return regex;
  var parts = regExpParts(regex);
  console.log(parts);
  if (parts) {
    return new RegExp(parts.pattern, parts.flags.replace("g", ""));
  } else {
    return false;
  }
}

function regExpParts(regex) {
  if (!regex instanceof RegExp) return false;
  var regex_string = regex.toString();
  var flags = regex_string.substring(regex_string.lastIndexOf('/') + 1);
  var pattern = regex_string.substring(1, regex_string.lastIndexOf('/'));
  return {
    flags: flags,
    pattern: pattern
  };
}
</code>```

Which for all of my test cases is doing great, but it seems like a very error prone method.

Is there a case where these functions wouldn't work or there a better cross browser method of doing this?

FIDDLE: http://jsfiddle.net/trex005/324k2as5/.

答:
Why not use the RegExp constructor to remove/overwrite the flags?

For example, when you log x from the following code:

```<code>let x = /ab(c)/g;
x = new RegExp(x, "");
</code>```

You should get the following output:

```<code>/ab(c)/
</code>```

You could even overwrite the flags, like this:

```<code>let x = /ab(c)/g;
x = new RegExp(x, "mi");
</code>```

Which should output:

```<code>/ab(c)/mi
</code>```

Good luck.

Body:
Given a user (developer) provided regular expression, I need to remove the global flag if it exists, on Firefox 38 and above you can just set it:

the_regex.global = false;

However that is not supported elsewhere.  So, I have created this pair of functions:

function deGlobal(regex) {
  if (!regex instanceof RegExp) return regex;
  if (!regex.global) return regex;
  var parts = regExpParts(regex);
  console.log(parts);
  if (parts) {
    return new RegExp(parts.pattern, parts.flags.replace("g", ""));
  } else {
    return false;
  }
}

function regExpParts(regex) {
  if (!regex instanceof RegExp) return false;
  var regex_string = regex.toString();
  var flags = regex_string.substring(regex_string.lastIndexOf('/') + 1);
  var pattern = regex_string.substring(1, regex_string.lastIndexOf('/'));
  return {
    flags: flags,
    pattern: pattern
  };
}

Which for all of my test cases is doing great, but it seems like a very error prone method.

Is there a case where these functions wouldn't work or there a better cross browser method of doing this?

FIDDLE: http://jsfiddle.net/trex005/324k2as5/.

Body:
Why not use the RegExp constructor to remove/overwrite the flags?

For example, when you log x from the following code:

let x = /ab(c)/g;
x = new RegExp(x, "");

You should get the following output:

/ab(c)/

You could even overwrite the flags, like this:

let x = /ab(c)/g;
x = new RegExp(x, "mi");

Which should output:

/ab(c)/mi

Good luck.


问:
Error: undefined reference to `sqlite3_open'
I'm trying to get started with the C++ API for SQLite.

```<code>#include <iostream>
#include <sqlite3.h>

using namespace std;

int main()
{
    sqlite3 *db;
    if (sqlite3_open("ex1.db", &db) == SQLITE_OK)
        cout << "Opened db successfully\n";
    else
        cout << "Failed to open db\n";

    return 0;
}
</code>```

Compiling this using the command "g++ main.cpp" gives the following error:

```<code>/tmp/ccu8sv4b.o: In function `main':
main.cpp:(.text+0x64): undefined reference to `sqlite3_open'
collect2: ld returned 1 exit status
</code>```

What could have gone wrong? Hasn't sqlite3 properly installed in the server I'm compiling this in?

答: Either link your program to lib g++ yourProgram.c -lsqlite3 in command line or in Open IDE -> project -> properties -> locate lib file for sqlite3 .</p>

Body:
I'm trying to get started with the C++ API for SQLite.

#include <iostream>
#include <sqlite3.h>

using namespace std;

int main()
{
    sqlite3 *db;
    if (sqlite3_open("ex1.db", &db) == SQLITE_OK)
        cout << "Opened db successfully\n";
    else
        cout << "Failed to open db\n";

    return 0;
}

Compiling this using the command "g++ main.cpp" gives the following error:

/tmp/ccu8sv4b.o: In function `main':
main.cpp:(.text+0x64): undefined reference to `sqlite3_open'
collect2: ld returned 1 exit status

What could have gone wrong? Hasn't sqlite3 properly installed in the server I'm compiling this in?


问:
Shift text above inside the footer in materialize
I have a materialize footer whose height I have set to 35px. But the problem is text inside the footer disappears. How do I shift it up as it goes off the screen whenever I decrease the size of footer

```<code>  <footer style="position:fixed;bottom:0;left:0;width:100%;" class = "page-footer">

 <div class = "footer-copyright">

    <div class = "container">
       © 2016 Copyright Information
       <a class = "grey-text text-lighten-4 right" href = "#!">Designed & Developed by XYZ</a>
    </div>
 </div>
</code>```

Which gives me

Now when I applied CSS to reduce the size of footer and move the text inside the container up I am getting.

```<code>    footer {
       height: 35px;
    }
    footer .container {
       margin-bottom : 50px;
    }
</code>```

The text has been disppeared and when I tried moving that text container up its not working.

How can I solve this and where am I going wrong.

Note : I have tried all answers that I was getting as suggestion but none of them worked for me.

答:
```<code>footer .container {
  margin-bottom: 50px;
}
</code>```

This doesn't work because .container it's inside footer with a fixed height.

For avoid the text disappear you can try add a line-height to footer with the same value:

```<code>footer {
  height: 35px;
  line-height: 35px;
}
</code>```

And if you wanna include that some extra space at bottom you can add a padding:

```<code>footer {
  height: 35px;
  line-height: 35px;
  padding-bottom: 50px;
}
</code>```

;)

Body:
I have a materialize footer whose height I have set to 35px. But the problem is text inside the footer disappears. How do I shift it up as it goes off the screen whenever I decrease the size of footer

       © 2016 Copyright Information
       Designed & Developed by XYZ

Which gives me

Now when I applied CSS to reduce the size of footer and move the text inside the container up I am getting.

    footer {
       height: 35px;
    }
    footer .container {
       margin-bottom : 50px;
    }

The text has been disppeared and when I tried moving that text container up its not working.

How can I solve this and where am I going wrong.

Note : I have tried all answers that I was getting as suggestion but none of them worked for me.

Body:
footer .container {
  margin-bottom: 50px;
}

This doesn't work because .container it's inside footer with a fixed height.

For avoid the text disappear you can try add a line-height to footer with the same value:

footer {
  height: 35px;
  line-height: 35px;
}

And if you wanna include that some extra space at bottom you can add a padding:

footer {
  height: 35px;
  line-height: 35px;
  padding-bottom: 50px;
}

;)


问:
Entity Framework Code-first Many to many relationship on the same table
I have a slightly odd scenario here, I have one entity and one many to many table. The following tables are like so:

AssetHeader.cs

```<code>[Table("AssetHeader", Schema = "assets")]
public class AssetHeader
{
    public Guid Id { get; set; }

    public virtual ICollection<AssetHeaderEquipment> AssetHeaders { get; set; }

    public virtual ICollection<AssetHeaderEquipment> AssetEquipment { get; set; }
}
</code>```

AssetHeaderEquipment.cs (many-to-many)

```<code>[Table("AssetHeaderEquipment", Schema = "assets")]
public class AssetHeaderEquipment
{
    [Key, Column(Order = 0)]
    public Guid AssetHeaderId { get; set; }
    [Key, Column(Order = 1)]
    public Guid AssetEquipmentId { get; set; }

    public virtual AssetHeader AssetHeader { get; set; }
    public virtual AssetHeader AssetEquipment { get; set; }

    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    [MaxLength(255)]
    public string Comment { get; set; }
}
</code>```

When I attempt to create the db with code-first migration I get the following in SQL:

How do I get the code-first to generate the correct db structure, I am happy to use either attributes or fluent in dbcontext.

UPDATE:
After following the answer from Ivan Stoev the structure is as expected. However when setting the fields the following now happens...

Model attempting to save:

Actual save result:

How is the AssetEquipmentId being set to the AssetHeaderId?

I have created a very lightweight dojo project for complete code visibility.
You can find this here:
GitHub Code Repo

答:
This is one of the cases where EF can't automatically pair the relationships navigation properties.

Usually it can be resolved with either InverseProperty attributes or Has / With fluent API.  But since this type of relationship always introduces "multiple cascade paths" problem, which requires turning off cascade delete for at least one of the relationships, and that could be done only with fluent API, there is no other choice than using fluent API (which for relationships IMHO is better anyway).

The bare minimum is to configure the relationship for which you want to turn off the cascade delete. Once you do that, EF conventionally will do the rest.

For instance:

```<code>modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetEquipment)
    .WithRequired(e => e.AssetEquipment)
    .WillCascadeOnDelete(false);
</code>```

The result:

```<code>CreateTable(
    "assets.AssetHeaderEquipment",
    c => new
        {
            AssetHeaderId = c.Guid(nullable: false),
            AssetEquipmentId = c.Guid(nullable: false),
            StartDate = c.DateTime(nullable: false),
            EndDate = c.DateTime(),
            Comment = c.String(maxLength: 255),
        })
    .PrimaryKey(t => new { t.AssetHeaderId, t.AssetEquipmentId })
    .ForeignKey("assets.AssetHeader", t => t.AssetEquipmentId)
    .ForeignKey("assets.AssetHeader", t => t.AssetHeaderId, cascadeDelete: true)
    .Index(t => t.AssetHeaderId)
    .Index(t => t.AssetEquipmentId);

CreateTable(
    "assets.AssetHeader",
    c => new
        {
            Id = c.Guid(nullable: false),
        })
    .PrimaryKey(t => t.Id);
</code>```

Update According to the problematic usage case, the correct pairings should be:

```<code>Collection       Inverse          FK
==========       =========        ==============
AssetHeaders     AssetEquipment   AssetEquipmentId
AssetEquipment   AssetHeader      AssetHeaderId
</code>```

Hence remove the misleading ForeignKey attributes and use the following fully explicit fluent configuration:

```<code>modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetHeaders)
    .WithRequired(e => e.AssetEquipment)
    .HasForeignKey(e => e.AssetEquipmentId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetEquipment)
    .WithRequired(e => e.AssetHeader)
    .HasForeignKey(e => e.AssetHeaderId)
    .WillCascadeOnDelete(true);
</code>```

Body:
I have a slightly odd scenario here, I have one entity and one many to many table. The following tables are like so:

AssetHeader.cs

[Table("AssetHeader", Schema = "assets")]
public class AssetHeader
{
    public Guid Id { get; set; }

    public virtual ICollection<AssetHeaderEquipment> AssetHeaders { get; set; }

    public virtual ICollection<AssetHeaderEquipment> AssetEquipment { get; set; }
}

AssetHeaderEquipment.cs (many-to-many)

[Table("AssetHeaderEquipment", Schema = "assets")]
public class AssetHeaderEquipment
{
    [Key, Column(Order = 0)]
    public Guid AssetHeaderId { get; set; }
    [Key, Column(Order = 1)]
    public Guid AssetEquipmentId { get; set; }

    public virtual AssetHeader AssetHeader { get; set; }
    public virtual AssetHeader AssetEquipment { get; set; }

    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    [MaxLength(255)]
    public string Comment { get; set; }
}

When I attempt to create the db with code-first migration I get the following in SQL:

How do I get the code-first to generate the correct db structure, I am happy to use either attributes or fluent in dbcontext.

UPDATE:
After following the answer from Ivan Stoev the structure is as expected. However when setting the fields the following now happens...

Model attempting to save:

Actual save result:

How is the AssetEquipmentId being set to the AssetHeaderId?

I have created a very lightweight dojo project for complete code visibility.
You can find this here:
GitHub Code Repo

Body:
This is one of the cases where EF can't automatically pair the relationships navigation properties.

Usually it can be resolved with either InverseProperty attributes or Has / With fluent API.  But since this type of relationship always introduces "multiple cascade paths" problem, which requires turning off cascade delete for at least one of the relationships, and that could be done only with fluent API, there is no other choice than using fluent API (which for relationships IMHO is better anyway).

The bare minimum is to configure the relationship for which you want to turn off the cascade delete. Once you do that, EF conventionally will do the rest.

For instance:

modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetEquipment)
    .WithRequired(e => e.AssetEquipment)
    .WillCascadeOnDelete(false);

The result:

CreateTable(
    "assets.AssetHeaderEquipment",
    c => new
        {
            AssetHeaderId = c.Guid(nullable: false),
            AssetEquipmentId = c.Guid(nullable: false),
            StartDate = c.DateTime(nullable: false),
            EndDate = c.DateTime(),
            Comment = c.String(maxLength: 255),
        })
    .PrimaryKey(t => new { t.AssetHeaderId, t.AssetEquipmentId })
    .ForeignKey("assets.AssetHeader", t => t.AssetEquipmentId)
    .ForeignKey("assets.AssetHeader", t => t.AssetHeaderId, cascadeDelete: true)
    .Index(t => t.AssetHeaderId)
    .Index(t => t.AssetEquipmentId);

CreateTable(
    "assets.AssetHeader",
    c => new
        {
            Id = c.Guid(nullable: false),
        })
    .PrimaryKey(t => t.Id);

Update According to the problematic usage case, the correct pairings should be:

Collection       Inverse          FK
==========       =========        ==============
AssetHeaders     AssetEquipment   AssetEquipmentId
AssetEquipment   AssetHeader      AssetHeaderId

Hence remove the misleading ForeignKey attributes and use the following fully explicit fluent configuration:

modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetHeaders)
    .WithRequired(e => e.AssetEquipment)
    .HasForeignKey(e => e.AssetEquipmentId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<AssetHeader>()
    .HasMany(e => e.AssetEquipment)
    .WithRequired(e => e.AssetHeader)
    .HasForeignKey(e => e.AssetHeaderId)
    .WillCascadeOnDelete(true);


问:
pselect() not recognizing the socket having any IO activity
take for instance the following code snippet, the creation of the socket, listening and acceptance of a new socket works fine.  The non-blocking mode is also working, however the pselect (or even replacing with select) is not recognizing any IO requests ready on the FDset.  so the return value is always 0 (timed out).

I was wondering if I need to set anything else further before going into pselect() so that it recognizes the IO activity.

```<code>.....
 // Create the socket
        *m_pSockFD = socket(AF_INET, SOCK_STREAM, 0);
        if( *this->m_pSockFD == -1 ){
            throw ....
        }

        // Set the socket address information
        m_pSockAddr->sin_family = AF_INET;
        m_pSockAddr->sin_port =  htons( 6001 );
        m_pSockAddr->sin_addr.s_addr = INADDR_ANY;

        if( bind(*m_pSockFD, (struct sockaddr *) m_pSockAddr, sizeof(*m_pSockAddr) ) != 0 ){
                .....
        }

        // Listen on this socket using a block queue of 5 - default Block Size
        if( listen( *m_pSockFD, 5) != 0 )
                ........

        // change function control to non blocking file descritor for I/O operations
        long fcntlArg;
        if( (fcntlArg = fcntl( *m_pSockFD, F_GETFL, NULL ) ) < 0 ){
               ...........
        }

        fcntlArg |= O_NONBLOCK;
        if( fcntl( *m_pSockFD, F_SETFL, fcntlArg ) <0 ){
              ...........
        }

        //.........

        int newFD = -1;
        socklen_t salen = sizeof(*m_pSockAddr);

        // loop selecting for a I/O operation ready on the file descriptor then go into accept mode
        struct timespec timeOut;
        timeOut.tv_sec = 1;
        timeOut.tv_nsec = 0;

        fd_set fdset;
        FD_SET( *this->m_pSockFD, &fdset );

        while( !m_bShutDownFinished ){

            // TODO pselect is not registering the activity on the socket
            if( pselect( *this->m_pSockFD, &fdset, NULL , NULL , &timeOut,  NULL ) > 0 ){
                cout << "hello client" << endl;
                break;
            }

            // re-initialize the time struct
            timeOut.tv_sec = 1;
            timeOut.tv_nsec = 0;
        }

        // application is shutting down do not try to accept a new socket
        if( m_bShutDownFinished ) return -1;

        newFD = accept(*m_pSockFD, (struct sockaddr *) m_pSockAddr, &salen);
        if( newFD > -1 ){
            ................
        }

        return newFD;
</code>```

答:
You have to re-initialize the fdset parameters before each call to select().

Each of readfds, writefds, and exceptfds is an input/output parameters.  On return, they have been modified to have ones only for the fds that, respectively, are readable, writeable, or have an exceptional condition of some sort.

```<code>for (;;) {
    fd_set rfds;
    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    /* code to set up timeout omitted */
    n = select(sock + 1, &rfds, 0, 0, &timeout);
    /* check n, and if sock is present in rfds */
}
</code>```

The way you've written the code, you'll only detect an incoming connection if it arrives during the very first call to pselect().  Also, given that you're not using the sigmask argument of pselect(), you might as well just call select().

ContentLicense: CC BY-SA 2.5

Body:
take for instance the following code snippet, the creation of the socket, listening and acceptance of a new socket works fine.  The non-blocking mode is also working, however the pselect (or even replacing with select) is not recognizing any IO requests ready on the FDset.  so the return value is always 0 (timed out).

I was wondering if I need to set anything else further before going into pselect() so that it recognizes the IO activity.

.....
 // Create the socket
        *m_pSockFD = socket(AF_INET, SOCK_STREAM, 0);
        if( *this->m_pSockFD == -1 ){
            throw ....
        }

        // Set the socket address information
        m_pSockAddr->sin_family = AF_INET;
        m_pSockAddr->sin_port =  htons( 6001 );
        m_pSockAddr->sin_addr.s_addr = INADDR_ANY;

        if( bind(*m_pSockFD, (struct sockaddr *) m_pSockAddr, sizeof(*m_pSockAddr) ) != 0 ){
                .....
        }

        // Listen on this socket using a block queue of 5 - default Block Size
        if( listen( *m_pSockFD, 5) != 0 )
                ........

        // change function control to non blocking file descritor for I/O operations
        long fcntlArg;
        if( (fcntlArg = fcntl( *m_pSockFD, F_GETFL, NULL ) ) < 0 ){
               ...........
        }

        fcntlArg |= O_NONBLOCK;
        if( fcntl( *m_pSockFD, F_SETFL, fcntlArg ) <0 ){
              ...........
        }

        //.........

        int newFD = -1;
        socklen_t salen = sizeof(*m_pSockAddr);

        // loop selecting for a I/O operation ready on the file descriptor then go into accept mode
        struct timespec timeOut;
        timeOut.tv_sec = 1;
        timeOut.tv_nsec = 0;

        fd_set fdset;
        FD_SET( *this->m_pSockFD, &fdset );

        while( !m_bShutDownFinished ){

            // TODO pselect is not registering the activity on the socket
            if( pselect( *this->m_pSockFD, &fdset, NULL , NULL , &timeOut,  NULL ) > 0 ){
                cout << "hello client" << endl;
                break;
            }

            // re-initialize the time struct
            timeOut.tv_sec = 1;
            timeOut.tv_nsec = 0;
        }

        // application is shutting down do not try to accept a new socket
        if( m_bShutDownFinished ) return -1;

        newFD = accept(*m_pSockFD, (struct sockaddr *) m_pSockAddr, &salen);
        if( newFD > -1 ){
            ................
        }

        return newFD;

Body:
You have to re-initialize the fdset parameters before each call to select().

Each of readfds, writefds, and exceptfds is an input/output parameters.  On return, they have been modified to have ones only for the fds that, respectively, are readable, writeable, or have an exceptional condition of some sort.

for (;;) {
    fd_set rfds;
    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    /* code to set up timeout omitted */
    n = select(sock + 1, &rfds, 0, 0, &timeout);
    /* check n, and if sock is present in rfds */
}

The way you've written the code, you'll only detect an incoming connection if it arrives during the very first call to pselect().  Also, given that you're not using the sigmask argument of pselect(), you might as well just call select().

OwnerDisplayName: Dale Hagglund


问:
OData Creating a Service Operation to return a value to an IPad
All i want to do is create a simple Service Operation in my .net OData solution that returns an integer value. Than on the IPad I will suck this integer value up using the OData Obj-c SDK. Here is my service op so far:

```<code><WebGet()> _
Public Function GetWorkOrderNumber() As Integer
    Return DomainModel.SystemOption.GetWorkOrderNo
End Function
</code>```

This returns the following when you hit it from the browser:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<GetWorkOrderNumber p1:type="Edm.Int32" xmlns:p1="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">112</GetWorkOrderNumber>
</code>```

When I try to call this operation from the IPad i get the entire response value. All I want is the value 112. Does anyone know what I'm doing wrong or need to change?

Thanks in advance

答: You can append $Response content to the URL.  But yeah, I thought the proxy classes would give a better way.  I'm still looking.

Body:
All i want to do is create a simple Service Operation in my .net OData solution that returns an integer value. Than on the IPad I will suck this integer value up using the OData Obj-c SDK. Here is my service op so far:

<WebGet()> _
Public Function GetWorkOrderNumber() As Integer
    Return DomainModel.SystemOption.GetWorkOrderNo
End Function

This returns the following when you hit it from the browser:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<GetWorkOrderNumber p1:type="Edm.Int32" xmlns:p1="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">112</GetWorkOrderNumber>

When I try to call this operation from the IPad i get the entire response value. All I want is the value 112. Does anyone know what I'm doing wrong or need to change?

Thanks in advance


问:
How to deal with two cases
I'm trying to get the image url from the meta using a regex like this one:

```<code>(?s)<meta property="og:image" content="(.*?)" \/>
</code>```

It works fine when the URL has the following:

```<code><meta property="og:image" content="https://the_image.jpg" />
</code>```

but sometimes this property is in the form:

```<code><meta property="og:image" content="https://the_image.jpg">
</code>```

so, the result is a disaster.

I'm a little confused about what should I do for adapt the regex for both cases.

Any help?

答:
You could make the last part an optional non capturing group:

```<code>(?s)<meta property="og:image" content="(.*?)"(?: \/)?>
                                             ^^^^^^^^
</code>```

See a regex demo

Perhaps you might also update (.*?) to use a negated character class ([^"]*)

Title: How to deal with two cases

Body:
I'm trying to get the image url from the meta using a regex like this one:

(?s)<meta property="og:image" content="(.*?)" \/>

It works fine when the URL has the following:

<meta property="og:image" content="https://the_image.jpg" />

but sometimes this property is in the form:

<meta property="og:image" content="https://the_image.jpg">

so, the result is a disaster.

I'm a little confused about what should I do for adapt the regex for both cases.

Any help?

Body:
You could make the last part an optional non capturing group:

(?s)<meta property="og:image" content="(.*?)"(?: \/)?>
                                             ^^^^^^^^

See a regex demo

Perhaps you might also update (.*?) to use a negated character class ([^"]*)


问:
When ID = certain value sum two values according to ID
The File# can appear multiple times. When file # =52,56,67 sum Reg Hours and O/T Hours. Also clear O/T Hours for 52,56,67.

Data:

I have tried to calculate by cell location then I realized the location is not fixed each time when I export a new report.

```<code>Sub Calculation()
  If range ("C2:C14")=52,56,67 THEN
    Range("G48").Formula = "=Sum(h48:i48)"
    Range("I48").Clear
    Range("G68").Formula = "=Sum(h68:i68)"
    Range("i68").Clear
    Range("G8").Formula = "=Sum(h8:i8)"
    Range("I8").Clear
  End If
End sub
</code>```

My actual result clears the O/T hour before calculating. And it doesn't relate to the File #

答:
Welcome to SO. If statement does not work quite like that...

If range ("C2:C14")=52,56,67 THEN

should be If Range("C2:C14") = 52 or Range("C2:C14") = 56 or Range("C2:C14") = 67 Then...

But for good practice, you should always qualify your ranges.. see below one way of doing what you are trying to achieve, and additional comments:

Sub Calculation()
    Dim ws As Worksheet: Set ws = ActiveWorkbook.ActiveSheet 'declare and allocate your worksheet, even better use .Sheets("sheet name")
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row 'get the last row in column C
    Dim R As Long

    For R = 2 To lRow 'iterate through all rows
        With ws
            Select Case .Cells(R, "C").Value
                Case 52, 56, 67
                    .Cells(R, "G") = .Cells(R, "H") + .Cells(R, "I") 'sum the values and allocate
                    .Cells(R, "I").Clear 'clear the value
            End Select
        End With
    Next R

End Sub
```

Body:
The File# can appear multiple times. When file # =52,56,67 sum Reg Hours and O/T Hours. Also clear O/T Hours for 52,56,67.

Data:

I have tried to calculate by cell location then I realized the location is not fixed each time when I export a new report.

Sub Calculation()
  If range ("C2:C14")=52,56,67 THEN
    Range("G48").Formula = "=Sum(h48:i48)"
    Range("I48").Clear
    Range("G68").Formula = "=Sum(h68:i68)"
    Range("i68").Clear
    Range("G8").Formula = "=Sum(h8:i8)"
    Range("I8").Clear
  End If
End sub

My actual result clears the O/T hour before calculating. And it doesn't relate to the File #


问:
How to disable registration new user in Laravel 5.6
I use laravel 5.6

I want to disable registration for new users, of course the login form must work

I see below question :

```<code>https://stackoverflow.com/questions/29183348/how-to-disable-registration-new-user-in-laravel-5
</code>```

But I did not find the showRegistrationForm() function on the following path:

Auth/RegisterController.php

答:
You may use middleware auth in RegisterController :

```<code>$this->middleware('auth');
</code>```

instead of :

```<code>$this->middleware('guest');
</code>```

Body:
I use laravel 5.6

I want to disable registration for new users, of course the login form must work

I see below question :

https://stackoverflow.com/questions/29183348/how-to-disable-registration-new-user-in-laravel-5

But I did not find the showRegistrationForm() function on the following path:

Auth/RegisterController.php

Body:
You may use middleware auth in RegisterController :

$this->middleware('auth');

instead of :

$this->middleware('guest');


问:
Angularfire and FirebaseListObservable has no exported member angularfire2 using ionic 2 app
FirebaseListObservable and Angularfire has no exported member "angularfire2" when i am creating Ionic 2 app import both files in home.ts

My Cordova and ionic version is
Cordova version 6.5.0
Ionic Version 2.2.3
Node version 6.10.2
typings version 2.1.1
typescript version 2.3.2

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, af:AngularFire ) {
}
}
</code>```

答:
FirebaseListObservable has been changed into AngularFireList.

simply use this to import

```<code>import { AngularFireList } from 'angularfire2/database';
</code>```

Check migration doc here

Body:
FirebaseListObservable and Angularfire has no exported member "angularfire2" when i am creating Ionic 2 app import both files in home.ts

My Cordova and ionic version is
Cordova version 6.5.0
Ionic Version 2.2.3
Node version 6.10.2
typings version 2.1.1
typescript version 2.3.2

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, af:AngularFire ) {
}
}

Body:
FirebaseListObservable has been changed into AngularFireList.

simply use this to import

import { AngularFireList } from 'angularfire2/database';

Check migration doc here


问:
IIS fails to run ASP.NET Core site - HTTP Error 502.5
We have a Windows 2012 R2 machine.
I had an existing ASP.NET Core site on it that had a working published ASP.NET Core site running.

However when I published to the site again today a month later after I made changes, I can't access the site anymore and get the following error in my browser

HTTP Error 502.5 - Process Failure

For more information visit: http://go.microsoft.com/fwlink/?LinkID=808681

If I log onto the server and click on the exe in my deployed directory it opens a command prompt and shows my site on port 5000. If I access the site on http://localhost:5000 it works perfectly so the problem is to do with IIS and not the site itself.

If I log onto the server I can see the following in Windows EventViewer

Application 'MACHINE/WEBROOT/APPHOST/DEFAULT WEB SITE/MySite' with physical root 'D:\Sites\MySite\' failed to start process with commandline '"%LAUNCHER_PATH%" %LAUNCHER_ARGS%', ErrorCode = '0x80070002 : 0.

When I visit the link in the browser error message it mentioned reinstalling the .net Core Hosting bundle which I did. However the error message in the browser is the same.

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore requestTimeout="02:00:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
  </system.webServer>
</configuration>
</code>```

When I look at my app log folder a stdout file does get created for every time it tries to access this site but each time it is of size 0KB and empty contents.

Why does IIS refuse to work suddenly where it worked previous but the app works if I access the compiled exe directly?

答: This completely drove me mad given I've tried all possible fixes found online but nothing worked for me. Until I found out the issue was that I had a space in my project name: App WebAPI.dll. So when "dotnet .\App WebAPI.dll" tries to execute it fails because it's really trying to execute "dotnet .\App" and forgetting the second part after the space. Renaming my solution and project names to remove spaces (AppWebAPI) fixed my issue. I hope this fix saves people time trying to figure out the issue. </p>

Body:
We have a Windows 2012 R2 machine.
I had an existing ASP.NET Core site on it that had a working published ASP.NET Core site running.

However when I published to the site again today a month later after I made changes, I can't access the site anymore and get the following error in my browser

HTTP Error 502.5 - Process Failure

For more information visit: http://go.microsoft.com/fwlink/?LinkID=808681

If I log onto the server and click on the exe in my deployed directory it opens a command prompt and shows my site on port 5000. If I access the site on http://localhost:5000 it works perfectly so the problem is to do with IIS and not the site itself.

If I log onto the server I can see the following in Windows EventViewer

Application 'MACHINE/WEBROOT/APPHOST/DEFAULT WEB SITE/MySite' with physical root 'D:\Sites\MySite\' failed to start process with commandline '"%LAUNCHER_PATH%" %LAUNCHER_ARGS%', ErrorCode = '0x80070002 : 0.

When I visit the link in the browser error message it mentioned reinstalling the .net Core Hosting bundle which I did. However the error message in the browser is the same.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore requestTimeout="02:00:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
  </system.webServer>
</configuration>

When I look at my app log folder a stdout file does get created for every time it tries to access this site but each time it is of size 0KB and empty contents.

Why does IIS refuse to work suddenly where it worked previous but the app works if I access the compiled exe directly?


问:
Is it a standard that the width or height of a "display:none" element is zero?
The offsetWidth or offsetHeight of a "display:none" element is 0 on Chrome.

What I want to know is this is standard behavior defined by W3C, or just a dialect of browsers? Or it is a de facto supported by all modern browsers?

I searched out the web and found almost no text addressing my question.

答:
Yes this is standard behaviour.

If display is none, then no layout box is created:

Please note that a display of 'none' does not create an invisible box; it creates no box at all. CSS includes mechanisms that enable an element to generate boxes in the formatting structure that affect formatting but are not visible themselves. Please consult the section on visibility for details.

https://drafts.csswg.org/css2/visuren.html#display-prop

And if there is no box, then it returns zero:

The offsetWidth attribute must return the result of running these steps:

If the element does not have any associated CSS layout box return zero and terminate this algorithm.

Return the border edge width of the first CSS layout box associated with the element, ignoring any transforms that apply to the element and its ancestors.

https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth


问:
how to just print the statement without any loop condition in java?
I just want to print the "hello" 5 times without using for loop,while loop ?</p>

答:
```<code>System.out.println("hello hello hello hello hello");
</code>```


问:
How to login into Yahoo Mail using Selenium
I am recently working through examples in Automate the Boring Stuff in Python, and came across this example which I have some issues with. In this exercise, I tried to log in to Yahoo Mail using Selenium on the Chrome browser. The code does not produce any error and successfully prints the last line, however, it fails to click on the submit button which leaves me stuck at the login page despite successfully filling up the password. However, if I click on the login button manually, I can login successfully.

I have tried both passwordelem.submit() and passwordsubmitbtn.click() but neither works. I have also tried changing the user-agent in chrome but to no avail.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

browser = webdriver.Chrome()
browser.get('https://login.yahoo.com?.src=ym&.lang=en-US&.intl=us&.done=https%3A%2F%2Fmail.yahoo.com%2Fd')
wait = WebDriverWait(browser, 10)

emailelem = wait.until(EC.presence_of_element_located((By.ID,'login-username')))
emailelem.send_keys('xxxxxx@yahoo.com')

wait.until(EC.presence_of_element_located((By.ID,'login-signin')))
emailelem.submit()

passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxx')
##passwordelem.submit()

passwordsubmitbtn = wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordsubmitbtn.click()

print ('Done')
</code>```

答:
Try this:

Add top of the script

```<code>from selenium.webdriver.common.keys import Keys
</code>```

Replace your code

```<code>passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxx')
##passwordelem.submit()

passwordsubmitbtn = wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordsubmitbtn.click()
</code>```

To:

```<code>wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxxx')
passwordelem.send_keys(Keys.RETURN)
</code>```

More details

Body:
I am recently working through examples in Automate the Boring Stuff in Python, and came across this example which I have some issues with. In this exercise, I tried to log in to Yahoo Mail using Selenium on the Chrome browser. The code does not produce any error and successfully prints the last line, however, it fails to click on the submit button which leaves me stuck at the login page despite successfully filling up the password. However, if I click on the login button manually, I can login successfully.

I have tried both passwordelem.submit() and passwordsubmitbtn.click() but neither works. I have also tried changing the user-agent in chrome but to no avail.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

browser = webdriver.Chrome()
browser.get('https://login.yahoo.com?.src=ym&.lang=en-US&.intl=us&.done=https%3A%2F%2Fmail.yahoo.com%2Fd')
wait = WebDriverWait(browser, 10)

emailelem = wait.until(EC.presence_of_element_located((By.ID,'login-username')))
emailelem.send_keys('xxxxxx@yahoo.com')

wait.until(EC.presence_of_element_located((By.ID,'login-signin')))
emailelem.submit()

passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxx')
##passwordelem.submit()

passwordsubmitbtn = wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordsubmitbtn.click()

print ('Done')

Body:
Try this:

Add top of the script

from selenium.webdriver.common.keys import Keys

Replace your code

passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxx')
##passwordelem.submit()

passwordsubmitbtn = wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordsubmitbtn.click()

To:

wait.until(EC.element_to_be_clickable((By.ID,'login-signin')))
passwordelem = wait.until(EC.presence_of_element_located((By.ID,'login-passwd')))
passwordelem.send_keys('xxxxxxx')
passwordelem.send_keys(Keys.RETURN)

More details


问:
Convert latitude, longitude & altitude to local ENU coordinates in Python
How can I convert geodetic (latitude, longitude, altitude) coordinates into local tangent plane ENU (East, North, Up) coordinates with Python?

pyproj package does not seem to have the right functionality ...

答:
Pymap3d module, https://scivision.github.io/pymap3d/  provides coordinate transforms and geodesy functions including ENU <--> (long, lat, alt).

Here are some examples.

```<code>import pymap3d
# create an ellipsoid object
ell_clrk66 = pymap3d.Ellipsoid('clrk66')
# print ellipsoid's properties
ell_clrk66.a, ell_clrk66.b, ell_clrk66.f

# output
(6378206.4, 6356583.8, 0.0033900753039287634)
</code>```

Suppose we have an ENU coordinate system defined with its origin at (lat0, lon0, h0 = 5.0, 48.0, 10.0). And let a point (point_1) with coordinate ENU: (0,0,0) be a test point, this point_1 will be used to do transformation, both direct and inverse.

```<code>lat0, lon0, h0 = 5.0, 48.0, 10.0   # origin of ENU, (h is height above ellipsoid)
e1, n1, u1     =  0.0,  0.0,  0.0  # ENU coordinates of test point, `point_1`
# From ENU to geodetic computation
lat1, lon1, h1 = pymap3d.enu2geodetic(e1, n1, u1, \
                                      lat0, lon0, h0, \
                                      ell=ell_clrk66, deg=True)  # use clark66 ellisoid
print(lat1, lon1, h1)
# display: (5.000000000000001, 48.0, 10.000000000097717)
</code>```

Now, using the obtained (lat1, lon1, h1), we compute geodetic to ENU conversion.

```<code>e2, n2, u2 = pymap3d.geodetic2enu(lat1, lon1, h1, \
                           lat0, lon0, h0, \
                           ell=ell_clrk66, deg=True)
print(e2, n2, u2)
</code>```

The output should agree with (e1, n1, u1).  Small discrepancies is normal for this kind of computation.

In the above computation, the option ell has WGS84 ellipsoid as the default value.

Body:
Pymap3d module, https://scivision.github.io/pymap3d/  provides coordinate transforms and geodesy functions including ENU <--> (long, lat, alt).

Here are some examples.

import pymap3d
# create an ellipsoid object
ell_clrk66 = pymap3d.Ellipsoid('clrk66')
# print ellipsoid's properties
ell_clrk66.a, ell_clrk66.b, ell_clrk66.f

# output
(6378206.4, 6356583.8, 0.0033900753039287634)

Suppose we have an ENU coordinate system defined with its origin at (lat0, lon0, h0 = 5.0, 48.0, 10.0). And let a point (point_1) with coordinate ENU: (0,0,0) be a test point, this point_1 will be used to do transformation, both direct and inverse.

lat0, lon0, h0 = 5.0, 48.0, 10.0   # origin of ENU, (h is height above ellipsoid)
e1, n1, u1     =  0.0,  0.0,  0.0  # ENU coordinates of test point, `point_1`
# From ENU to geodetic computation
lat1, lon1, h1 = pymap3d.enu2geodetic(e1, n1, u1, \
                                      lat0, lon0, h0, \
                                      ell=ell_clrk66, deg=True)  # use clark66 ellisoid
print(lat1, lon1, h1)
# display: (5.000000000000001, 48.0, 10.000000000097717)

Now, using the obtained (lat1, lon1, h1), we compute geodetic to ENU conversion.

e2, n2, u2 = pymap3d.geodetic2enu(lat1, lon1, h1, \
                           lat0, lon0, h0, \
                           ell=ell_clrk66, deg=True)
print(e2, n2, u2)

The output should agree with (e1, n1, u1).  Small discrepancies is normal for this kind of computation.

In the above computation, the option ell has WGS84 ellipsoid as the default value.


问:
Delete parent div if child with class is present, without deleting other instances
I need to remove a div from the DOM if it has a child div with a specific class name, without removing the child div.

I tried using .remove() within an if/then statement, but when I do that it still removes all the instances of the targeted parent div, even those without the child.

The parent and child-type-B classes are automatically generated.

```<code><div class="overall">
   <div class="parent">
      <div class="child-type-A">
         // stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff
      </div>
   </div>
</div>
</code>```

I want to remove the entire parent div if the child has class child-type-A, so it looks like this:

```<code><div class="overall">
   <div class="child-type-A">
      // stuff that can't be deleted
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff that can't be deleted
      </div>
   </div>
</div>
</code>```

This is the jQuery I thought would work, but it does not (it removes all parents and children if child-type-A is present).

```<code>if( '.parent > .child-type-A' ) {
 $( 'parent' ).remove();
}
</code>```

I would expect that the div targeted by the 'if' would be the only affected div, is there a way to do this?

答:
You need to do like this:-

```<code>$(document).ready(function(){
  $( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
  //you can do this one also
   //$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});
</code>```

Working snippet:-

$(document).ready(function(){
  $( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
  //you can do this one also
   //$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
   <div class="parent">
      <div class="child-type-A">
         // stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff
      </div>
   </div>
</div></code>```

In case more than one child-type-A div present inside overall div:-

$(document).ready(function(){
  $('.parent').each(function(){
    if($(this).children('div').hasClass('child-type-A')){
      $(this).replaceWith($(this).contents());
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
   <div class="parent">
      <div class="child-type-A">
         // stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-A">
         // some other stuff
      </div>
   </div>
</div></code>```

Body:
I need to remove a div from the DOM if it has a child div with a specific class name, without removing the child div.

I tried using .remove() within an if/then statement, but when I do that it still removes all the instances of the targeted parent div, even those without the child.

The parent and child-type-B classes are automatically generated.

         // stuff that can't be deleted

         // more stuff

         // even more stuff

I want to remove the entire parent div if the child has class child-type-A, so it looks like this:

      // stuff that can't be deleted

         // more stuff that can't be deleted

         // even more stuff that can't be deleted

This is the jQuery I thought would work, but it does not (it removes all parents and children if child-type-A is present).

if( '.parent > .child-type-A' ) {
 $( 'parent' ).remove();
}

I would expect that the div targeted by the 'if' would be the only affected div, is there a way to do this?

Body:
You need to do like this:-

$(document).ready(function(){
  $( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
  //you can do this one also
   //$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});

Working snippet:-

$(document).ready(function(){
  $( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
  //you can do this one also
   //$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
   <div class="parent">
      <div class="child-type-A">
         // stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff
      </div>
   </div>
</div>

In case more than one child-type-A div present inside overall div:-

$(document).ready(function(){
  $('.parent').each(function(){
    if($(this).children('div').hasClass('child-type-A')){
      $(this).replaceWith($(this).contents());
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
   <div class="parent">
      <div class="child-type-A">
         // stuff that can't be deleted
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-B">
         // even more stuff
      </div>
   </div>
   <div class="parent">
      <div class="child-type-A">
         // some other stuff
      </div>
   </div>
</div>


问:
Express a futumorphism specialized to lists as an imperative loop
I've been trying to translate this recursive Haskell implementation of a futumorphism specialized to Lists

futuL :: (a -> Maybe (b, ([b], Maybe a))) -> a -> [b]
futuL f x = case f x of
  Nothing -> []
  Just (y, (ys, mz)) -> y : (ys ++ fz)
    where fz = case mz of
      Nothing -> []
      Just z -> futuL f z
```

<p>into an imperative Javascript loop. It is remarkably difficult (at least for me):</p>

<pre class="lang-js prettyprint-override"><code>const None = ({type: "Option", tag: "None"});
const Some = x => ({type: "Option", tag: "Some", runOption: x});

const arrFutu = coalg => x => { // futuL f x
  const acc = []; // ~ fz

  while (true) {
    let optX = coalg(x); // f x

    switch (optX.tag) { // case
      case "None": return acc; // Nothing -> []

      case "Some": {
        let [y, [ys, optX_]] = optX.runOption; // Just (y, (ys, mz))

        switch(optX_.tag) {
          case "None": {
            arrPushFlat(acc) ((ys.unshift(y), ys)); // y : (ys ++ [])
            return acc;
          }

          case "Some": { // y : (ys ++ futuL f z)
            arrPushFlat(acc) ((ys.unshift(y), ys));
            x = optX_.runOption;
            break;
          }

          default: throw new UnionError("invalid tag");
        }

        break;
      }

      default: throw new UnionError("invalid tag");
    }
  }
};
</code>```

I have a difficult time to parse the Haskell code mentally, especially the where part containing the recursive call. I guess this call isn't in tail position, therefore I need an explicit stack (acc) for my JS loop.

Is my translation correct?

答:
Because Haskell is lazy, one can start consuming the beginning of the list returned by the "futu" before the rest has been calculated. In Javascript terms, this is best modeled with generators.

For example (for simplicity, I used null values to represent the Nones):

const arrFutu = coalg => function*(seed) {
    while (true) {
        const next = coalg(seed);
        if (next) {
            // Maybe (b, ([b], Maybe a)), using null for None & flattening nested tuple
            const [item, items, nextseed] = next;
            yield item;
            yield* items;
            // Maybe a, using null for None
            if (nextseed) {
                seed = nextseed;
                continue; // Continue iterating if the seed isn't null.
            }
        }
        return;
    }
}
```

<p>With an example coalgebra like:</p>

<pre class="lang-js prettyprint-override"><code>const coalg1 = seed => {
    if (seed < 5) {
        return ['a', ['a','a'], seed + 1];
    } else if (seed < 10) {
        return ['b', ['b','b'], seed + 1];
    } else if (seed == 10) {
        return ['c', ['c'], null];
    }
    return null;
}

for (const x of arrFutu(coalg1)(0)) {
    console.log(x);
}

for (const x of arrFutu(coalg1)(20)) {
    console.log(x);
}
</code>```

It would be nice to make the futu recursive instead of iterative, but it seems Javascript tail call optimization doesn't work with generators.

By the way, even if the Haskell code isn't tail recursive, the recursion is "guarded": the recursive call happens within one or more data constructors (here, list constructors) and the call can be delayed until the constructors have been "peeled away" by the client when he is consuming the returned list.

Body:
I've been trying to translate this recursive Haskell implementation of a futumorphism specialized to Lists

futuL :: (a -> Maybe (b, ([b], Maybe a))) -> a -> [b]
futuL f x = case f x of
  Nothing -> []
  Just (y, (ys, mz)) -> y : (ys ++ fz)
    where fz = case mz of
      Nothing -> []
      Just z -> futuL f z

into an imperative Javascript loop. It is remarkably difficult (at least for me):

const None = ({type: "Option", tag: "None"});
const Some = x => ({type: "Option", tag: "Some", runOption: x});

const arrFutu = coalg => x => { // futuL f x
  const acc = []; // ~ fz

  while (true) {
    let optX = coalg(x); // f x

    switch (optX.tag) { // case
      case "None": return acc; // Nothing -> []

      case "Some": {
        let [y, [ys, optX_]] = optX.runOption; // Just (y, (ys, mz))

        switch(optX_.tag) {
          case "None": {
            arrPushFlat(acc) ((ys.unshift(y), ys)); // y : (ys ++ [])
            return acc;
          }

          case "Some": { // y : (ys ++ futuL f z)
            arrPushFlat(acc) ((ys.unshift(y), ys));
            x = optX_.runOption;
            break;
          }

          default: throw new UnionError("invalid tag");
        }

        break;
      }

      default: throw new UnionError("invalid tag");
    }
  }
};

I have a difficult time to parse the Haskell code mentally, especially the where part containing the recursive call. I guess this call isn't in tail position, therefore I need an explicit stack (acc) for my JS loop.

Is my translation correct?

Body:
Because Haskell is lazy, one can start consuming the beginning of the list returned by the "futu" before the rest has been calculated. In Javascript terms, this is best modeled with generators.

For example (for simplicity, I used null values to represent the Nones):

const arrFutu = coalg => function*(seed) {
    while (true) {
        const next = coalg(seed);
        if (next) {
            // Maybe (b, ([b], Maybe a)), using null for None & flattening nested tuple
            const [item, items, nextseed] = next;
            yield item;
            yield* items;
            // Maybe a, using null for None
            if (nextseed) {
                seed = nextseed;
                continue; // Continue iterating if the seed isn't null.
            }
        }
        return;
    }
}

With an example coalgebra like:

const coalg1 = seed => {
    if (seed < 5) {
        return ['a', ['a','a'], seed + 1];
    } else if (seed < 10) {
        return ['b', ['b','b'], seed + 1];
    } else if (seed == 10) {
        return ['c', ['c'], null];
    }
    return null;
}

for (const x of arrFutu(coalg1)(0)) {
    console.log(x);
}

for (const x of arrFutu(coalg1)(20)) {
    console.log(x);
}

It would be nice to make the futu recursive instead of iterative, but it seems Javascript tail call optimization doesn't work with generators.

By the way, even if the Haskell code isn't tail recursive, the recursion is "guarded": the recursive call happens within one or more data constructors (here, list constructors) and the call can be delayed until the constructors have been "peeled away" by the client when he is consuming the returned list.


问:
Writing to a text file using ASP
Im totally new to ASP so any help would be very grateful. I have a html page which has a form for users to leave their details and when they submit it goes to a text file fine but what I want is once they have submitted it I want to have an alert saying "comment saved" and to stay on the original page so they can submit another if they choose but when the user submits it goes to a blank page.
My Form is

```<code><form method="post" action="comments.asp">
<br><br>
Age <input type="text" name="age" />
Name<textarea rows="1" cols="70" <input type="text" name="name" /></textarea>
<input type="submit" value="Send Comment">
</form>
</code>```

my comments.asp file code is

<%
Dim age, name
age = Request.Form("age")
name = Request.Form("name")
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("C:\Inetpub\wwwroot\Wiki\Comments.txt",8,true)
f.WriteLine(age & " " & date() & " " & name)
f.Close
set f=nothing
set fs=nothing
%>
```

答:
namespace A6
{
    public partial class imanik : System.Web.UI.Page
    {
        public class RedTabele {
            public string sifra { get; set; }
            public string ime { get; set; }
            public string prezime { get; set; }
            public string adresa { get; set; }
            public string mesto { get; set; }
            public string broj { get; set; }
            public string mail { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                // Lista za mesta
                List<string> mesta = new List<string>();

                using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        /* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail  */
                        string[] podeljeno = line.Split('|');

                        string mesto = podeljeno[4];

                        mesto = mesto.Trim();

                        mesta.Add(mesto);

                    }
                }

                List<string> bezDuplikata = mesta.Distinct().ToList();
                for (int i = 0; i < bezDuplikata.Count; i++)
                {
                    ListaMesto.Items.Add(bezDuplikata[i]);
                }
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // sakri i ocisti table
            Table1.Rows.Clear();
            Table1.Visible = false;

            // uzimanje podataka iz txtboxova
            string ime = txtIme.Text;
            string prezime = txtPrezime.Text;
            string adresa = txtAdresa.Text;
            string mesto = ListaMesto.Text;
            string br = txtTel.Text;

            // lista rezultata
            // Gore smo napravili klasu za ovo
            List<RedTabele> rezultati = new List<RedTabele>();

            using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    /* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail  */
                    string[] podeljeno = line.Split('|');

                    string sifraTXT = podeljeno[0];
                    string imeTXT = podeljeno[1];
                    string prezimeTXT = podeljeno[2];
                    string adresaTXT = podeljeno[3];
                    string mestoTXT = podeljeno[4];
                    string brTXT = podeljeno[5];
                    string mailTXT = podeljeno[6];

                    sifraTXT = sifraTXT.Trim();
                    imeTXT = imeTXT.Trim();
                    prezimeTXT = prezimeTXT.Trim();
                    adresaTXT = adresaTXT.Trim();
                    mestoTXT = mestoTXT.Trim();
                    brTXT = brTXT.Trim();
                    mailTXT = mailTXT.Trim();

                    bool ImeOk = true;
                    bool PrezimeOk = true;
                    bool AdresaOk = true;
                    bool MestoOk = true;
                    bool BrOk = true;

                    if (ime != "") {
                        ImeOk = imeTXT.StartsWith(ime);
                    }

                    if (prezime != "")
                    {
                        PrezimeOk = prezimeTXT.StartsWith(prezime);
                    }

                    if (adresa != "")
                    {
                        AdresaOk = adresaTXT.StartsWith(adresa);
                    }

                    if (br != "")
                    {
                        BrOk = brTXT.StartsWith(br);
                    }

                    if (mesto != mestoTXT)
                        MestoOk = false;

                    if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
                    {
                        rezultati.Add(new RedTabele {
                            sifra = sifraTXT,
                            ime = imeTXT,
                            prezime = prezimeTXT,
                            adresa = adresaTXT,
                            mesto = mestoTXT,
                            broj = brTXT,
                            mail = mailTXT
                        });
                    }

                }

                // Create Table
                TableRow naslovna = new TableRow();
                Table1.Rows.Add(naslovna);

                TableCell tdSifra = new TableCell();
                tdSifra.Text = "Sifra";

                TableCell tdIme = new TableCell();
                tdIme.Text = "Ime";

                TableCell tdPrezime = new TableCell();
                tdPrezime.Text = "Prezime";

                TableCell tdAdresa = new TableCell();
                tdAdresa.Text = "Adresa";

                TableCell tdMesto = new TableCell();
                tdMesto.Text = "Mesto";

                TableCell tdBroj = new TableCell();
                tdBroj.Text = "Broj";

                TableCell tdMail = new TableCell();
                tdMail.Text = "Mail";

                naslovna.Cells.Add(tdSifra);
                naslovna.Cells.Add(tdIme);
                naslovna.Cells.Add(tdPrezime);
                naslovna.Cells.Add(tdAdresa);
                naslovna.Cells.Add(tdMesto);
                naslovna.Cells.Add(tdBroj);
                naslovna.Cells.Add(tdMail);

                for (int i = 0; i < rezultati.Count; i++) {
                    TableRow red = new TableRow();

                    TableCell sifraKol = new TableCell();
                    TableCell imeKol = new TableCell();
                    TableCell prezimeKol = new TableCell();
                    TableCell adresaKol = new TableCell();
                    TableCell mestoKol = new TableCell();
                    TableCell brojKol = new TableCell();
                    TableCell mailKol = new TableCell();

                    sifraKol.Text = rezultati[i].sifra;
                    imeKol.Text = rezultati[i].ime;
                    prezimeKol.Text = rezultati[i].prezime;
                    adresaKol.Text = rezultati[i].adresa;
                    mestoKol.Text = rezultati[i].mesto;
                    brojKol.Text = rezultati[i].broj;
                    mailKol.Text = rezultati[i].mail;

                    red.Controls.Add(sifraKol);
                    red.Controls.Add(imeKol);
                    red.Controls.Add(prezimeKol);
                    red.Controls.Add(adresaKol);
                    red.Controls.Add(mestoKol);
                    red.Controls.Add(brojKol);
                    red.Controls.Add(mailKol);

                    Table1.Rows.Add(red);
                }

                Table1.Visible = true;

            }
        }
    }
}```
</div>
</div>
</p>

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// Za tekstualne fajlove
using System.IO;

namespace A6
{
    public partial class imanik : System.Web.UI.Page
    {
        public class RedTabele
        {
            public string sifra { get; set; }

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {

                List<string> mesta = new List<string>();

                using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {

                        string[] podeljeno = line.Split('|');

                        string mesto = podeljeno[4];

                        mesto = mesto.Trim();

                        mesta.Add(mesto);

                    }
                }

                List<string> bezDuplikata = mesta.Distinct().ToList();
                for (int i = 0; i < bezDuplikata.Count; i++)
                {
                    ListaMesto.Items.Add(bezDuplikata[i]);
                }
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            Table1.Rows.Clear();
            Table1.Visible = false;

            string ime = txtIme.Text;
            string prezime = txtPrezime.Text;
            string adresa = txtAdresa.Text;
            string mesto = ListaMesto.Text;
            string br = txtTel.Text;

            List<RedTabele> rezultati = new List<RedTabele>();

            using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {

                    string[] podeljeno = line.Split('|');

                    string sifraTXT = podeljeno[0];

                    sifraTXT = sifraTXT.Trim();

                    bool ImeOk = true;
                    bool PrezimeOk = true;
                    bool AdresaOk = true;
                    bool MestoOk = true;
                    bool BrOk = true;

                    if (ime != "")
                    {
                        ImeOk = imeTXT.StartsWith(ime);
                    }

                    if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
                    {
                        rezultati.Add(new RedTabele
                        {
                            sifra = sifraTXT,

                        });
                    }

                }

                // Create Table
                TableRow naslovna = new TableRow();
                Table1.Rows.Add(naslovna);

                TableCell tdSifra = new TableCell();
                tdSifra.Text = "Sifra";

                naslovna.Cells.Add(tdSifra);

                for (int i = 0; i < rezultati.Count; i++)
                {
                    TableRow red = new TableRow();

                    TableCell sifraKol = new TableCell();

                    sifraKol.Text = rezultati[i].sifra;

                    red.Controls.Add(sifraKol);

                    Table1.Rows.Add(red);
                }

                Table1.Visible = true;

            }
        }
    }
}
```

Title: Writing to a text file using ASP

Body:
Im totally new to ASP so any help would be very grateful. I have a html page which has a form for users to leave their details and when they submit it goes to a text file fine but what I want is once they have submitted it I want to have an alert saying "comment saved" and to stay on the original page so they can submit another if they choose but when the user submits it goes to a blank page.
My Form is

<form method="post" action="comments.asp">

Age <input type="text" name="age" />
Name<textarea rows="1" cols="70" <input type="text" name="name" /></textarea>
<input type="submit" value="Send Comment">
</form>

my comments.asp file code is

<%
Dim age, name
age = Request.Form("age")
name = Request.Form("name")
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("C:\Inetpub\wwwroot\Wiki\Comments.txt",8,true)
f.WriteLine(age & " " & date() & " " & name)
f.Close
set f=nothing
set fs=nothing
%>

Body:
namespace A6
{
    public partial class imanik : System.Web.UI.Page
    {
        public class RedTabele {
            public string sifra { get; set; }
            public string ime { get; set; }
            public string prezime { get; set; }
            public string adresa { get; set; }
            public string mesto { get; set; }
            public string broj { get; set; }
            public string mail { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                // Lista za mesta
                List<string> mesta = new List<string>();

                using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        /* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail  */
                        string[] podeljeno = line.Split('|');

                        string mesto = podeljeno[4];

                        mesto = mesto.Trim();

                        mesta.Add(mesto);

                    }
                }

                List<string> bezDuplikata = mesta.Distinct().ToList();
                for (int i = 0; i < bezDuplikata.Count; i++)
                {
                    ListaMesto.Items.Add(bezDuplikata[i]);
                }
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // sakri i ocisti table
            Table1.Rows.Clear();
            Table1.Visible = false;

            // uzimanje podataka iz txtboxova
            string ime = txtIme.Text;
            string prezime = txtPrezime.Text;
            string adresa = txtAdresa.Text;
            string mesto = ListaMesto.Text;
            string br = txtTel.Text;

            // lista rezultata
            // Gore smo napravili klasu za ovo
            List<RedTabele> rezultati = new List<RedTabele>();

            using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    /* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail  */
                    string[] podeljeno = line.Split('|');

                    string sifraTXT = podeljeno[0];
                    string imeTXT = podeljeno[1];
                    string prezimeTXT = podeljeno[2];
                    string adresaTXT = podeljeno[3];
                    string mestoTXT = podeljeno[4];
                    string brTXT = podeljeno[5];
                    string mailTXT = podeljeno[6];

                    sifraTXT = sifraTXT.Trim();
                    imeTXT = imeTXT.Trim();
                    prezimeTXT = prezimeTXT.Trim();
                    adresaTXT = adresaTXT.Trim();
                    mestoTXT = mestoTXT.Trim();
                    brTXT = brTXT.Trim();
                    mailTXT = mailTXT.Trim();

                    bool ImeOk = true;
                    bool PrezimeOk = true;
                    bool AdresaOk = true;
                    bool MestoOk = true;
                    bool BrOk = true;

                    if (ime != "") {
                        ImeOk = imeTXT.StartsWith(ime);
                    }

                    if (prezime != "")
                    {
                        PrezimeOk = prezimeTXT.StartsWith(prezime);
                    }

                    if (adresa != "")
                    {
                        AdresaOk = adresaTXT.StartsWith(adresa);
                    }

                    if (br != "")
                    {
                        BrOk = brTXT.StartsWith(br);
                    }

                    if (mesto != mestoTXT)
                        MestoOk = false;

                    if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
                    {
                        rezultati.Add(new RedTabele {
                            sifra = sifraTXT,
                            ime = imeTXT,
                            prezime = prezimeTXT,
                            adresa = adresaTXT,
                            mesto = mestoTXT,
                            broj = brTXT,
                            mail = mailTXT
                        });
                    }

                }

                // Create Table
                TableRow naslovna = new TableRow();
                Table1.Rows.Add(naslovna);

                TableCell tdSifra = new TableCell();
                tdSifra.Text = "Sifra";

                TableCell tdIme = new TableCell();
                tdIme.Text = "Ime";

                TableCell tdPrezime = new TableCell();
                tdPrezime.Text = "Prezime";

                TableCell tdAdresa = new TableCell();
                tdAdresa.Text = "Adresa";

                TableCell tdMesto = new TableCell();
                tdMesto.Text = "Mesto";

                TableCell tdBroj = new TableCell();
                tdBroj.Text = "Broj";

                TableCell tdMail = new TableCell();
                tdMail.Text = "Mail";

                naslovna.Cells.Add(tdSifra);
                naslovna.Cells.Add(tdIme);
                naslovna.Cells.Add(tdPrezime);
                naslovna.Cells.Add(tdAdresa);
                naslovna.Cells.Add(tdMesto);
                naslovna.Cells.Add(tdBroj);
                naslovna.Cells.Add(tdMail);

                for (int i = 0; i < rezultati.Count; i++) {
                    TableRow red = new TableRow();

                    TableCell sifraKol = new TableCell();
                    TableCell imeKol = new TableCell();
                    TableCell prezimeKol = new TableCell();
                    TableCell adresaKol = new TableCell();
                    TableCell mestoKol = new TableCell();
                    TableCell brojKol = new TableCell();
                    TableCell mailKol = new TableCell();

                    sifraKol.Text = rezultati[i].sifra;
                    imeKol.Text = rezultati[i].ime;
                    prezimeKol.Text = rezultati[i].prezime;
                    adresaKol.Text = rezultati[i].adresa;
                    mestoKol.Text = rezultati[i].mesto;
                    brojKol.Text = rezultati[i].broj;
                    mailKol.Text = rezultati[i].mail;

                    red.Controls.Add(sifraKol);
                    red.Controls.Add(imeKol);
                    red.Controls.Add(prezimeKol);
                    red.Controls.Add(adresaKol);
                    red.Controls.Add(mestoKol);
                    red.Controls.Add(brojKol);
                    red.Controls.Add(mailKol);

                    Table1.Rows.Add(red);
                }

                Table1.Visible = true;

            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// Za tekstualne fajlove
using System.IO;

namespace A6
{
    public partial class imanik : System.Web.UI.Page
    {
        public class RedTabele
        {
            public string sifra { get; set; }

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {

                List<string> mesta = new List<string>();

                using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {

                        string[] podeljeno = line.Split('|');

                        string mesto = podeljeno[4];

                        mesto = mesto.Trim();

                        mesta.Add(mesto);

                    }
                }

                List<string> bezDuplikata = mesta.Distinct().ToList();
                for (int i = 0; i < bezDuplikata.Count; i++)
                {
                    ListaMesto.Items.Add(bezDuplikata[i]);
                }
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            Table1.Rows.Clear();
            Table1.Visible = false;

            string ime = txtIme.Text;
            string prezime = txtPrezime.Text;
            string adresa = txtAdresa.Text;
            string mesto = ListaMesto.Text;
            string br = txtTel.Text;

            List<RedTabele> rezultati = new List<RedTabele>();

            using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {

                    string[] podeljeno = line.Split('|');

                    string sifraTXT = podeljeno[0];

                    sifraTXT = sifraTXT.Trim();

                    bool ImeOk = true;
                    bool PrezimeOk = true;
                    bool AdresaOk = true;
                    bool MestoOk = true;
                    bool BrOk = true;

                    if (ime != "")
                    {
                        ImeOk = imeTXT.StartsWith(ime);
                    }

                    if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
                    {
                        rezultati.Add(new RedTabele
                        {
                            sifra = sifraTXT,

                        });
                    }

                }

                // Create Table
                TableRow naslovna = new TableRow();
                Table1.Rows.Add(naslovna);

                TableCell tdSifra = new TableCell();
                tdSifra.Text = "Sifra";

                naslovna.Cells.Add(tdSifra);

                for (int i = 0; i < rezultati.Count; i++)
                {
                    TableRow red = new TableRow();

                    TableCell sifraKol = new TableCell();

                    sifraKol.Text = rezultati[i].sifra;

                    red.Controls.Add(sifraKol);

                    Table1.Rows.Add(red);
                }

                Table1.Visible = true;

            }
        }
    }
}