问:
plot(x,y) with strptime doesn't work with singular data point
I am trying to plot a scatterplot in shiny, using times of day on the y axis.
When plotting multiple points, the y axis looks great.

Here's the code:

```<code>     output$outputPlot <- renderPlot({
        coords <- subset(coords, location == input$cities)
        month <- coords$month
        time <- strptime(coords$format_time, format = "%l:%M:%S %p")
        plot(month, time)
      })
</code>```

But when there's only 1 data point in coords, the plot's time scale on the y-axis isn't in terms of time anymore, and the data point appears in the middle of the graph.

Thanks for your help!

答:
What you're seeing is that R doesn't know how to guess an appropriate range for a single point. Typically it expands the range of data by 4% of the range (look at ?par and look for 'xaxs'), but with a single point that means nothing.

So we need to tell it what ylim to use. (Similarly, your x-axis needs some guidance, too.)

Fake data:

set.seed(2)
coords <- data.frame(tm = Sys.time() + runif(20, -3e7, 3e7))
coords$month <- as.integer(format(coords$tm, format = "%m"))
coords$format_time <- format(coords$tm, format = "%l:%M:%S %p")
head(coords)
#                    tm month format_time
# 1 2018-10-24 20:15:17    10  8:15:17 PM
# 2 2019-10-19 05:07:04    10  5:07:04 AM
# 3 2019-07-21 14:19:22     7  2:19:22 PM
# 4 2018-10-13 03:44:57    10  3:44:57 AM
# 5 2020-04-03 21:32:22     4  9:32:22 PM
# 6 2020-04-03 15:27:59     4  3:27:59 PM
```

<p>The "normal" plot looks fine:</p>

<pre class="lang-r prettyprint-override"><code>month <- coords$month
time <- strptime(coords$format_time, format = "%l:%M:%S %p")
plot(month, time)
</code>```

but the single-point does not:

sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
plot(month, time)
```

<p><img src="https://i.stack.imgur.com/oTvbA.png" alt="single point, wrong y-axis"></p>

<p>So we fix it by specifying the <code>xlim</code> and <code>ylim</code> arguments. In this case, since I'm inferring it is meant to be a year of months (x) and a day of times (y), I can hard-code them, but in other situations you might want to just substract/add a small amount from the one datum you have:</p>

<pre class="lang-r prettyprint-override"><code>sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
xlim <- c(1, 12)
ylim <- strptime(c("12:00:00 AM", "11:59:59 PM"), format = "%l:%M:%S %p")
plot(month, time, xlim = xlim, ylim = as.numeric(ylim))
</code>```

You only need to specify ylim to answer this question, but without setting xlim= here, the previous x-axis spanned 6-14, not good for months. Also of note is that I had to coerce ylim to numeric for the plot, it did not work with ylim in its pure POSIXt form ... not sure exactly why that is the case, but this doesn't detract from the utility of the plot in general.

Body:
I am trying to plot a scatterplot in shiny, using times of day on the y axis.
When plotting multiple points, the y axis looks great.

Here's the code:

     output$outputPlot <- renderPlot({
        coords <- subset(coords, location == input$cities)
        month <- coords$month
        time <- strptime(coords$format_time, format = "%l:%M:%S %p")
        plot(month, time)
      })

But when there's only 1 data point in coords, the plot's time scale on the y-axis isn't in terms of time anymore, and the data point appears in the middle of the graph.

Thanks for your help!

Body:
What you're seeing is that R doesn't know how to guess an appropriate range for a single point. Typically it expands the range of data by 4% of the range (look at ?par and look for 'xaxs'), but with a single point that means nothing.

So we need to tell it what ylim to use. (Similarly, your x-axis needs some guidance, too.)

Fake data:

set.seed(2)
coords <- data.frame(tm = Sys.time() + runif(20, -3e7, 3e7))
coords$month <- as.integer(format(coords$tm, format = "%m"))
coords$format_time <- format(coords$tm, format = "%l:%M:%S %p")
head(coords)
#                    tm month format_time
# 1 2018-10-24 20:15:17    10  8:15:17 PM
# 2 2019-10-19 05:07:04    10  5:07:04 AM
# 3 2019-07-21 14:19:22     7  2:19:22 PM
# 4 2018-10-13 03:44:57    10  3:44:57 AM
# 5 2020-04-03 21:32:22     4  9:32:22 PM
# 6 2020-04-03 15:27:59     4  3:27:59 PM

The "normal" plot looks fine:

month <- coords$month
time <- strptime(coords$format_time, format = "%l:%M:%S %p")
plot(month, time)

but the single-point does not:

sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
plot(month, time)

So we fix it by specifying the xlim and ylim arguments. In this case, since I'm inferring it is meant to be a year of months (x) and a day of times (y), I can hard-code them, but in other situations you might want to just substract/add a small amount from the one datum you have:

sub <- coords[1,]
month <- sub$month
time <- strptime(sub$format_time, format = "%l:%M:%S %p")
xlim <- c(1, 12)
ylim <- strptime(c("12:00:00 AM", "11:59:59 PM"), format = "%l:%M:%S %p")
plot(month, time, xlim = xlim, ylim = as.numeric(ylim))

You only need to specify ylim to answer this question, but without setting xlim= here, the previous x-axis spanned 6-14, not good for months. Also of note is that I had to coerce ylim to numeric for the plot, it did not work with ylim in its pure POSIXt form ... not sure exactly why that is the case, but this doesn't detract from the utility of the plot in general.


来源: stackexchange

问:
CakePHP: Unable to save data to parent entity via belongsTo associated child

Problem description

