问:
Insert multiple data via datagridView in c# with the use of a checkbox
I have this code here, i wish to insert multiple students marks to the database through the datagridview once a checkbox is checked. The problem with the code below is that only the data from the first checked row is inserted. What can i do to ensure every selected row is inserted.</p>

```<code>    public override void Savebtn_Click(object sender, EventArgs e)
    {
        int select;
        for (int i = 0; i <= dataGridView1.Rows.Count -1; i++)
        {
            DataGridViewRow row = dataGridView1.Rows[i];
            if((bool)row.Cells["CheckBoxColumn"].FormattedValue == true)
            {
                select++;
            }

        }
        if(select == 0)
        {
            MainClass.showMSG("Please Select at least one Student", "Error", "Error");
        }
        for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
        {
            DataGridViewRow row = dataGridView1.Rows[i];

            if ((bool)row.Cells["CheckBoxColumn"].FormattedValue == true)
            {
              obj.st_InsertResults(Convert.ToInt32(row.Cells["stdIDGV"].Value.ToString()),
               row.Cells["StdNameGV"].Value.ToString(),
               Convert.ToInt32(row.Cells["EngGV"].Value.ToString()));
                MainClass.showMSG(" Data added successfully.", "Success....", "Success");
                MainClass.disable_reset(panel1);
                dataGridView1.DataSource = null;

            }
        }

    }
</code>```

答:
Why are you setting your datasource to null?

```<code>dataGridView1.DataSource = null;
</code>```

try removing this line, should work!

Body:
I have this code here, i wish to insert multiple students marks to the database through the datagridview once a checkbox is checked. The problem with the code below is that only the data from the first checked row is inserted. What can i do to ensure every selected row is inserted.

    public override void Savebtn_Click(object sender, EventArgs e)
    {
        int select;
        for (int i = 0; i <= dataGridView1.Rows.Count -1; i++)
        {
            DataGridViewRow row = dataGridView1.Rows[i];
            if((bool)row.Cells["CheckBoxColumn"].FormattedValue == true)
            {
                select++;
            }

        }
        if(select == 0)
        {
            MainClass.showMSG("Please Select at least one Student", "Error", "Error");
        }
        for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
        {
            DataGridViewRow row = dataGridView1.Rows[i];

            if ((bool)row.Cells["CheckBoxColumn"].FormattedValue == true)
            {
              obj.st_InsertResults(Convert.ToInt32(row.Cells["stdIDGV"].Value.ToString()),
               row.Cells["StdNameGV"].Value.ToString(),
               Convert.ToInt32(row.Cells["EngGV"].Value.ToString()));
                MainClass.showMSG(" Data added successfully.", "Success....", "Success");
                MainClass.disable_reset(panel1);
                dataGridView1.DataSource = null;

            }
        }

    }

Body:
Why are you setting your datasource to null?

dataGridView1.DataSource = null;

try removing this line, should work!


来源: stackexchange

问:
Remember Password alert for the site
In my website login page I can't get the alert "remember password for the site".I had already enabled remember password for the site from tools->options->security->"remember password for the site" but still it is not working . I am using mozilla 3.6 version</p>

答: If your login form contains autocomplete="off" browser won't save your password and form history this could be a possible reason.

ContentLicense: CC BY-SA 3.0

Title: Remember Password alert for the site


问:
HTML using a function to write the <options> of a select inside a form
So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.

```<code><select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0"><br>
</code>```

Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?

```<code><select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0"><br>

<script>
function printHTML()
{
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
}
</script>
</code>```

```<code>printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0"><br>

<script>
function printHTML(val)
{
<select name="val">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select>
}
</script>
</code>```

I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.

答:
```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <html>
    <body>
    <select name="HelmAtt1" id="select">

    </select>

    <script>
    var html = '<option value="">default</option>';
    for (var i = 0; i<10; i++)
    {
    html += '<option value="' + i + '"';

    html += '>' + i + '</option>';

    }

    document.getElementById('select').innerHTML=html;

    </script>

    </body>
    </html></code>```
</div>
</div>

</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.

<select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0">

Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?

<select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0">

printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0">

I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.


问:
IEndpointRouteBuilder interface not found
I have

```<code>NuGet Microsoft.AspNetCore.Http.Abstractions
NuGet Microsoft.AspNetCore.Routing
</code>```

and use the namespaces

```<code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
</code>```

I wanted to build something like this but it does not seem to know IEndpointConventionBuilder nor IEndpointRouteBuilder and refuses to compile.

```<code>public static class EndpointRouteBuilderExtensions
{
    public static IEndpointConventionBuilder MapServiceEndpoints(this IEndpointRouteBuilder endpoints)
    {

       //some code
    }
}
</code>```

What am I missing...?

答:
So after some looking in the .net framework I found a work around and access the backing store in the builder

```<code>var endpointDataSource = app.ApplicationServices.GetService(typeof(EndpointDataSource)) as EndpointDataSource;
</code>```

After this you have all endpoints that have been configured as well as add your own.

Body:
I have

NuGet Microsoft.AspNetCore.Http.Abstractions
NuGet Microsoft.AspNetCore.Routing

and use the namespaces

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;

I wanted to build something like this but it does not seem to know IEndpointConventionBuilder nor IEndpointRouteBuilder and refuses to compile.

public static class EndpointRouteBuilderExtensions
{
    public static IEndpointConventionBuilder MapServiceEndpoints(this IEndpointRouteBuilder endpoints)
    {

       //some code
    }
}

What am I missing...?

Body:
So after some looking in the .net framework I found a work around and access the backing store in the builder

var endpointDataSource = app.ApplicationServices.GetService(typeof(EndpointDataSource)) as EndpointDataSource;

After this you have all endpoints that have been configured as well as add your own.


问:
Span hover not working and how to change properties of elements outside of div
Is there a way for me to hover on the span text ("engpar1call") and have the div called "engpar1" appear on the screen?

In my CSS file, I have my body set up such that the content appears in 2 columns; "transpar1" is always visible on the left, and "engpar1" is supposed to appear when the span "engpar1call" is hovered over. I can't seem to get the :hover to work, but I am able to style the span.

.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}
```

<pre class="lang-html prettyprint-override"><code>    <body>
      <div class="content">
        <div class="transpar1">
          <p>
            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
<span class="engpar1call">vaalele</span> i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.
          </p>
        </div>

        <div class="engpar1">
          <p>
            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.
          </p>
        </div>
      </div>
</code>```

I've done a bit of searching, and I saw some Javascript that may be of help to me? But I'm not sure if I wrote it correctly because when I tried it, it wasn't working either.

```<code>    var engpar1call = document.getElementsByClassName(".engpar1call");

function showengpar1() {
    var engpar1 = document.getElementsByClassName(".engpar1");

    engpar1.style.display = "inline";
}
engpar1call.addEventListener("mouseover", showengpar1);
</code>```

答:
Do you Need something like this? I made it by jQuery.

