问:
Setting state of Date Picker onChange
I am trying to update my two states based on the currently selected date using html date picker. The two states; startdate and enddate, none of them is getting updated onChange. Based on those updated states, I need to fetch data using those states data as query paramters. It consoles only initial state dates.

Here is the code:

```<code>import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();

    var date = new Date();

    var newdate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + (date.getDate())) ;

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  setStartDate = e => {
      this.setState({
        startdate: e.target.value
      })

      console.log(this.state.startdate, 'STARTDATE');
  }

  setEndDate = e => {
    //console.log(e.target.value)

    this.setState({
      enddate: e.target.value,
    });

    console.log(this.state.enddate, 'ENDDATE');
    axios.post('http://132.148.144.133:5000/api/v2/resources/sentiments', {
        sentiment_type: 'positive',
        startdate:this.state.startdate,
        enddate: this.state.enddate
    })
    .then( (result) => {

        console.log(result.data)
    })
    .catch(err => {
        console.log(err)
    })
  }

  render() {
    return (
      <div>
        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setStartDate}
        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setEndDate}
        />
      </div>
    );
  }
}
</code>```

I have got to fetch the data as soon as the second input box gets updated with the selected date from the picker.

答:
Give it a try with this code:

```<code>import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();
    const date = new Date();
    const newDate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + date.getDate());

    this.state = {
      startDate: newDate,
      endDate: newDate
    };
  }

  handleDateChange = ({ target: { name, value } }) => {
    this.setState({
      [name]: value
    });

    if (name === "endDate") {
      const { endDate, startDate } = this.state;
      axios
        .post("http://132.148.144.133:5000/api/v2/resources/sentiments", {
          sentiment_type: "positive",
          startdate: startDate,
          enddate: endDate
        })
        .then(result => {
          console.log(result.data);
        })
        .catch(err => {
          console.log(err);
        });
    }
  };

  render() {
    const { endDate, startDate } = this.state;
    console.log(this.state);
    return (
      <>
        <label>From</label>
        <input
          type="date"
          name="startDate"
          value={startDate}
          onChange={this.handleDateChange}
        />
        <label>To</label>
        <input
          type="date"
          name="endDate"
          value={endDate}
          onChange={this.handleDateChange}
        />
      </>
    );
  }
}
</code>```

It's cleaner with a generic method that manages your date changes. I also felt free to refactor it a bit. Let me know if it works the way you wanted it to.

Title: Setting state of Date Picker onChange

Body:
I am trying to update my two states based on the currently selected date using html date picker. The two states; startdate and enddate, none of them is getting updated onChange. Based on those updated states, I need to fetch data using those states data as query paramters. It consoles only initial state dates.

Here is the code:

import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();

    var date = new Date();

    var newdate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + (date.getDate())) ;

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  setStartDate = e => {
      this.setState({
        startdate: e.target.value
      })

      console.log(this.state.startdate, 'STARTDATE');
  }

  setEndDate = e => {
    //console.log(e.target.value)

    this.setState({
      enddate: e.target.value,
    });

    console.log(this.state.enddate, 'ENDDATE');
    axios.post('http://132.148.144.133:5000/api/v2/resources/sentiments', {
        sentiment_type: 'positive',
        startdate:this.state.startdate,
        enddate: this.state.enddate
    })
    .then( (result) => {

        console.log(result.data)
    })
    .catch(err => {
        console.log(err)
    })
  }

  render() {
    return (

        From
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setStartDate}
        />

        To
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setEndDate}
        />

    );
  }
}

I have got to fetch the data as soon as the second input box gets updated with the selected date from the picker.

Body:
Give it a try with this code:

import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();
    const date = new Date();
    const newDate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + date.getDate());

    this.state = {
      startDate: newDate,
      endDate: newDate
    };
  }

  handleDateChange = ({ target: { name, value } }) => {
    this.setState({
      [name]: value
    });

    if (name === "endDate") {
      const { endDate, startDate } = this.state;
      axios
        .post("http://132.148.144.133:5000/api/v2/resources/sentiments", {
          sentiment_type: "positive",
          startdate: startDate,
          enddate: endDate
        })
        .then(result => {
          console.log(result.data);
        })
        .catch(err => {
          console.log(err);
        });
    }
  };

  render() {
    const { endDate, startDate } = this.state;
    console.log(this.state);
    return (
      <>
        <label>From</label>
        <input
          type="date"
          name="startDate"
          value={startDate}
          onChange={this.handleDateChange}
        />
        <label>To</label>
        <input
          type="date"
          name="endDate"
          value={endDate}
          onChange={this.handleDateChange}
        />
      </>
    );
  }
}

It's cleaner with a generic method that manages your date changes. I also felt free to refactor it a bit. Let me know if it works the way you wanted it to.


来源: stackexchange

问:
How to fix url contains arabic characters
I want to get the url of each file in certain directory

i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.

example:

this is my code output:

String A :

https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3

this code is not working in some android devices

but the next code works with all devices

String B:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

Note: i got String B from internet download manager that converts it automatically when i tried to use string A

my question is:

how to convert String A to String B by php

and is there better way to readdir and get the url of each file

My code is:

```<code>if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){

if($file == "." or $file == ".."){
//...
} else { //create object with two fields

sort($file);
$fileName = pathinfo($file)['filename'];

if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}

</code>```

答:
this code worked for me

thanks every one

```<code>

$res1 = "https://linkimage2url.com" .$path."/".$file;
$query = flash_encode ($res1);
$url = htmlentities($query);

 function flash_encode($string)
   {
      $string = rawurlencode($string);
      $string = str_replace("%2F", "/", $string);
      $string = str_replace("%3A", ":", $string);
      return $string;
   }

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get the url of each file in certain directory

i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.

example:

this is my code output:

String A :

https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3

this code is not working in some android devices

but the next code works with all devices

String B:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

Note: i got String B from internet download manager that converts it automatically when i tried to use string A

my question is:

how to convert String A to String B by php

and is there better way to readdir and get the url of each file

My code is:

if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){

if($file == "." or $file == ".."){
//...
} else { //create object with two fields

sort($file);
$fileName = pathinfo($file)['filename'];

if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}

Body:
this code worked for me

thanks every one

$res1 = "https://linkimage2url.com" .$path."/".$file;
$query = flash_encode ($res1);
$url = htmlentities($query);

 function flash_encode($string)
   {
      $string = rawurlencode($string);
      $string = str_replace("%2F", "/", $string);
      $string = str_replace("%3A", ":", $string);
      return $string;
   }


问:
How to implement sessions and logout in a react+node web application?
I am creating a webapp using  nodejs backend and reactjs frontend with a mysql database, where each user has their own separate set of data.

I need to maintain sessions to identify users(for example, which user clicked the reset password button) whilst also implementing the logout feature (necessary).

I have read articles stating that logout with jwt defeats the purpose as it requires storing tokens on database.

I am confused whether to use cookies(way less secure) or jwt with database for maintaining sessions as I have never implemented this before.

答: One way to do this, I think, is to create jwt tokens, store them in cookies and then remove the cookie on logout, and hence not storing it in a database . I would still like to know other ways to do this.</p>


问:
xsd:dateTime to Java OffsetDateTime
In order to properly handle an xs:dateTime with JAXB, I have to write my own converter from String->java.time.OffsetDateTime.

As mentioned in the XML Schema Definition, dateTime was inspired by ISO 8601. I used OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME) to parse the xs:dateTime, which works fine for e.g.

```<code>"2007-12-03T10:15:30+01:00" //or
"2007-12-03T10:15:30Z"
</code>```

Sadly, in xs:dateTime the offset part is declared optional, so parsing the valid

```<code>"2016-03-02T17:09:55"
</code>```

throws an DateTimeParseException.

Is there a DateTimeFormatter for OffsetDateTime, which also handles unzoned xs:dateTimes (probably with a default timezone)?

答:
The jTextTime library solves this. This is a minimal no-dep library available from Maven Central. It handles the case of the missing timezone offset.

The library includes prebuild XmlAdapters so you can just annotate your classes with those as in the example below:

```<code>public class Customer {

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class)
    @XmlSchemaType(name="dateTime")
    public OffsetDateTime getLastOrderTime() {
        ....
    }

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateXmlAdapter.class)
    @XmlSchemaType(name="date")
    public OffsetDateTime getDateOfBirth() {   // returns a date-only value
        ....
    }
}
</code>```

Alternatively you can do the annotation at the package level so that you don't have to do it for every class and every attribute.

If you are unhappy with the library's default handling of the case of the missing timezone offset then you can customize.

Full disclosure: I'm the author of jTextTime.

ContentLicense: CC BY-SA 3.0

Title: xsd:dateTime to Java OffsetDateTime

Body:
In order to properly handle an xs:dateTime with JAXB, I have to write my own converter from String->java.time.OffsetDateTime.

As mentioned in the XML Schema Definition, dateTime was inspired by ISO 8601. I used OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME) to parse the xs:dateTime, which works fine for e.g.

"2007-12-03T10:15:30+01:00" //or
"2007-12-03T10:15:30Z"

Sadly, in xs:dateTime the offset part is declared optional, so parsing the valid

"2016-03-02T17:09:55"

throws an DateTimeParseException.

Is there a DateTimeFormatter for OffsetDateTime, which also handles unzoned xs:dateTimes (probably with a default timezone)?

Body:
The jTextTime library solves this. This is a minimal no-dep library available from Maven Central. It handles the case of the missing timezone offset.

The library includes prebuild XmlAdapters so you can just annotate your classes with those as in the example below:

public class Customer {

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class)
    @XmlSchemaType(name="dateTime")
    public OffsetDateTime getLastOrderTime() {
        ....
    }

    @XmlElement
    @XmlJavaTypeAdapter(OffsetDateXmlAdapter.class)
    @XmlSchemaType(name="date")
    public OffsetDateTime getDateOfBirth() {   // returns a date-only value
        ....
    }
}

Alternatively you can do the annotation at the package level so that you don't have to do it for every class and every attribute.

If you are unhappy with the library's default handling of the case of the missing timezone offset then you can customize.

Full disclosure: I'm the author of jTextTime.


问:
Getting row Count only returns value of 1
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

```<code>Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount
</code>```

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

```<code>Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult
</code>```

答:
Aren't you missing quotes around Unread?

Also... you're susceptible to SQL Injection. Use Parameters instead

Also... if all you are doing is getting the number of rows, your code is overkill

I just noticed.... you Dimmed comm2 but your adapter uses comm

Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.

You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that

```<code>Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = @param"
sql.Parameters.AddWithValue("@param", Session("sessionvariable"))

sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
</code>```

Body:
I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.

Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
    Dim sqlda2 As New SqlDataAdapter(comm2)
    Dim dt2 As New DataTable
    sqlda2.Fill(dt2)
    Dim recordcount As Integer = dt2.Rows.Count
    messagecountlbl.Text = recordcount

this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.

I have also tried the Select Count statement and it does the same thing.

Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.

Dim sqlresult As Object
    Dim constring As String = "Connection string goes here"
    Dim dbcon As SqlConnection = New SqlConnection(constring)
    Dim sql As New SqlCommand
    dbcon.Open()
    sql.Connection = dbcon
    sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
    sqlresult = sql.ExecuteScalar
    messagecountlbl.Text = sqlresult

Body:
Aren't you missing quotes around Unread?

Also... you're susceptible to SQL Injection. Use Parameters instead

Also... if all you are doing is getting the number of rows, your code is overkill

I just noticed.... you Dimmed comm2 but your adapter uses comm

Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.

You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that

Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = @param"
sql.Parameters.AddWithValue("@param", Session("sessionvariable"))

sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult


问:
How to get commit hash in git show-branch?

git show-branch branchX branchY
```

<p><strong>Output Format:</strong></p>

<pre class="lang-sh prettyprint-override"><code>+  [branchX~1] Commit Message Here
</code>```

This shows the relative count from the tip commit of branchX. Is there any way to include the corresponding commit hash (short or long) too? I referred the docs but was unable to find anything.

PS: I have many commits on the output list, so I don't prefer to check in logs one by one.

答:
You can use git for-each-ref and benefit from its formatting options, like this

```<code>git for-each-ref --format="[%(refname:short) %(upstream:track)] %(objectname:short) %(contents)" refs/heads/<branchName>
</code>```

Example output :

```<code>[master [ahead 1]] e1c8aad Commit message here
</code>```

This is for one branch <branchName>, but for the branches list in this format, just replace refs/heads/<branchName> with refs/heads/

Body:
git show-branch branchX branchY

Output Format:

+  [branchX~1] Commit Message Here

This shows the relative count from the tip commit of branchX. Is there any way to include the corresponding commit hash (short or long) too? I referred the docs but was unable to find anything.

PS: I have many commits on the output list, so I don't prefer to check in logs one by one.

Body:
You can use git for-each-ref and benefit from its formatting options, like this

git for-each-ref --format="[%(refname:short) %(upstream:track)] %(objectname:short) %(contents)" refs/heads/<branchName>

Example output :

[master [ahead 1]] e1c8aad Commit message here

This is for one branch <branchName>, but for the branches list in this format, just replace refs/heads/<branchName> with refs/heads/


问:
ValueError: invalid literal for int() with base 10: 'fee_code'
when I am running

```<code>python manage.py migrate
</code>```

it gives me an error

ValueError: invalid literal for int() with base 10: 'fee_code'

I am trying to migrate my code

```<code>from django.db import models
from django.utils import timezone
from students.models import gr_register, Classes, gardian

class fees_type(models.Model):
    fee_code = models.AutoField(primary_key=True)
    fee_type = models.CharField(max_length=255, default=1)

    def __str__(self):
        return str(self.fee_type)

class concession_type(models.Model):
    concession_code = models.AutoField(primary_key=True)
    concession_type = models.CharField(max_length=255, default=1)
    concession_percent = models.CharField(max_length=255, default=1)

    def __str__(self):
        return str(self.concession_type)

class fees_source(models.Model):
    source_code = models.AutoField(primary_key=True)
    source_name = models.CharField(max_length=255, default='source_name')

    def __str__(self):
        return str(self.source_name)

class class_fees(models.Model):
    class_code = models.ForeignKey(Classes, on_delete=models.CASCADE)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
    default='fee_code')
    fees_amount = models.BigIntegerField(default=1000)

    def __str__(self):
        return str(self.fees_amount)

class fee(models.Model):
    BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))

    Gr_num = models.ForeignKey(gr_register, on_delete=models.CASCADE,
     default=231)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
     default=1)
    fee_dues = models. BigIntegerField(default=1000)
    paid_source = models.ForeignKey(fees_source, on_delete=models.CASCADE,
    default=1)
    class_name = models.ForeignKey(Classes, on_delete=models.CASCADE,
    default=1)
    paid = models.BooleanField(choices=BOOL_CHOICES, default=1)
    guradian_code = models.ForeignKey(gardian , on_delete=models.CASCADE,
    default=1)
    due_date = models.DateField(default=timezone.now)
    paid_date = models.DateField(default=timezone.now)

    def __str__(self):
        return str(self.paid)
</code>```

urls.py

```<code>path('', views.index, name='index'),

path('feestype/', views.feestype, name='feestype'),
path('addfeestype/', views.addfeestype, name='addfeestype'),
path('editfeestype/<int:pk>/', views.editfeestype, name='editfeestype'),
path('deletefeestype/<int:pk>/', views.deletefeestype,
 name='deletefeestype'),

path('concessiontype/', views.concessiontype, name='concessiontype'),
path('addconcession/', views.addconcession, name='addconcession'),
path('editconcession/<int:pk>/', views.editconcession,
 name='editconcession'),
path('deleteconcession/<int:pk>/', views.deleteconcession,
  name='deleteconcession'),

path('feessource/', views.feessource, name='feessource'),
path('addfeessource/', views.addfeessource, name='addfeessource'),
path('editfeessource/<int:pk>/', views.editfeessource,
 name='editfeessource'),
path('deletefeessource/<int:pk>/', views.deletefeessource,
 name='deletefeessource'),

path('classfees/', views.classfees, name='classfees'),
path('addclassfees/', views.addclassfees, name='addclassfees'),
path('editclassfees/<int:pk>/', views.editclassfees,
 name='editclassfees'),
path('delclassfees/<int:pk>/', views.delclassfees, name='delclassfees'),