I'm trying to configure a CakePHP 3.7 API to save associated data in a child-first manner. The entities - for the sake of example, lets call them Users and Persons - and their relationships are as follows:

UsersTable.php

```<code>...
  $this->belongsTo('Persons', [
    'foreignKey' => 'person_id',
    'joinType' => 'LEFT',
    'className' => 'MyPlugin.Persons',
  ]);
...
</code>```

PersonsTable.php

```<code>  $this->hasOne('Users', [
    'foreignKey' => 'person_id',
    'className' => 'MyPlugin.Users'
  ]);
</code>```

In their respective entities, they each have one another's property visibility set to true. What I'm trying to do is POST to the /users/ route (UsersController.php) and have it also save the Persons object included. The payload is as such:

```<code>{
    "username": "foo",
    "password": "bar",
    "persons": {
        "dob": "1982-07-03",
    }
}
</code>```

The relevant part of the saving method is below, from UsersController.php:

```<code>  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->save($newEntity);
  ...
</code>```

The error

This produces the following SQL error.

PDOException: SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column 'person_id' violates not-null constraint
  DETAIL: Failing row contains (1, null, foo, bar)

I understand this is because Cake is attempting to save to Users without having a person_id to satisfy the foreign key constraint. It's not possible to reverse this FK relationship in my application domain as we desire leftward one-to-many relationship (User -> 1 Person).

I suspect sending an id in the persons object of the JSON payload will allow this to save correctly. However, for various reasons, this isn't possible at runtime. For example, this is how it's shown in the "Saving Data" CakePHP Book page...

```<code>$data = [
  'title' => 'First Post',
  'user' => [
      'id' => 1,
      'username' => 'mark'
  ]
];

...
$article = $articles->newEntity($data, [
    'associated' => ['Users']
]);

$articles->save($article);
</code>```

I know the following would also likely work as suggested by xPfqHZ for a similar issue, as Persons can save to Users, but it feels less suitable as compared to what I'm trying to do and feels as if there is a way via the associations on Users.

```<code>  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->Persons->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->Persons->save($newEntity);
  ...
</code>```

Workings

Now I believe this used to be possible in CakePHP 2.X, as stated in this answer by ndm on a similar question where a person is attempting to save the belongsTo associated entity and it's parent hasOne entity in one request via the belongsTo entity.

That's the expected behavior, saveAssociated() is not meant to save only the associated records, it will save the main record as well, so you should use saveAssociated() only, no need to manually set the foreign key, etc, CakePHP will do that automatically.

Controller

```<code>public function create() {
    if ($this->request->is('post') && !empty($this->request->data)):
        $this->CandidatesProblemReport->create();
        if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):
            // ...
        endif;
    endif;
}
</code>```

However, I'm not able to find or use the saveAssociated() method upon the Cake\ORM\Table object which the Users entity inherits from, in the documentation. Calling it produces a method not found error. This method only appears to exist on the Cake\ORM\Association object as detailed in the documentation. Unless I'm missing the obvious, is there a way to use this or is it used internally by BelongsTo() and its sibling methods?

Logging / Dumping entity

Using Cake\Log\Log::error($newEntity); or die(var_dump($newEntity)); shows the Users data of the payload hydrated into an object, but I don't see the Persons object attached (see below).

```<code>object(MyPlugin\Model\Entity\User)[299]
  public 'username' => string 'foo' (length=3)
  public 'password' => string 'bar' (length=3)
  public '[new]' => boolean true
  public '[accessible]' =>
    array (size=5)
      '*' => boolean false
      'person_id' => boolean true
      'username' => boolean true
      'password' => boolean true
      'person' => boolean true
  public '[dirty]' =>
    array (size=2)
      'username' => boolean true
      'password' => boolean true
  public '[original]' =>
    array (size=0)
      empty
  public '[virtual]' =>
    array (size=0)
      empty
  public '[hasErrors]' => boolean false
  public '[errors]' =>
    array (size=0)
      empty
  public '[invalid]' =>
    array (size=0)
      empty
  public '[repository]' => string 'MyPlugin.Users' (length=17)
</code>```

Attempting to \Cake\Log\Log::error($savedEntity); shows nothing in the log file.

save() associations arguments