$( document ).ready(function() {
$('.transpar1').find('.engpar1call').hover(function() {
  $('.engpar1').toggleClass( 'fadein' );
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
  color:#000;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  opacity:0; visibility:hidden;
  transition: all .3s ease-in-out;
}

span.engpar1call {
  color: #D93636;
}
.engpar1.fadein{opacity:1;visibility:visible;}</code>```

        O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o vaalele i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
        o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
        mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
        ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.

        The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
        and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
        One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
        other, satisfy one's fecal necessities.

```

Body:
Is there a way for me to hover on the span text ("engpar1call") and have the div called "engpar1" appear on the screen?

In my CSS file, I have my body set up such that the content appears in 2 columns; "transpar1" is always visible on the left, and "engpar1" is supposed to appear when the span "engpar1call" is hovered over. I can't seem to get the :hover to work, but I am able to style the span.

.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}

            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
vaalele i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.

            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.

I've done a bit of searching, and I saw some Javascript that may be of help to me? But I'm not sure if I wrote it correctly because when I tried it, it wasn't working either.

    var engpar1call = document.getElementsByClassName(".engpar1call");

function showengpar1() {
    var engpar1 = document.getElementsByClassName(".engpar1");

    engpar1.style.display = "inline";
}
engpar1call.addEventListener("mouseover", showengpar1);

Body:
Do you Need something like this? I made it by jQuery.

$( document ).ready(function() {
$('.transpar1').find('.engpar1call').hover(function() {
  $('.engpar1').toggleClass( 'fadein' );
});
});

.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
  color:#000;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  opacity:0; visibility:hidden;
  transition: all .3s ease-in-out;
}

span.engpar1call {
  color: #D93636;
}
.engpar1.fadein{opacity:1;visibility:visible;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
    <div class="transpar1">
      <p>
        O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o <span class="engpar1call">vaalele</span> i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
        o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
        mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
        ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.
      </p>
    </div>

    <div class="engpar1">
      <p>
        The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
        and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
        One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
        other, satisfy one's fecal necessities.
      </p>
    </div>
  </div>


问:
PyQt - Accessing SQL data from a table entry
I will briefly describe my program first

Program Description

Below are the 2 widows used in the program:

Main Window (Group List)

Input Window (Student Table)

The Main Window allows users to create/edit/delete entries in Groups list (QListWidget), which shows title of each entry read from a Sqlite database(DB). The 'New' button opens a new Input Window, which allows users to insert entries in Student table (QTableWidget). '+' button adds new row to table, and '-' button removes selected row. 'Name' and 'Age' of each entry can be edited directly by clicking on a cell in the table. The 'Save' button saves the title and the table inputs(entries of students: 'Name' and 'Age') to DB and updates the 'Groups' list in the Main Window. The 'Cancel' button closes the Input Window without saving the changes made in the window.

Database

Group list (QListView)

Student table (QTableWidget)

I am using SQLite using PyQt5's Qtsql class for database. 'group_id' in Student table is FK to Group list's 'id'.

My Problem

I would like to be able to select an entry in 'Groups' list, press 'Edit' button, and show Input Window's Student table filled with data from DB, just as shown above. I tried using QDataWidgetMapper, as it worked well with populating QTextEdit and QLineEdit, but I am having trouble populating QTableWidget with it.

How to populate QTableWidget from database in this context. Is there a method I am missing in QDataWidgetMapper?

Codes

Relevant snippets of my code where I attempt to map Student table in DB to PyQt5 (Most of this is my adapted version of eyllanesc's answer to Accessing SQL data from a list entry)

```<code>class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._groups_model = QtSql.QSqlTableModel(self)
        self.groups_model.setTable("Groups")
        self.groups_model.select()

        self._student_model = QtSql.QSqlTableModel(self)
        self.student_model.setTable("Student")
        self.student_model.select()

        self.sql_list_view = QtWidgets.QListView()
        self.sql_list_view.setModel(self.groups_model)
        self.sql_list_view.setModelColumn(self.groups_model.record().indexOf("group_name"))
        ...

    @property
    def macro_model(self):
        return self._macro_model

    @property
    def sheets_model(self):
        return self._sheets_model

    @QtCore.pyqtSlot()
    def edit(self):
        ixs = self.listView_macros.selectionModel().selectedIndexes()
        if ixs:
            print(ixs)
            d = EditDialog(self.groups_model, ixs[0].row(), self.student_model)
            d.exec_()

class EditDialog(QtWidgets.QDialog):
    def __init__(self, gr_model, gr_idx, std_model, parent=None):
        super().__init__(parent)

        self.title_le = QtWidgets.QLineEdit()
        self.student_table = QtWidgets.QTableWidget(self)

        groups_mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        groups_mapper.setModel(gr_model)
        groups_mapper.addMapping(self.title_le, gr_model.record().indexOf("group_name"))
        groups_mapper.setCurrentIndex(gr_idx)

        student_mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        student_mapper.setModel(std_model)
        student_mapper.addMapping(self.student_table, ????)  # << I am having trouble here

</code>```

答:
You are confusing the concepts(I recommend you review the official Qt documentation and test the PyQt5 examples that are in its source code). QDataWidgetMapper is used to map a single row of a model so it will not be useful to handle several rows. You should not use QTableWidget but a QTableView with a QSqlTableModel with a filter based on the FK. Then applying the same logic that was implemented to add groups to add students.

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql

def create_connection(database):
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(database)
    if not db.open():
        print("Cannot open database")
        print(
            "Unable to establish a database connection.\n"
            "This example needs SQLite support. Please read "
            "the Qt SQL driver documentation for information "
            "how to build it.\n\n"
            "Click Cancel to exit."
        )
        return False

    query = QtSql.QSqlQuery()
    if not query.exec_(
        """CREATE TABLE IF NOT EXISTS Groups (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "group_name" TEXT)"""
    ):
        print(query.lastError().text())
        return False
    if not query.exec_(
        """CREATE TABLE IF NOT EXISTS Student (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "group_id" INTEGER,
    "name" TEXT,
    "age" INTEGER,
    FOREIGN KEY(group_id) REFERENCES Groups(id))"""
    ):
        print(query.lastError().text())
        return False
    return True

class AddGroupDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.title_le = QtWidgets.QLineEdit()

        button_box = QtWidgets.QDialogButtonBox(self)
        button_box.setOrientation(QtCore.Qt.Horizontal)
        button_box.setStandardButtons(
            QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
        )

        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.title_le)
        lay.addWidget(button_box)

    @property
    def title(self):
        return self.title_le.text()

class EditMacroDialog(QtWidgets.QDialog):
    def __init__(self, model, index, parent=None):
        super().__init__(parent)

        self._group_id = model.record(index).value("id")

        self.title_le = QtWidgets.QLineEdit()

        self.student_table_model = QtSql.QSqlTableModel()
        self.student_table_model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
        self.student_table_model.setTable("Student")
        self.student_table_model.setFilter("group_id={}".format(self.group_id))
        self.student_table_model.select()
        self.table_view = QtWidgets.QTableView(selectionBehavior=QtWidgets.QAbstractItemView.SelectRows)
        self.table_view.setModel(self.student_table_model)
        self.table_view.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)

        for name in ("group_id", "id"):
            self.table_view.hideColumn(self.student_table_model.record().indexOf(name))
        self.table_view.verticalHeader().hide()

        self.plus_button = QtWidgets.QPushButton(self.tr("+"))
        self.minus_button = QtWidgets.QPushButton(self.tr("-"))
        self.save_button = QtWidgets.QPushButton(self.tr("Save"))

        mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        mapper.setModel(model)
        mapper.addMapping(self.title_le, model.record().indexOf("group_name"))
        mapper.setCurrentIndex(index)

        self.plus_button.clicked.connect(self.addRow)
        self.minus_button.clicked.connect(self.removeRow)

        self.save_button.clicked.connect(mapper.submit)
        self.save_button.clicked.connect(self.accept)

        hlay = QtWidgets.QHBoxLayout(self)

        vlay = QtWidgets.QVBoxLayout()
        vlay.addWidget(self.title_le)
        vlay.addWidget(self.table_view)
        hlay.addLayout(vlay)

        vlay2 = QtWidgets.QVBoxLayout()
        vlay2.addWidget(self.plus_button)
        vlay2.addWidget(self.minus_button)
        vlay2.addWidget(self.save_button)
        hlay.addLayout(vlay2)

    @property
    def group_id(self):
        return self._group_id

    @QtCore.pyqtSlot()
    def addRow(self):
        r = self.student_table_model.record()
        r.setValue("group_id", self.group_id)
        if self.student_table_model.insertRecord(
            self.student_table_model.rowCount(), r
        ):
            self.student_table_model.select()

    @QtCore.pyqtSlot()
    def removeRow(self):
        ixs = self.table_view.selectionModel().selectedIndexes()
        if ixs:
            self.student_table_model.removeRow(ixs[0].row())
            self.student_table_model.select()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._model = QtSql.QSqlTableModel(self)
        self.model.setTable("Groups")
        self.model.select()

        self.sql_list_view = QtWidgets.QListView()
        self.sql_list_view.setModel(self.model)
        self.sql_list_view.setModelColumn(self.model.record().indexOf("group_name"))

        self.new_button = QtWidgets.QPushButton(self.tr("New"))
        self.edit_button = QtWidgets.QPushButton(self.tr("Edit"))
        self.remove_button = QtWidgets.QPushButton(self.tr("Remove"))

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        grid_layout = QtWidgets.QGridLayout(central_widget)
        grid_layout.addWidget(
            QtWidgets.QLabel(self.tr("Groups"), alignment=QtCore.Qt.AlignCenter)
        )
        grid_layout.addWidget(self.sql_list_view, 1, 0)

        vlay = QtWidgets.QVBoxLayout()
        vlay.addWidget(self.new_button)
        vlay.addWidget(self.edit_button)
        vlay.addWidget(self.remove_button)
        grid_layout.addLayout(vlay, 1, 1)
        self.resize(640, 480)

        self.new_button.clicked.connect(self.new)
        self.edit_button.clicked.connect(self.edit)
        self.remove_button.clicked.connect(self.remove)

        self.sql_list_view.selectionModel().selectionChanged.connect(
            self.onSelectionChanged
        )
        self.onSelectionChanged()

    @property
    def model(self):
        return self._model

    @QtCore.pyqtSlot()
    def new(self):
        d = AddGroupDialog()
        if d.exec_() == QtWidgets.QDialog.Accepted:
            r = self.model.record()
            r.setValue("group_name", d.title)
            if self.model.insertRecord(self.model.rowCount(), r):
                self.model.select()

    @QtCore.pyqtSlot()
    def edit(self):
        ixs = self.sql_list_view.selectionModel().selectedIndexes()
        if ixs:
            d = EditMacroDialog(self.model, ixs[0].row())
            d.exec_()

    @QtCore.pyqtSlot()
    def remove(self):
        ixs = self.sql_list_view.selectionModel().selectedIndexes()
        if ixs:
            row = ixs[0].row()
            id_ = self.model.record(row).value("id")
            query = QtSql.QSqlQuery()
            query.prepare("DELETE FROM Student WHERE group_id = ?")
            query.addBindValue(id_)
            if not query.exec_():
                print(query.lastError().text())
                return
            self.model.removeRow(row)
            self.model.select()

    @QtCore.pyqtSlot()
    def onSelectionChanged(self):
        state = bool(self.sql_list_view.selectionModel().selectedIndexes())
        self.edit_button.setEnabled(state)
        self.remove_button.setEnabled(state)

if __name__ == "__main__":
    import sys

    database = "database.db"  # ":memory:"
    app = QtWidgets.QApplication(sys.argv)
    if not create_connection(database):
        sys.exit(app.exec_())
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
```

Body:
I will briefly describe my program first

Program Description

Below are the 2 widows used in the program:

Main Window (Group List)

Input Window (Student Table)

The Main Window allows users to create/edit/delete entries in Groups list (QListWidget), which shows title of each entry read from a Sqlite database(DB). The 'New' button opens a new Input Window, which allows users to insert entries in Student table (QTableWidget). '+' button adds new row to table, and '-' button removes selected row. 'Name' and 'Age' of each entry can be edited directly by clicking on a cell in the table. The 'Save' button saves the title and the table inputs(entries of students: 'Name' and 'Age') to DB and updates the 'Groups' list in the Main Window. The 'Cancel' button closes the Input Window without saving the changes made in the window.

Database

Group list (QListView)

Student table (QTableWidget)

I am using SQLite using PyQt5's Qtsql class for database. 'group_id' in Student table is FK to Group list's 'id'.

My Problem

I would like to be able to select an entry in 'Groups' list, press 'Edit' button, and show Input Window's Student table filled with data from DB, just as shown above. I tried using QDataWidgetMapper, as it worked well with populating QTextEdit and QLineEdit, but I am having trouble populating QTableWidget with it.

How to populate QTableWidget from database in this context. Is there a method I am missing in QDataWidgetMapper?

Codes

Relevant snippets of my code where I attempt to map Student table in DB to PyQt5 (Most of this is my adapted version of eyllanesc's answer to Accessing SQL data from a list entry)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._groups_model = QtSql.QSqlTableModel(self)
        self.groups_model.setTable("Groups")
        self.groups_model.select()

        self._student_model = QtSql.QSqlTableModel(self)
        self.student_model.setTable("Student")
        self.student_model.select()

        self.sql_list_view = QtWidgets.QListView()
        self.sql_list_view.setModel(self.groups_model)
        self.sql_list_view.setModelColumn(self.groups_model.record().indexOf("group_name"))
        ...

    @property
    def macro_model(self):
        return self._macro_model

    @property
    def sheets_model(self):
        return self._sheets_model

    @QtCore.pyqtSlot()
    def edit(self):
        ixs = self.listView_macros.selectionModel().selectedIndexes()
        if ixs:
            print(ixs)
            d = EditDialog(self.groups_model, ixs[0].row(), self.student_model)
            d.exec_()

class EditDialog(QtWidgets.QDialog):
    def __init__(self, gr_model, gr_idx, std_model, parent=None):
        super().__init__(parent)

        self.title_le = QtWidgets.QLineEdit()
        self.student_table = QtWidgets.QTableWidget(self)

        groups_mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        groups_mapper.setModel(gr_model)
        groups_mapper.addMapping(self.title_le, gr_model.record().indexOf("group_name"))
        groups_mapper.setCurrentIndex(gr_idx)

        student_mapper = QtWidgets.QDataWidgetMapper(
            self, submitPolicy=QtWidgets.QDataWidgetMapper.ManualSubmit
        )
        student_mapper.setModel(std_model)
        student_mapper.addMapping(self.student_table, ????)  # << I am having trouble here


问:
How to realize a 3d web Applet
i've been request from a customer to realize a 3d applet (maybe flex or silverlight ?) that gives me the possibility to apply clothes textures (such as pants or shoes) to human 3d models.

I also need to modify the height of the models...

can you give me any suggestion about where to start ? i'm pretty new in this world and i need a way to start from scratch.

Thanks in adavance.

答:
If you are planning to use Silverlight, than you clients can run your application only on Windows and Mac. If it's OK for you than take a look to this frameworks:

Balder

Kit3D

Postvision

Olso you can use new 3D engine for Silverlight 5, which is on beta, but avaliable only for Windows OS.

Title: How to realize a 3d web Applet


问:
Javascript simple animation lagging on mobile
I'm trying to use a typing effect using 'setInterval', it works fine but lagging on mobile devices. I've slowed it down but still it lags, below I've attached the representation of what happening, also my code.

code:

```<code>function animate() {
  var a = "We DESIGN,";
  var b = "We DEVELOP";
  var c = "and";
  var d = "We CARE";
  var e = 0;

  var one = setInterval(function () {
    document.getElementById('one').insertAdjacentHTML('beforeend',a[e]);
    e = e + 1;
    if (e == 10) {
      clearInterval(one);
      var f = 0;
      var two = setInterval(function () {
        document.getElementById('two').insertAdjacentHTML('beforeend',b[f]);
        f = f + 1;
        if (f == 10) {
          clearInterval(two);
          var g = 0;
          var three = setInterval(function () {
            document.getElementById('three').insertAdjacentHTML('beforeend',c[g]);
            g = g + 1;
            if (g == 3) {
              clearInterval(three);
              var h = 0;
              var four = setInterval(function () {
                document.getElementById('four').insertAdjacentHTML('beforeend',d[h]);
                h = h + 1;
                if (h == 7) {
                  clearInterval(four);
                }
              },200);
            }
          },150);
        }
      },200);
    }
  },200);
}
</code>```

at first i used jquery's .append() but then tried pure js to see if it is doing anything, but no luck, and i'm calling this function onload() on body.
 Anyway, I've not really looked into the code to make it much smaller, so unless it isn't the reason please don't judge it.

on desktop: https://drive.google.com/open?id=1Rv4bNu1X0wcHgbehYUb5WqzcVlA2gHTV

on mobile: https://drive.google.com/open?id=1z8hCT71Xr_X9n3StDGRdn4TpLbx5TeQk

答:
document.getElementById is expensive. It traverses the DOM to find your element again and again for every character in the string. It makes more sense to store these elements in variables (better yet, use one container for the entire text block).

I'm not sure if setting and clearing intervals is more or less performant than the one-shot setTimeout, but I don't think there's any harm in making the switch, if only for cleanliness. I'm also using a promise for the same reason, but you can use a callback as easily if there's any trouble with making it async.

Beyond that, the code is difficult to maintain. If you want to add more text, the pyramid of doom grows and the code generally needs to be re-written. Use a loop.

I'd approach it as follows:

const text = `We DESIGN,
We DEVELOP
and
We CARE`;
const typeElem = document.querySelector("#typewriter");

(async () => {
  for (const line of text.split("\n")) {
    const div = document.createElement("div");
    typeElem.appendChild(div);

    for (const char of [...line]) {
      div.insertAdjacentHTML("beforeend", char);
      await new Promise(resolve => setTimeout(resolve, 200));
    }
  }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="typewriter"></div></code>```

Adjust timeouts to your specification (you could pause after a line, keep pauses per line/character in a separate data structure, etc).

Body:
I'm trying to use a typing effect using 'setInterval', it works fine but lagging on mobile devices. I've slowed it down but still it lags, below I've attached the representation of what happening, also my code.

code:

function animate() {
  var a = "We DESIGN,";
  var b = "We DEVELOP";
  var c = "and";
  var d = "We CARE";
  var e = 0;

  var one = setInterval(function () {
    document.getElementById('one').insertAdjacentHTML('beforeend',a[e]);
    e = e + 1;
    if (e == 10) {
      clearInterval(one);
      var f = 0;
      var two = setInterval(function () {
        document.getElementById('two').insertAdjacentHTML('beforeend',b[f]);
        f = f + 1;
        if (f == 10) {
          clearInterval(two);
          var g = 0;
          var three = setInterval(function () {
            document.getElementById('three').insertAdjacentHTML('beforeend',c[g]);
            g = g + 1;
            if (g == 3) {
              clearInterval(three);
              var h = 0;
              var four = setInterval(function () {
                document.getElementById('four').insertAdjacentHTML('beforeend',d[h]);
                h = h + 1;
                if (h == 7) {
                  clearInterval(four);
                }
              },200);
            }
          },150);
        }
      },200);
    }
  },200);
}

at first i used jquery's .append() but then tried pure js to see if it is doing anything, but no luck, and i'm calling this function onload() on body.
 Anyway, I've not really looked into the code to make it much smaller, so unless it isn't the reason please don't judge it.

on desktop: https://drive.google.com/open?id=1Rv4bNu1X0wcHgbehYUb5WqzcVlA2gHTV

on mobile: https://drive.google.com/open?id=1z8hCT71Xr_X9n3StDGRdn4TpLbx5TeQk

Body:
document.getElementById is expensive. It traverses the DOM to find your element again and again for every character in the string. It makes more sense to store these elements in variables (better yet, use one container for the entire text block).

I'm not sure if setting and clearing intervals is more or less performant than the one-shot setTimeout, but I don't think there's any harm in making the switch, if only for cleanliness. I'm also using a promise for the same reason, but you can use a callback as easily if there's any trouble with making it async.

Beyond that, the code is difficult to maintain. If you want to add more text, the pyramid of doom grows and the code generally needs to be re-written. Use a loop.

I'd approach it as follows:

const text = `We DESIGN,
We DEVELOP
and
We CARE`;
const typeElem = document.querySelector("#typewriter");

(async () => {
  for (const line of text.split("\n")) {
    const div = document.createElement("div");
    typeElem.appendChild(div);

    for (const char of [...line]) {
      div.insertAdjacentHTML("beforeend", char);
      await new Promise(resolve => setTimeout(resolve, 200));
    }
  }
})();

<div id="typewriter"></div>

Adjust timeouts to your specification (you could pause after a line, keep pauses per line/character in a separate data structure, etc).


问:
How to send data from router to express handlebar template
I'm having a hard time trying to get data retrieved from a postgres DB via router into a handlebar template.

This is the folder structure:

```<code>-node_modules
-public
-routes
--api
---db.js
-views
--layouts
---main.handlebars
--index.handlebars
-index.js
</code>```

Here is an example request in the db.js file:

```<code>//get all users
router.get("/", (req, res) => {
  db.result("SELECT * FROM users ORDER BY id")
    .then(data => {
      res.json(data.rows);
    })
    .catch(error => {
      return console.log("error");
    });
});
</code>```

And I want this data to be displayed into a template.

This is the index.js file:

```<code>const users = require('./routes/api/db')

const app = express();

//init middleware
app.use(logger);

//handle bars middle
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

// body parser
app.use(express.json());
app.use(express.urlencoded({extended: false}));

//render
// app.get('/', users.getAllUsers);

app.get('/displaydata', (req,res)=> {
    res.render('index', {
        title: 'DATA',

/* HOW DO I GET THE DATA TO BE DISPLAYED OVER HERE?*/

    });
});

//members api routes
app.use('/api/db', users);
</code>```

答:
You have to change below i guess,..

// db.js need to changes like below

```<code>//get all users
// router.get("/", (req, res) => {
module.exports.getUsers = function (reqParams) {
  return new Proimise((resolve, reject) => {
    db.result("SELECT * FROM users ORDER BY id")
      .then(data => resolve(status : true, data: data.rows));
      .catch(error =>reject({status : false, data: error}));
  })
};
// });
</code>```

// index.js need to changes like below

```<code>const users = require(`/db`);

app.get('/displaydata', async(req, res)=> {
  const reslt = await users.getUsers(req);
  res.render('index', {
      title: 'DATA',
      data: reslt.status ? reslt.data : []
  });
});
</code>```

Body:
I'm having a hard time trying to get data retrieved from a postgres DB via router into a handlebar template.

This is the folder structure:

-node_modules
-public
-routes
--api
---db.js
-views
--layouts
---main.handlebars
--index.handlebars
-index.js

Here is an example request in the db.js file:

//get all users
router.get("/", (req, res) => {
  db.result("SELECT * FROM users ORDER BY id")
    .then(data => {
      res.json(data.rows);
    })
    .catch(error => {
      return console.log("error");
    });
});

And I want this data to be displayed into a template.

This is the index.js file:

const users = require('./routes/api/db')

const app = express();

//init middleware
app.use(logger);

//handle bars middle
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

// body parser
app.use(express.json());
app.use(express.urlencoded({extended: false}));

//render
// app.get('/', users.getAllUsers);

app.get('/displaydata', (req,res)=> {
    res.render('index', {
        title: 'DATA',

/* HOW DO I GET THE DATA TO BE DISPLAYED OVER HERE?*/

    });
});

//members api routes
app.use('/api/db', users);

Body:
You have to change below i guess,..

// db.js need to changes like below

//get all users
// router.get("/", (req, res) => {
module.exports.getUsers = function (reqParams) {
  return new Proimise((resolve, reject) => {
    db.result("SELECT * FROM users ORDER BY id")
      .then(data => resolve(status : true, data: data.rows));
      .catch(error =>reject({status : false, data: error}));
  })
};
// });

// index.js need to changes like below

const users = require(`/db`);

app.get('/displaydata', async(req, res)=> {
  const reslt = await users.getUsers(req);
  res.render('index', {
      title: 'DATA',
      data: reslt.status ? reslt.data : []
  });
});


问:
How do I map volume to WSO2 API Manager Container?
I am using WSO2 API Manager Docker version for my API Gateway. I want to persist the files on the disk so that configurations are not lost during restarts. However, When I map the volume using docker "-v" command, WSO2 cannot find any files. Here is my complete docker command.

```<code>docker run --rm -d \
--name api-gateway \
--expose 9443 \
--expose 8280 \
-v /home/ubuntu/wso2am-2.6.0:/home/wso2carbon/wso2am-2.6.0 \
wso2/wso2am:2.6.0
</code>```

Please help me out with this.

答:
You have mounted to the root directory of API Manager installation. This should mount to the following location.

```<code>/home/wso2carbon/wso2am-2.6.0/repository/deployment/server
</code>```

This is where we store Synapse artifacts for the gateway.

Body:
I am using WSO2 API Manager Docker version for my API Gateway. I want to persist the files on the disk so that configurations are not lost during restarts. However, When I map the volume using docker "-v" command, WSO2 cannot find any files. Here is my complete docker command.

docker run --rm -d \
--name api-gateway \
--expose 9443 \
--expose 8280 \
-v /home/ubuntu/wso2am-2.6.0:/home/wso2carbon/wso2am-2.6.0 \
wso2/wso2am:2.6.0

Please help me out with this.

Body:
You have mounted to the root directory of API Manager installation. This should mount to the following location.

/home/wso2carbon/wso2am-2.6.0/repository/deployment/server

This is where we store Synapse artifacts for the gateway.


问:
Django Newbie error: - TypeError: view must be a callable or a list/tuple in the case of include()
I am a total newbie to python Django and would like to know why are views not being created.
here's my urls.py which is under myproject.

```<code>from django.contrib import admin

from django.urls import path,include
from django.conf.urls import url
admin.autodiscover()

urlpatterns = ['',
    path('admin/', admin.site.urls),
    url('myapp/', include('myapp.url'))
]
</code>```

here's my view.py which is in myapp folder

```<code>from django.shortcuts import render

# Create your views here.
def hello(request):
    return render(request,"myapp/templates/hello.html", {})
</code>```

here's my url.py in myapp folder

```<code>from django.conf.urls import include, url

urlpatterns = ['', url('hello/', 'views.hello', name='hello'),]
</code>```

and here's the complete traceback

```<code>Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in check
    for pattern in self.url_patterns:
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 588, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 581, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/mayureshkadam/PycharmProjects/Learning-Django/myproject/myproject/urls.py", line 23, in <module>
    url('myapp/', include('myapp.url'))
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/mayureshkadam/PycharmProjects/Learning-Django/myproject/myapp/url.py", line 3, in <module>
    urlpatterns = ['', url('hello/', 'views.hello', name='hello'),]
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/conf/urls/__init__.py", line 13, in url
    return re_path(regex, view, kwargs, name)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/conf.py", line 73, in _path
    raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
</code>```

i've read a few tutorials and the code is being referred from https://www.tutorialspoint.com/django/django_url_mapping.htm but not sure why i am getting an error.

答:
Just replace the url with path:

```<code># main urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.url'))
]

# app urls.py
from django.urls import path
from .view import hello

urlpatterns = [
    path('hello/', hello, name='hello'),
]
</code>```

As you can see in documetation, path has been introduced(from Django>=2.0), so you don't have to use url here. The tutorial you are following is for older versions, so it is using url with regex to generate URLs.

Body:
I am a total newbie to python Django and would like to know why are views not being created.
here's my urls.py which is under myproject.

from django.contrib import admin

from django.urls import path,include
from django.conf.urls import url
admin.autodiscover()

urlpatterns = ['',
    path('admin/', admin.site.urls),
    url('myapp/', include('myapp.url'))
]

here's my view.py which is in myapp folder

from django.shortcuts import render

# Create your views here.
def hello(request):
    return render(request,"myapp/templates/hello.html", {})

here's my url.py in myapp folder

from django.conf.urls import include, url

urlpatterns = ['', url('hello/', 'views.hello', name='hello'),]

and here's the complete traceback

Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in check
    for pattern in self.url_patterns:
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 588, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 581, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/mayureshkadam/PycharmProjects/Learning-Django/myproject/myproject/urls.py", line 23, in <module>
    url('myapp/', include('myapp.url'))
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/mayureshkadam/PycharmProjects/Learning-Django/myproject/myapp/url.py", line 3, in <module>
    urlpatterns = ['', url('hello/', 'views.hello', name='hello'),]
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/conf/urls/__init__.py", line 13, in url
    return re_path(regex, view, kwargs, name)
  File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/conf.py", line 73, in _path
    raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().

i've read a few tutorials and the code is being referred from https://www.tutorialspoint.com/django/django_url_mapping.htm but not sure why i am getting an error.

Body:
Just replace the url with path:

# main urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.url'))
]