path('fees/', views.fees, name='fees'),
path('addfees/', views.addfees, name='addfees'),
path('editfees/<int:pk>/', views.editfees, name='editfees'),
</code>```

Error Trace:

Apply all migrations: admin, auth, contenttypes, fees, sessions,
  students Running migrations:   Applying fees.0001_initial...Traceback
  (most recent call last):   File "manage.py", line 15, in
      execute_from_command_line(sys.argv)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py",
  line 381, in execute_from_command_line
      utility.execute()   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py",
  line 375, in execute
      self.fetch_command(subcommand).run_from_argv(self.argv)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 323, in run_from_argv
      self.execute(*args, **cmd_options)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 364, in execute
      output = self.handle(*args, **options)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 83, in wrapped
      res = handle_func(*args, **kwargs)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\migrate.py",
  line 234, in handle
      fake_initial=fake_initial,   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 117, in migrate
      state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 147, in _migrate_all_forwards
      state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 245, in apply_migration
      state = migration.apply(state, schema_editor)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\migration.py",
  line 124, in apply
      operation.database_forwards(self.app_label, schema_editor, old_state, project_state)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\operations\fields.py",
  line 112, in database_forwards
      field,   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 433, in add_field
      definition, params = self.column_sql(model, field, include_default=True)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 161, in column_sql
      default_value = self.effective_default(field)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 233, in effective_default
      return field.get_db_prep_save(self._effective_default(field), self.connection)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py",
  line 937, in get_db_prep_save
      return self.target_field.get_db_prep_save(value, connection=connection)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 789, in get_db_prep_save
      return self.get_db_prep_value(value, connection=connection, prepared=False)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 957, in get_db_prep_value
      value = self.get_prep_value(value)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 966, in get_prep_value
      return int(value) ValueError: invalid literal for int() with base 10: 'fee_code'

答:
In this model

```<code>class class_fees(models.Model):
    class_code = models.ForeignKey(Classes, on_delete=models.CASCADE)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
    default='fee_code')
    fees_amount = models.BigIntegerField(default=1000)

    def __str__(self):
        return str(self.fees_amount)
</code>```

You are setting default='fee_code' on the fee_code foreign key field. As the error says, you can't use a string there, it expects an integer.

Body:
when I am running

python manage.py migrate

it gives me an error

ValueError: invalid literal for int() with base 10: 'fee_code'

I am trying to migrate my code

from django.db import models
from django.utils import timezone
from students.models import gr_register, Classes, gardian

class fees_type(models.Model):
    fee_code = models.AutoField(primary_key=True)
    fee_type = models.CharField(max_length=255, default=1)

    def __str__(self):
        return str(self.fee_type)

class concession_type(models.Model):
    concession_code = models.AutoField(primary_key=True)
    concession_type = models.CharField(max_length=255, default=1)
    concession_percent = models.CharField(max_length=255, default=1)

    def __str__(self):
        return str(self.concession_type)

class fees_source(models.Model):
    source_code = models.AutoField(primary_key=True)
    source_name = models.CharField(max_length=255, default='source_name')

    def __str__(self):
        return str(self.source_name)

class class_fees(models.Model):
    class_code = models.ForeignKey(Classes, on_delete=models.CASCADE)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
    default='fee_code')
    fees_amount = models.BigIntegerField(default=1000)

    def __str__(self):
        return str(self.fees_amount)

class fee(models.Model):
    BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))

    Gr_num = models.ForeignKey(gr_register, on_delete=models.CASCADE,
     default=231)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
     default=1)
    fee_dues = models. BigIntegerField(default=1000)
    paid_source = models.ForeignKey(fees_source, on_delete=models.CASCADE,
    default=1)
    class_name = models.ForeignKey(Classes, on_delete=models.CASCADE,
    default=1)
    paid = models.BooleanField(choices=BOOL_CHOICES, default=1)
    guradian_code = models.ForeignKey(gardian , on_delete=models.CASCADE,
    default=1)
    due_date = models.DateField(default=timezone.now)
    paid_date = models.DateField(default=timezone.now)

    def __str__(self):
        return str(self.paid)

urls.py

path('', views.index, name='index'),

path('feestype/', views.feestype, name='feestype'),
path('addfeestype/', views.addfeestype, name='addfeestype'),
path('editfeestype/<int:pk>/', views.editfeestype, name='editfeestype'),
path('deletefeestype/<int:pk>/', views.deletefeestype,
 name='deletefeestype'),

path('concessiontype/', views.concessiontype, name='concessiontype'),
path('addconcession/', views.addconcession, name='addconcession'),
path('editconcession/<int:pk>/', views.editconcession,
 name='editconcession'),
path('deleteconcession/<int:pk>/', views.deleteconcession,
  name='deleteconcession'),

path('feessource/', views.feessource, name='feessource'),
path('addfeessource/', views.addfeessource, name='addfeessource'),
path('editfeessource/<int:pk>/', views.editfeessource,
 name='editfeessource'),
path('deletefeessource/<int:pk>/', views.deletefeessource,
 name='deletefeessource'),

path('classfees/', views.classfees, name='classfees'),
path('addclassfees/', views.addclassfees, name='addclassfees'),
path('editclassfees/<int:pk>/', views.editclassfees,
 name='editclassfees'),
path('delclassfees/<int:pk>/', views.delclassfees, name='delclassfees'),

path('fees/', views.fees, name='fees'),
path('addfees/', views.addfees, name='addfees'),
path('editfees/<int:pk>/', views.editfees, name='editfees'),

Error Trace:

Apply all migrations: admin, auth, contenttypes, fees, sessions,
  students Running migrations:   Applying fees.0001_initial...Traceback
  (most recent call last):   File "manage.py", line 15, in
      execute_from_command_line(sys.argv)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py",
  line 381, in execute_from_command_line
      utility.execute()   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py",
  line 375, in execute
      self.fetch_command(subcommand).run_from_argv(self.argv)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 323, in run_from_argv
      self.execute(*args, **cmd_options)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 364, in execute
      output = self.handle(*args, **options)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py",
  line 83, in wrapped
      res = handle_func(*args, **kwargs)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\migrate.py",
  line 234, in handle
      fake_initial=fake_initial,   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 117, in migrate
      state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 147, in _migrate_all_forwards
      state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py",
  line 245, in apply_migration
      state = migration.apply(state, schema_editor)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\migration.py",
  line 124, in apply
      operation.database_forwards(self.app_label, schema_editor, old_state, project_state)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\operations\fields.py",
  line 112, in database_forwards
      field,   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 433, in add_field
      definition, params = self.column_sql(model, field, include_default=True)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 161, in column_sql
      default_value = self.effective_default(field)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py",
  line 233, in effective_default
      return field.get_db_prep_save(self._effective_default(field), self.connection)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py",
  line 937, in get_db_prep_save
      return self.target_field.get_db_prep_save(value, connection=connection)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 789, in get_db_prep_save
      return self.get_db_prep_value(value, connection=connection, prepared=False)   File
  "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 957, in get_db_prep_value
      value = self.get_prep_value(value)   File "C:\Users\Hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields__init__.py",
  line 966, in get_prep_value
      return int(value) ValueError: invalid literal for int() with base 10: 'fee_code'

Body:
In this model

class class_fees(models.Model):
    class_code = models.ForeignKey(Classes, on_delete=models.CASCADE)
    fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE,
    default='fee_code')
    fees_amount = models.BigIntegerField(default=1000)

    def __str__(self):
        return str(self.fees_amount)

You are setting default='fee_code' on the fee_code foreign key field. As the error says, you can't use a string there, it expects an integer.


问:
JavaScript naming conventions
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.

How do you name your variables, functions, objects and such?

I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.

The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.

答:
You can follow the Google JavaScript Style Guide.

In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

See a nice collection of JavaScript Style Guides And Beautifiers.

Title: JavaScript naming conventions


问:
How to identify blank `td` seperating each column in a table
I am scraping data from sec uoip_10k, Consolidated Balance Sheets table. Each column is separated by 1 or twotd with blank data. Is there a way to identify those blanks tds.

currently , what i am doing is a below.

```<code>def check_if_cell_seperator(cell):
    if 'width' in str(cell):
        width = int(cell["width"].strip('%').strip())
        if width < 2 and cell.text.strip() == '':
            return True
        else:
            return False
    else:
        return False

def main(url):
    htmlpage = urllib.request.urlopen(url)
    page = BeautifulSoup(htmlpage, "html.parser")
    all_divtables = page.find_all('table')
    # only taking data from 38th table
    for i,table in enumerate(all_divtables[38:39]):
        rows = table.find_all(['th', 'td'],recursive=False)
        table_data = []
        for tr in rows:
            row_data=[]
            cells = tr.find_all('td')
            for cell in cells:
                if check_if_cell_seperator(cell):
                    continue
                else:
                    cell_data = cell.text
                row_data.append(cell_data.encode('utf-8'))
        table_data.append([x.decode('utf-8').strip() for x in row_data])
    print(table_data)