Another solution I considered was using the $options['associated] of save() as shown in the documentation (extract below). With this set to true as below, the error still occurred.

save( Cake\Datasource\EntityInterface $entity , array $options [] )

... associated: If true it will save 1st level associated entities as they are found in the passed $entity whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If false no associated records will be saved. (default: true) ...

UsersController.php:

```<code>  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->save($newEntity, ['associated' => true]);
  ...
</code>```

Summary

Without going through the PersonsController.php and utilising its hasOne relationship, I'm not having much luck getting my Users and Persons data to save through the UsersController.php.

If I've missed any important information, or you have questions/need more, please ask! I might have missed something obvious, but I'd appreciate any suggestions/solutions possible.

答:
As @ndm identified, the error lay in the posted data. As per the "Saving Data: Saving BelongsTo Associations" page of the documentation:

When saving belongsTo associations, the ORM expects a single nested entity named with the singular, underscored version of the association name.

The posted key persons should have been person. Equally, if the entity were named PersonSnapshots, the relevant key in the payload hydrated into the entities would need to have been person_snapshot.

ContentLicense: CC BY-SA 4.0

Body:
Problem description

I'm trying to configure a CakePHP 3.7 API to save associated data in a child-first manner. The entities - for the sake of example, lets call them Users and Persons - and their relationships are as follows:

UsersTable.php

...
  $this->belongsTo('Persons', [
    'foreignKey' => 'person_id',
    'joinType' => 'LEFT',
    'className' => 'MyPlugin.Persons',
  ]);
...

PersonsTable.php

  $this->hasOne('Users', [
    'foreignKey' => 'person_id',
    'className' => 'MyPlugin.Users'
  ]);

In their respective entities, they each have one another's property visibility set to true. What I'm trying to do is POST to the /users/ route (UsersController.php) and have it also save the Persons object included. The payload is as such:

{
    "username": "foo",
    "password": "bar",
    "persons": {
        "dob": "1982-07-03",
    }
}

The relevant part of the saving method is below, from UsersController.php:

  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->save($newEntity);
  ...

The error

This produces the following SQL error.

PDOException: SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column 'person_id' violates not-null constraint
  DETAIL: Failing row contains (1, null, foo, bar)

I understand this is because Cake is attempting to save to Users without having a person_id to satisfy the foreign key constraint. It's not possible to reverse this FK relationship in my application domain as we desire leftward one-to-many relationship (User -> 1 Person).

I suspect sending an id in the persons object of the JSON payload will allow this to save correctly. However, for various reasons, this isn't possible at runtime. For example, this is how it's shown in the "Saving Data" CakePHP Book page...

$data = [
  'title' => 'First Post',
  'user' => [
      'id' => 1,
      'username' => 'mark'
  ]
];

...
$article = $articles->newEntity($data, [
    'associated' => ['Users']
]);

$articles->save($article);

I know the following would also likely work as suggested by xPfqHZ for a similar issue, as Persons can save to Users, but it feels less suitable as compared to what I'm trying to do and feels as if there is a way via the associations on Users.

  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->Persons->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->Persons->save($newEntity);
  ...

Workings

Now I believe this used to be possible in CakePHP 2.X, as stated in this answer by ndm on a similar question where a person is attempting to save the belongsTo associated entity and it's parent hasOne entity in one request via the belongsTo entity.

That's the expected behavior, saveAssociated() is not meant to save only the associated records, it will save the main record as well, so you should use saveAssociated() only, no need to manually set the foreign key, etc, CakePHP will do that automatically.

Controller

public function create() {
    if ($this->request->is('post') && !empty($this->request->data)):
        $this->CandidatesProblemReport->create();
        if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):
            // ...
        endif;
    endif;
}

However, I'm not able to find or use the saveAssociated() method upon the Cake\ORM\Table object which the Users entity inherits from, in the documentation. Calling it produces a method not found error. This method only appears to exist on the Cake\ORM\Association object as detailed in the documentation. Unless I'm missing the obvious, is there a way to use this or is it used internally by BelongsTo() and its sibling methods?

Logging / Dumping entity

Using Cake\Log\Log::error($newEntity); or die(var_dump($newEntity)); shows the Users data of the payload hydrated into an object, but I don't see the Persons object attached (see below).

object(MyPlugin\Model\Entity\User)[299]
  public 'username' => string 'foo' (length=3)
  public 'password' => string 'bar' (length=3)
  public '[new]' => boolean true
  public '[accessible]' =>
    array (size=5)
      '*' => boolean false
      'person_id' => boolean true
      'username' => boolean true
      'password' => boolean true
      'person' => boolean true
  public '[dirty]' =>
    array (size=2)
      'username' => boolean true
      'password' => boolean true
  public '[original]' =>
    array (size=0)
      empty
  public '[virtual]' =>
    array (size=0)
      empty
  public '[hasErrors]' => boolean false
  public '[errors]' =>
    array (size=0)
      empty
  public '[invalid]' =>
    array (size=0)
      empty
  public '[repository]' => string 'MyPlugin.Users' (length=17)

Attempting to \Cake\Log\Log::error($savedEntity); shows nothing in the log file.

save() associations arguments