# app urls.py
from django.urls import path
from .view import hello

urlpatterns = [
    path('hello/', hello, name='hello'),
]

As you can see in documetation, path has been introduced(from Django>=2.0), so you don't have to use url here. The tutorial you are following is for older versions, so it is using url with regex to generate URLs.


问:
A badge in GitHub template repository that will refer to clones' build status, not the template repo's build status
I'm new to GitHub's template repositories. We've created a template repo for our course's code labs. Let's say it's on GitHub under myorg/labX. The students are using GitHub Classroom, which clones the template repo for each student under myorg/labX-studentlogin. We've got actions to run some tests against their code using GitHub's own CI, and I want to include badges in the repo's README.md to see the test results at a glance. So I know that

```<code>![](https://github.com/myorg/labX/workflows/task1/badge.svg)
</code>```

will include the badge, but this is the status of the template repo, not student repos. Is there a way to automate this so that when the students get their clone, it will contain a README with the URL that refers to the status of their own repo?

答:
Turns out there is a simple solution, but only for GitHub's own Actions status badges. We've changed the image URL in our README.mds to relative.
The only minor thing is GitHub will insert /blob/<branch>/ into relative links when rendering the readmes.
For example, workflows/task1/badge.svg will become https://github.com/myorg/labX/blob/master/workflows/task1/badge.svg), which won't render. So we had to prepend '../../' to fool it.