</code>```

But the issue here is scraping data from rows where cell width is not specified (e.g.: heading rows).

Is there any way i can identify and delete td which are there only to separate columns.

cannot delete  all the blanks from my final list as it will affect indentation.

Example

```<code>    <tr>
    <td valign="bottom" style="PADDING-BOTTOM: 2px"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt">  </font></td>
    <td valign="bottom" style="PADDING-BOTTOM: 2px"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt; FONT-WEIGHT: bold"> </font></td>
    <td colspan="2" valign="bottom" style="BORDER-BOTTOM: black 2px solid">
        <div style="TEXT-INDENT: 0pt; DISPLAY: block; MARGIN-LEFT: 0pt; MARGIN-RIGHT: 0pt" align="center"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt; FONT-WEIGHT: bold">2015</font></div>
    </td>
    <td nowrap="" valign="bottom" style="TEXT-ALIGN: left; PADDING-BOTTOM: 2px"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt; FONT-WEIGHT: bold"> </font></td>
    <td valign="bottom" style="PADDING-BOTTOM: 2px"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt; FONT-WEIGHT: bold"> </font></td>
    <td colspan="2" valign="bottom" style="BORDER-BOTTOM: black 2px solid">
        <div style="TEXT-INDENT: 0pt; DISPLAY: block; MARGIN-LEFT: 0pt; MARGIN-RIGHT: 0pt" align="center"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 8pt; FONT-WEIGHT: bold">2014</font></div>
    </td>
    <td nowrap="" valign="bottom" style="TEXT-ALIGN: left; PADDING-BOTTOM: 2px"><font style="DISPLAY: inline; FONT-FAMILY: times new roman; FONT-SIZE: 10pt; FONT-WEIGHT: bold"> </font></td>
    </tr>
</code>```

in the above example tds 2,4,5 are blanks tds only for separating columns.

please help.

答:
The code below (tested under python 3.6) skips empty cells and empty rows. It also skips table headers.

You can remove the debug print if the code work for you.

```<code>import requests

from bs4 import BeautifulSoup

def main(url):
    def _is_separator_cell(cell):
        width = cell.attrs.get('width', None)
        if width:
            _width = int(cell.attrs.get('width')[:-1])
            return _width <= 2
        else:
            return False

    htmlpage = requests.get(url).content
    page = BeautifulSoup(htmlpage, "html.parser")
    all_divtables = page.find_all('table')
    # only taking data from 38th table
    for i, table in enumerate(all_divtables[38:39]):
        rows = table.find_all('tr', recursive=False)
        table_data = []
        for r, tr in enumerate(rows):
            row_data = []
            print('DBG {}.'.format(r))
            cells = tr.find_all('td')
            is_header = len(cells) < 8
            for c, cell in enumerate(cells):
                data = cell.text.strip()
                separator_cell = _is_separator_cell(cell)
                print('\tDBG {}. [{}] (width: {})'.format(c, data, cell.attrs.get('width')))
                if data or (not separator_cell and not is_header):
                    row_data.append(data)
            if row_data:
                table_data.append(row_data)
    return table_data

table_data = main('https://www.sec.gov/Archives/edgar/data/1097718/000135448815004617/uoip_10k.htm')
print('results:')
for row in table_data:
    print(row)
</code>```

results:

```<code>['June 30,', 'June 30,']
['2015', '2014']
['Assets']
['Current Assets:']
['Cash', '$', '21,745', '$', '56,827']
['Accounts receivable, net', '19,945', '84,091']
['Inventory', '-', '19,069']
['Prepaid expenses', '66,543', '136,927']
['Marketable securities', '2', '3']
['Other current assets', '10,208', '51,708']
['Total Current Assets', '118,443', '348,625']
['', '', '']
['Property and equipment, net of accumulated depreciation of $1,140,249 and\xa0\xa0$939,408 respectively', '51,462', '451,843']
['Deposits', '5,923', '5,923']
['Other assets', '1,545', '1,545']
['Total Assets', '$', '177,373', '$', '807,936']
['', '', '']
["Liabilities and Stockholders' Deficit", '', '']
['Current Liabilities:', '', '']
['Accounts payable and accrued liabilities', '$', '1,043,088', '$', '840,009']
['Notes payable, current portion', '962,810', '472,017']
['Capital lease payable, current portion', '886,356', '660,458']
['Note payable, related party', '1,029,005', '479,578']
['Deferred revenue', '85,407', '74,824']
['Convertible notes payable, net of discount', '115,632', '197,645']
['Derivative liability - warrants', '83,766', '302,065']
['Derivative liability - embedded conversion option', '346,734', '469,632']
['Total Current Liabilities', '4,552,798', '3,496,228']
['', '', '']
['Capital lease payable, long term portion', '517,686', '1,143,501']
['Total Liabilities', '5,070,484', '4,639,729']
['', '', '']
['Commitments and Contingencies (Note 14)', '', '']
['', '', '']
["Stockholders' Deficit:", '', '']
['Series B convertible preferred stock ($.001 par value; 10,000,000 shares authorized; 626,667 shares issued and outstanding)', '626', '626']
['Series AA convertible preferred stock ($.001 par value; 10,000,000 shares authorized; 0 and 400,000 shares issued and outstanding, respectively)', '-', '400']
['Common stock ($.001 par value; 6,000,000,000 shares authorized; 912,466,204 and 1,742,940 shares issued and\xa0\xa0outstanding, respectively)', '912,466', '1,743']
['Additional paid in capital', '48,984,686', '49,075,659']
['Accumulated deficit', '(54,696,891', ')', '(52,816,224', ')']
['Accumulated other comprehensive loss', '(80,998', ')', '(80,997', ')']
['Treasury stock, at cost, (406 shares)', '(13,000', ')', '(13,000', ')']
["Total Stockholders' Deficit", '(4,893,111', ')', '(3,831,793', ')']
["Total Liabilities and Stockholders' Deficit", '$', '177,373', '$', '807,936']
</code>```

Body:
I am scraping data from sec uoip_10k, Consolidated Balance Sheets table. Each column is separated by 1 or twotd with blank data. Is there a way to identify those blanks tds.

currently , what i am doing is a below.

def check_if_cell_seperator(cell):
    if 'width' in str(cell):
        width = int(cell["width"].strip('%').strip())
        if width < 2 and cell.text.strip() == '':
            return True
        else:
            return False
    else:
        return False

def main(url):
    htmlpage = urllib.request.urlopen(url)
    page = BeautifulSoup(htmlpage, "html.parser")
    all_divtables = page.find_all('table')
    # only taking data from 38th table
    for i,table in enumerate(all_divtables[38:39]):
        rows = table.find_all(['th', 'td'],recursive=False)
        table_data = []
        for tr in rows:
            row_data=[]
            cells = tr.find_all('td')
            for cell in cells:
                if check_if_cell_seperator(cell):
                    continue
                else:
                    cell_data = cell.text
                row_data.append(cell_data.encode('utf-8'))
        table_data.append([x.decode('utf-8').strip() for x in row_data])
    print(table_data)

But the issue here is scraping data from rows where cell width is not specified (e.g.: heading rows).

Is there any way i can identify and delete td which are there only to separate columns.

cannot delete  all the blanks from my final list as it will affect indentation.

Example

2015

2014

in the above example tds 2,4,5 are blanks tds only for separating columns.

please help.

Body:
The code below (tested under python 3.6) skips empty cells and empty rows. It also skips table headers.

You can remove the debug print if the code work for you.

import requests

from bs4 import BeautifulSoup

def main(url):
    def _is_separator_cell(cell):
        width = cell.attrs.get('width', None)
        if width:
            _width = int(cell.attrs.get('width')[:-1])
            return _width <= 2
        else:
            return False

    htmlpage = requests.get(url).content
    page = BeautifulSoup(htmlpage, "html.parser")
    all_divtables = page.find_all('table')
    # only taking data from 38th table
    for i, table in enumerate(all_divtables[38:39]):
        rows = table.find_all('tr', recursive=False)
        table_data = []
        for r, tr in enumerate(rows):
            row_data = []
            print('DBG {}.'.format(r))
            cells = tr.find_all('td')
            is_header = len(cells) < 8
            for c, cell in enumerate(cells):
                data = cell.text.strip()
                separator_cell = _is_separator_cell(cell)
                print('\tDBG {}. [{}] (width: {})'.format(c, data, cell.attrs.get('width')))
                if data or (not separator_cell and not is_header):
                    row_data.append(data)
            if row_data:
                table_data.append(row_data)
    return table_data

table_data = main('https://www.sec.gov/Archives/edgar/data/1097718/000135448815004617/uoip_10k.htm')
print('results:')
for row in table_data:
    print(row)

results:

['June 30,', 'June 30,']
['2015', '2014']
['Assets']
['Current Assets:']
['Cash', '$', '21,745', '$', '56,827']
['Accounts receivable, net', '19,945', '84,091']
['Inventory', '-', '19,069']
['Prepaid expenses', '66,543', '136,927']
['Marketable securities', '2', '3']
['Other current assets', '10,208', '51,708']
['Total Current Assets', '118,443', '348,625']
['', '', '']
['Property and equipment, net of accumulated depreciation of $1,140,249 and\xa0\xa0$939,408 respectively', '51,462', '451,843']
['Deposits', '5,923', '5,923']
['Other assets', '1,545', '1,545']
['Total Assets', '$', '177,373', '$', '807,936']
['', '', '']
["Liabilities and Stockholders' Deficit", '', '']
['Current Liabilities:', '', '']
['Accounts payable and accrued liabilities', '$', '1,043,088', '$', '840,009']
['Notes payable, current portion', '962,810', '472,017']
['Capital lease payable, current portion', '886,356', '660,458']
['Note payable, related party', '1,029,005', '479,578']
['Deferred revenue', '85,407', '74,824']
['Convertible notes payable, net of discount', '115,632', '197,645']
['Derivative liability - warrants', '83,766', '302,065']
['Derivative liability - embedded conversion option', '346,734', '469,632']
['Total Current Liabilities', '4,552,798', '3,496,228']
['', '', '']
['Capital lease payable, long term portion', '517,686', '1,143,501']
['Total Liabilities', '5,070,484', '4,639,729']
['', '', '']
['Commitments and Contingencies (Note 14)', '', '']
['', '', '']
["Stockholders' Deficit:", '', '']
['Series B convertible preferred stock ($.001 par value; 10,000,000 shares authorized; 626,667 shares issued and outstanding)', '626', '626']
['Series AA convertible preferred stock ($.001 par value; 10,000,000 shares authorized; 0 and 400,000 shares issued and outstanding, respectively)', '-', '400']
['Common stock ($.001 par value; 6,000,000,000 shares authorized; 912,466,204 and 1,742,940 shares issued and\xa0\xa0outstanding, respectively)', '912,466', '1,743']
['Additional paid in capital', '48,984,686', '49,075,659']
['Accumulated deficit', '(54,696,891', ')', '(52,816,224', ')']
['Accumulated other comprehensive loss', '(80,998', ')', '(80,997', ')']
['Treasury stock, at cost, (406 shares)', '(13,000', ')', '(13,000', ')']
["Total Stockholders' Deficit", '(4,893,111', ')', '(3,831,793', ')']
["Total Liabilities and Stockholders' Deficit", '$', '177,373', '$', '807,936']


问:
Can you tell me what's wrong in the query I'm using to retrieve info on when a customer last placed an order?
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

```<code>left join orders o
on ocd.id = o.customer_details_id
</code>```

I've also tried using a left outer join, and the following join:

```<code>from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
</code>```

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

```<code> SELECT customer_id, MAX(order.id)
</code>```

and then grouped by customer_id, but to no avail.

Here's the entire code:

```<code>select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;
</code>```

答:
Try this-</p>

```<code>SELECT
customer_details_id customer_id,
MAX(o.id) AS id_of_last_order,
MAX(order_date) AS last_ordered,
TIMESTAMPDIFF(DAY, MAX(order_date), NOW()) AS days_since_last_ordered
FROM orders O
INNER JOIN orders_customers_details OCD
    ON O.customer_details_id = OCD.id
