问:
How can I pass a list of objects from Controller to View, where data is retrieved from database using Linq in ASP.Net MVC5
I am trying to pass a list of Objects from controller to View ,where the attributes of the objects are retrieved from database using LINQ. The MODEL Code is given below:

```<code>public class Department
    {

        [Key]
        public int DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Department Name")]
        [DisplayName("Department Name")]
        public string DepartmentName { get; set; }
    }
</code>```

The Controller Code is :

```<code>public ActionResult ShowDepartments()
        {

          var departmentList = db.Deapartment.Select(x => new
            {
                x.DepartmentId,
                x.DepartmentName

            }).ToList();

            return View(departmentList);
        }
</code>```

And the View Code is:

```<code>@model List<PractiseMVC11_17_2017.Models.Department>

@{
    ViewBag.Title = "ShowDepartments";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Show Departments</h2>

        <div>

    <table class="table table-bordered table-hover">
        <tbody>

            @foreach (var department in Model)
            {

                <tr>
                    <td>
                        @department.DepartmentId
                    </td>

                    <td>
                        @department.DepartmentName

                    </td>

                </tr>

            }

        </tbody>

    </table>

</div>

}
</code>```

But when I run the project, it shows the following exception:

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType32[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'.

答:
Your view is strongly typed to a collection of Department class objects. But in your action method, you are creating a list of new anonymous objects with this code

```<code>db.Deapartment.Select(x => new
                             {
                                x.DepartmentId,
                                x.DepartmentName

                     })
</code>```

Here you are creating  an anonymous  object with the DepartmentId and DepartmentName property, for each item in the db.Deapartment collection. You are passing the result of the above code, which is a list of anonymous objects to the view. Your view now getting a different type than it is strongly typed to , hence you are getting the exception.

So simply pass ToList() on db.Deapartment and pass that to the view.

```<code>public ActionResult ShowDepartments()
{
    var departmentList = db.Deapartment.ToList();
    return View(departmentList);
}
</code>```

Here departmentList variable will be a collection of Deapartment objects.

Body:
I am trying to pass a list of Objects from controller to View ,where the attributes of the objects are retrieved from database using LINQ. The MODEL Code is given below:

public class Department
    {

        [Key]
        public int DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Department Name")]
        [DisplayName("Department Name")]
        public string DepartmentName { get; set; }
    }

The Controller Code is :

public ActionResult ShowDepartments()
        {

          var departmentList = db.Deapartment.Select(x => new
            {
                x.DepartmentId,
                x.DepartmentName

            }).ToList();

            return View(departmentList);
        }

And the View Code is:

@model List<PractiseMVC11_17_2017.Models.Department>

@{
    ViewBag.Title = "ShowDepartments";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Show Departments

            @foreach (var department in Model)
            {

                        @department.DepartmentId

                        @department.DepartmentName

            }

}

But when I run the project, it shows the following exception:

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType32[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[PractiseMVC11_17_2017.Models.Department]'.

Body:
Your view is strongly typed to a collection of Department class objects. But in your action method, you are creating a list of new anonymous objects with this code

db.Deapartment.Select(x => new
                             {
                                x.DepartmentId,
                                x.DepartmentName

                     })

Here you are creating  an anonymous  object with the DepartmentId and DepartmentName property, for each item in the db.Deapartment collection. You are passing the result of the above code, which is a list of anonymous objects to the view. Your view now getting a different type than it is strongly typed to , hence you are getting the exception.

So simply pass ToList() on db.Deapartment and pass that to the view.

public ActionResult ShowDepartments()
{
    var departmentList = db.Deapartment.ToList();
    return View(departmentList);
}

Here departmentList variable will be a collection of Deapartment objects.


来源: stackexchange

问:
How to receive full stacktrace with methods, file paths, and line numbers for JavaScript instead native errors via fabric.io in React-native
I have manage to setup the fabric.io in ios and android using https://github.com/corymsmith/react-native-fabric but the crash report is in native code i.e. java and objective-c, that is completely unhelpful.

Is there way to receive the full stacktrace with methods, file paths, and line numbers for JavaScript instead native errors.

by doing some research I found if I upload sourcemap than there is a possibility of receiving the JavaScript stacktrace.

答: Mike from Fabric here. We do not have official support for React-Native built apps at the moment so if you set things up, you may see less helpful crash logs. We always prioritize being excellent in a few areas rather then ok in many.</p>

ContentLicense: CC BY-SA 3.0


问:
The module has been successfully installed but then it's not found when imported? - Python
I'm trying to use the graphviz Python module and I've run into this problem:
I pip installed it in my command prompt, but it's not showing up in IPython.  I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython.

I've been recommended to include the sys.path for each of the interpreters.

Anyone have any ideas as to how I'd change it?

答:
It is quite common to have such cases when there are multiple installations of python.

From the snapshot, we can infer that python 3.5 is default for the system and python 3.6 is installed for the specific user (Oliver Jr).

Installing any module without setting path variable will result in installing the module in default python (python 3.5)

Inorder to use the module in python 3.6, set the path variable as

SET PATH=C:\Users\Oliver Jr\Anaconda>;%PATH%;

Check if default python version is changed to python 3.6 by using

python --version

Then install the module using

pip install graphviz

You can also install using C:\UsersOliver Jr\Anaconda\bin\pip install graphviz


问:
Amazon Redshift: ERROR: 3F000: schema does not exist
When I go to try to run a very simple query, using a stupid little test db that I set up in postgres testing out amazon's CDC:

```<code>SELECT * FROM schemastreamtest.testdatatable
</code>```

I get the following:

```<code>/*
Current path set to $user, public */
/*
ERROR: 3F000: schema "schemastreamtest" does not exist */
SELECT * FROM schemastreamtest.testdatatable;
</code>```

Again, this is not a dummy query, literally called them those, and the data is pushed from postgres to this DB using Data Migration's CDC.

I'm using the Aginity IDE for redshift, and pgAdmin3 for postgres if that matters. The data according to AWS is flowing into it, it just seems to be a retrieval issue.

答: Reloaded the db and it refreshed the schema and it works now. </p>

Body:
When I go to try to run a very simple query, using a stupid little test db that I set up in postgres testing out amazon's CDC:

SELECT * FROM schemastreamtest.testdatatable

I get the following:

/*
Current path set to $user, public */
/*
ERROR: 3F000: schema "schemastreamtest" does not exist */
SELECT * FROM schemastreamtest.testdatatable;

Again, this is not a dummy query, literally called them those, and the data is pushed from postgres to this DB using Data Migration's CDC.

I'm using the Aginity IDE for redshift, and pgAdmin3 for postgres if that matters. The data according to AWS is flowing into it, it just seems to be a retrieval issue.


问:
jquery to remove duplicate links
I have jQuery to remove duplicate links but it remove links from the entire page. I need to target a specific div. I just need to remove duplicate A from nav-report-category

var seen = {};
$('a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-report-category">
  <li>Other</li>
  <li>Inventory</li>
  <li>Manufacturing</li>
  <li>Metrics</li>
  <li>Operational</li>
  <li>Planning</li>
  <li>Procurement</li>
  <li>Sales Order</li>
  <li>Other</li>
</div></code>```

答:
In your code, please use the right selector:

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav-report-category">
  <li>Other</li>
  <li>Inventory</li>
  <li>Manufacturing</li>
  <li>Metrics</li>
  <li>Operational</li>
  <li>Planning</li>
  <li>Procurement</li>
  <li>Sales Order</li>
  <li>Other</li>
</ul></code>```

Also, you cannot have
 directly inside a
. Since you have everything in
, I suggest you remove the whole tag:

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).closest("li").remove();
  else
    seen[txt] = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav-report-category">
  <li>Other</li>
  <li>Inventory</li>
  <li>Manufacturing</li>
  <li>Metrics</li>
  <li>Operational</li>
  <li>Planning</li>
  <li>Procurement</li>
  <li>Sales Order</li>
  <li>Other</li>
</ul></code>```

Title: jquery to remove duplicate links

Body:
I have jQuery to remove duplicate links but it remove links from the entire page. I need to target a specific div. I just need to remove duplicate A from nav-report-category

var seen = {};
$('a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});

Other

Inventory

Manufacturing

Metrics

Operational

Planning

Procurement

Sales Order

Other

Body:
In your code, please use the right selector:

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav-report-category">
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=">Other</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Inventory">Inventory</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Manufacturing">Manufacturing</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Metrics">Metrics</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Operational">Operational</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Planning">Planning</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Procurement">Procurement</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Sales Order">Sales Order</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=">Other</a></li>
</ul>

Also, you cannot have <li> directly inside a <div>. Since you have everything in <li>, I suggest you remove the whole tag:

var seen = {};
$('.nav-report-category a').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).closest("li").remove();
  else
    seen[txt] = true;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav-report-category">
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=">Other</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Inventory">Inventory</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Manufacturing">Manufacturing</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Metrics">Metrics</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Operational">Operational</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Planning">Planning</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Procurement">Procurement</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=Sales Order">Sales Order</a></li>
  <li><a href="https://myanalytix.beta.com/Pages/test2.aspx?BF=supply%20chain&amp;RC=">Other</a></li>
</ul>


问:
Weird rails migration behaviour - migration is successful but still data doesn't populate
The below migration file runs successfully without any error and even column gets created but weirdly the data doesn't gets updated.

If I run the code in rails console (ignoring the create column) it works super good. Any Explanation:

```<code>class AddSubjectListToTestType < ActiveRecord::Migration
  def change
    add_column :test_types, :subject_list, :integer, array:true, default: []

    type_hash = {
        "NEET" => ["Physics" , "Chemistry", "Botany", "Zoology"],
        "JEE" => ["Physics", "Chemistry", "Mathematics"],
        "CET" => ["Physics", "Chemistry", "Mathematics"]
    }
    TestType.all.each do |test_type|
        type_hash[test_type.name].each do |subject|
            test_type.subject_list << Subject.find_by_name(subject).id
        end
        test_type.save
    end
  end
end
</code>```

答:
first thing to check is your development.log file, scroll all the way to the bottom for the latest entries.

here's how to add a column
https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_column

take all of the other stuff out and move to your model.

Body:
The below migration file runs successfully without any error and even column gets created but weirdly the data doesn't gets updated.

If I run the code in rails console (ignoring the create column) it works super good. Any Explanation:

class AddSubjectListToTestType < ActiveRecord::Migration
  def change
    add_column :test_types, :subject_list, :integer, array:true, default: []

    type_hash = {
        "NEET" => ["Physics" , "Chemistry", "Botany", "Zoology"],
        "JEE" => ["Physics", "Chemistry", "Mathematics"],
        "CET" => ["Physics", "Chemistry", "Mathematics"]
    }
    TestType.all.each do |test_type|
        type_hash[test_type.name].each do |subject|
            test_type.subject_list << Subject.find_by_name(subject).id
        end
        test_type.save
    end
  end
end


答:
I think a correlated subquery in the WHERE clause will fit the bill here:</p>

```<code>SELECT id_name, date
FROM tbl as t1
WHERE score = (SELECT max(score) FROM tbl WHERE id_name = t1.id_name)
</code>```

Title: Get max for each row between two dates?

Body:
learning sql here and I ran into a challenge.

I have the following table:

tbl <- data.frame(
   id_name = c("a", "a", "b", "c", "d", "f", "b", "c", "d", "f"),
   value = c(1, -1, 1, 1, 1, 1, -1, -1, -1, -1),
   score = c(1, 0, 1, 2, 3, 4, 3, 2, 1, 0),
   date = as.Date(c("2001-1-1", "2002-1-1", "2003-1-1", "2005-1-1",
                    "2005-1-1", "2007-1-1", "2008-1-1", "2010-1-1",
                    "2011-1-1", "2012-1-1"), "%Y-%m-%d")
                   )

+---------+-------+-------+-----------+
| id_name | value | score |   date    |
+---------+-------+-------+-----------+
| a       |     1 |     1 |  2001-1-1 |
|  a      |    -1 |     0 |  2002-1-1 |
|  b      |     1 |     1 |  2003-1-1 |
|  c      |     1 |     2 |  2005-1-1 |
|  d      |     1 |     3 |  2005-1-1 |
|  f      |     1 |     4 |  2007-1-1 |
|  b      |    -1 |     3 |  2008-1-1 |
|  c      |    -1 |     2 |  2010-1-1 |
|  d      |    -1 |     1 |  2011-1-1 |
|  f      |    -1 |     0 |  2012-1-1 |
+---------+-------+-------+-----------+

My goal is this:

For each id_name, I'd like to get the first date (in case of tie breakers) of maximum score from the tbl between the dates where the current row = id_name (inclusive)

For example, id_name 'a' should return '2001-1-1' since its score is 1
id_name 'b' should return '2007-1-1' since its score is 4:

+---------+----------+
| id_name |   date   |
+---------+----------+
| a       | 2001-1-1 |
| b       | 2007-1-1 |
+---------+----------+

This is what I have thus far,

   sqldf("
  SELECT
    id_name,
    date,
    score
  FROM
    tbl As d
  WHERE
    score = (
                        SELECT MAX(score)
                        FROM tbl As b
                        WHERE
                          date >= (
                                        SELECT MIN(date)
                                        FROM tbl
                                        WHERE id_name = b.id_name
                          ) AND
                          date <= (
                                        SELECT MAX(date)
                                        FROM tbl
                                        WHERE id_name = b.id_name
                          )
    )
  ")

Problem is that it is returning the rows with the global max value irrespective of the current row value

Thanks!

Body:
I think a correlated subquery in the WHERE clause will fit the bill here:

SELECT id_name, date
FROM tbl as t1
WHERE score = (SELECT max(score) FROM tbl WHERE id_name = t1.id_name)


问:
PyQt5 QWebview Refresh Issue
I use a QWebEngineView and set it's HTML. When I display it, the HTML is always smaller than the total area I gave the QWebEngineView. Right clicking the page and clicking "Reload" always fixes the problem, but I don't want end users to click "Reload" every time. I've already searched online for a way to reload, and found:

```<code>my_qwebengineview.page().action(QWebEnginePage.Reload).trigger()
</code>```

This isn't resizing it the same way a right click does, though.

If it helps with reading the code, it's displaying a Plotly plot as an HTML page (long story).

I create the widget it sits on with the code below:

```<code>grid_layout = QGridLayout()
logo = QLabel()
logo_pixmap = QPixmap('logo.jpg')
logo.setPixmap(logo_pixmap)
grid_layout.addWidget(logo, 0, 0, 2, 6)
grid_layout.addItem(QSpacerItem(500, 50, QSizePolicy.Minimum, QSizePolicy.Expanding), 0, 6)

graph_label = QLabel('Graph')
graph_names_combobox = QComboBox()

grid_layout.addWidget(graph_label, 0, 7, 1, 1)
grid_layout.addWidget(self.graph_names_combobox, 0, 8, 1, 4)

self.graph_widget = QStackedWidget()
grid_layout.addWidget(self.graph_widget, 2, 1, 10, 12)

self.graph_window_widget = QWidget()
self.graph_window_widget.setLayout(grid_layout)
</code>```

Later on I use:

```<code>temp_webpage = QWebEngineView()
temp_webpage.setHTML(*graph html goes here*)
self.graph_widget.addWidget(temp_webpage)

# In the course of the full program, a lot of graphs are added, so reloading
# them all here.
for child in self.graph_widget.children()
    if type(child) == QWebEngineView:
        child.page().action(QWebEnginePage.Reload).trigger()
</code>```

I've tried using the reload code right after I set it the stacked widget to the selected graph, but like I said, it's having the same result.

Is there a way to make the page do the same thing as right click -> reload?

Edit

In response to a comment, the code I use to generate the html comes from this (data is a pandas DataFrame that I load somewhere else from SQL, but I've included a toy DataFrame here):

```<code>path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()

data_frame = DataFrame(index=(range(2)),columns=('Date', 'SKUs', 'Lines', 'Orders', 'Eaches'))

data_frame.loc[0:1,'Date'] = (datetime.date(1999, 1, 1), datetime.date(1999, 1, 2))
data_frame.loc[0:1,'SKUs'] = (12, 13)
data_frame.loc[0:1,'Lines'] = (14, 15)
data_frame.loc[0:1,'Orders'] = (16, 17)
data_frame.loc[0:1,'Eaches'] = (18, 19)

trace_lines = Bar(x=data_frame['Date'], y=data_frame['Lines'], name='Lines', visible=True)
            trace_orders = Bar(x=data_frame['Date'], y=data_frame['Orders'], name='Orders', visible=False)
            trace_eaches = Bar(x=data_frame['Date'], y=data_frame['Eaches'], name='Eaches', visible=False)
            trace_SKUs = Bar(x=data_frame['Date'], y=data_frame['SKUs'], name='SKUs', visible=False)

data = [trace_lines, trace_orders, trace_eaches, trace_SKUs]

lines_title = "%s Lines" % name
orders_title = "%s Orders" % name
eaches_title = "%s Eaches" % name
skus_title = "%s SKUs" % name

update_menus = list([dict(active=0,
                                  buttons=list([dict(label='Lines',
                                                     method='update',
                                                     args=[{'visible': [True, False, False, False]},
                                                           {'title': lines_title}]),
                                                dict(label='Orders',
                                                     method='update',
                                                     args=[{'visible': [False, True, False, False]},
                                                           {'title': orders_title}]),
                                                dict(label='Eaches',
                                                     method='update',
                                                     args=[{'visible': [False, False, True, False]},
                                                           {'title': eaches_title}]),
                                                dict(label='SKUs',
                                                     method='update',
                                                     args=[{'visible': [False, False, False, True]},
                                                           {'title': skus_title}])]))])

layout = dict(title=lines_title, showlegend=False, updatemenus=update_menus, xaxis=dict(
            rangeselector=dict(buttons=list([dict(count=1, label='1m', step='month', stepmode='backward'),
                                             dict(count=6, label='6m', step='month', stepmode='backward'),
                                             dict(step='all')])),
            rangeslider=dict(),
            type='date'
        ))

fig = dict(data=data, layout=layout)

raw_html = '<html><head><meta charset="utf-8" /><script src="{}"></script></head>'.format(local)
raw_html += '<body>'
raw_html += plot(fig, include_plotlyjs=False, output_type='div')
raw_html += '</body></html>'

return raw_html
</code>```

答:
A possible solution is to reload the page for the second time as shown below:</p>

```<code>    self.isFirst = True
    temp_webpage.loadFinished.connect(self.onLoadFinished)

def onLoadFinished(self, ok):
    if self.isFirst:
        # self.sender().page().action(QWebEnginePage.Reload).trigger()
        self.sender().reload()
    self.isFirst = False
</code>```

Title: PyQt5 QWebview Refresh Issue

Body:
I use a QWebEngineView and set it's HTML. When I display it, the HTML is always smaller than the total area I gave the QWebEngineView. Right clicking the page and clicking "Reload" always fixes the problem, but I don't want end users to click "Reload" every time. I've already searched online for a way to reload, and found:

my_qwebengineview.page().action(QWebEnginePage.Reload).trigger()

This isn't resizing it the same way a right click does, though.

If it helps with reading the code, it's displaying a Plotly plot as an HTML page (long story).

I create the widget it sits on with the code below:

grid_layout = QGridLayout()
logo = QLabel()
logo_pixmap = QPixmap('logo.jpg')
logo.setPixmap(logo_pixmap)
grid_layout.addWidget(logo, 0, 0, 2, 6)
grid_layout.addItem(QSpacerItem(500, 50, QSizePolicy.Minimum, QSizePolicy.Expanding), 0, 6)

graph_label = QLabel('Graph')
graph_names_combobox = QComboBox()

grid_layout.addWidget(graph_label, 0, 7, 1, 1)
grid_layout.addWidget(self.graph_names_combobox, 0, 8, 1, 4)

self.graph_widget = QStackedWidget()
grid_layout.addWidget(self.graph_widget, 2, 1, 10, 12)

self.graph_window_widget = QWidget()
self.graph_window_widget.setLayout(grid_layout)

Later on I use:

temp_webpage = QWebEngineView()
temp_webpage.setHTML(*graph html goes here*)
self.graph_widget.addWidget(temp_webpage)

# In the course of the full program, a lot of graphs are added, so reloading
# them all here.
for child in self.graph_widget.children()
    if type(child) == QWebEngineView:
        child.page().action(QWebEnginePage.Reload).trigger()

I've tried using the reload code right after I set it the stacked widget to the selected graph, but like I said, it's having the same result.

Is there a way to make the page do the same thing as right click -> reload?

Edit

In response to a comment, the code I use to generate the html comes from this (data is a pandas DataFrame that I load somewhere else from SQL, but I've included a toy DataFrame here):

path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()

data_frame = DataFrame(index=(range(2)),columns=('Date', 'SKUs', 'Lines', 'Orders', 'Eaches'))

data_frame.loc[0:1,'Date'] = (datetime.date(1999, 1, 1), datetime.date(1999, 1, 2))
data_frame.loc[0:1,'SKUs'] = (12, 13)
data_frame.loc[0:1,'Lines'] = (14, 15)
data_frame.loc[0:1,'Orders'] = (16, 17)
data_frame.loc[0:1,'Eaches'] = (18, 19)

trace_lines = Bar(x=data_frame['Date'], y=data_frame['Lines'], name='Lines', visible=True)
            trace_orders = Bar(x=data_frame['Date'], y=data_frame['Orders'], name='Orders', visible=False)
            trace_eaches = Bar(x=data_frame['Date'], y=data_frame['Eaches'], name='Eaches', visible=False)
            trace_SKUs = Bar(x=data_frame['Date'], y=data_frame['SKUs'], name='SKUs', visible=False)

data = [trace_lines, trace_orders, trace_eaches, trace_SKUs]

lines_title = "%s Lines" % name
orders_title = "%s Orders" % name
eaches_title = "%s Eaches" % name
skus_title = "%s SKUs" % name

update_menus = list([dict(active=0,
                                  buttons=list([dict(label='Lines',
                                                     method='update',
                                                     args=[{'visible': [True, False, False, False]},
                                                           {'title': lines_title}]),
                                                dict(label='Orders',
                                                     method='update',
                                                     args=[{'visible': [False, True, False, False]},
                                                           {'title': orders_title}]),
                                                dict(label='Eaches',
                                                     method='update',
                                                     args=[{'visible': [False, False, True, False]},
                                                           {'title': eaches_title}]),
                                                dict(label='SKUs',
                                                     method='update',
                                                     args=[{'visible': [False, False, False, True]},
                                                           {'title': skus_title}])]))])

layout = dict(title=lines_title, showlegend=False, updatemenus=update_menus, xaxis=dict(
            rangeselector=dict(buttons=list([dict(count=1, label='1m', step='month', stepmode='backward'),
                                             dict(count=6, label='6m', step='month', stepmode='backward'),
                                             dict(step='all')])),
            rangeslider=dict(),
            type='date'
        ))

fig = dict(data=data, layout=layout)

raw_html = '<meta charset="utf-8" />'.format(local)
raw_html += ''
raw_html += plot(fig, include_plotlyjs=False, output_type='div')
raw_html += ''

return raw_html

Body:
A possible solution is to reload the page for the second time as shown below:

    self.isFirst = True
    temp_webpage.loadFinished.connect(self.onLoadFinished)

def onLoadFinished(self, ok):
    if self.isFirst:
        # self.sender().page().action(QWebEnginePage.Reload).trigger()
        self.sender().reload()
    self.isFirst = False


问:
Drop down parameters based on Condition for Cloud Formation
Is there way by which we can change the drop down list of parameters based on one of the above parameters?
If we select "Env: Prod" choice out of Prod/Dev in the dropdown list of environments list, it should list all the VPCs which belongs to Prod environment. Similarly for Dev as well..
Based on those Environment VPCs, it should list available subnets and Security Groups..</p>

答:
That functionality is not yet suported but you can implement some assertions rule for ex.

```<code>Rules:
  SubnetsInVPC:
    Assertions:
      - Assert: !EachMemberIn [!ValueOfAll ['AWS::EC2::Subnet::Id', VpcId], !RefAll 'AWS::EC2::VPC::Id']
        AssertDescription: All subnets must in the VPC
</code>```

With this, you can make sure that selected values are within or related to the valid range or service parameters.

Body:
That functionality is not yet suported but you can implement some assertions rule for ex.

Rules:
  SubnetsInVPC:
    Assertions:
      - Assert: !EachMemberIn [!ValueOfAll ['AWS::EC2::Subnet::Id', VpcId], !RefAll 'AWS::EC2::VPC::Id']
        AssertDescription: All subnets must in the VPC

With this, you can make sure that selected values are within or related to the valid range or service parameters.


问:
"Invalid folder" error when compressing files with SharpZipLib
I have this function that I'm using to compress a list of files from the user's session, and then streaming it to the user's browser for download:

```<code>public static void DownloadAllPhotos()
{
    HttpContext.Current.Response.AddHeader(
        "Content-Disposition", "attachment; filename=Photos.zip");
    HttpContext.Current.Response.ContentType = "application/zip";

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

    if (HttpContext.Current.Session != null &&
        HttpContext.Current.Session["userPhotos"] != null)
    {
        photos = (List<string>)HttpContext.Current.Session["userPhotos"];
    }

    using (var zipStream = new
        ZipOutputStream(HttpContext.Current.Response.OutputStream))
    {
        foreach (string photoUrl in photos)
        {
            byte[] fileBytes = File.ReadAllBytes(photoUrl);

            var fileEntry = new ZipEntry(
                Path.GetFileName(photoUrl))
            {
                Size = fileBytes.Length
            };

            zipStream.PutNextEntry(fileEntry);
            zipStream.Write(fileBytes, 0, fileBytes.Length);
        }

        zipStream.Flush();
        zipStream.Close();

        // reset session
        HttpContext.Current.Session["userPhotos"] = new List<string>();
    }
}
</code>```

When the user has photo urls in their session, and they click a button to call this function, the files are compressed and the download starts in the user's browser.

But when I try to open the compressed file, I get this error:

Windows cannot open the folder.

The compressed folder "{Path to my file}" is invalid.

Am I doing something wrong that's causing this error?

答:
Also per the example in @cfeduke 's answer, there is a comment in the 'Create a Zip as a browser download attachment in IIS' that suggests changing Response.ContentType = "application/octet-stream" instead of "application/zip"

// If the browser is receiving a mangled zipfile, IIS Compression may
  cause this problem. Some members have found that
    //Response.ContentType = "application/octet-stream" has solved this.
  May be specific to Internet Explorer.

Worked for me. And it was not IE specific (I use Chrome).

Body:
I have this function that I'm using to compress a list of files from the user's session, and then streaming it to the user's browser for download:

public static void DownloadAllPhotos()
{
    HttpContext.Current.Response.AddHeader(
        "Content-Disposition", "attachment; filename=Photos.zip");
    HttpContext.Current.Response.ContentType = "application/zip";

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

    if (HttpContext.Current.Session != null &&
        HttpContext.Current.Session["userPhotos"] != null)
    {
        photos = (List<string>)HttpContext.Current.Session["userPhotos"];
    }

    using (var zipStream = new
        ZipOutputStream(HttpContext.Current.Response.OutputStream))
    {
        foreach (string photoUrl in photos)
        {
            byte[] fileBytes = File.ReadAllBytes(photoUrl);

            var fileEntry = new ZipEntry(
                Path.GetFileName(photoUrl))
            {
                Size = fileBytes.Length
            };

            zipStream.PutNextEntry(fileEntry);
            zipStream.Write(fileBytes, 0, fileBytes.Length);
        }

        zipStream.Flush();
        zipStream.Close();

        // reset session
        HttpContext.Current.Session["userPhotos"] = new List<string>();
    }
}

When the user has photo urls in their session, and they click a button to call this function, the files are compressed and the download starts in the user's browser.

But when I try to open the compressed file, I get this error:

Windows cannot open the folder.

The compressed folder "{Path to my file}" is invalid.

Am I doing something wrong that's causing this error?


问:
Running Scala Spark Jobs on Existing EMR
I have Spark Job aggregationfinal_2.11-0.1 jar which I am running on my machine.the composition of it is as follows :

```<code>package deploy
    object FinalJob {
      def main(args: Array[String]): Unit = {
        val spark = SparkSession
          .builder()
          .appName(s"${this.getClass.getSimpleName}")
          .config("spark.sql.shuffle.partitions", "4")
          .getOrCreate()

    //continued code
    }
    }
</code>```

When I am running this code in local mode, it is running fine but when I am deploying this on the EMR cluster with putting its jar in main node.It is giving error as :

```<code>ClassNotFoundException : deploy.FinalJob
</code>```

What am i missing here?

答: try to unjar it to some folder and look for target/classes using the below command jar -xvf myapp.jar. If the target classes is not containing the class you are executing then there is an issue with the way you build your jar. I would recommend maven assembly to be in your pom for packaging. </p>

Body:
I have Spark Job aggregationfinal_2.11-0.1 jar which I am running on my machine.the composition of it is as follows :

package deploy
    object FinalJob {
      def main(args: Array[String]): Unit = {
        val spark = SparkSession
          .builder()
          .appName(s"${this.getClass.getSimpleName}")
          .config("spark.sql.shuffle.partitions", "4")
          .getOrCreate()

    //continued code
    }
    }

When I am running this code in local mode, it is running fine but when I am deploying this on the EMR cluster with putting its jar in main node.It is giving error as :

ClassNotFoundException : deploy.FinalJob

What am i missing here?


问:
Generalization vs Specialization of DB table
When I want to design database tables that model a finite parent-child relationship, for e.g., computer as parent, and the components inside as the child; or a simple organizational hierarchy, I am usually torn at which approach to use -

A 'specialized table' approach, in which I create a table for each of the possible entity. In the computer component example, I would have a Computer table and a Component table, with the ComputerID as FK in the Component table referencing back to Computer.ComputerID.
or

A 'generalized table approach, in which I have one table table called Component, with ComponentID as PK, and a ParentComponentID as FK referencing to its parent's ComponentID.

答:
I prefer the generalized table if I know I need the ability to extend the model to support new levels in a hierarchy.

The disadvantage with a generalized table is losing the strong typing, which I've usually solved by adding a 'Type' table (i.e. 'ComponentType' for the generic 'Component' table).

This allows for a model that can be extended, and still provides strong typing of each component in the hierarchy.

EDIT:  Marcus brought up the question of Computer being the same as a Component.  I should clarify that the generalized table approach should be used for like objects.

OwnerDisplayName: Jay S

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jay S


问:
Shorter version of string match in Scala
I have the following code:

```<code>if (element.matches("class Int"))
      true
    else
      false
</code>```

Is it possible to use a function like the *.getOrElse for Sets to have cleaner code?

答:
Is it something like this you're thinking about. I don't see how it makes things better unless you have a for()-comprehension and want to stop on a condition:</p>

```<code>Some("a".matches("b")).filter(t => t).getOrElse(false)
</code>```

Body:
I have the following code:

if (element.matches("class Int"))
      true
    else
      false

Is it possible to use a function like the *.getOrElse for Sets to have cleaner code?

Body:
Is it something like this you're thinking about. I don't see how it makes things better unless you have a for()-comprehension and want to stop on a condition:

Some("a".matches("b")).filter(t => t).getOrElse(false)


问:
How to balance the thread number in nested case when using OpenMP?
This fabulous post teaches me a lot, but I still have a question. For the following code:

```<code>double multiply(std::vector<double> const& a, std::vector<double> const& b){
    double tmp(0);
    int active_levels = omp_get_active_level();
    #pragma omp parallel for reduction(+:tmp) if(active_level < 1)
    for(unsigned int i=0;i<a.size();i++){
        tmp += a[i]+b[i];
    }
    return tmp;
}
</code>```

If multiply() is called from another parallel part:

```<code>#pragma omp parallel for
for (int i = 0; i < count; i++) {
    multiply(a[i], b[i]);
}
</code>```

Because the outer loop iteration depends on count variable, if count is a big number, it is reasonable. But if count is only 1 and our server is a multiple-core machine(e.g., has 512 cores), then the multiply() function only generate 1 thread. So in this case, the server is under-utilized. BTW, the answer also mentioned:

In any case, writing such code is a bad practice. You should simply leave the parallel regions as they are and allow the end user choose whether nested parallelism should be enabled or not.

So how to balance the thread number in nested case when using OpenMP?

答:
Consider using OpenMP tasks (omp taskloop within one parallel section and an intermediate omp single). This allows you to flexibly use the threads in OpenMP on different nesting levels instead of manually defining numbers of threads for each level or oversubscribing OS threads.

However this comes at increased scheduling costs. At the end of the day, there is no perfect solution that will always do best. Instead you will have to keep measuring and analyzing your performance on practical inputs.

Body:
This fabulous post teaches me a lot, but I still have a question. For the following code:

double multiply(std::vector<double> const& a, std::vector<double> const& b){
    double tmp(0);
    int active_levels = omp_get_active_level();
    #pragma omp parallel for reduction(+:tmp) if(active_level < 1)
    for(unsigned int i=0;i<a.size();i++){
        tmp += a[i]+b[i];
    }
    return tmp;
}

If multiply() is called from another parallel part:

#pragma omp parallel for
for (int i = 0; i < count; i++) {
    multiply(a[i], b[i]);
}

Because the outer loop iteration depends on count variable, if count is a big number, it is reasonable. But if count is only 1 and our server is a multiple-core machine(e.g., has 512 cores), then the multiply() function only generate 1 thread. So in this case, the server is under-utilized. BTW, the answer also mentioned:

In any case, writing such code is a bad practice. You should simply leave the parallel regions as they are and allow the end user choose whether nested parallelism should be enabled or not.

So how to balance the thread number in nested case when using OpenMP?


问:
Spring webflux interact with Mono object
I have a simple CRUD controller. When updating I want merge the updated model with the model that has to be updated, this is what I have at the moment:

```<code>@PutMapping("{id}")
public Mono<Map> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    // Update the server here.
    // server.setName(updatedServer.getName());
    // server.setHost(updatedServer.getHost());

    server.flatMap(this.serverRepository::save).subscribe();

    return Mono.just(Collections.singletonMap("success", true));
}
</code>```

How can I edit the server variable before the save? When subscribing on the Mono it will be executed after the save.

I know this is a pretty simple question, but I just can't find a way to do it.

答:
I always find the answer just after asking the question...

I just used another flatmap to edit the object:

```<code>@PutMapping("{id}")
public Mono<Server> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    return server.flatMap(value -> {
        value.setName(updatedServer.getName());
        value.setHost(updatedServer.getHost());
        return Mono.just(value); // Can this be done cleaner?
    }).flatMap(this.serverRepository::save);
}
</code>```

Or when still returning success: true:

```<code>@PutMapping("{id}")
public Mono<Map> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    return server.flatMap(value -> {
        value.setName(updatedServer.getName());
        value.setHost(updatedServer.getHost());
        return Mono.just(value); // Can this be done cleaner?
    }).flatMap(this.serverRepository::save).subscribe();

    return Mono.just(Collections.singletonMap("success", true));
}
</code>```

Body:
I have a simple CRUD controller. When updating I want merge the updated model with the model that has to be updated, this is what I have at the moment:

@PutMapping("{id}")
public Mono<Map> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    // Update the server here.
    // server.setName(updatedServer.getName());
    // server.setHost(updatedServer.getHost());

    server.flatMap(this.serverRepository::save).subscribe();

    return Mono.just(Collections.singletonMap("success", true));
}

How can I edit the server variable before the save? When subscribing on the Mono it will be executed after the save.

I know this is a pretty simple question, but I just can't find a way to do it.

Body:
I always find the answer just after asking the question...

I just used another flatmap to edit the object:

@PutMapping("{id}")
public Mono<Server> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    return server.flatMap(value -> {
        value.setName(updatedServer.getName());
        value.setHost(updatedServer.getHost());
        return Mono.just(value); // Can this be done cleaner?
    }).flatMap(this.serverRepository::save);
}

Or when still returning success: true:

@PutMapping("{id}")
public Mono<Map> update(@PathVariable UUID id, @RequestBody Server updatedServer) {
    Mono<Server> server = this.serverRepository.findById(id);

    return server.flatMap(value -> {
        value.setName(updatedServer.getName());
        value.setHost(updatedServer.getHost());
        return Mono.just(value); // Can this be done cleaner?
    }).flatMap(this.serverRepository::save).subscribe();

    return Mono.just(Collections.singletonMap("success", true));
}


问:
How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1
When I run XAMPP Control Panel v3.2.1 I get this error:

07:37:24  [Apache]  Problem detected!
07:37:24  [Apache]  Port 443 in use by ""C:\Program Files (x86)\VMware\VMware Workstation\vmware-hostd.exe" -u "C:\ProgramData\VMware\hostd\config.xml"" with PID 2148!
07:37:24  [Apache]  Apache WILL NOT start without the configured ports free!
07:37:24  [Apache]  You need to uninstall/disable/reconfigure the blocking application
07:37:24  [Apache]  or reconfigure Apache and the Control Panel to listen on a different port
```