TLDR: in repo's README.md, use

```<code>![](../../workflows/<workflowname>/badge.svg)
</code>```

to get a badge for an Action status in this repo. This way, each student will get a badge referring to his own repo, not the template repo.

However, still looking for a way to use an external badge service like shields.io in a way relative to the repo.

Body:
I'm new to GitHub's template repositories. We've created a template repo for our course's code labs. Let's say it's on GitHub under myorg/labX. The students are using GitHub Classroom, which clones the template repo for each student under myorg/labX-studentlogin. We've got actions to run some tests against their code using GitHub's own CI, and I want to include badges in the repo's README.md to see the test results at a glance. So I know that

![](https://github.com/myorg/labX/workflows/task1/badge.svg)

will include the badge, but this is the status of the template repo, not student repos. Is there a way to automate this so that when the students get their clone, it will contain a README with the URL that refers to the status of their own repo?

Body:
Turns out there is a simple solution, but only for GitHub's own Actions status badges. We've changed the image URL in our README.mds to relative.
The only minor thing is GitHub will insert /blob/<branch>/ into relative links when rendering the readmes.
For example, workflows/task1/badge.svg will become https://github.com/myorg/labX/blob/master/workflows/task1/badge.svg), which won't render. So we had to prepend '../../' to fool it.

TLDR: in repo's README.md, use

![](../../workflows/<workflowname>/badge.svg)

to get a badge for an Action status in this repo. This way, each student will get a badge referring to his own repo, not the template repo.

However, still looking for a way to use an external badge service like shields.io in a way relative to the repo.


问:
Text lowercase after capitalization is possible?
My database give mixed font styles, for Example:

" Hi THis is TEST teXT "

I want to capitalization this type of fonts. I found a way, first using lowercase and then ::first-letter to be capitalized. This give the first letter only capital.

But I want capitalization in every first word, is there any way?

答:
What you want is impossible using pure CSS. Please refer to this answer.

Alternative, you can use it with angular lowercase pipe and titlecase pipe:

```<code>{{ textToTransform | lowercase | titlecase }}
</code>```

Body:
What you want is impossible using pure CSS. Please refer to this answer.

Alternative, you can use it with angular lowercase pipe and titlecase pipe:

{{ textToTransform | lowercase | titlecase }}


问:
Markers show after hot reload but not when I press the button. (Flutter - Google Maps)
When I try to place a marker in my google map, it doesn't show until I click hot reload. Am I missing a setState() somewhere?

My issue is that I don't know where. The documentation for this package is really confusing because the google maps controller has been updated and changed dramatically since it's inception. A lot of guides simply don't help because the code has changed.

```<code>import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app_dev/UI/base_widget.dart';
import 'package:mobile_app_dev/UI/widgets.dart';

import '../main.dart';

class myMapScreen extends StatefulWidget {
  @override
  myMapState createState() => myMapState();

}

class myMapState extends State<myMapScreen> {

  PageController _pageController;
  GoogleMapController mapController;
  LatLng center = const LatLng(37.352727, -122.034227);
//  Location location = new Location();
  Position currentLocation;

  final Set<Marker> _markers = {};

  void _getLocation() async {
    var currentLocation = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);

    setState(() {
      _markers.clear();
      final marker = Marker(
        markerId: MarkerId("curr_loc"),
        position: LatLng(currentLocation.latitude, currentLocation.longitude),
        infoWindow: InfoWindow(title: 'Your Location'),
        icon: BitmapDescriptor.defaultMarker
      );
      _markers.add(marker);
    });

    currentLocation = currentLocation;
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  void initState() {
    _markers.clear();
    super.initState();
    _pageController = PageController();
    _getLocation();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(builder: (context, sizingInformation) {
      return Scaffold(
        backgroundColor: MyApp.backgroundColor,
        appBar: AppBar(
          automaticallyImplyLeading: true,
          backgroundColor: MyApp.appBarColor,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              Text(
                'Map View',
                style: TextStyle(
                    color: MyApp.whiteNoChangeColor,
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold
                ),
              ),
            ],
          ),
          centerTitle: true,
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(right: 20.0),
                child: GestureDetector(
                  onTap: () async {
                    _getLocation();

                  },
                  child: Icon(
                    Icons.search,
                    size: 26.0,
                  ),
                )
            )
          ],
        ),
        body: Container(
          height: sizingInformation.myScreenSize.height,
          width: sizingInformation.myScreenSize.width,
          child: Stack(
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                initialCameraPosition: CameraPosition(
                  target: center,
                  zoom: 15.0,
                ),
                myLocationEnabled: true,
                mapType: MapType.hybrid,
                compassEnabled: true,
                markers: _markers,
          ),
              Positioned(
                child: FlatButton(
                  color: Colors.green,
                  child: Text("button"),
                  onPressed: (){
                    final marker = Marker(
                      markerId: MarkerId("curr_loc"),
                      position: center,
                      infoWindow: InfoWindow(title: 'Your Location'),
                      icon: BitmapDescriptor.defaultMarker
                    );
                    _markers.add(marker);
//                    _getLocation();
                  },
                ),
              )

            ],
          ),
        ),
      );
    },
    );
  }
}
</code>```

答:
Just create a list of markers and first of you have to clear the list then after that add marker on that list</p>

```<code>  var markers = Set<Marker>();

 addMarker(double lat, double lng, String id) {
    var marker = Marker(
      markerId: MarkerId(id),
      position: LatLng(
        lat,
        lng,
      ),
      infoWindow: InfoWindow(title: locationName),
      onTap: () {},
    );

    markers.clear();
    markers.add(marker);
  }
</code>```

Body:
When I try to place a marker in my google map, it doesn't show until I click hot reload. Am I missing a setState() somewhere?

My issue is that I don't know where. The documentation for this package is really confusing because the google maps controller has been updated and changed dramatically since it's inception. A lot of guides simply don't help because the code has changed.

import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app_dev/UI/base_widget.dart';
import 'package:mobile_app_dev/UI/widgets.dart';

import '../main.dart';

class myMapScreen extends StatefulWidget {
  @override
  myMapState createState() => myMapState();

}

class myMapState extends State<myMapScreen> {

  PageController _pageController;
  GoogleMapController mapController;
  LatLng center = const LatLng(37.352727, -122.034227);
//  Location location = new Location();
  Position currentLocation;

  final Set<Marker> _markers = {};

  void _getLocation() async {
    var currentLocation = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);

    setState(() {
      _markers.clear();
      final marker = Marker(
        markerId: MarkerId("curr_loc"),
        position: LatLng(currentLocation.latitude, currentLocation.longitude),
        infoWindow: InfoWindow(title: 'Your Location'),
        icon: BitmapDescriptor.defaultMarker
      );
      _markers.add(marker);
    });

    currentLocation = currentLocation;
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  void initState() {
    _markers.clear();
    super.initState();
    _pageController = PageController();
    _getLocation();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(builder: (context, sizingInformation) {
      return Scaffold(
        backgroundColor: MyApp.backgroundColor,
        appBar: AppBar(
          automaticallyImplyLeading: true,
          backgroundColor: MyApp.appBarColor,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              Text(
                'Map View',
                style: TextStyle(
                    color: MyApp.whiteNoChangeColor,
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold
                ),
              ),
            ],
          ),
          centerTitle: true,
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(right: 20.0),
                child: GestureDetector(
                  onTap: () async {
                    _getLocation();

                  },
                  child: Icon(
                    Icons.search,
                    size: 26.0,
                  ),
                )
            )
          ],
        ),
        body: Container(
          height: sizingInformation.myScreenSize.height,
          width: sizingInformation.myScreenSize.width,
          child: Stack(
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                initialCameraPosition: CameraPosition(
                  target: center,
                  zoom: 15.0,
                ),
                myLocationEnabled: true,
                mapType: MapType.hybrid,
                compassEnabled: true,
                markers: _markers,
          ),
              Positioned(
                child: FlatButton(
                  color: Colors.green,
                  child: Text("button"),
                  onPressed: (){
                    final marker = Marker(
                      markerId: MarkerId("curr_loc"),
                      position: center,
                      infoWindow: InfoWindow(title: 'Your Location'),
                      icon: BitmapDescriptor.defaultMarker
                    );
                    _markers.add(marker);
//                    _getLocation();
                  },
                ),
              )

            ],
          ),
        ),
      );
    },
    );
  }
}