GROUP BY customer_details_id
ORDER BY customer_details_id;
</code>```

Body:
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

left join orders o
on ocd.id = o.customer_details_id

I've also tried using a left outer join, and the following join:

from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

 SELECT customer_id, MAX(order.id)

and then grouped by customer_id, but to no avail.

Here's the entire code:

select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;

Body:
Try this-

SELECT
customer_details_id customer_id,
MAX(o.id) AS id_of_last_order,
MAX(order_date) AS last_ordered,
TIMESTAMPDIFF(DAY, MAX(order_date), NOW()) AS days_since_last_ordered
FROM orders O
INNER JOIN orders_customers_details OCD
    ON O.customer_details_id = OCD.id
GROUP BY customer_details_id
ORDER BY customer_details_id;


问:
Image manipulation, theory, formulas and pseudo code
I'd like to know where read materials to learn how to manipulate image via code.
I just created a simple software to read any pixels from an image and i'm able to apply some simple code to modify it, for example i can create a gray scale image using this (pseudo)code:

```<code>foreach(pixel in image){
 red = pixel.r;
 green = pixel.g;
 blue = pixel.b;
 alpha = pixel.a;

 gray = (red + green + blue) / 3;

 pixel.r = gray;
 pixel.g = gray;
 pixel.b = gray;
}
</code>```

Do you know websites (or a books) where i can find any informations about image manipulation applied to software development ?

答: One good reference that starts with absolute basics and covers some interesting material is Digital Image Processing Algorithms and Applications By Ioannis Pitas</p>

Body:
I'd like to know where read materials to learn how to manipulate image via code.
I just created a simple software to read any pixels from an image and i'm able to apply some simple code to modify it, for example i can create a gray scale image using this (pseudo)code:

foreach(pixel in image){
 red = pixel.r;
 green = pixel.g;
 blue = pixel.b;
 alpha = pixel.a;

 gray = (red + green + blue) / 3;

 pixel.r = gray;
 pixel.g = gray;
 pixel.b = gray;
}

Do you know websites (or a books) where i can find any informations about image manipulation applied to software development ?


问:
Gson deserialization for a list in Kotlin
This is what my json looks like

```<code>{
  "sub": "9",

  "auth_time": 1559381757,
  "idp": "idsrv",

  "role": [
    "Employer",
    "Employee",
    "Student"
  ],

  "iss": "",
  "aud": "",
  "exp": 1574933757,
  "nbf": 1559381757
}
</code>```

This is the object I want to convert this Json into.

```<code>data class Claims (
    @SerializedName("nameid") val nameId: String,
    @SerializedName("unique_id") val uniqueId: String,
    @SerializedName("sub") val sub: String,
    @SerializedName("unifiedNumber") val unifiedNumber: String,
    @SerializedName("role") var roleList: List<Role>
)
</code>```

I wrote a custom Deserializer (which works in Java) for the List type

```<code>class RoleDeserializer : JsonDeserializer<List<Role>> {

    private var roleId = 0
    @Throws(JsonParseException::class)
    override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): MutableList<Role> {
        val resultList = ArrayList<Role>()
        if (json.isJsonArray) {
            for (e in json.asJsonArray) {
                resultList.add(Role(id = roleId++, name = e.asString))
            }
        } else if (json.isJsonObject) {
            resultList.add(Role(id = roleId++, name = json.asString))
        } else if (json.isJsonPrimitive) {
            if ((json as JsonPrimitive).isString)
                resultList.add(Role(id = roleId++, name = json.getAsString()))
        } else {
            throw RuntimeException("Unexpected JSON type: " + json.javaClass)
        }
        return resultList
    }
}
</code>```

This is how I register my type adapter

```<code>val listType: Type = object : TypeToken<List<Role>>() {}.type
        val gson = GsonBuilder().registerTypeAdapter(listType, RoleDeserializer()).create()
        val claims = gson.fromJson(stringJson, Claims::class.java)