I could not fix it myself. Getting help soon will be thankful.

答:
Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel.
You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left).
Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

Body:
When I run XAMPP Control Panel v3.2.1 I get this error:

07:37:24  [Apache]  Problem detected!
07:37:24  [Apache]  Port 443 in use by ""C:\Program Files (x86)\VMware\VMware Workstation\vmware-hostd.exe" -u "C:\ProgramData\VMware\hostd\config.xml"" with PID 2148!
07:37:24  [Apache]  Apache WILL NOT start without the configured ports free!
07:37:24  [Apache]  You need to uninstall/disable/reconfigure the blocking application
07:37:24  [Apache]  or reconfigure Apache and the Control Panel to listen on a different port

I could not fix it myself. Getting help soon will be thankful.


问:
paragraph comparison in PHP
i was wondering... let's say i have a webpage that crawls articles from the web. all i get is the title and the article in plain-text. is there a PHP script or webservice that can relate articles between them? or... is there a PHP script that can generate keywords from a paragraph?

i have tested a script in JAVA that works, but maybe there's a PHPclass somewhere that can help...

thanks!

答:
The functions from this answer can be used to extract words from text and compare them against each other. Rough example:</p>

```<code>// For better results grab the texts manually and paste them here.
$nyt = file_get_contents('http://www.nytimes.com/2011/01/19/technology/19apple.html?pagewanted=print');
$sfc = file_get_contents('http://www.sfgate.com/cgi-bin/article.cgi?f=/c/a/2011/01/19/BUAK1HARUL.DTL&type=business');

$nyt = strip_tags($nyt);
$sfc = strip_tags($sfc);

// stopwords from english snowball porter stemmer
$stopwordsFile = dirname(__FILE__).'/includes/stopwords_en.txt';
if (file_exists($stopwordsFile)) {
    $stopwords = file($stopwordsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
    $stopwords = array();
}

$nytWords = extractWords($nyt, 3, $stopwords);
$sfcWords = extractWords($sfc, 3, $stopwords);

$nyt2sfcCount = countKeywords($nytWords, $sfcWords, 4);
$sfc2nytCount = countKeywords($sfcWords, $nytWords, 4);

// absolute
print_r($nyt2sfcCount);
print_r($sfc2nytCount);

$nyt2sfcFactor = strlen($sfc) / strlen($nyt);
$sfc2nytFactor = strlen($nyt) / strlen($sfc);

print($nyt2sfcFactor . PHP_EOL);
print($sfc2nytFactor . PHP_EOL);

foreach ($nyt2sfcCount as $word => $count) {
    $nyt2sfcCountRel[$word] = $count * $nyt2sfcFactor;
}

foreach ($sfc2nytCount as $word => $count) {
    $sfc2nytCountRel[$word] = $count * $sfc2nytFactor;
}

// relative
print_r($nyt2sfcCountRel);
print_r($sfc2nytCount);
print_r($nyt2sfcCount);
print_r($sfc2nytCountRel);

// reduce
$nyt2sfcCountRed = array_intersect_key($nyt2sfcCount, $sfc2nytCount);
$sfc2nytCountRed = array_intersect_key($sfc2nytCount, $nyt2sfcCount);

// reduced absolute
print_r($nyt2sfcCountRed);
print_r($sfc2nytCountRed);

foreach ($nyt2sfcCountRed as $word => $count) {
    $nyt2sfcCountRedRel[$word] = $count * $nyt2sfcFactor;
}

foreach ($sfc2nytCountRed as $word => $count) {
    $sfc2nytCountRedRel[$word] = $count * $sfc2nytFactor;
}

// reduced relative
print_r($nyt2sfcCountRedRel);
print_r($sfc2nytCountRed);
print_r($nyt2sfcCountRed);
print_r($sfc2nytCountRedRel);
</code>```