Body:
Just create a list of markers and first of you have to clear the list then after that add marker on that list

  var markers = Set<Marker>();

 addMarker(double lat, double lng, String id) {
    var marker = Marker(
      markerId: MarkerId(id),
      position: LatLng(
        lat,
        lng,
      ),
      infoWindow: InfoWindow(title: locationName),
      onTap: () {},
    );

    markers.clear();
    markers.add(marker);
  }


问:
Nested form doesn't show up on page
I'm trying to build a nested form, but I can't get it to work. I'm using rails 5.2, devise and wicked wizard.
I have tried to use the cocoon gem, but without luck. The problem is, that the nested form doesn't show up on the page, it's just a blank section on the page.

This is what I have tried so far with the cocoon gem installed, and I have added //= require cocoon to application.js.

I have a user table and a services table. The service table is the nested form.

This is how I created the services table

```<code>class Services < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :name
      t.text :description
      t.integer :duration
      t.integer :price
      t.timestamps
  end
end
end
</code>```

I have added a foreign key to the services table like this

AddUserReferenceToServices

```<code>class AddUserReferenceToServices < ActiveRecord::Migration[5.2]
  def change
    add_reference :services, :user, foreign_key: true
  end
end
</code>```

I have created these relations

user.rb

```<code>class User < ApplicationRecord
    has_many :services
    accepts_nested_attributes_for :services, reject_if: :all_blank, allow_destroy: true
end
</code>```