</code>```

I still get a parse exception stating that

```<code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 161 path $.role[0]
</code>```

and my RoleDeserializer is never called. Am I doing something wrong while registering the type adapter?

答:
Try to replace

```<code>val listType: Type = object : TypeToken<List<Role>>() {}.type
</code>```

with

```<code>val listType: Type = object : TypeToken<MutableList<Role>>() {}.type
</code>```

Body:
This is what my json looks like

{
  "sub": "9",

  "auth_time": 1559381757,
  "idp": "idsrv",

  "role": [
    "Employer",
    "Employee",
    "Student"
  ],

  "iss": "",
  "aud": "",
  "exp": 1574933757,
  "nbf": 1559381757
}

This is the object I want to convert this Json into.

data class Claims (
    @SerializedName("nameid") val nameId: String,
    @SerializedName("unique_id") val uniqueId: String,
    @SerializedName("sub") val sub: String,
    @SerializedName("unifiedNumber") val unifiedNumber: String,
    @SerializedName("role") var roleList: List<Role>
)

I wrote a custom Deserializer (which works in Java) for the List type

class RoleDeserializer : JsonDeserializer<List<Role>> {

    private var roleId = 0
    @Throws(JsonParseException::class)
    override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): MutableList<Role> {
        val resultList = ArrayList<Role>()
        if (json.isJsonArray) {
            for (e in json.asJsonArray) {
                resultList.add(Role(id = roleId++, name = e.asString))
            }
        } else if (json.isJsonObject) {
            resultList.add(Role(id = roleId++, name = json.asString))
        } else if (json.isJsonPrimitive) {
            if ((json as JsonPrimitive).isString)
                resultList.add(Role(id = roleId++, name = json.getAsString()))
        } else {
            throw RuntimeException("Unexpected JSON type: " + json.javaClass)
        }
        return resultList
    }
}

This is how I register my type adapter

val listType: Type = object : TypeToken<List<Role>>() {}.type
        val gson = GsonBuilder().registerTypeAdapter(listType, RoleDeserializer()).create()
        val claims = gson.fromJson(stringJson, Claims::class.java)

I still get a parse exception stating that

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 161 path $.role[0]

and my RoleDeserializer is never called. Am I doing something wrong while registering the type adapter?

Body:
Try to replace

val listType: Type = object : TypeToken<List<Role>>() {}.type

with

val listType: Type = object : TypeToken<MutableList<Role>>() {}.type


问:
problems to get correct reuseIdentifier
I've created an extension for UITableView and want to get the correct reuseIdentifier at runtime, but I can't:

```<code>extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {

    let s = T.reuseIdentifier
</code>```

The variable "s" always contains "UITableViewCell" and not the name which I did specify within the storyboard.

答:
My way of handling this is as follows.

I create a protocol which declares a type as loadable from a nib:

```<code>//  MARK: Nib Loadable
public protocol NibLoadable {
    /// The name of the .xib file in which this view is defined.
    static var nibName: String { get }
}
//  MARK: Nib Loadable Convenience
public extension NibLoadable where Self: UIView {
    static var nibName: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}
</code>```

I create another type which declares a type as reusable and automatically conform table and collection view cells:

```<code>//  MARK: Reusable View
/**
Indicates that a view can be reused provided it matches a provided identifier.
*/
public protocol ReusableView: class {
    /// The identifier for this type of reusable view.
    static var defaultReuseIdentifier: String { get }
}
//  MARK: Reusable View Convenience
public extension ReusableView where Self: UIView {
    static var defaultReuseIdentifier: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}
extension UICollectionViewCell: ReusableView { }
extension UITableViewCell: ReusableView { }
</code>```

I then create an easy means with which to register such a cell:

```<code>//  MARK: Registration
public extension UICollectionView {
    func register<T: UICollectionViewCell>(_: T.Type) {
        register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
    }
    func register<T: UICollectionViewCell>(_: T.Type) where T: NibLoadable {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
    }
}
public extension UITableView {
    func register<T: UITableViewCell>(_: T.Type) {
        register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
    func register<T: UITableViewCell>(_: T.Type) where T: NibLoadable {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
}
</code>```

Finally I have a convenient way of dequeuing these cells:

```<code>//  MARK: Dequeuing
public extension UICollectionView {
    func dequeue<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
        guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
        }
        return cell
    }
}
public extension UITableView {
    func dequeue<T: UITableViewCell>(for indexPath: IndexPath) -> T {
        guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
        }
        return cell
    }
}
</code>```

In use the app I make the reuse identifier for any cell its class name. I then conform the cell like so:

```<code>extension PersonalDetailTableViewCell: NibLoadable { }
</code>```

The owner of the table view will register the cell within viewDidLoad():

```<code>tableView.register(PersonalDetailTableViewCell.self)
</code>```

Within the cellForRow function I'll dequeue appropriately:

```<code>let cell: PersonalDetailTableViewCell = tableView.dequeue(for: indexPath)
</code>```

I have made this available in a gist here.

Title: problems to get correct reuseIdentifier

Body:
I've created an extension for UITableView and want to get the correct reuseIdentifier at runtime, but I can't:

extension UITableView {

func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {

    let s = T.reuseIdentifier

The variable "s" always contains "UITableViewCell" and not the name which I did specify within the storyboard.

Body:
My way of handling this is as follows.

I create a protocol which declares a type as loadable from a nib:

//  MARK: Nib Loadable
public protocol NibLoadable {
    /// The name of the .xib file in which this view is defined.
    static var nibName: String { get }
}
//  MARK: Nib Loadable Convenience
public extension NibLoadable where Self: UIView {
    static var nibName: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}

I create another type which declares a type as reusable and automatically conform table and collection view cells:

//  MARK: Reusable View
/**
Indicates that a view can be reused provided it matches a provided identifier.
*/
public protocol ReusableView: class {
    /// The identifier for this type of reusable view.
    static var defaultReuseIdentifier: String { get }
}
//  MARK: Reusable View Convenience
public extension ReusableView where Self: UIView {
    static var defaultReuseIdentifier: String { return NSStringFromClass(self).components(separatedBy: ".").last! }
}
extension UICollectionViewCell: ReusableView { }
extension UITableViewCell: ReusableView { }

I then create an easy means with which to register such a cell:

//  MARK: Registration
public extension UICollectionView {
    func register<T: UICollectionViewCell>(_: T.Type) {
        register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
    }
    func register<T: UICollectionViewCell>(_: T.Type) where T: NibLoadable {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
    }
}
public extension UITableView {
    func register<T: UITableViewCell>(_: T.Type) {
        register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
    func register<T: UITableViewCell>(_: T.Type) where T: NibLoadable {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
}

Finally I have a convenient way of dequeuing these cells:

//  MARK: Dequeuing
public extension UICollectionView {
    func dequeue<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
        guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
        }
        return cell
    }
}
public extension UITableView {
    func dequeue<T: UITableViewCell>(for indexPath: IndexPath) -> T {
        guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
        }
        return cell
    }
}

In use the app I make the reuse identifier for any cell its class name. I then conform the cell like so:

extension PersonalDetailTableViewCell: NibLoadable { }

The owner of the table view will register the cell within viewDidLoad():

tableView.register(PersonalDetailTableViewCell.self)

Within the cellForRow function I'll dequeue appropriately:

let cell: PersonalDetailTableViewCell = tableView.dequeue(for: indexPath)

I have made this available in a gist here.


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
It appears that your attempt appears testing the value that comes to argument  "int j".
The checking should fit in with a try catch,

```<code>try
{
   // take a object as argument and try parse it to an int here
   // or a TryParse will return a true/false if bool can return without exception.
   int something = int.Parse(j);
}
catch (TestOnJThatcanThrowOutOfMemoryException e)
{
   return true;
}
catch (OutOfMemoryException e)
{
    // this will be hit if it isn't a TestOnJ.. exception
    return false;
}
catch
{
    // and here if not any of above
    return false;
}
</code>```

Though, i'm not sure if I ever would create a method which purpose would be just to force a specific kind of exception. Sorry if missunderstand you completely,

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}

Body:
It appears that your attempt appears testing the value that comes to argument  "int j".
The checking should fit in with a try catch,

try
{
   // take a object as argument and try parse it to an int here
   // or a TryParse will return a true/false if bool can return without exception.
   int something = int.Parse(j);
}
catch (TestOnJThatcanThrowOutOfMemoryException e)
{
   return true;
}
catch (OutOfMemoryException e)
{
    // this will be hit if it isn't a TestOnJ.. exception
    return false;
}
catch
{
    // and here if not any of above
    return false;
}

Though, i'm not sure if I ever would create a method which purpose would be just to force a specific kind of exception. Sorry if missunderstand you completely,


答:
The role is String array in JSON

Use this

```<code>@SerializedName("role") var roleList: List<String>
</code>```

Instead of this

```<code>@SerializedName("role") var roleList: List<Role>
</code>```

Try this

```<code>data class Claims (
    @SerializedName("nameid") val nameId: String,
    @SerializedName("unique_id") val uniqueId: String,
    @SerializedName("sub") val sub: String,
    @SerializedName("unifiedNumber") val unifiedNumber: String,
    @SerializedName("role") var roleList: List<String>
)
</code>```

Title: Gson deserialization for a list in Kotlin

Body:
The role is String array in JSON

Use this

@SerializedName("role") var roleList: List<String>

Instead of this

@SerializedName("role") var roleList: List<Role>

Try this

data class Claims (
    @SerializedName("nameid") val nameId: String,
    @SerializedName("unique_id") val uniqueId: String,
    @SerializedName("sub") val sub: String,
    @SerializedName("unifiedNumber") val unifiedNumber: String,
    @SerializedName("role") var roleList: List<String>
)


问:
How to fire an wx.EVT_CLOSE from an inner panel
I'm building a wxPython application.
The main frame includes a main panel.
The main panel include other panels.
In one of those panels there is an "Exit" button.
I want the application to close when I press the "Exit" button.
For that, I require to fire a wx.EVT_CLOSE to the main frame of the application. How do I fire that event?
Any other ideas are most welcome too.
Thanks in advance.

I'm adding the example below to show the case:

```<code>    import wx

    class MainScene(wx.Frame):

        def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

       def InitUI(self):
       # Define Master Panel
           masterPanel = wx.Panel(self)
           masterPanel.SetBackgroundColour("gold")
           horzbox = wx.BoxSizer(wx.HORIZONTAL)
          subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    class SubPanel(wx.Panel):
       def __init__(self, parent, size):
           wx.Panel.__init__(self, parent, size=size)
           self.SetBackgroundColour("gray")
           vbox = wx.BoxSizer(wx.VERTICAL)
           exit_button = wx.Button(self, label="Exit")
           exit_button.Bind(wx.EVT_BUTTON, self.onClose)
           vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
           self.SetSizer(vbox)

       def onClose(self, event):
           self.Destroy()

    def main():
       app = wx.App()
       mainFrame = MainScene(None, title='Melanoma Buster')
       mainFrame.Show()
       app.MainLoop()

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