Title: paragraph comparison in PHP

Body:
The functions from this answer can be used to extract words from text and compare them against each other. Rough example:

// For better results grab the texts manually and paste them here.
$nyt = file_get_contents('http://www.nytimes.com/2011/01/19/technology/19apple.html?pagewanted=print');
$sfc = file_get_contents('http://www.sfgate.com/cgi-bin/article.cgi?f=/c/a/2011/01/19/BUAK1HARUL.DTL&type=business');

$nyt = strip_tags($nyt);
$sfc = strip_tags($sfc);

// stopwords from english snowball porter stemmer
$stopwordsFile = dirname(__FILE__).'/includes/stopwords_en.txt';
if (file_exists($stopwordsFile)) {
    $stopwords = file($stopwordsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
    $stopwords = array();
}

$nytWords = extractWords($nyt, 3, $stopwords);
$sfcWords = extractWords($sfc, 3, $stopwords);

$nyt2sfcCount = countKeywords($nytWords, $sfcWords, 4);
$sfc2nytCount = countKeywords($sfcWords, $nytWords, 4);

// absolute
print_r($nyt2sfcCount);
print_r($sfc2nytCount);

$nyt2sfcFactor = strlen($sfc) / strlen($nyt);
$sfc2nytFactor = strlen($nyt) / strlen($sfc);

print($nyt2sfcFactor . PHP_EOL);
print($sfc2nytFactor . PHP_EOL);

foreach ($nyt2sfcCount as $word => $count) {
    $nyt2sfcCountRel[$word] = $count * $nyt2sfcFactor;
}

foreach ($sfc2nytCount as $word => $count) {
    $sfc2nytCountRel[$word] = $count * $sfc2nytFactor;
}

// relative
print_r($nyt2sfcCountRel);
print_r($sfc2nytCount);
print_r($nyt2sfcCount);
print_r($sfc2nytCountRel);

// reduce
$nyt2sfcCountRed = array_intersect_key($nyt2sfcCount, $sfc2nytCount);
$sfc2nytCountRed = array_intersect_key($sfc2nytCount, $nyt2sfcCount);

// reduced absolute
print_r($nyt2sfcCountRed);
print_r($sfc2nytCountRed);

foreach ($nyt2sfcCountRed as $word => $count) {
    $nyt2sfcCountRedRel[$word] = $count * $nyt2sfcFactor;
}

foreach ($sfc2nytCountRed as $word => $count) {
    $sfc2nytCountRedRel[$word] = $count * $sfc2nytFactor;
}

// reduced relative
print_r($nyt2sfcCountRedRel);
print_r($sfc2nytCountRed);
print_r($nyt2sfcCountRed);
print_r($sfc2nytCountRedRel);


问:
Update Access Database (.mdb) using GridView where ID column is not visible
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query.

I have a GridView in which I am displaying the following:

```<code><asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false"
runat="server" DataKeyNames="ID"
OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
    </Columns>
</asp:GridView>
</code>```

My database has an ID field that I am not displaying on the GridView.

When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database.

My Button Click event is the following:

```<code>protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        con.Open();
        string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>...";
        OleDBCommand updateCommand = new OleDBCommand(updateQuery,con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGrid();    // Method to populate and display the GridView on the screen.
    }
</code>```

I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner:

```<code>protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int rowID = Convert.ToInt32(e.CommandArgument);
        }
    }
</code>```

In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update.

I am trying to do what David mentioned in his answer here:

https://stackoverflow.com/a/19824029/8930129

But "row" is getting a null value, because of which I am getting an System.NullReferenceException.

```<code>// ****Update Command **** //
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
    try
    {
        int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex;
        int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]);
        con.Open();
        string ConnString = GetConnString();
        string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + "";
        using (OleDbConnection conn = new OleDbConnection(ConnString))
        {
            using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn))
            {
                commandUpdate.CommandType = CommandType.Text;
                commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
                commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
                commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
                commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue);
                commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue);
            }
        }
        OleDbCommand updateCommand = new OleDbCommand(updateQuery, con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGridView();    // Function to populate data in GridView
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        // Some code...
    }
    finally
    {
        // Some code...
    }
}
</code>```

答:
I'm not sure you are quite going about it the right way. You want to use the gridview row number to lookup the database ID so that you can use that database ID to update the row in the database?

You should be able to store the IDs as part of the GridView, even if you aren't displaying them.

Check out the DataKeyNames property of a GridView. It allows you to specify the primary key fields of your object.

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames(v=vs.110).aspx

Then you can access the IDs on postback events, check out this example:

https://www.aspsnippets.com/Articles/DataKeyNames-in-GridView-example-in-ASPNet.aspx

Body:
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query.

I have a GridView in which I am displaying the following:

<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false"
runat="server" DataKeyNames="ID"
OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
    </Columns>
</asp:GridView>

My database has an ID field that I am not displaying on the GridView.

When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database.

My Button Click event is the following:

protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        con.Open();
        string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>...";
        OleDBCommand updateCommand = new OleDBCommand(updateQuery,con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGrid();    // Method to populate and display the GridView on the screen.
    }

I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner:

protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int rowID = Convert.ToInt32(e.CommandArgument);
        }
    }