Another solution I considered was using the $options['associated] of save() as shown in the documentation (extract below). With this set to true as below, the error still occurred.

save( Cake\Datasource\EntityInterface $entity , array $options [] )

... associated: If true it will save 1st level associated entities as they are found in the passed $entity whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If false no associated records will be saved. (default: true) ...

UsersController.php:

  if ($this->request->is('post') && !empty($this->request->getData())) {
    $data = $this->request->getData();
    $newEntity = $this->Users->newEntity($data, ['associated' => 'Persons']);

    $savedEntity =  $this->Users->save($newEntity, ['associated' => true]);
  ...

Summary

Without going through the PersonsController.php and utilising its hasOne relationship, I'm not having much luck getting my Users and Persons data to save through the UsersController.php.

If I've missed any important information, or you have questions/need more, please ask! I might have missed something obvious, but I'd appreciate any suggestions/solutions possible.


问:
how to set the locaction in nginx.conf for removing URL's trailing slash?
Today I used two servers for nginx, the content of nginx.conf as follows:

```<code>#192.168.2.98
server {
    listen 8091;
    location ^~ /ttank {
        alias /develop/servers-running/front/vue-public/dist;
        index index.html;
        try_files $uri $uri/ /ttank/index.html;
     }
 }

#192.168.2.97
location /ttank {
   proxy_pass http://192.168.2.98:8091;
   proxy_set_header Host $host;
   proxy_set_header  X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_redirect off;
}
</code>```

I can access the 192.168.2.98:8091/ttank by enter address: http://192.168.2.98:8091/ttank in chrome, I also can access 192.168.2.98's ttank by entering the address http://192.168.2.97/ttank/,  but when I change the addres http://192.168.2.97/ttank/ into http://192.168.2.97/ttank, my chrome entered into waiting status forever, the only difference between two addresses is the last "/", I don't know how to modify the config file for removing the last "/" when accessing ttank by 192.168.2.97?

答:
Try usinge a rewrite rule to get rid of the ending slashes

```<code>location /ttank {
    rewrite ^/(.*)/$ /$1 break;
    ...;
    ...;
    proxy_pass ...;
}
</code>```

it should do it

Body:
Today I used two servers for nginx, the content of nginx.conf as follows:

#192.168.2.98
server {
    listen 8091;
    location ^~ /ttank {
        alias /develop/servers-running/front/vue-public/dist;
        index index.html;
        try_files $uri $uri/ /ttank/index.html;
     }
 }

#192.168.2.97
location /ttank {
   proxy_pass http://192.168.2.98:8091;
   proxy_set_header Host $host;
   proxy_set_header  X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_redirect off;
}

I can access the 192.168.2.98:8091/ttank by enter address: http://192.168.2.98:8091/ttank in chrome, I also can access 192.168.2.98's ttank by entering the address http://192.168.2.97/ttank/,  but when I change the addres http://192.168.2.97/ttank/ into http://192.168.2.97/ttank, my chrome entered into waiting status forever, the only difference between two addresses is the last "/", I don't know how to modify the config file for removing the last "/" when accessing ttank by 192.168.2.97?

Body:
Try usinge a rewrite rule to get rid of the ending slashes

location /ttank {
    rewrite ^/(.*)/$ /$1 break;
    ...;
    ...;
    proxy_pass ...;
}

it should do it


问:
Enable a button in Swift only if all text fields have been filled out
I am having trouble figuring out how to change my code to make it so the Done button in the navigation bar is enabled when my three text fields are filled out.

I currently have three UITextFields and one UIButtonItem. Both the habitNameField and the goalField are manual text fields, and the frequencyField is a Picker View.

```<code>@IBOutlet weak var habitNameField: UITextField!
@IBOutlet weak var goalField: UITextField!
@IBOutlet weak var frequencyField: UITextField!

@IBOutlet weak var doneBarButton: UIBarButtonItem!
</code>```

I also have the following function that works when there is something typed in the first field.

```<code>func textField(habitNameField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldHabitNameText: NSString = habitNameField.text!
    let newHabitNameText: NSString = oldHabitNameText.stringByReplacingCharactersInRange(range, withString: string)
    doneBarButton.enabled = (newHabitNameText.length != 0)
    return true
}
</code>```

I tried change the code so that it took in the other two fields as parameters and enabled the doneBarButton only if all three fields were filled out.

```<code>func textField(habitNameField: UITextField, goalField: UITextField, frequencyField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let habitNameText: NSString = (habitNameField.text!).stringByReplacingCharactersInRange(range, withString: string)
    let goalText: NSString = (goalField.text!).stringByReplacingCharactersInRange(range, withString: string)
    let frequencyText: NSString = (frequencyField.text!).stringByReplacingCharactersInRange(range, withString: string)

    doneBarButton.enabled = (habitNameText.length != 0) && (goalText.length != 0) && (frequencyText.length != 0)
    return true
}
</code>```

However, it's not working, even when I fill out all three text fields.

I would really appreciate any help, and thanks to anyone who contributes in advance!

All code here:

```<code>class HabitDetailViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var habitNameField: UITextField!
@IBOutlet weak var goalField: UITextField!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
@IBOutlet weak var frequencyField: UITextField!

var frequencies = ["Day", "Week", "Month", "Year"]
var frequencyPicker = UIPickerView()

var habitToEdit: HabitItem?
weak var delegate: HabitDetailViewControllerDelegate?

@IBAction func cancel() {
    delegate?.habitDetailViewControllerDidCancel(self)
}

@IBAction func done() {
    print("You plan to do \(habitNameField.text!) \(goalField.text!) times a \(frequencyField.text!.lowercaseString).")
    if let habit = habitToEdit {
        habit.name = habitNameField.text!
        habit.numberLeft = Int(goalField.text!)!
        habit.frequency = frequencyField.text!
        delegate?.habitDetailViewController(self, didFinishEditingHabit: habit)
    } else {
        let habit = HabitItem()
        habit.name = habitNameField.text!
        habit.numberLeft = Int(goalField.text!)!
        habit.frequency = frequencyField.text!
        habit.completed = false
        delegate?.habitDetailViewController(self, didFinishAddingHabit: habit)
    }
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    habitNameField.becomeFirstResponder()
    frequencyPicker.hidden = false
}

override func viewDidLoad() {
    super.viewDidLoad()
    frequencyPicker.dataSource = self
    frequencyPicker.delegate = self
    doneBarButton.enabled = false
    habitNameField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    goalField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    frequencyField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    frequencyField.inputView = frequencyPicker
    if let habit = habitToEdit {
        title = "Edit Item"
        habitNameField.text = habit.name
        goalField.text = String(habit.numberLeft)
        doneBarButton.enabled = true
    }
}

override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    return nil
}

func textField(habitNameField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldHabitNameText: NSString = habitNameField.text!
    let newHabitNameText: NSString = oldHabitNameText.stringByReplacingCharactersInRange(range, withString: string)
    doneBarButton.enabled = (newHabitNameText.length != 0)
    return true
}

func checkFields(sender: UITextField) {
    sender.text = sender.text?.stringByTrimmingCharactersInSet(.whitespaceCharacterSet())
    guard
        let habit = habitNameField.text where !habit.isEmpty,
        let goal = goalField.text where !goal.isEmpty,
        let frequency = frequencyField.text where !frequency.isEmpty
        else { return }
    // enable your button if all conditions are met
    doneBarButton.enabled = true
}
</code>```

答:
Xcode 10.2 • Swift 4.3 version of Leo Dabus above.

This solution is for adding a user, probably the most common implementation
for such validation.

```<code>override func viewDidLoad() {
super.viewDidLoad()
addUserButton.backgroundColor = disabledButtonColor
addUserButton.isEnabled = false

[emailField, userNameField, firstNameField, lastNameField].forEach { (field) in
    field?.addTarget(self,
                     action: #selector(editingChanged(_:)),
                     for: .editingChanged)
}}

@objc private func editingChanged(_ textField: UITextField) {
if textField.text?.count == 1 {
    if textField.text?.first == " " {
        textField.text = ""
        return
    }
}
guard
    let email       = emailField.text,      !email.isEmpty,
    let userName    = userNameField.text,   !userName.isEmpty,
    let firstName   = firstNameField.text,  !firstName.isEmpty,
    let lastName    = lastNameField.text,   !lastName.isEmpty
    else {
        addUserButton.isEnabled = false
        addUserButton.backgroundColor = disabledButtonColor
        return
}
addUserButton.isEnabled = true
addUserButton.backgroundColor = activeButtonColor
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble figuring out how to change my code to make it so the Done button in the navigation bar is enabled when my three text fields are filled out.

I currently have three UITextFields and one UIButtonItem. Both the habitNameField and the goalField are manual text fields, and the frequencyField is a Picker View.

@IBOutlet weak var habitNameField: UITextField!
@IBOutlet weak var goalField: UITextField!
@IBOutlet weak var frequencyField: UITextField!

@IBOutlet weak var doneBarButton: UIBarButtonItem!

I also have the following function that works when there is something typed in the first field.

func textField(habitNameField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldHabitNameText: NSString = habitNameField.text!
    let newHabitNameText: NSString = oldHabitNameText.stringByReplacingCharactersInRange(range, withString: string)
    doneBarButton.enabled = (newHabitNameText.length != 0)
    return true
}

I tried change the code so that it took in the other two fields as parameters and enabled the doneBarButton only if all three fields were filled out.

func textField(habitNameField: UITextField, goalField: UITextField, frequencyField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let habitNameText: NSString = (habitNameField.text!).stringByReplacingCharactersInRange(range, withString: string)
    let goalText: NSString = (goalField.text!).stringByReplacingCharactersInRange(range, withString: string)
    let frequencyText: NSString = (frequencyField.text!).stringByReplacingCharactersInRange(range, withString: string)

    doneBarButton.enabled = (habitNameText.length != 0) && (goalText.length != 0) && (frequencyText.length != 0)
    return true
}

However, it's not working, even when I fill out all three text fields.

I would really appreciate any help, and thanks to anyone who contributes in advance!

All code here:

class HabitDetailViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var habitNameField: UITextField!
@IBOutlet weak var goalField: UITextField!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
@IBOutlet weak var frequencyField: UITextField!

var frequencies = ["Day", "Week", "Month", "Year"]
var frequencyPicker = UIPickerView()

var habitToEdit: HabitItem?
weak var delegate: HabitDetailViewControllerDelegate?

@IBAction func cancel() {
    delegate?.habitDetailViewControllerDidCancel(self)
}

@IBAction func done() {
    print("You plan to do \(habitNameField.text!) \(goalField.text!) times a \(frequencyField.text!.lowercaseString).")
    if let habit = habitToEdit {
        habit.name = habitNameField.text!
        habit.numberLeft = Int(goalField.text!)!
        habit.frequency = frequencyField.text!
        delegate?.habitDetailViewController(self, didFinishEditingHabit: habit)
    } else {
        let habit = HabitItem()
        habit.name = habitNameField.text!
        habit.numberLeft = Int(goalField.text!)!
        habit.frequency = frequencyField.text!
        habit.completed = false
        delegate?.habitDetailViewController(self, didFinishAddingHabit: habit)
    }
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    habitNameField.becomeFirstResponder()
    frequencyPicker.hidden = false
}

override func viewDidLoad() {
    super.viewDidLoad()
    frequencyPicker.dataSource = self
    frequencyPicker.delegate = self
    doneBarButton.enabled = false
    habitNameField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    goalField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    frequencyField.addTarget(self, action: "checkFields:", forControlEvents: .EditingChanged)
    frequencyField.inputView = frequencyPicker
    if let habit = habitToEdit {
        title = "Edit Item"
        habitNameField.text = habit.name
        goalField.text = String(habit.numberLeft)
        doneBarButton.enabled = true
    }
}

override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    return nil
}

func textField(habitNameField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldHabitNameText: NSString = habitNameField.text!
    let newHabitNameText: NSString = oldHabitNameText.stringByReplacingCharactersInRange(range, withString: string)
    doneBarButton.enabled = (newHabitNameText.length != 0)
    return true
}

func checkFields(sender: UITextField) {
    sender.text = sender.text?.stringByTrimmingCharactersInSet(.whitespaceCharacterSet())
    guard
        let habit = habitNameField.text where !habit.isEmpty,
        let goal = goalField.text where !goal.isEmpty,
        let frequency = frequencyField.text where !frequency.isEmpty
        else { return }
    // enable your button if all conditions are met
    doneBarButton.enabled = true
}

Body:
Xcode 10.2 • Swift 4.3 version of Leo Dabus above.

This solution is for adding a user, probably the most common implementation
for such validation.

override func viewDidLoad() {
super.viewDidLoad()
addUserButton.backgroundColor = disabledButtonColor
addUserButton.isEnabled = false

[emailField, userNameField, firstNameField, lastNameField].forEach { (field) in
    field?.addTarget(self,
                     action: #selector(editingChanged(_:)),
                     for: .editingChanged)
}}

@objc private func editingChanged(_ textField: UITextField) {
if textField.text?.count == 1 {
    if textField.text?.first == " " {
        textField.text = ""
        return
    }
}
guard
    let email       = emailField.text,      !email.isEmpty,
    let userName    = userNameField.text,   !userName.isEmpty,
    let firstName   = firstNameField.text,  !firstName.isEmpty,
    let lastName    = lastNameField.text,   !lastName.isEmpty
    else {
        addUserButton.isEnabled = false
        addUserButton.backgroundColor = disabledButtonColor
        return
}
addUserButton.isEnabled = true
addUserButton.backgroundColor = activeButtonColor

}


问:
run py script from another py script using relative path
There are answers for when both scripts are in the same directory.

However, I can't get any of the answers mentioned here  working for a relative path. They are for when the full path is known.

I have the following folder hierarchy

i need to call and run sub.py in commander.py

the following is in commander.py

```<code>import importlib.util
spec = importlib.util.spec_from_file_location('sub.py', '..//main/sub/sub.py')
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.main()
</code>```

it certainly recognized the directory as I can see the pycache 'folder getting created in sub folder.

However the sub script doesn't run.
I have launched the sub script manually and i know it is functional.

the sub script has the following structure

```<code>import stuff

def main():
   do stuff
return

while true:
  main()
break
</code>```

I am new to python.
I have also tried:

```<code>import sys
    sys.path.insert(0, '..\\main\sub')

    import sub.py

    sub.main()
</code>```

i'm using py 3.7
there are no errors

答:
Importing a file in python, runs that file.

Given this structure

```<code>-project
    -module
        -__init__.py
        -module_hello.py
    -__init__.py
    -hello.py
</code>```

And these files

```<code># module_hello.py
print('hello')
</code>```

and

```<code># hello.py
from project.module import module_hello
</code>```

running hello.py would result in printing hello.

Body:
There are answers for when both scripts are in the same directory.

However, I can't get any of the answers mentioned here  working for a relative path. They are for when the full path is known.

I have the following folder hierarchy

i need to call and run sub.py in commander.py

the following is in commander.py

import importlib.util
spec = importlib.util.spec_from_file_location('sub.py', '..//main/sub/sub.py')
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.main()

it certainly recognized the directory as I can see the pycache 'folder getting created in sub folder.

However the sub script doesn't run.
I have launched the sub script manually and i know it is functional.

the sub script has the following structure

import stuff

def main():
   do stuff
return

while true:
  main()
break

I am new to python.
I have also tried:

import sys
    sys.path.insert(0, '..\\main\sub')

    import sub.py

    sub.main()

i'm using py 3.7
there are no errors

Body:
Importing a file in python, runs that file.

Given this structure

-project
    -module
        -__init__.py
        -module_hello.py
    -__init__.py
    -hello.py

And these files

# module_hello.py
print('hello')

and

# hello.py
from project.module import module_hello

running hello.py would result in printing hello.


问:
A non-relational embedded database with a permissive free software license?
many thanks in advance for taking the time to look at my question.

(I am aware of this question Nonrelational Databases for C++, but my needs are a bit different and it only has one answer.)

I am developing a commercial C++ library that must, among other things, persist messages. I would like to avoid reinventing the wheel by writing my own DBMS. Unfortunately, I have the following restricting criteria:

It must be usable from C++ - I'm writing a C++ library. Bindings are potentially acceptable, if the level of effort to make them work isn't too high.

I need an embedded database. Stand-alone will not work.

I want to avoid a relational database. In addition to concerns about performance overhead, there are technical politics beyond my control as a developer that discourage a relational database.

I need a permissive free software license. It'll be hard to buy licenses, but the client doesn't want to give his source away.

I'd like a solution that's established (been around for at least a little while, beyond the experimental stage, has been used by several projects).

Sadly, the two go-to choices don't work because of the above:
-SQLite is relational
-BerkeleyDB is GPL or commercial

Again, thanks for any help.

答: Use SQLite in b-tree mode.  Public domain.  Avoids politics.  Let's you work around the political issues by avoiding the SQL interface for performance-critical paths, and optionally using the SQL parser path for those queries that are not on the critical path.


问:
Is WebGL Shader Caching Possible?
My question is similar to Saving/Loading compiled WebGL shaders, but I don't want to pre-compile my shaders. Instead, I just want the browser to store the shaders it compiles longer than the default. Right now, every time I refresh the page the shaders have to be recompiled.

I understand the security and portability issues raised in answers like this one and this one. It seems that these are both non-issues assuming that the browser is caching shaders that it compiled for my web app.

Assuming the same OS + browser + GPU + driver combination, is there a way to make the browser cache compiled shaders in such a way that shader compilation will not be required after each time the page is refreshed?

答:
There is nothing the user can do to force the browser to cache shaders. It's up to the browser to implement shader caching and to decide when to use it. Further, the browser relies on the OS to provide a way to cache shaders so if the OS doesn't support it then of course the browser can't either. As an example, currently on MacOS, WebGL runs on top of OpenGL and OpenGL on MacOS provides no way to cache shaders.

For example search for 'BINARY' in this official Apple OpenGL feature table and you'll see the number of formats for caching is 0. In other words you can't cache OpenGL shaders on MacOS

I don't know Metal that well, it possible that some future version of WebGL could be written on top of Metal and maybe Metal provides a way.

Chrome can cache shaders. Here's the code for caching them. But it can't if the OS doesn't support it.

Then there's the question of when to clear or not use the cache. Should the cache be cleared if the user presses 'refresh'. Note that 'refresh' is a signal from the user to NOT cache the page. There are many ways to revisit. One, click a link to the page again, pick it from a bookmark, enter it in the URL bar. All of these don't clear the cache. Clicking the 'Refresh' button AFAIK ignores the cache for at least the specific request (ie, the page itself) but not the things the page references.

Should the cache be cleared if the user picks to empty the browser's normal cache of web resources? Clearly the cache should be cleared anytime the driver changes version numbers. There may be other reasons to clear the cache as the browser needs to make sure it never delivers a bad or out of date shader.

As for Windows I believe DirectX allows caching shaders and Chrome, via ANGLE caches them. A quick test on Windows seems to bare this out. Going to shadertoy.com the first time I load the page it takes a while. The next time it doesn't. Another test. Pick a complex shader on shadertoy. Edit some constant in the shader, for example change 1.0 to 1.01 and press the compile button. Look at the compile time. Now change it back to 1.0 and press compile. In my tests the second compile takes much less time suggesting the shader was cached.

I have no idea if Firefox caches shaders. Safari doesn't since it only runs on platforms that don't support caching.

Title: Is WebGL Shader Caching Possible?


问:
Duplicate on 2 fields
I looking a way to avoid the duplicates in Laravel. For example, I have a table with 2 fields which are name and firstname.

How to manage the duplicates on the Controller? I am newbie...

Here is my function store().

```<code>public function store(Request $request)
    {
        $request->validate([
                'name' => 'required|string|max:25',
                'firstname' => 'required|string|max:25'

        ]);

        $exists = Auteur::where('name', $request->get('name'))->where('firstName', $request->get('firstName'))->count();

        if (!$exists){
            Auteur::create($request->all());
            return redirect()->route('auteurs.index')
                    ->with('success', 'save');
        }

    }
</code>```

I thank you for your help and your explanations.

答:
Just add unique in your validation rule. If you would like to check unique validation each field separately.</p>

```<code>$request->validate([
                'name' => 'required|unique:auteurs,name|string|max:25',
                'firstname' => 'required|unique:auteurs,firstname|string|max:25'

        ]);

Here I hope the table name is `auteurs`
</code>```

Title: Duplicate on 2 fields

Body:
I looking a way to avoid the duplicates in Laravel. For example, I have a table with 2 fields which are name and firstname.

How to manage the duplicates on the Controller? I am newbie...

Here is my function store().

public function store(Request $request)
    {
        $request->validate([
                'name' => 'required|string|max:25',
                'firstname' => 'required|string|max:25'

        ]);

        $exists = Auteur::where('name', $request->get('name'))->where('firstName', $request->get('firstName'))->count();

        if (!$exists){
            Auteur::create($request->all());
            return redirect()->route('auteurs.index')
                    ->with('success', 'save');
        }

    }

I thank you for your help and your explanations.

Body:
Just add unique in your validation rule. If you would like to check unique validation each field separately.

$request->validate([
                'name' => 'required|unique:auteurs,name|string|max:25',
                'firstname' => 'required|unique:auteurs,firstname|string|max:25'

        ]);

Here I hope the table name is `auteurs`


问:
CoreData transient relationship example
Does anybody have an example on how to model and code a transient to-one relationship in CoreData?  For example, I have 2 entities with a one-to-many relationship.  Doctor and Appointment.  Now I want an transient relationship called mostRecentAppointment on the doctor entity.  It's straightforward to model in the xcode designer, but I'm not sure about the implementation side.  Also should I implement an inverse?  Seems silly.

答:
In this case, the appropriate method to override is -awakeFromFetch in the Doctor entity, for example like so:

```<code>- (void)awakeFromFetch {
    [super awakeFromFetch];// important: call this first!
    self.mostRecentAppointment = <something>; // normal  relationship
    self.mostRecentAppointment.doctor = self; // inverse relationship
}
</code>```

In the model designer, mark both the normal and the inverse relationship as transient. That should be it.

Title: CoreData transient relationship example

Body:
In this case, the appropriate method to override is -awakeFromFetch in the Doctor entity, for example like so:

- (void)awakeFromFetch {
    [super awakeFromFetch];// important: call this first!
    self.mostRecentAppointment = <something>; // normal  relationship
    self.mostRecentAppointment.doctor = self; // inverse relationship
}

In the model designer, mark both the normal and the inverse relationship as transient. That should be it.


问:
Get list of all loaded python packages & versions, and variables
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

```<code>library(dplyr)
x=3;
y=4;
</code>```

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

```<code>ls()
</code>```

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.

答:
Show me everything available python package I can import & corresponding versions?

help('modules')

NB: You can also type pip freeze on the command line to see which third-party modules you have installed using pip. (Use python -m pip freeze if you have multiple Python versions and want to be sure you list the packages for the same version as python.) However, this list is not complete, since it does not contain built-in modules and your own modules.

Show me the packages I have already loaded thus far in my session and their corresponding versions?

I don't think this is possible, but see next question:

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

globals()

This also includes all loaded modules. You could filter out the 'modules' if you want.

Body:
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

library(dplyr)
x=3;
y=4;

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

ls()

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.


问:
Multiple occurances of the same Column variable in a query
I have two tables

TicketsForSale

ticket_id (PK)

type

category

Transactions

transaction_id (PK)

ticket_id (FK)

I want to get the transactions per type of tickets. This is what I've tried:

```<code>SELECT ticketsforsale.type
      , COUNT(transactions.ticket_id)
FROM  ticketsforsale
        INNER JOIN transactions ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type
</code>```

What I hope for as a result is something like this

```<code>{
    Sports  5
    Theater 7
    Cruise 8
    Cinema 10
}
</code>```

But instead I get the following :

```<code>{  Theater 2
   Cruise  1
   Sports  1
   Sports  2
   Cruise  3
   Cinema 5
}
</code>```

The numbers aren't accurate, just used for demonstration.

(The category column is listing the specific show you attend by "purchasing" the ticket. E.G If the type is "Sports", the category could be Basketball or Football or Volleyball etc. etc. ) I just thought that this column could somehow be the issue here, but maybe I'm wrong.

答:
Try this:

```<code>select distinct type
     , encode(type::bytea,'hex') hex_type
  from TicketsForSale order by 1;
</code>```

You'll probably find that you have multiple type values that appear identical but have different hexadecimal representations.  Fix those discrepancies, and the you should be good to go.

Body:
I have two tables

TicketsForSale

ticket_id (PK)

type

category

Transactions

transaction_id (PK)

ticket_id (FK)

I want to get the transactions per type of tickets. This is what I've tried:

SELECT ticketsforsale.type
      , COUNT(transactions.ticket_id)
FROM  ticketsforsale
        INNER JOIN transactions ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type

What I hope for as a result is something like this

{
    Sports  5
    Theater 7
    Cruise 8
    Cinema 10
}

But instead I get the following :

{  Theater 2
   Cruise  1
   Sports  1
   Sports  2
   Cruise  3
   Cinema 5
}

The numbers aren't accurate, just used for demonstration.

(The category column is listing the specific show you attend by "purchasing" the ticket. E.G If the type is "Sports", the category could be Basketball or Football or Volleyball etc. etc. ) I just thought that this column could somehow be the issue here, but maybe I'm wrong.

Body:
Try this:

select distinct type
     , encode(type::bytea,'hex') hex_type
  from TicketsForSale order by 1;

You'll probably find that you have multiple type values that appear identical but have different hexadecimal representations.  Fix those discrepancies, and the you should be good to go.


问:
SQL INSERT INTO - Duplicates still exist (How to modify insert into?)
I have 3 MariaDB-SQL tables and I want to insert some data:

Restaurant

ID_Restaurant (Primary Key, Auto Increment)

RestaurantName

Location

Restaurant_has_Request

ID_Restaurant(Foreign Key)

ID_Request (Foreign Key)

Request

ID_Request (Primary Key, Auto Increment)

Date

Adults

One Restaurant has 0 or infinity Requests. One Request can have 1 or infinity Restaurants.

I am iterating through a request site for only one Request. That means I want to treat first one Request and then I save the related one or more Restaurants. After I have done this another Request will be treated and so on.

I have the following Python Code for inserting the data:

```<code>cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))