service.rb

```<code>class Service < ApplicationRecord
    belongs_to :user
end
</code>```

I have added values to the user params

```<code>def user_params

  params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

end
</code>```

main_form.html.erb

```<code><div class="content">
    <%= simple_form_for @user, url: wizard_path, method: :put do |f| %>
    <div class="specializations-section">
        <h2 class="page-title">Professioner</h2>
        <div class="field select-field ">
            <%= f.association :professions, input_html: { id: 'professions-select', class: 'js-example-basic-multiple' } %>
        </div>
        <div class="content">
            <p>Mangler der en profession på listen? Så skriv til os på <a href="mailto:info@betterwing.dk?Subject=Forslag%20til%20ny%20profession">info@betterwing.dk</a></p>
        </div>
    </div>

    <div id="services">
        <%= f.simple_fields_for :services do |t| %>
        <%= render 'services/services_fields', :f => t %>
        <% end %>
    <div class="links">
      <%= link_to_add_association 'add services', f, :services, :partial => 'services/services_fields' %>
    </div>
</div>
</code>```

services/_services_fields.html.erb

```<code><%= f.input_field :name, required: true, autofocus: true, autocomplete: "Navn på behandling", placeholder: "Navn på behandling" %>
<%= f.input_field :description, required: true, rows: '1', autofocus: true, autocomplete: "Beskrivelse af behandling", placeholder: "Beskrivelse af behandling"%>
<%= f.input_field :duration, required: true, rows: '1', autofocus: true, autocomplete: "Tid", placeholder: "Tid"%>
<%= f.input_field :price, required: true, rows: '1', autofocus: true, autocomplete: "Pris", placeholder: "Pris"%>

<%= link_to_remove_association 'x', f %>
</code>```