In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update.

I am trying to do what David mentioned in his answer here:

https://stackoverflow.com/a/19824029/8930129

But "row" is getting a null value, because of which I am getting an System.NullReferenceException.

// ****Update Command **** //
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
    try
    {
        int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex;
        int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]);
        con.Open();
        string ConnString = GetConnString();
        string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + "";
        using (OleDbConnection conn = new OleDbConnection(ConnString))
        {
            using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn))
            {
                commandUpdate.CommandType = CommandType.Text;
                commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text);
                commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text);
                commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text);
                commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue);
                commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue);
            }
        }
        OleDbCommand updateCommand = new OleDbCommand(updateQuery, con);
        updateCommand.ExecuteNonQuery();
        con.Close();
        ShowGridView();    // Function to populate data in GridView
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        // Some code...
    }
    finally
    {
        // Some code...
    }
}


问:
Android studio Firebase and Github pushing and cloning
I have created a small project for user register and login in(Authentication) android studio using firebase and it was working fine. Basically i need to keep this project on github, I have moved to project to my desktop and then pushed it to github. My version of the project works, however, the cloned project doesn't seem to work as it just keeps loading when the user wants to register or login.

Also, it comes up with some errors like missing iml's or that the app has multiple slice apk's and need to uninstall.