enter image description here

And this is after the click on the Exit button:

enter image description here

答:
Why not use Destroy?

An object example in why your code sample is important, when asking a question.

You can still use Destroy but simply specify what is to be destroyed.

Because you have specified that SubPanel has the parent masterPanel the object to be destroyed is self.GrandParent. However, if you made the parent of SubPanel self, then you could use self.Parent.Destroy().

```<code>import wx

class MainScene(wx.Frame):

    def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

    def InitUI(self):
    # Define Master Panel
        masterPanel = wx.Panel(self)
        masterPanel.SetBackgroundColour("gold")
        horzbox = wx.BoxSizer(wx.HORIZONTAL)
        subPanel=SubPanel(parent=masterPanel, size=(200, 200))

class SubPanel(wx.Panel):
    def __init__(self, parent, size):
        wx.Panel.__init__(self, parent, size=size)
        self.SetBackgroundColour("gray")
        vbox = wx.BoxSizer(wx.VERTICAL)
        exit_button = wx.Button(self, label="Exit")
        exit_button.Bind(wx.EVT_BUTTON, self.onClose)
        vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
        self.SetSizer(vbox)

    def onClose(self, event):
        self.Close()
        self.GrandParent.Destroy()

def main():
    app = wx.App()
    mainFrame = MainScene(None, title='Melanoma Buster')
    mainFrame.Show()
    app.MainLoop()

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

Body:
I'm building a wxPython application.
The main frame includes a main panel.
The main panel include other panels.
In one of those panels there is an "Exit" button.
I want the application to close when I press the "Exit" button.
For that, I require to fire a wx.EVT_CLOSE to the main frame of the application. How do I fire that event?
Any other ideas are most welcome too.
Thanks in advance.

I'm adding the example below to show the case:

    import wx

    class MainScene(wx.Frame):

        def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

       def InitUI(self):
       # Define Master Panel
           masterPanel = wx.Panel(self)
           masterPanel.SetBackgroundColour("gold")
           horzbox = wx.BoxSizer(wx.HORIZONTAL)
          subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    class SubPanel(wx.Panel):
       def __init__(self, parent, size):
           wx.Panel.__init__(self, parent, size=size)
           self.SetBackgroundColour("gray")
           vbox = wx.BoxSizer(wx.VERTICAL)
           exit_button = wx.Button(self, label="Exit")
           exit_button.Bind(wx.EVT_BUTTON, self.onClose)
           vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
           self.SetSizer(vbox)

       def onClose(self, event):
           self.Destroy()

    def main():
       app = wx.App()
       mainFrame = MainScene(None, title='Melanoma Buster')
       mainFrame.Show()
       app.MainLoop()

    if __name__ == '__main__':
       main()

enter image description here

And this is after the click on the Exit button:

enter image description here

Body:
Why not use Destroy?

An object example in why your code sample is important, when asking a question.

You can still use Destroy but simply specify what is to be destroyed.

Because you have specified that SubPanel has the parent masterPanel the object to be destroyed is self.GrandParent. However, if you made the parent of SubPanel self, then you could use self.Parent.Destroy().

import wx

class MainScene(wx.Frame):

    def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

    def InitUI(self):
    # Define Master Panel
        masterPanel = wx.Panel(self)
        masterPanel.SetBackgroundColour("gold")
        horzbox = wx.BoxSizer(wx.HORIZONTAL)
        subPanel=SubPanel(parent=masterPanel, size=(200, 200))

class SubPanel(wx.Panel):
    def __init__(self, parent, size):
        wx.Panel.__init__(self, parent, size=size)
        self.SetBackgroundColour("gray")
        vbox = wx.BoxSizer(wx.VERTICAL)
        exit_button = wx.Button(self, label="Exit")
        exit_button.Bind(wx.EVT_BUTTON, self.onClose)
        vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
        self.SetSizer(vbox)

    def onClose(self, event):
        self.Close()
        self.GrandParent.Destroy()

def main():
    app = wx.App()
    mainFrame = MainScene(None, title='Melanoma Buster')
    mainFrame.Show()
    app.MainLoop()

if __name__ == '__main__':
   main()


问:
How can I create a Network class in swift that will handle all my database firestore operations & can be called from any view controller?
I'm creating an event/venue management app & I want to create a Networking layer to interact with my firestore with various operations so as to reduce the amount of code & redundancy in my app</p>

答:
You can look into Singleton design pattern to have shared instance for these operations. You would define it like so:

```<code>class Firestore {
  static let shared = Firestore()

  func loadEvents() -> [Event] {
   ....
  }
}
</code>```

And usage:

```<code>Firestore.shared.loadEvents()
</code>```

However be careful with Singletons as they can quickly become “solution” to every problem you will encounter... In this case I think it can be a good option.

Body:
You can look into Singleton design pattern to have shared instance for these operations. You would define it like so:

class Firestore {
  static let shared = Firestore()

  func loadEvents() -> [Event] {
   ....
  }
}

And usage:

Firestore.shared.loadEvents()

However be careful with Singletons as they can quickly become “solution” to every problem you will encounter... In this case I think it can be a good option.


问:
Getting data from a range of values in jquery
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

```<code><form id="shoe_size">
    <label for="size">Enter sizes</label>
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>
</code>```

my jquery

```<code>$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});
</code>```

答:
Ok, I am recreating your problem and solving it (Because your question is not clear | please give me your table and I will try to code according to it. Till then I am using an example table)
Let's you have a table like this.

table to search

```<code><table>
  <tr size="10" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="11" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="12" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="13" >
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="14" >
    <td>...</td>
    <td>...</td>
  </tr>
</table>
</code>```

Let's user has submitted your form to get between
any size range

Jquery

```<code>$('#shoe_size').on('submit', function(){
  var size1 = $('.size1').val();
  var size2 = $('.size2').val();

  $("table tr").each(function(){
     var tr_size = $(this).attr("size");
     if(tr_size >= size1 && tr_size <= size2){
         $(this).show();
     }else{
         $(this).hide();
     }
  });
});
</code>```

Body:
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

<form id="shoe_size">
    Enter sizes
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>

my jquery

$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});

Body:
Ok, I am recreating your problem and solving it (Because your question is not clear | please give me your table and I will try to code according to it. Till then I am using an example table)
Let's you have a table like this.

table to search

<table>
  <tr size="10" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="11" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="12" >
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="13" >
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>
  <tr size="14" >
    <td>...</td>
    <td>...</td>
  </tr>
</table>

Let's user has submitted your form to get between
any size range

Jquery

$('#shoe_size').on('submit', function(){
  var size1 = $('.size1').val();
  var size2 = $('.size2').val();

  $("table tr").each(function(){
     var tr_size = $(this).attr("size");
     if(tr_size >= size1 && tr_size <= size2){
         $(this).show();
     }else{
         $(this).hide();
     }
  });
});


问:
How to add Icon to Pyinstaller in Windows 10
I modified the spec file to include the icon but every time I generate the exe, the system is throwing this error:

```<code>2105 INFO: Writing RT_ICON 1 resource with 40 bytes
Traceback (most recent call last):
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\pywin32\pywintypes.py", line 35, in pywin32error
    yield
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\pywin32\win32api.py", line 269, in UpdateResource
    handle, type, name, language, lp_data, len(lp_data))
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_resource.py", line 134, in _UpdateResource
    function_name='UpdateResource')
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_util.py", line 81, in __call__
    self._raise_error(function_name)
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_util.py", line 92, in _raise_error
    raise exception