registration_steps_controller.rb

```<code>class RegistrationStepsController < ApplicationController

    include Wicked::Wizard
    steps :company_general, :company_images, :practitioners_general, :practitioners_professions, :practitioners_educations

    def new
      @user.services.new
    end

    def show
   @user = current_user
   render_wizard
    end

    def update
      @user = current_user
      # Change @user.attributes(user_params) by @user.update_attributes(user_params)
      @user.update_attributes(user_params)
      render_wizard @user
    end

private
    def user_params

      params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

    end

end
</code>```

答:
You need to instantiate the object, in controller action

```<code>@user.services.new
</code>```

or if this partial is only used in new form not shared with edit form, you can try this

```<code><%= f.simple_fields_for @user.services.new do |t| %>
</code>```

Give it a try!

Title: Nested form doesn't show up on page

Body:
I'm trying to build a nested form, but I can't get it to work. I'm using rails 5.2, devise and wicked wizard.
I have tried to use the cocoon gem, but without luck. The problem is, that the nested form doesn't show up on the page, it's just a blank section on the page.

This is what I have tried so far with the cocoon gem installed, and I have added //= require cocoon to application.js.

I have a user table and a services table. The service table is the nested form.

This is how I created the services table

class Services < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :name
      t.text :description
      t.integer :duration
      t.integer :price
      t.timestamps
  end
end
end

I have added a foreign key to the services table like this

AddUserReferenceToServices

class AddUserReferenceToServices < ActiveRecord::Migration[5.2]
  def change
    add_reference :services, :user, foreign_key: true
  end
end

I have created these relations

user.rb

class User < ApplicationRecord
    has_many :services
    accepts_nested_attributes_for :services, reject_if: :all_blank, allow_destroy: true
end

service.rb

class Service < ApplicationRecord
    belongs_to :user
end

I have added values to the user params

def user_params

  params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

end

main_form.html.erb

    <%= simple_form_for @user, url: wizard_path, method: :put do |f| %>

Professioner

            <%= f.association :professions, input_html: { id: 'professions-select', class: 'js-example-basic-multiple' } %>

Mangler der en profession på listen? Så skriv til os på info@betterwing.dk

        <%= f.simple_fields_for :services do |t| %>
        <%= render 'services/services_fields', :f => t %>
        <% end %>

      <%= link_to_add_association 'add services', f, :services, :partial => 'services/services_fields' %>

services/_services_fields.html.erb

<%= f.input_field :name, required: true, autofocus: true, autocomplete: "Navn på behandling", placeholder: "Navn på behandling" %>
<%= f.input_field :description, required: true, rows: '1', autofocus: true, autocomplete: "Beskrivelse af behandling", placeholder: "Beskrivelse af behandling"%>
<%= f.input_field :duration, required: true, rows: '1', autofocus: true, autocomplete: "Tid", placeholder: "Tid"%>
<%= f.input_field :price, required: true, rows: '1', autofocus: true, autocomplete: "Pris", placeholder: "Pris"%>

<%= link_to_remove_association 'x', f %>

registration_steps_controller.rb

class RegistrationStepsController < ApplicationController

    include Wicked::Wizard
    steps :company_general, :company_images, :practitioners_general, :practitioners_professions, :practitioners_educations

    def new
      @user.services.new
    end

    def show
   @user = current_user
   render_wizard
    end

    def update
      @user = current_user
      # Change @user.attributes(user_params) by @user.update_attributes(user_params)
      @user.update_attributes(user_params)
      render_wizard @user
    end

private
    def user_params

      params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

    end

end

Body:
You need to instantiate the object, in controller action

@user.services.new

or if this partial is only used in new form not shared with edit form, you can try this

<%= f.simple_fields_for @user.services.new do |t| %>

Give it a try!


问:
How do I remove the selected tab indicator from the TabWidget?
Here's what I'd like to remove :

How do I replace the indicator showing which tab is currently shown as well as the blue line that spans the entire tabwidget?

To Specify: All I want indicating which tab is selected is this :

tab_button_active.9.png should be shown as background if the tab is SELECTED

tab_button_inactive.9.png should be shown as the background if the tab is NOT SELECTED.