My question is what steps do I need to undertake to make sure that the application will work when pushed to a github repo and then cloned back from the repo, so that the application runs when downloaded on any pc, and do i have to do anything to the firebase?

since what i see is that everything is in place, package name hasnt changed, all files and dependencies are present.

答:
First of all i was using Email and password authentication.

Secondly the issue was that the google play was not updated inside of the emulator.

For anyone that runs into the same problem click the three dots at the bottom of the emulator panel and go into "Google Play" and update.

Hope this helps someone!


问:
Excel VBA Macro - find text in cell one, replace value in adjacent cell
Working on a vendor's sales document provided by a grocer, which lists the number of units they sold. Issue is that their excel sheet and the way they record sales (which I cannot change) doesn't differentiate between single bars sold and boxes sold - so some rows state "Mint Bar" = 1 sold and some state "Mint Bar Box" = 1 sold. The unit values are the same in the sheet, but the "box" should really = 12 (since a box is 12 units, not just 1).

The second issue is that every time "box" appears that value needs to be n*12 (so 1box*12 = 12 bars).

Thus, I am looking for some code to help me out. I know this is easy in SQL and have less experience running excel macros.

--
Fixed:

Where the Boxes appear in D2, D6, D8, etc:

```<code>=if(Cell="Box", 12*D2, 12*D6, 12*D8)
</code>```

Drag formula down for all the rows in the sheet.

答:
do you have to do this in a macro? I would just add another column that says

=if(Cell="Mint Bar Box", 12, 1)

Body:
Working on a vendor's sales document provided by a grocer, which lists the number of units they sold. Issue is that their excel sheet and the way they record sales (which I cannot change) doesn't differentiate between single bars sold and boxes sold - so some rows state "Mint Bar" = 1 sold and some state "Mint Bar Box" = 1 sold. The unit values are the same in the sheet, but the "box" should really = 12 (since a box is 12 units, not just 1).

The second issue is that every time "box" appears that value needs to be n*12 (so 1box*12 = 12 bars).

Thus, I am looking for some code to help me out. I know this is easy in SQL and have less experience running excel macros.

--
Fixed:

Where the Boxes appear in D2, D6, D8, etc:

=if(Cell="Box", 12*D2, 12*D6, 12*D8)

Drag formula down for all the rows in the sheet.


问:
How do I add multiple inputs from a prompt in an array together?
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct. </p>

```<code>var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "<br>");
}
</code>```

答:
```<code>    var number = new Array(10);
    var total; //create a variable for your total
    var average; //create a variable for your average
    for(var i=0; i<10; i++)
    {
    var number[i] = prompt("PLEASE ENTER A NUMBER"); //make sure all the
                                                     //numbers have their
                                                     //own ids which is 'i'
                                                     //in this case
    total +=  parseInt(number); //this basically means total = previoustotal
             //+ newly parsed number
    }

    average = total/10; //leave this outside because you want to do the
                        //calculations at the end

    for(var i=0; i < number.length ; i++)
    {
    document.write("The difference from the average for the number," +
    number[i] + "is equal to " + (number[i] - average) +  "<br>");
    } //this will print out a difference output for all 10 numbers you
      //inputted
</code>```

Not sure how your CSS and HTML was made so i'll just leave the br in there

Body:
I was instructed to create a program that takes 10 numbers from a user. Then it should display it and find its difference from the average (from the 10 numbers inputted.) I've messed around with the code for a while but I'm not sure what I'm doing wrong. When I open in browser, the calculations aren't correct.

var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total =  parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) +  "
");
}

Body:
    var number = new Array(10);
    var total; //create a variable for your total
    var average; //create a variable for your average
    for(var i=0; i<10; i++)
    {
    var number[i] = prompt("PLEASE ENTER A NUMBER"); //make sure all the
                                                     //numbers have their
                                                     //own ids which is 'i'
                                                     //in this case
    total +=  parseInt(number); //this basically means total = previoustotal
             //+ newly parsed number
    }

    average = total/10; //leave this outside because you want to do the
                        //calculations at the end

    for(var i=0; i < number.length ; i++)
    {
    document.write("The difference from the average for the number," +
    number[i] + "is equal to " + (number[i] - average) +  "<br>");
    } //this will print out a difference output for all 10 numbers you
      //inputted

Not sure how your CSS and HTML was made so i'll just leave the br in there


问:
What are JavaScript Objects and Properties?
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

```<code>{}, 'hello'
{ x: 5 }, 'y'
</code>```

Output Example:

```<code>{ hello: null }
{ x: 5, y: null }
</code>```

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

```<code>function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');
</code>```

答:
I think you're over-thinking it.

First the question:

Add the value of the property argument as a key on the object
  argument. The value of the new property should be set to null. Return
  object after adding the new property.

emphasis added

So, property will be the KEY (of a key/value pair), and the VALUE will be null of object, which we are also passing in as an argument.

One way to interrogate key/value pairs on a javascript object is through the square-brackets [].  So, if you have a key/value pair: { foo: "bar" }, you can get "bar" by: object['foo'].  You can also create new key/value pairs like this, so your function can look like:

```<code>function addProperty(object, property) {
    object[property] = null;
    return object;
}

var obj = {};

obj = addProperty(obj, "hello");

console.log(obj);
console.log(addProperty({x: 5}, 'y'));
</code>```

What our function is doing is taking the object passed into it (as an argument), creating a new KEY with our property argument, and setting its VALUE to null, and simply returning the object.

*Side note -

Be careful, the code you have posted will create an endless recursive loop, as you keep calling the same function with no way to break out of it.

Body:
Can anyone explain objects and properties to me in Javascript in layman's terms? The Javascript MDN documentation is confusing me.

I am trying to solve a problem in a Javascript tutorial about objects and properties The question is below and my attempt at the code, I think I followed the MDN as far as I can grasp it. Any help would be appreciated!

Question: Add the value of the property argument as a key on the object argument.
The value of the new property should be set to null.
Return object after adding the new property.

Input Example:

{}, 'hello'
{ x: 5 }, 'y'

Output Example:

{ hello: null }
{ x: 5, y: null }

note: the property name is NOT 'property'.  The name is the value of the argument called property (a string).

My code:
//NOTE: the function addProperty(object, property) was already in the console and I have to write the solution inside of it.

function addProperty(object, property) {
  // code here
  let result = addProperty({x: 5}, 'y');
  obj[property] = null;
  return obj;
}

addProperty(x, 'y');

Body:
I think you're over-thinking it.

First the question:

Add the value of the property argument as a key on the object
  argument. The value of the new property should be set to null. Return
  object after adding the new property.

emphasis added

So, property will be the KEY (of a key/value pair), and the VALUE will be null of object, which we are also passing in as an argument.

One way to interrogate key/value pairs on a javascript object is through the square-brackets [].  So, if you have a key/value pair: { foo: "bar" }, you can get "bar" by: object['foo'].  You can also create new key/value pairs like this, so your function can look like:

function addProperty(object, property) {
    object[property] = null;
    return object;
}

var obj = {};

obj = addProperty(obj, "hello");

console.log(obj);
console.log(addProperty({x: 5}, 'y'));

What our function is doing is taking the object passed into it (as an argument), creating a new KEY with our property argument, and setting its VALUE to null, and simply returning the object.

*Side note -

Be careful, the code you have posted will create an endless recursive loop, as you keep calling the same function with no way to break out of it.


问:
Call stored procedure specifying only parameters with a value
In an instance of SQL Server 2016 I have a stored procedure with dozens of parameters. For example:

```<code>CREATE PROCEDURE spName (
    @par1 INT = NULL,
    @par2 VARCHAR(10) = NULL,
        ....
        ....
    @par98 INT = NULL,
    @par99 INT = NULL,
) AS
BEGIN
    ....
    ....
END
</code>```

I have a client written in C# that calls the stored procedure specifying only the parameters with a value. Ex:

```<code>SqlCommand cmd = new SqlCommand();

cmd.CommandText = "spName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = dbConn;

cmd.Parameters.Add(new SqlParameter("par1", "val1"));
cmd.Parameters.Add(new SqlParameter("par47", "val47"));

...

cmd.ExecuteNonQuery();
</code>```

It works perfectly! So, the procedure is executed and only the 2 parameters (par1 and par47) have a value. Other parameters maintain the default value (NULL).

I would do the same from a Java client using Microsoft JDBC driver 6.2.
I specify the parameters with List<Map<String, Object>>, so a list of couple parameterName-->parameterValue. The following method builds the PreparedStatement object:

```<code>private CallableStatement prepareStatement(String spName, Map<String, ?> parameters) throws SQLException {
    setupConnection();
    CallableStatement stmt = null;
    try {
        stmt = conn.prepareCall(getSpCallString(spName, parameters));
        if (parameters != null) {
            for (String parName : parameters.keySet())
                stmt.setObject(parName, parameters.get(parName));
        }
    } catch (SQLException e) {
        ApplicationLogging.severe("Cannot prepare callable statement", e);
        throw e;
    }
    return stmt;
}
</code>```

The method getSpCallString() generates a string  of the type { call spName ?,?, ... , ? } with a number of ? as the number of parameters with a value passed to the procedure, so not all 99 parameters. If I have 2 parameter it generates the string { call spName ?,? }.
By passing for example par15=val15 and par47=val47 it raises the following exception:

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.
</code>```

I could resolve this putting in the call command the same number of ? as the number of parameter of the stored procedure but... I don't know the number of parameters for each stored procedure (and their position)!
In C# this is simply resolved because the parameters are assigned only with their name, so the number and the order of parameters can be really a black box.

Can I do this in some way in Java?

答:
This is a confirmed deficiency in the current implementation of named parameter support for CallableStatement in the mssql-jdbc driver. Despite section 13.3.2 of the JDBC 4.2 specification stating ...

Named parameters can be used to specify only the values that have no default value.

... we seem to be required to provide a parameter placeholder for every possible parameter, and there doesn't appear to be a way to specify DEFAULT for the parameters we might otherwise simply omit.

As a workaround we could use code like this

public static ResultSet executeStoredProcedureQuery(
        Connection conn, String spName, Map<String, Object> paramItems)
        throws SQLException {
    StringBuffer sqlBuf = new StringBuffer("EXEC ");
    sqlBuf.append(spName);
    int paramCount = 1;
    for (String paramName : paramItems.keySet()) {
        sqlBuf.append(
                (paramCount++ > 1 ? ", " : " ") +
                (paramName.startsWith("@") ? "" : "@") + paramName + "=?");
    }
    String sql = sqlBuf.toString();
    myLogger.log(Level.INFO, sql);
    // e.g., EXEC dbo.BreakfastSP @helpings=?, @person=?, @food=?
    PreparedStatement ps = conn.prepareStatement(sql);
    paramCount = 1;
    for (String paramName : paramItems.keySet()) {
        ps.setObject(paramCount++, paramItems.get(paramName));
    }
    return ps.executeQuery();
}
```

<p>which we could call like this</p>

```// test data
Map<String, Object> paramItems = new HashMap<>();
paramItems.put("@person", "Gord");
paramItems.put("@food", "bacon");
paramItems.put("@helpings", 3);
//
ResultSet rs = executeStoredProcedureQuery(conn, "dbo.BreakfastSP", paramItems);
```

Body:
In an instance of SQL Server 2016 I have a stored procedure with dozens of parameters. For example:

CREATE PROCEDURE spName (
    @par1 INT = NULL,
    @par2 VARCHAR(10) = NULL,
        ....
        ....
    @par98 INT = NULL,
    @par99 INT = NULL,
) AS
BEGIN
    ....
    ....
END

I have a client written in C# that calls the stored procedure specifying only the parameters with a value. Ex:

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "spName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = dbConn;

cmd.Parameters.Add(new SqlParameter("par1", "val1"));
cmd.Parameters.Add(new SqlParameter("par47", "val47"));

...

cmd.ExecuteNonQuery();

It works perfectly! So, the procedure is executed and only the 2 parameters (par1 and par47) have a value. Other parameters maintain the default value (NULL).

I would do the same from a Java client using Microsoft JDBC driver 6.2.
I specify the parameters with List<Map<String, Object>>, so a list of couple parameterName-->parameterValue. The following method builds the PreparedStatement object:

private CallableStatement prepareStatement(String spName, Map<String, ?> parameters) throws SQLException {
    setupConnection();
    CallableStatement stmt = null;
    try {
        stmt = conn.prepareCall(getSpCallString(spName, parameters));
        if (parameters != null) {
            for (String parName : parameters.keySet())
                stmt.setObject(parName, parameters.get(parName));
        }
    } catch (SQLException e) {
        ApplicationLogging.severe("Cannot prepare callable statement", e);
        throw e;
    }
    return stmt;
}

The method getSpCallString() generates a string  of the type { call spName ?,?, ... , ? } with a number of ? as the number of parameters with a value passed to the procedure, so not all 99 parameters. If I have 2 parameter it generates the string { call spName ?,? }.
By passing for example par15=val15 and par47=val47 it raises the following exception:

com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.

I could resolve this putting in the call command the same number of ? as the number of parameter of the stored procedure but... I don't know the number of parameters for each stored procedure (and their position)!
In C# this is simply resolved because the parameters are assigned only with their name, so the number and the order of parameters can be really a black box.

Can I do this in some way in Java?

Body:
This is a confirmed deficiency in the current implementation of named parameter support for CallableStatement in the mssql-jdbc driver. Despite section 13.3.2 of the JDBC 4.2 specification stating ...

Named parameters can be used to specify only the values that have no default value.

... we seem to be required to provide a parameter placeholder for every possible parameter, and there doesn't appear to be a way to specify DEFAULT for the parameters we might otherwise simply omit.

As a workaround we could use code like this

public static ResultSet executeStoredProcedureQuery(
        Connection conn, String spName, Map<String, Object> paramItems)
        throws SQLException {
    StringBuffer sqlBuf = new StringBuffer("EXEC ");
    sqlBuf.append(spName);
    int paramCount = 1;
    for (String paramName : paramItems.keySet()) {
        sqlBuf.append(
                (paramCount++ > 1 ? ", " : " ") +
                (paramName.startsWith("@") ? "" : "@") + paramName + "=?");
    }
    String sql = sqlBuf.toString();
    myLogger.log(Level.INFO, sql);
    // e.g., EXEC dbo.BreakfastSP @helpings=?, @person=?, @food=?
    PreparedStatement ps = conn.prepareStatement(sql);
    paramCount = 1;
    for (String paramName : paramItems.keySet()) {
        ps.setObject(paramCount++, paramItems.get(paramName));
    }
    return ps.executeQuery();
}

which we could call like this

// test data
Map<String, Object> paramItems = new HashMap<>();
paramItems.put("@person", "Gord");
paramItems.put("@food", "bacon");
paramItems.put("@helpings", 3);
//
ResultSet rs = executeStoredProcedureQuery(conn, "dbo.BreakfastSP", paramItems);


问:
Inverse of a permutation?
would someone please explain this example and its answer. I understand if an  array has {3,2,6} then its inverse would be {6,2,3}. Is this what being asked because the piece of code below doesn't seem to achieve this?

Suppose that the array int pi[128] contains a permutation of the numbers 0, 1, ...., 127.

What one or two lines of Java code would you use to efficiently produce the inverse of
pi in the array ip[128]?

ANSWER:

```<code> for (i=0; i<128; ++i)
      ip[pi[i]] = i
</code>```

答: This is an "inverse permutation" for permutation $\pi$, in the sense any mathematician would use. http://mathworld.wolfram.com/InversePermutation.html</p>

Title: Inverse of a permutation?

Body:
would someone please explain this example and its answer. I understand if an  array has {3,2,6} then its inverse would be {6,2,3}. Is this what being asked because the piece of code below doesn't seem to achieve this?

Suppose that the array int pi[128] contains a permutation of the numbers 0, 1, ...., 127.

What one or two lines of Java code would you use to efficiently produce the inverse of
pi in the array ip[128]?

ANSWER:

 for (i=0; i<128; ++i)
      ip[pi[i]] = i


问:
SQL: querying specific value in column with XML Data
Boy, I've been researching this subject, but I am just not getting it. Sorry if I'm asking a question that has all ready been asked a million times, but its hard to understand when you're a noob like me, and the values in my tables aren't like the others I've seen. So here it goes...

In my SQL Server database, I have a table that has all my listings in it, called ItemsEbay.

The main identifier for each individual item has a column ID value called ItemID, so I would like to refer to that as needed.

Within that table is a column named ItemSpecifics that contains XML data.
Within the ItemSpecifics XML Data, is a node with a <Name> of UPC text and random value for that node:

What I would like, is a query that would allow me to search all the items in the ItemsEbay table that have a specific UPC value of my choosing, such as 1000100 or 10U100 for instance.

When I find the match values I'm querying, I would like to be able to replace them all at once with a new value Does Not Apply.

答:
First of all: do not poste pictures!

What I've done here is your job: How to create a MCVE!

A dummy table with two rows, one contains the searched value, one doesn't

```<code>DECLARE @dummyTable TABLE(ID INT IDENTITY, ItemSpecifications XML);
INSERT INTO @dummyTable VALUES
 (N'<SelectedValues>
  <SelectedValue>
    <Name>TestName</Name>
    <Value>Xml1</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>UPC</Name>
    <Value>123</Value><!--The UPC named value = 123 -->
  </SelectedValue>
</SelectedValues>')
,(N'<SelectedValues>
  <SelectedValue>
    <Name>TestName</Name>
    <Value>Xml2</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>UPC</Name>
    <Value>999</Value><!--The UPC named value = 999 -->
  </SelectedValue>
</SelectedValues>');
</code>```

--I search for "123" and want to replace it with "SomeOther"

```<code>DECLARE @SearchFor VARCHAR(100)='123';
DECLARE @ReplaceWith VARCHAR(100)='SomeOther';
</code>```

--The update statement uses .modify() for the XML change and .exist() to check for the search value below a <SelectedValue>, which <Name> element has a text() of "123":

```<code>UPDATE @dummyTable SET ItemSpecifications.modify(N'replace value of (/SelectedValues
                                                                     /SelectedValue[(Name/text())[1]="UPC"]
                                                                     /Value/text())[1]
                                                           with sql:variable("@ReplaceWith")')
WHERE ItemSpecifications.exist(N'/SelectedValues
                                 /SelectedValue[(Name/text())[1]="UPC"]
                                 /Value[text()=sql:variable("@SearchFor")]')=1;
</code>```

--Check the result

```<code>SELECT * FROM @dummyTable;
</code>```

Body:
First of all: do not poste pictures!

What I've done here is your job: How to create a MCVE!

A dummy table with two rows, one contains the searched value, one doesn't