OSError: [WinError 87] The parameter is incorrect
</code>```

I tried generating the exe file directly from pyinstaller using --onefile and also from .spec file.

block_cipher = None

Add the ico to exe file

答:
According to docs:

-i , --icon       FILE.ico: apply that icon to a Windows
  executable. FILE.exe,ID, extract the icon with ID from an exe.
  FILE.icns: apply the icon to the .app bundle on Mac OS X

So you need to use:

pyinstaller -F --icon "youricon.ico" "yourscript.py"

Body:
I modified the spec file to include the icon but every time I generate the exe, the system is throwing this error:

2105 INFO: Writing RT_ICON 1 resource with 40 bytes
Traceback (most recent call last):
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\pywin32\pywintypes.py", line 35, in pywin32error
    yield
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\pywin32\win32api.py", line 269, in UpdateResource
    handle, type, name, language, lp_data, len(lp_data))
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_resource.py", line 134, in _UpdateResource
    function_name='UpdateResource')
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_util.py", line 81, in __call__
    self._raise_error(function_name)
  File "c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\win32ctypes\core\cffi\_util.py", line 92, in _raise_error
    raise exception
OSError: [WinError 87] The parameter is incorrect

I tried generating the exe file directly from pyinstaller using --onefile and also from .spec file.

block_cipher = None

Add the ico to exe file


问:
Windows Azure Hello World sample fails: Start role failed for one or more roles
I can't run the Windows Azure Hello World sample. It gives me the following error:

"Start role failed for one or more roles".

I put the project in the root of my D drive to be sure that path length is not an issue. I also cleared the Azure temp folder.

I am using the newly released version 1.4 of the SDK.

答:
One common cause of this problem is that the development fabric (also known as "compute emulator") isn't running as Administrator on the local machine.  If you manually start the compute fabric, this may be the reason.  If you start the compute emulator from Visual Studio (e.g. by pressing F5), it will start the compute emulator running as administrator provided the VS instance is running as Administrator (you have to right click VS in the Start menu and select "Run As Administrator" to run it that way).

Another cause is that the web role is the startup project rather than the Azure service.  The Azure service (the one with the .cscfg under it) has to be the startup project (right click on it and select "Set as Startup Project").

ContentLicense: CC BY-SA 2.5


问:
Sum the number equivalent of alphabets in a word until it's single digit?
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.

So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.

var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.trim();
someText = someText.match(/\S/g);

var result = "";
for (i = 0; i < someText.length; i++) {
  result += values[someText[i]];
}

alert(result);```

For Example if input is "action" then numeric values will be
 =>1.3.20.9.15.14.
-Add these values together.
   1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
   e.g 62 = 6+2= 8.

Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.

答:
You can use reduce() to get the sum of all the digits of string. If the result is single digit then return the the number otherwise call the function recursively.

You also don't need to hard code the object with letter values. Just use reduce() and chatCodeAt to make a string of numbers.

var someText = prompt('').trim().toLowerCase().match(/\S/g)

let result = someText.reduce((ac,a) => ac + (a.charCodeAt(0) - 96),'');
function findSum(num){
  if(num.length === 1) return num;
  else return findSum(String(num.split('').reduce((ac,a) => ac + +a,0)))
}

console.log(findSum(result))```

Body:
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.

So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.

var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.trim();
someText = someText.match(/\S/g);

var result = "";
for (i = 0; i < someText.length; i++) {
  result += values[someText[i]];
}

alert(result);

For Example if input is "action" then numeric values will be
 =>1.3.20.9.15.14.
-Add these values together.
   1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
   e.g 62 = 6+2= 8.

Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.


问:
Multiple Sidebars or overlap of sidebar
In google sheets, when we click on Format->Conditional Formatting, a sidebar opens. Now click on Format->Alternating colors, another sidebar opens and it actually is on top of the earlier sidebar. when we close the "Alternating colors" sidebar, the "Conditional format rules" sidebar is still there.

From apps script, when we open a sidebar using SpreadsheetApp.getUi().showSidebar() and then try to open a second sidebar, the first sidebar is closed.

How can I replicate the behavior as seen in google sheets? i.e when I create 2 sidebar's both should exist unless I explicitly close it.

答: Perhaps the answer is to ask Google if multiple sidebars can be made the default. There needs to be a reason. Mine is that, given that a TBA interface can "work" Google sheets from JSON records, it will also be able to "work" all different types of multimedia (like 3D animation), if there were sidebars to properly accommodate them. Moreover, because JSON records can be individually stored at sites like myjson.com, multiple records can be combined and controlled by TBA to support collaborative work.</p>

Title: Multiple Sidebars or overlap of sidebar


问:
How to fix "DOMException" error in Web Bluetooth API?
I'm setting up a Bluetooth LE GATT Server in Android, and want to use Web Bluetooth API in Chrome as a GATT client to check if it properly works. Actually, this is my first step to build a FIDO Authenticator in Android later on.

Firstly, I tried to set my service's uuid is 0000fffd-0000-1000-8000-00805f9b34fb in my Android app. Something like this:

// start gatt server

bluetoothGattServer = bluetoothManager.openGattServer(this, callback);
bluetoothGattServer.addService(
new BluetoothGattService(UUID.fromString("0000fffd-0000-1000-8000-00805f9b34fb"),
BluetoothGattService.SERVICE_TYPE_PRIMARY));

// start advertising
// ...
```

<p>Then, I executed the following Javascript code in Chrome to check whether the connection can be established.</p>

```navigator.bluetooth.requestDevice({
filters: [{ services: ['0000fffd-0000-1000-8000-00805f9b34fb'] }] })
.then(device => { console.log(device); })
.catch(error => { console.log(error); });
```

<p>However, I only got the exception as below</p>

```DOMException
```

When I changed the uuid to another one such as 62893031-5e68-4a71-94e4-01fb81f16818 in my Android code, then it worked! (I mean it was able to connect to my phone and I could see my device info in Chrome's console)

I didn't know what exactly the problem. What was the problem with my former uuid? How can I debug it to know the root cause?

Thank you for checking!

答:
You can try

```<code>console.log(error.messsage);
</code>```

in stead of

```<code>console.log(error);
</code>```

You will see

requestDevice() called with a filter containing a blocklisted UUID.
  https://webbluetoothcg.github.io/web-bluetooth/#attacks-on-devices

Check it out to see the security reason.

Body:
I'm setting up a Bluetooth LE GATT Server in Android, and want to use Web Bluetooth API in Chrome as a GATT client to check if it properly works. Actually, this is my first step to build a FIDO Authenticator in Android later on.

Firstly, I tried to set my service's uuid is 0000fffd-0000-1000-8000-00805f9b34fb in my Android app. Something like this:

// start gatt server

bluetoothGattServer = bluetoothManager.openGattServer(this, callback);
bluetoothGattServer.addService(
new BluetoothGattService(UUID.fromString("0000fffd-0000-1000-8000-00805f9b34fb"),
BluetoothGattService.SERVICE_TYPE_PRIMARY));

// start advertising
// ...

Then, I executed the following Javascript code in Chrome to check whether the connection can be established.

navigator.bluetooth.requestDevice({
filters: [{ services: ['0000fffd-0000-1000-8000-00805f9b34fb'] }] })
.then(device => { console.log(device); })
.catch(error => { console.log(error); });

However, I only got the exception as below

DOMException

When I changed the uuid to another one such as 62893031-5e68-4a71-94e4-01fb81f16818 in my Android code, then it worked! (I mean it was able to connect to my phone and I could see my device info in Chrome's console)

I didn't know what exactly the problem. What was the problem with my former uuid? How can I debug it to know the root cause?

Thank you for checking!

Body:
You can try

console.log(error.messsage);

in stead of

console.log(error);

You will see

requestDevice() called with a filter containing a blocklisted UUID.
  https://webbluetoothcg.github.io/web-bluetooth/#attacks-on-devices

Check it out to see the security reason.


问:
How to get commit hash in git show-branch?

git show-branch branchX branchY
```

<p><strong>Output Format:</strong></p>

<pre class="lang-sh prettyprint-override"><code>+  [branchX~1] Commit Message Here
</code>```

This shows the relative count from the tip commit of branchX. Is there any way to include the corresponding commit hash (short or long) too? I referred the docs but was unable to find anything.

PS: I have many commits on the output list, so I don't prefer to check in logs one by one.

答:
Found it in the docs link itself which has been mentioned.

--sha1-name does the trick.

Sol:

git show-branch --sha1-name branchX branchY
```

<p><strong>Output</strong>:</p>

<pre class="lang-sh prettyprint-override"><code>+  [COMMIT-HASH] Commit Message Here
</code>```

Body:
git show-branch branchX branchY

Output Format:

+  [branchX~1] Commit Message Here

This shows the relative count from the tip commit of branchX. Is there any way to include the corresponding commit hash (short or long) too? I referred the docs but was unable to find anything.

PS: I have many commits on the output list, so I don't prefer to check in logs one by one.

Body:
Found it in the docs link itself which has been mentioned.

--sha1-name does the trick.

Sol:

git show-branch --sha1-name branchX branchY

Output:

+  [COMMIT-HASH] Commit Message Here