edit : Setting tabStripEnabled to false has no effect. Adding a style to it and having "@android:style/Widget.Holo.ActionBar" as its parent is also not possible since im targetting API level 7 and the ActionBar was implemented in API level 11.

答:
here what I use, since the tabIndicator.setSelectedTabIndicatorHeight(0); is depcrecated

use  tabIndicator.setSelectedTabIndicator(0);


问:
MaxMind Geolite2-City doesn't show city and region information
I am using Geolite2-City Database for Geolocation. In some cases not possible to get city, region except the country. For the IP - 205.145.64.6, the database provides the below details only (city, region details are missing).

Which Maxmind database have to use to get all the information including city, region details?

答: Not all IP addresses will resolve to city level. In this case, there is no city information for 205.145.64.6</p>


问:
How to compare Firebase datasnapshot value and show data in list

Basically there is a string value currentuserid which contains the UNIQUE ID of user.

There are many child items in "notifications"

I only want to show data that is of currentuser only. Is it correct?

My code so far..

```<code>    DatabaseReference dbReff = database.getReference("notifications");
    dbReff.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for (DataSnapshot npsnapshot : dataSnapshot.getChildren()){

                    if(currentUserId.equals(npsnapshot.child("id").getValue()))
                    {
                        ListData l = npsnapshot.getValue(ListData.class);
                        listData.add(l);
                    }

                    else
                    {
                        Toast.makeText(getApplicationContext(),"No notifications",Toast.LENGTH_LONG).show();
                    }
                }
                adapter=new MyAdapter(listData);
                rv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
You can compare the data based on your current user id in server side using orderByChild and equalTo method provided by firebase. Check below:

```<code>DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notifications");
databaseReference.orderByChild("id").equalTo(currentUserId).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            ListData l = childSnapshot.getValue(ListData.class);
            listData.add(l);
        }

        ....
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Body:
Basically there is a string value currentuserid which contains the UNIQUE ID of user.

There are many child items in "notifications"

I only want to show data that is of currentuser only. Is it correct?

My code so far..

    DatabaseReference dbReff = database.getReference("notifications");
    dbReff.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for (DataSnapshot npsnapshot : dataSnapshot.getChildren()){

                    if(currentUserId.equals(npsnapshot.child("id").getValue()))
                    {
                        ListData l = npsnapshot.getValue(ListData.class);
                        listData.add(l);
                    }

                    else
                    {
                        Toast.makeText(getApplicationContext(),"No notifications",Toast.LENGTH_LONG).show();
                    }
                }
                adapter=new MyAdapter(listData);
                rv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
You can compare the data based on your current user id in server side using orderByChild and equalTo method provided by firebase. Check below:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notifications");
databaseReference.orderByChild("id").equalTo(currentUserId).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            ListData l = childSnapshot.getValue(ListData.class);
            listData.add(l);
        }

        ....
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


问:
how to display alert when networking connection is disable?
i am new to iphone in my app i am connecting to database through web services it working correctly,but i want to displat alert  when network connection is disable.please any help me how to alert when net connection is disable,
  thanks in advance.</p>

答:
Have a look at this S.O. entry

In particular, the main point of interest for you is the first one, about using the Reachability framework to detect network connectivity.


问:
Detect specific device (with or without screen) for Google Assistant in DialogFlow
I am creating an app for Google Assistant using DialogFlow, without any external web server.

Some answers redirect to a YouTube video (using a basic card). I would like to handle devices which can not play YT videos (like Google Home/Nest) by returning a different answer (like "please use the assistant on your phone to play the video") or maybe prevent the full intent to be available on a device without a screen.

Is there a way to restrict an intent for a specific type of device only ?

Thanks.

答:
You can use the below method to check the screen capabilities.

```<code>const conv = agent.conv();
const hasScreen = conv.surface.capabilities.has('actions.capability.SCREEN_OUTPUT');
</code>```

You can even check other capabilities as well. check the doc here.

Body:
You can use the below method to check the screen capabilities.

const conv = agent.conv();
const hasScreen = conv.surface.capabilities.has('actions.capability.SCREEN_OUTPUT');

You can even check other capabilities as well. check the doc here.


问:
Error relating to conversion from list to tensor in Pytorch
There is a variable 'tmp' (3 dimension).

```<code>tmp = [torch.tensor([1]),torch.tensor([2,3])]
type(tmp) -> <class 'list'>
type(tmp[0]) -> <class 'torch.Tensor'>
type(tmp[0][0]) -> <class 'torch.Tensor'>

</code>```

I want to convert 'tmp' into torch.Tensor type.

But, when I run this code below, an error occurs.

```<code>torch.Tensor(tmp)
>> ValueError: only one element tensors can be converted to Python scalars

</code>```

How can I fix this?
torch.stack cannot be effective in this case because tensors in 'tmp' are not the same shape.

答:
Use torch.stack - All tensors need to be of the same size in the list.

>>> torch.stack(tmp)
```

<p>Ex:</p>

<pre class="lang-py prettyprint-override"><code>>>> tmp = [torch.rand(2,2),torch.rand(2,2)]

>>> tmp = torch.stack(tmp)
>>> tmp
tensor([[[0.0212, 0.1864],
         [0.0070, 0.3381]],

        [[0.1607, 0.9568],
         [0.9093, 0.1835]]])
>>> type(tmp)
<class 'torch.Tensor'>
</code>```

Body:
There is a variable 'tmp' (3 dimension).

tmp = [torch.tensor([1]),torch.tensor([2,3])]
type(tmp) -> <class 'list'>
type(tmp[0]) -> <class 'torch.Tensor'>
type(tmp[0][0]) -> <class 'torch.Tensor'>

I want to convert 'tmp' into torch.Tensor type.

But, when I run this code below, an error occurs.

torch.Tensor(tmp)
>> ValueError: only one element tensors can be converted to Python scalars

How can I fix this?
torch.stack cannot be effective in this case because tensors in 'tmp' are not the same shape.

Body:
Use torch.stack - All tensors need to be of the same size in the list.

>>> torch.stack(tmp)

Ex:

>>> tmp = [torch.rand(2,2),torch.rand(2,2)]

>>> tmp = torch.stack(tmp)
>>> tmp
tensor([[[0.0212, 0.1864],
         [0.0070, 0.3381]],

        [[0.1607, 0.9568],
         [0.9093, 0.1835]]])
>>> type(tmp)
<class 'torch.Tensor'>


问:
Python3.0:-the variable which is assigned inside a path function is not readable outside it
I am trying to create function which takes the path and then store it in a variable but the variable which is assigned inside a function is not readable outside it

```<code>def source_func(path):
    source_path=path
    print("source path is:",source_path)

source_func("C:/Users/Tools Lab1/Downloads/RBI")
source_path
</code>```

Actual Output:

function main.source_path(path)

Expected Output:

C:/Users/Tools Lab1/Downloads/RBI

答:
This is expected behavior due to "scope."  Any variable that you create inside a function is a local variable and only available inside the function. If you want it to exist outside the function, you must make it global, with the global statement.  But...
in general, globals are not good practice, because they can make code harder to read and debug.

There is also a hierarchy for resolving variables... It's called LEGB for short: Local, Enclosing, Global, Built-in.  Check out (Geeks for Geeks)[https://www.geeksforgeeks.org/scope-resolution-in-python-legb-rule/] for a quick overview.

Body:
I am trying to create function which takes the path and then store it in a variable but the variable which is assigned inside a function is not readable outside it

def source_func(path):
    source_path=path
    print("source path is:",source_path)

source_func("C:/Users/Tools Lab1/Downloads/RBI")
source_path

Actual Output:

function main.source_path(path)

Expected Output:

C:/Users/Tools Lab1/Downloads/RBI