DECLARE @dummyTable TABLE(ID INT IDENTITY, ItemSpecifications XML);
INSERT INTO @dummyTable VALUES
 (N'<SelectedValues>
  <SelectedValue>
    <Name>TestName</Name>
    <Value>Xml1</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>UPC</Name>
    <Value>123</Value><!--The UPC named value = 123 -->
  </SelectedValue>
</SelectedValues>')
,(N'<SelectedValues>
  <SelectedValue>
    <Name>TestName</Name>
    <Value>Xml2</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>UPC</Name>
    <Value>999</Value><!--The UPC named value = 999 -->
  </SelectedValue>
</SelectedValues>');

--I search for "123" and want to replace it with "SomeOther"

DECLARE @SearchFor VARCHAR(100)='123';
DECLARE @ReplaceWith VARCHAR(100)='SomeOther';

--The update statement uses .modify() for the XML change and .exist() to check for the search value below a <SelectedValue>, which <Name> element has a text() of "123":

UPDATE @dummyTable SET ItemSpecifications.modify(N'replace value of (/SelectedValues
                                                                     /SelectedValue[(Name/text())[1]="UPC"]
                                                                     /Value/text())[1]
                                                           with sql:variable("@ReplaceWith")')
WHERE ItemSpecifications.exist(N'/SelectedValues
                                 /SelectedValue[(Name/text())[1]="UPC"]
                                 /Value[text()=sql:variable("@SearchFor")]')=1;

--Check the result

SELECT * FROM @dummyTable;


答:
As https://stackoverflow.com/users/2369963/adamson-jeremiah posted, the best way to solve this problem is by using classes and objects. But if you are looking to modify your existing code, the problem is that you are trying to compare records which are already checked. We can use a boolean array to not compare records which are already compared. A record in this case is a combination of 4 array elements. </p>

```<code>import java.util.*;
class Main {
  public static void main(String[] args) {
   String[] arr = {
            "room1", "10.11.2017", "17:00-18:00", "meeting event",
            "room2", "12.11.2017", "19:00-20:00", "meeting event",
            "room3", "20.11.2017", "20:00:21:00", "meeting event",
            "room1", "10.11.2017", "18:00-19:00", "meeting event",
            "room1", "15.11.2017", "10:00-11:00", "meeting event",
            "room2", "12.11.2017", "21:00-22:00", "meeting event",
            "room2", "12.11.2017", "22:00-23:00", "meeting event",
            "room3", "20.11.2017", "21:00:22:00", "meeting event",
            "room1", "10.11.2017", "19:00-20:00", "meeting event",
            "room4", "30.11.2017", "09:00-10:00", "meeting event"
    };

ArrayList<String> arr2 = new ArrayList<String>();

    String roomNumber= new String();
    String bookedDate = new String();
    String bookedTime = new String();
    String event = new String();
    // array to check if record is already checked.
    boolean[] alreadyChecked = new boolean[arr.length/4];
    for (int i = 0; i < arr.length; i+=4) {
        roomNumber = arr[i];
        bookedDate = arr[i+1];
        bookedTime = arr[i+2];
        event = arr[i+3];
        // If record is already checked, continue
        if(alreadyChecked[i/4] == true)
          continue;

        for (int j = i + 4; j < arr.length; j+=4) {
                if (arr[i].equals(arr[j]) && arr[i+1].equals(arr[j+1]) && !arr[i+2].equals(arr[j+2]) && alreadyChecked[j/4] == false){
                    bookedTime = bookedTime + " , " + arr[j+2];
                    // Mark the record as checked
                    alreadyChecked[j/4] = true;
                }
            }

        arr2.add(roomNumber +  " , " + bookedDate + " , " + bookedTime +  " , " + event);
        // mark the record as checked
        alreadyChecked[i/4] = true;
        }

    for (int k =  0; k <arr2.size(); k++) {
        System.out.println(arr2.get(k));
    }

  }
}
</code>```

Title: Copy elements from an array to an array list but skip element if some elements have been previously entered

Body:
I am trying to loop through the array below and then add elements from it to an array list using the format below.

This is the array:

    String[] arr = {
            "room1", "10.11.2017", "17:00-18:00", "meeting event",
            "room2", "12.11.2017", "19:00-20:00", "meeting event",
            "room3", "20.11.2017", "20:00:21:00", "meeting event",
            "room1", "10.11.2017", "18:00-19:00", "meeting event",
            "room1", "15.11.2017", "10:00-11:00", "meeting event",
            "room2", "12.11.2017", "21:00-22:00", "meeting event",
            "room2", "12.11.2017", "22:00-23:00", "meeting event",
            "room3", "20.11.2017", "21:00:22:00", "meeting event",
            "room1", "10.11.2017", "19:00-20:00", "meeting event",
            "room4", "30.11.2017", "09:00-10:00", "meeting event"
    };

I would like to get a new array list containing the following string elements:

room1 , 10.11.2017 , 17:00-18:00 , 18:00-19:00 , 19:00-20:00 , meeting event
room2 , 12.11.2017 , 19:00-20:00 , 21:00-22:00 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 20:00:21:00 , 21:00:22:00 , meeting event
room1 , 15.11.2017 , 10:00-11:00 , meeting event
room4 , 30.11.2017 , 09:00-10:00 , meeting event

But instead I get:

room1 , 10.11.2017 , 17:00-18:00 , 18:00-19:00 , 19:00-20:00 , meeting event
room2 , 12.11.2017 , 19:00-20:00 , 21:00-22:00 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 20:00:21:00 , 21:00:22:00 , meeting event
room1 , 10.11.2017 , 18:00-19:00 , 19:00-20:00 , meeting event
room1 , 15.11.2017 , 10:00-11:00 , meeting event
room2 , 12.11.2017 , 21:00-22:00 , 22:00-23:00 , meeting event
room2 , 12.11.2017 , 22:00-23:00 , meeting event
room3 , 20.11.2017 , 21:00:22:00 , meeting event
room1 , 10.11.2017 , 19:00-20:00 , meeting event
room4 , 30.11.2017 , 09:00-10:00 , meeting event

Is there a way to change the code below such that to get the result I need?

ArrayList<String> arr2 = new ArrayList<String>();

    String roomNumber= new String();
    String bookedDate = new String();
    String bookedTime = new String();
    String event = new String();

    for (int i = 0; i < arr.length; i+=4) {
        roomNumber = arr[i];
        bookedDate = arr[i+1];
        bookedTime = arr[i+2];
        event = arr[i+3];

        for (int j = i + 4; j < arr.length; j+=4) {
                if (arr[i].equals(arr[j]) && arr[i+1].equals(arr[j+1]) && !arr[i+2].equals(arr[j+2])){
                    bookedTime = bookedTime + " , " + arr[j+2];
                }
            }

        arr2.add(roomNumber +  " , " + bookedDate + " , " + bookedTime +  " , " + event);
        }

    for (int k =  0; k <arr2.size(); k++) {
        System.out.println(arr2.get(k));
    }

Thank you.

Body:
As https://stackoverflow.com/users/2369963/adamson-jeremiah posted, the best way to solve this problem is by using classes and objects. But if you are looking to modify your existing code, the problem is that you are trying to compare records which are already checked. We can use a boolean array to not compare records which are already compared. A record in this case is a combination of 4 array elements.

import java.util.*;
class Main {
  public static void main(String[] args) {
   String[] arr = {
            "room1", "10.11.2017", "17:00-18:00", "meeting event",
            "room2", "12.11.2017", "19:00-20:00", "meeting event",
            "room3", "20.11.2017", "20:00:21:00", "meeting event",
            "room1", "10.11.2017", "18:00-19:00", "meeting event",
            "room1", "15.11.2017", "10:00-11:00", "meeting event",
            "room2", "12.11.2017", "21:00-22:00", "meeting event",
            "room2", "12.11.2017", "22:00-23:00", "meeting event",
            "room3", "20.11.2017", "21:00:22:00", "meeting event",
            "room1", "10.11.2017", "19:00-20:00", "meeting event",
            "room4", "30.11.2017", "09:00-10:00", "meeting event"
    };

ArrayList<String> arr2 = new ArrayList<String>();

    String roomNumber= new String();
    String bookedDate = new String();
    String bookedTime = new String();
    String event = new String();
    // array to check if record is already checked.
    boolean[] alreadyChecked = new boolean[arr.length/4];
    for (int i = 0; i < arr.length; i+=4) {
        roomNumber = arr[i];
        bookedDate = arr[i+1];
        bookedTime = arr[i+2];
        event = arr[i+3];
        // If record is already checked, continue
        if(alreadyChecked[i/4] == true)
          continue;

        for (int j = i + 4; j < arr.length; j+=4) {
                if (arr[i].equals(arr[j]) && arr[i+1].equals(arr[j+1]) && !arr[i+2].equals(arr[j+2]) && alreadyChecked[j/4] == false){
                    bookedTime = bookedTime + " , " + arr[j+2];
                    // Mark the record as checked
                    alreadyChecked[j/4] = true;
                }
            }

        arr2.add(roomNumber +  " , " + bookedDate + " , " + bookedTime +  " , " + event);
        // mark the record as checked
        alreadyChecked[i/4] = true;
        }

    for (int k =  0; k <arr2.size(); k++) {
        System.out.println(arr2.get(k));
    }

  }
}


问:
SQL Server Index Naming Conventions
Is there some standard way to name indexes for SQL Server?  It seems that the primary key index is named PK_ and non-clustered indexes typically start with IX_.  Are there any naming conventions beyond that for unique indexes?</p>

答:
Is it worth a special prefix for indices associated with foreign keys?  I think so, since it reminds me that indices on foreign keys are not created by default, and so it is easier to see if they are missing.

For this, I am using names that match the name of the foreign key:

```<code>FK_[table]_[foreign_key_table]
</code>```

or, where multiple foreign keys exist on the same table

```<code>FK_[table]_[foreign_key_table]_[foreign_key_field]
</code>```

Title: SQL Server Index Naming Conventions

Body:
Is it worth a special prefix for indices associated with foreign keys?  I think so, since it reminds me that indices on foreign keys are not created by default, and so it is easier to see if they are missing.

For this, I am using names that match the name of the foreign key:

FK_[table]_[foreign_key_table]

or, where multiple foreign keys exist on the same table

FK_[table]_[foreign_key_table]_[foreign_key_field]


问:
parseInt() string hash returns integer
I have a hash as an ID that I accidentally used parseInt() on.

I am wondering why it returns an actual integer (7) instead of NaN

const hash = "7bb94588-4f62-4c41-a782-e5164844cc0d";
console.log(hash);
console.log(typeof hash);
console.log(parseInt(hash))```

Not really a question in need of help... but I would like to have a better understanding of how JS works.

答:
According to the spec

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.

Title: parseInt() string hash returns integer

Body:
I have a hash as an ID that I accidentally used parseInt() on.

I am wondering why it returns an actual integer (7) instead of NaN

const hash = "7bb94588-4f62-4c41-a782-e5164844cc0d";
console.log(hash);
console.log(typeof hash);
console.log(parseInt(hash))

Not really a question in need of help... but I would like to have a better understanding of how JS works.


问:
SQL Server / hexadecimal string as primary key, which collation to use?
I am working on a database where MD5 hashes are used as primary keys on some tables, with the type char(32).

In the past, I only worked with databases using int for primary key but on this project, I have no choice.
I wonder, what collation(s) should be used to deal with a char(32) primary key (which contains an hexadecimal string) ?

EDIT :

Currently, the collation of the database is French_CI_AS. I would like to know if it's OK for such kind of primary key or if I should switch to a CS or BIN2 collation to have better performance ?

答:
If you haven't changed the collation during setup, according to this Microsoft Article "When SQL Server Setup detects that the computer is running the U.S. English system locale, Setup automatically selects the Dictionary order, case-insensitive, for use with 1252 character set SQL Server 2008 collation ..."

There are many Sort order for a collation:

Binary (BIN): Sorts and compares data in SQL Server tables based on the bit patterns defined for each character. Binary sort order is case-sensitive and accent-sensitive. Binary is also the fastest sorting order

Binary-Point (BIN2): Sorts and compares data in SQL Server tables based on Unicode code points for Unicode data. For non-Unicode data, Binary-code point will use comparisons identical to binary sorts

Case Sensitive (CS): Distinguishes between uppercase and lowercase letters. If selected, lowercase letters sort ahead of their uppercase versions.

Accent Sensitive (AS): Distinguishes between accented and unaccented characters. For example, 'a' is not equal to 'ấ'.

Kana-sensitive (KS): Distinguishes between the two types of Japanese kana characters: Hiragana and Katakana.

Width-Sensitive (WS): Distinguishes between a single-byte character and the same character when represented as a double-byte character.

And Hexadecimal values are not case sensitive nor width,kana sensitive. And as you provided in comments the default collation is French_CI_AS (which means French - case insensitive - Accent sensitive) so it is case insensitive (which is good) and it is accent sensitive (hexadecimal doesn't contains accented characters so this feature is not necessary, but if chosen it will not affect anything).

So the French_CI_AS collation is good for your case

References

Windows Collation Sorting Styles

Selecting a SQL Server Collation

Side Note: selecting a HASH code as primary key is not recommended at all!! It is better to choose an integer as primary key