# ID from last insert
ID_Restaurant_Cache = cursor.lastrowid

cursor.execute('insert into Request(Date, Adults) values(%s, %s)',(Date, Adults))

# ID from last insert
ID_Request_Cache = cursor.lastrowid

cursor.execute('insert into Restaurant_has_Request(ID_Restaurant, ID_Request) values(%s, %s)',(ID_Restaurant_Cache, ID_Request_Cache))
</code>```

The problem is that I have still duplicates... How can I modify the Python code that I use the existing entry from a Restaurant, when it already exists (RestaurantName & Location is already in the database)?
I have also duplicates for the Request. I want to use the same Request ID for one iteration and then I want to use another Request ID.

Thank you :)

答:
You need to check whether the restaurant already exists before inserting.

```<code>cursor.execute('select ID_Restaurant from Restaurant where RestaurantName = %s', (RestaurantName,))
row = cursor.fetchone()
if row:
    ID_Restaurant_Cache = row[0]
else:
    cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))
    ID_Restaurant_Cache = cursor.lastrowid
</code>```

You should also add a unique index on the RestaurantName column, to prevent duplicates.

Body:
I have 3 MariaDB-SQL tables and I want to insert some data:

Restaurant

ID_Restaurant (Primary Key, Auto Increment)

RestaurantName

Location

Restaurant_has_Request

ID_Restaurant(Foreign Key)

ID_Request (Foreign Key)

Request

ID_Request (Primary Key, Auto Increment)

Date

Adults

One Restaurant has 0 or infinity Requests. One Request can have 1 or infinity Restaurants.

I am iterating through a request site for only one Request. That means I want to treat first one Request and then I save the related one or more Restaurants. After I have done this another Request will be treated and so on.

I have the following Python Code for inserting the data:

cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))

# ID from last insert
ID_Restaurant_Cache = cursor.lastrowid

cursor.execute('insert into Request(Date, Adults) values(%s, %s)',(Date, Adults))

# ID from last insert
ID_Request_Cache = cursor.lastrowid

cursor.execute('insert into Restaurant_has_Request(ID_Restaurant, ID_Request) values(%s, %s)',(ID_Restaurant_Cache, ID_Request_Cache))

The problem is that I have still duplicates... How can I modify the Python code that I use the existing entry from a Restaurant, when it already exists (RestaurantName & Location is already in the database)?
I have also duplicates for the Request. I want to use the same Request ID for one iteration and then I want to use another Request ID.

Thank you :)

Body:
You need to check whether the restaurant already exists before inserting.

cursor.execute('select ID_Restaurant from Restaurant where RestaurantName = %s', (RestaurantName,))
row = cursor.fetchone()
if row:
    ID_Restaurant_Cache = row[0]
else:
    cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))
    ID_Restaurant_Cache = cursor.lastrowid

You should also add a unique index on the RestaurantName column, to prevent duplicates.