问:
one-hot encode : list of column_values has to encode
I have a column_names in the list and I want to One-Hot encode values from the columns in list . I want to encode categorical variable from the dataset.I tried few procedures but it throws me an error

```<code>from sklearn import preprocessing
#training_set_ed is where my .csv file is stored
edited_training_set = 'edited_dataset/test_set.csv'
trainig_set_ed = pd.read_csv(edited_training_set)

column_header = ['cat_var_1','cat_var_2','cat_var_3','cat_var_4','cat_var_5','cat_var_6',
        'cat_var_7','cat_var_8','cat_var_9','cat_var_10','cat_var_11','cat_var_12','cat_var_13',
        'cat_var_14','cat_var_15','cat_var_16','cat_var_17','cat_var_18']
clfs = {c:LabelEncoder() for c in column_header}

for col,clf in clfs.items():

      trainig_set_ed[col] = clfs[col].fit_transform(trainig_set_ed[col])

trainig_set_ed.to_csv('edited_dataset/train_set_encode.csv',sep='\t',encoding='utf-8')
</code>```

error it throws

Traceback (most recent call last):
    File "preprocessing.py", line 83, in
      trainig_set_ed[col] = clfs[col].fit_transform(trainig_set_ed[col])
    File "/root/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2139, in getitem
      return self._getitem_column(key)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2146, in _getitem_column
      return self._get_item_cache(key)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 1842, in _get_item_cache
      values = self._data.get(item)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/internals.py", line 3838, in get
      loc = self.items.get_loc(item)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2524, in get_loc
      return self._engine.get_loc(self._maybe_cast_indexer(key))
    File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
    File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
    File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
    File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
  KeyError: 'cat_var_6'

Thanks !

答:
Demo:

Source DF:

```<code>In [93]: df
Out[93]:
     a    b    c
0  aaa  xxx  ddd
1  bbb  zzz  bbb
2  ccc  aaa  aaa
</code>```

Solution:

```<code>In [94]: from sklearn.preprocessing import LabelEncoder
    ...:
    ...: cols = ['a','b','c']
    ...: clfs = {c:LabelEncoder() for c in cols}
    ...:

In [95]: for col, clf in clfs.items():
    ...:     df[col] = clfs[col].fit_transform(df[col])
    ...:

In [96]: df
Out[96]:
   a  b  c
0  0  1  2
1  1  2  1
2  2  0  0
</code>```

Inverse transformation:

```<code>In [97]: clfs['a'].inverse_transform(df['a'])
Out[97]: array(['aaa', 'bbb', 'ccc'], dtype=object)

In [98]: clfs['b'].inverse_transform(df['b'])
Out[98]: array(['xxx', 'zzz', 'aaa'], dtype=object)

In [99]: clfs['c'].inverse_transform(df['c'])
Out[99]: array(['ddd', 'bbb', 'aaa'], dtype=object)
</code>```

Body:
I have a column_names in the list and I want to One-Hot encode values from the columns in list . I want to encode categorical variable from the dataset.I tried few procedures but it throws me an error

from sklearn import preprocessing
#training_set_ed is where my .csv file is stored
edited_training_set = 'edited_dataset/test_set.csv'
trainig_set_ed = pd.read_csv(edited_training_set)

column_header = ['cat_var_1','cat_var_2','cat_var_3','cat_var_4','cat_var_5','cat_var_6',
        'cat_var_7','cat_var_8','cat_var_9','cat_var_10','cat_var_11','cat_var_12','cat_var_13',
        'cat_var_14','cat_var_15','cat_var_16','cat_var_17','cat_var_18']
clfs = {c:LabelEncoder() for c in column_header}

for col,clf in clfs.items():

      trainig_set_ed[col] = clfs[col].fit_transform(trainig_set_ed[col])

trainig_set_ed.to_csv('edited_dataset/train_set_encode.csv',sep='\t',encoding='utf-8')

error it throws

Traceback (most recent call last):
    File "preprocessing.py", line 83, in
      trainig_set_ed[col] = clfs[col].fit_transform(trainig_set_ed[col])
    File "/root/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2139, in getitem
      return self._getitem_column(key)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2146, in _getitem_column
      return self._get_item_cache(key)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 1842, in _get_item_cache
      values = self._data.get(item)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/internals.py", line 3838, in get
      loc = self.items.get_loc(item)
    File "/root/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2524, in get_loc
      return self._engine.get_loc(self._maybe_cast_indexer(key))
    File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
    File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
    File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
    File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
  KeyError: 'cat_var_6'

Thanks !

Body:
Demo:

Source DF:

In [93]: df
Out[93]:
     a    b    c
0  aaa  xxx  ddd
1  bbb  zzz  bbb
2  ccc  aaa  aaa

Solution:

In [94]: from sklearn.preprocessing import LabelEncoder
    ...:
    ...: cols = ['a','b','c']
    ...: clfs = {c:LabelEncoder() for c in cols}
    ...:

In [95]: for col, clf in clfs.items():
    ...:     df[col] = clfs[col].fit_transform(df[col])
    ...:

In [96]: df
Out[96]:
   a  b  c
0  0  1  2
1  1  2  1
2  2  0  0

Inverse transformation:

In [97]: clfs['a'].inverse_transform(df['a'])
Out[97]: array(['aaa', 'bbb', 'ccc'], dtype=object)

In [98]: clfs['b'].inverse_transform(df['b'])
Out[98]: array(['xxx', 'zzz', 'aaa'], dtype=object)

In [99]: clfs['c'].inverse_transform(df['c'])
Out[99]: array(['ddd', 'bbb', 'aaa'], dtype=object)


来源: stackexchange

问:
How do I get the <title> from a child iframe to set on the index.html
Currently I have the following in my index.html file

```<code>document.title = document.getElementById('title').contentWindow.document.title;
</code>```

But it makes the title blank instead of the title of the iframe.

How do I fix this?

Here is my site

答:
Getting the title of an iframe is as easy as:

```<code>var iframe = document.getElementById("iframeId");
var iframeTitle = iframe.contentDocument.title;
</code>```

If you want to get the value of title when the iframe is loaded, execute:

```<code>document.getElementById("iframeId").onload = function() {
  var iframeTitle = document.getElementById("iframeId").contentDocument.title;
}
</code>```

The title value is now stored in your iframeTitle variable.

Afterwards, you can replace you title value on your current page with this variable.

```<code>if (document.title != iframeTitle) {
    document.title = iframeTitle;
}
</code>```

If you want to insert this code to your html file, add the following code after your content in your  element.

```<code><script>
    document.getElementById("iframeId").onload = function() {
      var iframeTitle = document.getElementById("iframeId").contentDocument.title;
      if (document.title != iframeTitle) {
        document.title = iframeTitle;
      }
    }
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Currently I have the following in my index.html file

document.title = document.getElementById('title').contentWindow.document.title;

But it makes the title blank instead of the title of the iframe.

How do I fix this?

Here is my site

Body:
Getting the title of an iframe is as easy as:

var iframe = document.getElementById("iframeId");
var iframeTitle = iframe.contentDocument.title;

If you want to get the value of title when the iframe is loaded, execute:

document.getElementById("iframeId").onload = function() {
  var iframeTitle = document.getElementById("iframeId").contentDocument.title;
}

The title value is now stored in your iframeTitle variable.

Afterwards, you can replace you title value on your current page with this variable.

if (document.title != iframeTitle) {
    document.title = iframeTitle;
}

If you want to insert this code to your html file, add the following code after your content in your <body> element.

<script>
    document.getElementById("iframeId").onload = function() {
      var iframeTitle = document.getElementById("iframeId").contentDocument.title;
      if (document.title != iframeTitle) {
        document.title = iframeTitle;
      }
    }
</script>


问:
Cannot find symbol when already declared
Please someone help me on this error :

```<code>import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}
</code>```

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

答: Your 't' variable is declared within the case blocks repeatedly, which creates different variables. In this case, it can be seen only inside those blocks. You might consider putting the variable declaration before your switch block.</p>

Body:
Please someone help me on this error :

import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it


问:
Why does the simplest requests_mock example fail with pytest?
I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library.

I've tried to use the first example in the requests_mock docs, except I put it in a test_mock()-function and added an assert-statement for pytest to discover it.

The following code fails:

```<code># tests/test_mock.py

import requests
import requests_mock

with requests_mock.Mocker() as m:
    def test_mock():
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'
</code>```

However, when running the following example in ipython, it works as expected. This is the exact code from the example:

```<code>with requests_mock.Mocker() as m:
    m.get('http://test.com', text='resp')
    print(requests.get('http://test.com').text)

# prints 'resp'
</code>```

Because I can make requests_mock work from ipython, I assume the issue is with pytest, but I might be wrong.

It seems like the adapter isn't used at all, so that requests sends a real http request to the target url instead of using the mocked object.

I'm using Python 3.6.3 (Anaconda3), requests_mock 1.3.0 and pytest 3.3.0

Output from running the code that fails:

```<code>C:\dev\mylib>pytest -v
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 -- e:\anaconda3\envs\benv\python.exe
cachedir: .cache
rootdir: C:\dev\mylib, inifile: setup.cfg
collected 1 item

tests/test_mocks.py::test_mock FAILED                                    [100%]

================================== FAILURES ===================================
__________________________________ test_mock __________________________________

    def test_mock():
        m.get('http://test.com', text='resp')
>       assert requests.get('http://test.com').text == 'resp'
E       assert '<!DOCTYPE ht...y>\n</html>\n' == 'resp'
E         + resp
E         - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
E         - <html>
E         - <head>
E         - <title>Client Validation</title>
E         - <script type="text/javascript">
E         - function setCookie(c_name, value, expiredays) {...
E
E         ...Full output truncated (26 lines hidden), use '-vv' to show

tests\test_mocks.py:9: AssertionError
------------------------------ Captured log call ------------------------------
connectionpool.py          208 DEBUG    Starting new HTTP connection (1): test.com
connectionpool.py          396 DEBUG    http://test.com:80 "GET / HTTP/1.1" 302 161
connectionpool.py          824 DEBUG    Starting new HTTPS connection (1): www.test.com
connectionpool.py          396 DEBUG    https://www.test.com:443 "GET / HTTP/1.1" 200 None
========================== 1 failed in 2.05 seconds ===========================
</code>```

答:
Why it works in IPython seems like a mystery to me. To fix the issue just swap the lines of the function definition with the opening of the context manager.</p>

```<code># tests/test_mock.py

import requests
import requests_mock

def test_mock():
    with requests_mock.Mocker() as m:
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'
</code>```

Body:
I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library.

I've tried to use the first example in the requests_mock docs, except I put it in a test_mock()-function and added an assert-statement for pytest to discover it.

The following code fails:

# tests/test_mock.py

import requests
import requests_mock

with requests_mock.Mocker() as m:
    def test_mock():
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'

However, when running the following example in ipython, it works as expected. This is the exact code from the example:

with requests_mock.Mocker() as m:
    m.get('http://test.com', text='resp')
    print(requests.get('http://test.com').text)

# prints 'resp'

Because I can make requests_mock work from ipython, I assume the issue is with pytest, but I might be wrong.

It seems like the adapter isn't used at all, so that requests sends a real http request to the target url instead of using the mocked object.

I'm using Python 3.6.3 (Anaconda3), requests_mock 1.3.0 and pytest 3.3.0

Output from running the code that fails:

C:\dev\mylib>pytest -v
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 -- e:\anaconda3\envs\benv\python.exe
cachedir: .cache
rootdir: C:\dev\mylib, inifile: setup.cfg
collected 1 item

tests/test_mocks.py::test_mock FAILED                                    [100%]

================================== FAILURES ===================================
__________________________________ test_mock __________________________________

    def test_mock():
        m.get('http://test.com', text='resp')
>       assert requests.get('http://test.com').text == 'resp'
E       assert '<!DOCTYPE ht...y>\n\n' == 'resp'
E         + resp
E         - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
E         -
E         -
E         - <title>Client Validation</title>
E         -

Body:
Why it works in IPython seems like a mystery to me. To fix the issue just swap the lines of the function definition with the opening of the context manager.

# tests/test_mock.py

import requests
import requests_mock

def test_mock():
    with requests_mock.Mocker() as m:
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'


问:
I cannot access tomcat admin console?
I am try to build an app with the integration of JPA and Struts. to do it need to access tomcat manager. But when I access URL http://localhost:8080/manager/html it gives 404 Error to me.

My tomcat-users.xml

```<code><?xml version='1.0' encoding='cp1252'?>

  <tomcat-users>

    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-status"/>

    <!--<user name="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status" />-->
    <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

    </tomcat-users>
</code>```

Thanks in Advance.

答:
Your tomcat-users.xml looks good.

Make sure you have the manager/ application inside your $CATALINA_BASE/webapps/

Linux:

You have to install tomcat-admin package: sudo apt-get install tomcat8-admin (for version 8)

Windows:

I am using Eclipse. I had to copy the manager/ folder from C:\Program Files\apache-tomcat-8.5.20\webapps to my Eclipse workspace (~\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\).

Title: I cannot access tomcat admin console?

Body:
I am try to build an app with the integration of JPA and Struts. to do it need to access tomcat manager. But when I access URL http://localhost:8080/manager/html it gives 404 Error to me.

My tomcat-users.xml

<?xml version='1.0' encoding='cp1252'?>

  <tomcat-users>

    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-status"/>

    <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

    </tomcat-users>

Thanks in Advance.


问:
How do I get rid of the concurrency issue with update statements with an auto-incrementing key?
I have run into the following error message at run-time with my novice's Sql / Visual C# database program:

Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

I have done some searching around about this issue and have seen several threads about it, but they aren't enough for me to resolve the issue.  I noticed people talking about how it can often occur when you're using an auto-incrementing primary key.  That is the case in this program.  Also there is no multithreading or anything else like that that I am coding into this program.  Therefore I think the auto-increment is possibly the only problem.

That being said, how do I get the update command to work, despite the auto-increment?  I can hardly stand on two feet when it comes to database programming, so please be detailed, if you don't mind.  Also the command I'm using is via a SqlCommandBuilder object.  I have set that object to new SqlCommandBuilder(DataAdapter), and I have not done anything special with it.

Thanks.

This edit is the second one.  The first one is below.

Due to my inexperience with database programming, I am unable to say this for sure.  However I have good reason to believe that the problem I am experiencing has to do with new rows not getting added to the database completely until the program terminates.  I do not understand why they are waiting until program termination to do that, or if they are waiting until then, just what exactly what about the program's termination causes them to suddenly get saved completely.  However I have forgotten to mention that this error only occurs on rows that I have added during that specific execution of the program.  If the row was already added on a previous execution or through pre-existing table data, everything's fine.  I am getting the same error with the delete method, and it also only occurs with new rows.

How do I get these rows to be fully saved to everything so that this doesn't happen?  What about the program's termination is causing these rows to get fully saved?  Thanks!

Due to a request, I have left here two code snippets.  The first one will be the method in which the the problem occurs.  The next one will include the entire class.  There are only two classes in the entire program, and the other class doesn't seem important to me in this particular issue.

```<code>    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }
</code>```

Next snippet:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Dakota
{
public partial class Form1 : Form
{
    SqlConnection con;
    DataSet dataset;
    SqlDataAdapter dAdapter;
    DataRow currentRow;
    string primaryKey;
    SqlCommandBuilder cmdBuilder;
    bool recordShown = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataset = new DataSet();
        con = new SqlConnection();

        con.ConnectionString = "Data Source=.\\SQLEXPRESS;" +
            "AttachDbFilename=C:\\Users\\Sterling\\Documents\\Contacts.mdf;" +
            "Integrated Security=True;Connect Timeout=30;User Instance=True";

        con.Open();

        string getData = "SELECT * FROM tblContacts";
        dAdapter = new SqlDataAdapter(getData, con);
        dAdapter.Fill(dataset, "Contacts");
        cmdBuilder = new SqlCommandBuilder(dAdapter);
        cmdBuilder.ConflictOption = ConflictOption.OverwriteChanges;

        con.Close();
    }

    private void clearTextBoxes()
    {
        tbFirstName.Clear();
        tbMiddleName.Clear();
        tbLastName.Clear();
        tbSuffix.Clear();
        tbHomePhone.Clear();
        tbCellPhone.Clear();
        tbOtherPhone.Clear();
        tbStreetAddress.Clear();
        tbCityAndState.Clear();
        tbCountry.Clear();
        tbEmail.Clear();
    }

    private void fillTextBoxes(int row)
    {
        DataRow dr = dataset.Tables["Contacts"].Rows[row];
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void fillTextBoxes(DataRow dr)
    {
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        string searchFor = tbSearchFor.Text;
        string column;
        if (rbFirstName.Checked)
        {
            column = "firstName";
        }
        else
        {
            column = "lastName";
        }

        DataRow[] rows = dataset.Tables["Contacts"].Select(column + "='" + searchFor + "'");
        int number = rows.Length;

        if (number == 0)
        {
            MessageBox.Show("No such records were found.");
        }
        else if (number > 1)
        {
            string[] strings = new string[rows.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                bool hasFirst = false;
                bool hasMiddle = false;

                strings[i] = "";
                if (rows[i].ItemArray.GetValue(1).ToString() != "")
                {
                    hasFirst = true;
                    strings[i] += rows[i].ItemArray.GetValue(1).ToString();
                }
                if (rows[i].ItemArray.GetValue(2).ToString() != "")
                {
                    hasMiddle = true;
                    if (hasFirst)
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(2).ToString();
                }
                if (rows[i].ItemArray.GetValue(3).ToString() != "")
                {
                    if ((hasFirst && !hasMiddle) || (hasMiddle))
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(3).ToString();
                }
                if (rows[i].ItemArray.GetValue(4).ToString() != "")
                {
                    strings[i] += " " + rows[i].ItemArray.GetValue(4).ToString();
                }
            }

           // int choice;
            Form2 form2 = new Form2(strings);
            if (form2.ShowDialog(this) == DialogResult.OK)
            {
                primaryKey = rows[form2.choice].ItemArray.GetValue(0).ToString();
               // choice = form2.choice;
                fillTextBoxes(rows[form2.choice]);
                currentRow = rows[form2.choice];
                recordShown = true;
            }
        }
        else
        {
            primaryKey = rows[0].ItemArray.GetValue(0).ToString();
            currentRow = rows[0];
            fillTextBoxes(rows[0]);
            recordShown = true;
        }
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        con.Open();

        DataRow row = dataset.Tables["Contacts"].NewRow();
        row[1] = tbFirstName.Text;
        row[2] = tbMiddleName.Text;
        row[3] = tbLastName.Text;
        row[4] = tbSuffix.Text;
        row[5] = tbHomePhone.Text;
        row[6] = tbCellPhone.Text;
        row[7] = tbOtherPhone.Text;
        row[8] = tbStreetAddress.Text;
        row[9] = tbCityAndState.Text;
        row[10] = tbCountry.Text;
        row[11] = tbEmail.Text;
        currentRow = row;

        dataset.Tables["Contacts"].Rows.Add(row);
        dAdapter.Update(dataset, "Contacts");
        recordShown = true;

        con.Close();
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        con.Open();

        currentRow.Delete();
        dAdapter.Update(dataset, "Contacts");
        clearTextBoxes();
        recordShown = false;

        con.Close();
    }
}
}
</code>```

Thanks!

答:
A couple things, it looks like you are not passing it back the ID of your identity column when calling update.  Wouldn't it need to know the ID when doing an update?

In addition to the comment that srutzky made about the redundant code in fillTextBoxes, you might also consider not referencing your columns by ordinal value and instead reference them by their actual column name.  If you were to add a column to your DB, it would break all of your code that is doing things like:

```<code>tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
</code>```

Instead, you might do something like:

```<code>tbLastName.Text = dr.ItemArray.GetValue("LastName").ToString();
</code>```

I don't know offhand if GetValue takes the column name as a parameter, but I'm sure it is something like that.

ContentLicense: CC BY-SA 2.5

Body:
I have run into the following error message at run-time with my novice's Sql / Visual C# database program:

Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

I have done some searching around about this issue and have seen several threads about it, but they aren't enough for me to resolve the issue.  I noticed people talking about how it can often occur when you're using an auto-incrementing primary key.  That is the case in this program.  Also there is no multithreading or anything else like that that I am coding into this program.  Therefore I think the auto-increment is possibly the only problem.

That being said, how do I get the update command to work, despite the auto-increment?  I can hardly stand on two feet when it comes to database programming, so please be detailed, if you don't mind.  Also the command I'm using is via a SqlCommandBuilder object.  I have set that object to new SqlCommandBuilder(DataAdapter), and I have not done anything special with it.

Thanks.

This edit is the second one.  The first one is below.

Due to my inexperience with database programming, I am unable to say this for sure.  However I have good reason to believe that the problem I am experiencing has to do with new rows not getting added to the database completely until the program terminates.  I do not understand why they are waiting until program termination to do that, or if they are waiting until then, just what exactly what about the program's termination causes them to suddenly get saved completely.  However I have forgotten to mention that this error only occurs on rows that I have added during that specific execution of the program.  If the row was already added on a previous execution or through pre-existing table data, everything's fine.  I am getting the same error with the delete method, and it also only occurs with new rows.

How do I get these rows to be fully saved to everything so that this doesn't happen?  What about the program's termination is causing these rows to get fully saved?  Thanks!

Due to a request, I have left here two code snippets.  The first one will be the method in which the the problem occurs.  The next one will include the entire class.  There are only two classes in the entire program, and the other class doesn't seem important to me in this particular issue.

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

Next snippet:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Dakota
{
public partial class Form1 : Form
{
    SqlConnection con;
    DataSet dataset;
    SqlDataAdapter dAdapter;
    DataRow currentRow;
    string primaryKey;
    SqlCommandBuilder cmdBuilder;
    bool recordShown = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataset = new DataSet();
        con = new SqlConnection();

        con.ConnectionString = "Data Source=.\\SQLEXPRESS;" +
            "AttachDbFilename=C:\\Users\\Sterling\\Documents\\Contacts.mdf;" +
            "Integrated Security=True;Connect Timeout=30;User Instance=True";

        con.Open();

        string getData = "SELECT * FROM tblContacts";
        dAdapter = new SqlDataAdapter(getData, con);
        dAdapter.Fill(dataset, "Contacts");
        cmdBuilder = new SqlCommandBuilder(dAdapter);
        cmdBuilder.ConflictOption = ConflictOption.OverwriteChanges;

        con.Close();
    }

    private void clearTextBoxes()
    {
        tbFirstName.Clear();
        tbMiddleName.Clear();
        tbLastName.Clear();
        tbSuffix.Clear();
        tbHomePhone.Clear();
        tbCellPhone.Clear();
        tbOtherPhone.Clear();
        tbStreetAddress.Clear();
        tbCityAndState.Clear();
        tbCountry.Clear();
        tbEmail.Clear();
    }

    private void fillTextBoxes(int row)
    {
        DataRow dr = dataset.Tables["Contacts"].Rows[row];
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void fillTextBoxes(DataRow dr)
    {
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        string searchFor = tbSearchFor.Text;
        string column;
        if (rbFirstName.Checked)
        {
            column = "firstName";
        }
        else
        {
            column = "lastName";
        }

        DataRow[] rows = dataset.Tables["Contacts"].Select(column + "='" + searchFor + "'");
        int number = rows.Length;

        if (number == 0)
        {
            MessageBox.Show("No such records were found.");
        }
        else if (number > 1)
        {
            string[] strings = new string[rows.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                bool hasFirst = false;
                bool hasMiddle = false;

                strings[i] = "";
                if (rows[i].ItemArray.GetValue(1).ToString() != "")
                {
                    hasFirst = true;
                    strings[i] += rows[i].ItemArray.GetValue(1).ToString();
                }
                if (rows[i].ItemArray.GetValue(2).ToString() != "")
                {
                    hasMiddle = true;
                    if (hasFirst)
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(2).ToString();
                }
                if (rows[i].ItemArray.GetValue(3).ToString() != "")
                {
                    if ((hasFirst && !hasMiddle) || (hasMiddle))
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(3).ToString();
                }
                if (rows[i].ItemArray.GetValue(4).ToString() != "")
                {
                    strings[i] += " " + rows[i].ItemArray.GetValue(4).ToString();
                }
            }

           // int choice;
            Form2 form2 = new Form2(strings);
            if (form2.ShowDialog(this) == DialogResult.OK)
            {
                primaryKey = rows[form2.choice].ItemArray.GetValue(0).ToString();
               // choice = form2.choice;
                fillTextBoxes(rows[form2.choice]);
                currentRow = rows[form2.choice];
                recordShown = true;
            }
        }
        else
        {
            primaryKey = rows[0].ItemArray.GetValue(0).ToString();
            currentRow = rows[0];
            fillTextBoxes(rows[0]);
            recordShown = true;
        }
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        con.Open();

        DataRow row = dataset.Tables["Contacts"].NewRow();
        row[1] = tbFirstName.Text;
        row[2] = tbMiddleName.Text;
        row[3] = tbLastName.Text;
        row[4] = tbSuffix.Text;
        row[5] = tbHomePhone.Text;
        row[6] = tbCellPhone.Text;
        row[7] = tbOtherPhone.Text;
        row[8] = tbStreetAddress.Text;
        row[9] = tbCityAndState.Text;
        row[10] = tbCountry.Text;
        row[11] = tbEmail.Text;
        currentRow = row;

        dataset.Tables["Contacts"].Rows.Add(row);
        dAdapter.Update(dataset, "Contacts");
        recordShown = true;

        con.Close();
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        con.Open();

        currentRow.Delete();
        dAdapter.Update(dataset, "Contacts");
        clearTextBoxes();
        recordShown = false;

        con.Close();
    }
}
}

Thanks!

Body:
A couple things, it looks like you are not passing it back the ID of your identity column when calling update.  Wouldn't it need to know the ID when doing an update?

In addition to the comment that srutzky made about the redundant code in fillTextBoxes, you might also consider not referencing your columns by ordinal value and instead reference them by their actual column name.  If you were to add a column to your DB, it would break all of your code that is doing things like:

tbLastName.Text = dr.ItemArray.GetValue(3).ToString();

Instead, you might do something like:

tbLastName.Text = dr.ItemArray.GetValue("LastName").ToString();

I don't know offhand if GetValue takes the column name as a parameter, but I'm sure it is something like that.


问:
Having problems with questdlg in matlab
I'm sorry for having only a part of the code but it is unnecessarily complicated.
I want to have multiple question dialog boxes embedded with cases. The first switch case which is switch secim works fine when I put the last option twice which is 'Uc','Uc' and unless I write it that way it shows only the other options. But when I do the same thing for the inner switch case which isswitch secim2 it gives an error on the line secim2 = questdlg('İslem?', ... and when I delete the second 'Birim vektor' it works fine but doesn't show the Birim vektor option at all. How do I fix this?

```<code>secim = questdlg('Vektorler kac boyutlu?', ...
'Vektor', ...
'Bir','İki','Uc','Uc');
switch secim
case 'Bir'
    secim2 = questdlg('İslem?', ...
    'Vektor', ...,
    'Toplam','Fark','Skaler Carpim','Birim vektor');
switch secim2
...
</code>```

答:
If you see the documentation, the syntax you're using in secim when you're repeating 'Uc' is:

```<code>button = questdlg(qstring,title,str1,str2,str3,default)
</code>```

As mentioned in the documentation, default should be one of str1, str2 and str3 and hence when you repeat 'Uc', it takes 'Uc' as the default value and you have no problem.

In secim2, 'Birim vektor' doesn't match any of the three strings and hence you'd get this warning:

Warning: Default character vector does not match any button
  character vector name.

If you repeat 'Birim vektor', it doesn't match with any of the valid syntaxes.

Above explanation is also pointed out in the comments.

For more than three strings, use listdlg.

```<code>choices = {'Toplam' ,'Fark','Skaler Carpim','Birim vektor'};
SelInd = listdlg('Name','Vektor', 'PromptString','İslem?','ListString',choices,...
    'CancelString', 'Default Choice', 'SelectionMode','single',...
    'ListSize',[200 100]) %adjust listsize as per requirement
SelInd(end+1) = 4;  %Default Choice (Biriam vektor)
secim2 = choices{SelInd(1)};
</code>```

which gives:

Title: Having problems with questdlg in matlab

Body:
I'm sorry for having only a part of the code but it is unnecessarily complicated.
I want to have multiple question dialog boxes embedded with cases. The first switch case which is switch secim works fine when I put the last option twice which is 'Uc','Uc' and unless I write it that way it shows only the other options. But when I do the same thing for the inner switch case which isswitch secim2 it gives an error on the line secim2 = questdlg('İslem?', ... and when I delete the second 'Birim vektor' it works fine but doesn't show the Birim vektor option at all. How do I fix this?

secim = questdlg('Vektorler kac boyutlu?', ...
'Vektor', ...
'Bir','İki','Uc','Uc');
switch secim
case 'Bir'
    secim2 = questdlg('İslem?', ...
    'Vektor', ...,
    'Toplam','Fark','Skaler Carpim','Birim vektor');
switch secim2
...

Body:
If you see the documentation, the syntax you're using in secim when you're repeating 'Uc' is:

button = questdlg(qstring,title,str1,str2,str3,default)

As mentioned in the documentation, default should be one of str1, str2 and str3 and hence when you repeat 'Uc', it takes 'Uc' as the default value and you have no problem.

In secim2, 'Birim vektor' doesn't match any of the three strings and hence you'd get this warning:

Warning: Default character vector does not match any button
  character vector name.

If you repeat 'Birim vektor', it doesn't match with any of the valid syntaxes.

Above explanation is also pointed out in the comments.

For more than three strings, use listdlg.

choices = {'Toplam' ,'Fark','Skaler Carpim','Birim vektor'};
SelInd = listdlg('Name','Vektor', 'PromptString','İslem?','ListString',choices,...
    'CancelString', 'Default Choice', 'SelectionMode','single',...
    'ListSize',[200 100]) %adjust listsize as per requirement
SelInd(end+1) = 4;  %Default Choice (Biriam vektor)
secim2 = choices{SelInd(1)};

which gives:


问:
Scanner crashes catch statement
I'm having issues with catch statements crashing when I try to use a scanner within them. I'm making a simple rock paper scissors program for my comp sci class and my goal is to make it virtually impossible to crash. Here is my code:

```<code>public class RPS {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Random gen = new Random();
    int rounds = 0, choice, playerchoice = 0, complete, playerwins, compwins;
    String cont = "y";

    System.out.println("Rock, Paper, Scissors!");

    while ("y".equalsIgnoreCase(cont)) {
        complete = 0;
        playerwins = 0;
        compwins = 0;
        System.out.println("How many rounds would you like to play?"
                + " (1, best of 3, or best of 5)");

        while (true) {

            try {
                rounds = scan.nextInt();
                while (rounds != 1 && rounds != 3 && rounds != 5) {
                    System.out.println("Invalid number of rounds.");
                    System.out.println("One game, best of 3, or best of 5?");
                    rounds = scan.nextInt();
                }
                break;

            } catch (Exception e) {
                while (rounds != 1 && rounds != 3 && rounds != 5) {
                    System.out.println("Invalid number of rounds.");
                    System.out.println("One game, best of 3, or best of 5?");
                    rounds = scan.nextInt();
                }
            }
        }
</code>```

My code advances perfectly fine unless netbeans throws an InputMismatchException in the try block. While the catch statement is supposed to stop this kind of thing, it still crashes and I have no idea why.

As I am a measly high school student, I apologize for any terrible coding practices I may be using. My only goal it to get this to work.

答:
Try{this} / Catch{that} is like saying "Try this, and if that doesn't work, do that". The issue here is that you put the same code in the catch block as in the try block. Imagine this:

We enter the Try block

User inputs something that isn't valid

Therefore, we go to the catch block

Now, the user is in the catch block and they input something invalid

Now we've failed, but we have nowhere left to go! We're already in the catch block.

We fail out

scan.nextInt(); will fail whenever it receives an invalid input, so any time you call that function it should be within a try block.

Thus, this can be solved simply by leaving the catch block blank (or just printing "Please input a valid number of rounds!" and doing nothing else). If we fail into the catch block, nothing will happen, we'll hit the while loop and come back around to the try block for another stab at it.

Title: Scanner crashes catch statement

Body:
I'm having issues with catch statements crashing when I try to use a scanner within them. I'm making a simple rock paper scissors program for my comp sci class and my goal is to make it virtually impossible to crash. Here is my code:

public class RPS {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Random gen = new Random();
    int rounds = 0, choice, playerchoice = 0, complete, playerwins, compwins;
    String cont = "y";

    System.out.println("Rock, Paper, Scissors!");

    while ("y".equalsIgnoreCase(cont)) {
        complete = 0;
        playerwins = 0;
        compwins = 0;
        System.out.println("How many rounds would you like to play?"
                + " (1, best of 3, or best of 5)");

        while (true) {

            try {
                rounds = scan.nextInt();
                while (rounds != 1 && rounds != 3 && rounds != 5) {
                    System.out.println("Invalid number of rounds.");
                    System.out.println("One game, best of 3, or best of 5?");
                    rounds = scan.nextInt();
                }
                break;

            } catch (Exception e) {
                while (rounds != 1 && rounds != 3 && rounds != 5) {
                    System.out.println("Invalid number of rounds.");
                    System.out.println("One game, best of 3, or best of 5?");
                    rounds = scan.nextInt();
                }
            }
        }

My code advances perfectly fine unless netbeans throws an InputMismatchException in the try block. While the catch statement is supposed to stop this kind of thing, it still crashes and I have no idea why.

As I am a measly high school student, I apologize for any terrible coding practices I may be using. My only goal it to get this to work.


问:
How to configure settings.xml to pull from Artifactory private virtual repository?
I'm an Apache Archiva veteran who has recently switched over to Artifactory Pro.  I've been attempting to replicate, in Artifactory, a setup where I implemented virtual, private repositories within Archiva.  The end result should be that different teams have access to their own team's artifacts, remote repos, the default local repos, and a company-wide repository.

However, I'm having trouble downloading only some dependencies, that are available on and pulled from Maven Central, whenever I configure my Maven settings.xml to use my private virtual repository.  If I use Artifactory's default settings.xml (libs-release, libs-snapshot, plugins-release, plugins-snapshot and no virtual repository), then I can download all dependencies that are available on Maven Central and that my projects require.

I'm running Artifactory v4.4.2 on their provided Tomcat within a Windows server 2012 virtual server.  I am not running behind a proxy.  I have no such issues with Archiva.

In regard to my private virtual repository setup, I have a virtual repository named "test" that is a "generic" Package Type.  That repository includes the following repos:

remote-repos

libs-release

libs-snapshot

plugins-release

plugins-snapshot

test-release-local

test-snapshot-local

company-release-local

company-snapshot-local

The first 5 repos listed are the default virtual repository repos provided by Artifactory.  The last 4 repos listed are the local repos, and they are of a Generic Package Type.

I think I should use a mirror.

Here is an example settings.xml that I am using (my username and password are getting populated within the generated settings.xml that I save to my Maven conf folder):

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd" xmlns="http://maven.apache.org/SETTINGS/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <servers>
    <server>
      <username>${security.getCurrentUsername()}</username>
      <password>${security.getEscapedEncryptedPassword()!"*** Insert encrypted password here ***"}</password>
      <id>central</id>
    </server>
    <server>
      <username>${security.getCurrentUsername()}</username>
      <password>${security.getEscapedEncryptedPassword()!"*** Insert encrypted password here ***"}</password>
      <id>snapshots</id>
    </server>
  </servers>
  <mirrors>
    <mirror>
      <mirrorOf>*</mirrorOf>
      <name>test</name>
      <url>http://localhost:8082/artifactory/test</url>
      <id>test</id>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
      <repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>libs-release</name>
          <url>http://localhost:8082/artifactory/libs-release</url>
        </repository>
        <repository>
          <snapshots />
          <id>snapshots</id>
          <name>libs-snapshot</name>
          <url>http://localhost:8082/artifactory/libs-snapshot</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>plugins-release</name>
          <url>http://localhost:8082/artifactory/plugins-release</url>
        </pluginRepository>
        <pluginRepository>
          <snapshots />
          <id>snapshots</id>
          <name>plugins-snapshot</name>
          <url>http://localhost:8082/artifactory/plugins-snapshot</url>
        </pluginRepository>
      </pluginRepositories>
      <id>artifactory</id>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>artifactory</activeProfile>
  </activeProfiles>
</settings>
</code>```

An example of an artifact that I cannot pull from Maven Central through my virtual repository is poi-ooxml-schemas-3.10-FINAL.jar or many Apache Maven plugins.  As soon as I remove the mirror section, I can download all dependencies from Maven Central.  This makes no sense to me.  My virtual repository is configured to include the remote-repos virtual repository and therefore should be able to pull everything from Maven Central.

What am I doing wrong?

答:
As soon as I remove the mirror section, I can download all dependencies from Maven Central.

You cannot access the mirror because you have not specified the credentials to use.  (Also you don't have anonymous access enabled)

From: https://www.jfrog.com/confluence/display/RTF/Maven+Repository#MavenRepository-ConfiguringAuthentication

Each <repository> and <mirror> element specified in the file must have a corresponding <server> element with a matching <id> that specifies the username and password.

Your mirror's id is test.  So you need to add another server entry for it:

```<code><servers>
    <server>
        <username>USERNAME</username>
        <password>PASSWORD</password>
        <id>test-maven</id>
    </server>
    <server>
        <!-- credentials for mirror -->
        <username>USERNAME</username>
        <password>PASSWORD</password>
        <id>test</id>
    </server>
</servers>
</code>```

It's a tad annoying that Artifactory's "Set me up" feature for creating settings.xml files doesn't add a <server> entry for mirrors automatically.

ContentLicense: CC BY-SA 4.0

Body:
I'm an Apache Archiva veteran who has recently switched over to Artifactory Pro.  I've been attempting to replicate, in Artifactory, a setup where I implemented virtual, private repositories within Archiva.  The end result should be that different teams have access to their own team's artifacts, remote repos, the default local repos, and a company-wide repository.

However, I'm having trouble downloading only some dependencies, that are available on and pulled from Maven Central, whenever I configure my Maven settings.xml to use my private virtual repository.  If I use Artifactory's default settings.xml (libs-release, libs-snapshot, plugins-release, plugins-snapshot and no virtual repository), then I can download all dependencies that are available on Maven Central and that my projects require.

I'm running Artifactory v4.4.2 on their provided Tomcat within a Windows server 2012 virtual server.  I am not running behind a proxy.  I have no such issues with Archiva.

In regard to my private virtual repository setup, I have a virtual repository named "test" that is a "generic" Package Type.  That repository includes the following repos:

remote-repos

libs-release

libs-snapshot

plugins-release

plugins-snapshot

test-release-local

test-snapshot-local

company-release-local

company-snapshot-local

The first 5 repos listed are the default virtual repository repos provided by Artifactory.  The last 4 repos listed are the local repos, and they are of a Generic Package Type.

I think I should use a mirror.

Here is an example settings.xml that I am using (my username and password are getting populated within the generated settings.xml that I save to my Maven conf folder):

<?xml version="1.0" encoding="UTF-8"?>
<settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd" xmlns="http://maven.apache.org/SETTINGS/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <servers>
    <server>
      <username>${security.getCurrentUsername()}</username>
      <password>${security.getEscapedEncryptedPassword()!"*** Insert encrypted password here ***"}</password>
      <id>central</id>
    </server>
    <server>
      <username>${security.getCurrentUsername()}</username>
      <password>${security.getEscapedEncryptedPassword()!"*** Insert encrypted password here ***"}</password>
      <id>snapshots</id>
    </server>
  </servers>
  <mirrors>
    <mirror>
      <mirrorOf>*</mirrorOf>
      <name>test</name>
      <url>http://localhost:8082/artifactory/test</url>
      <id>test</id>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
      <repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>libs-release</name>
          <url>http://localhost:8082/artifactory/libs-release</url>
        </repository>
        <repository>
          <snapshots />
          <id>snapshots</id>
          <name>libs-snapshot</name>
          <url>http://localhost:8082/artifactory/libs-snapshot</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>plugins-release</name>
          <url>http://localhost:8082/artifactory/plugins-release</url>
        </pluginRepository>
        <pluginRepository>
          <snapshots />
          <id>snapshots</id>
          <name>plugins-snapshot</name>
          <url>http://localhost:8082/artifactory/plugins-snapshot</url>
        </pluginRepository>
      </pluginRepositories>
      <id>artifactory</id>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>artifactory</activeProfile>
  </activeProfiles>
</settings>

An example of an artifact that I cannot pull from Maven Central through my virtual repository is poi-ooxml-schemas-3.10-FINAL.jar or many Apache Maven plugins.  As soon as I remove the mirror section, I can download all dependencies from Maven Central.  This makes no sense to me.  My virtual repository is configured to include the remote-repos virtual repository and therefore should be able to pull everything from Maven Central.

What am I doing wrong?

Body:
As soon as I remove the mirror section, I can download all dependencies from Maven Central.

You cannot access the mirror because you have not specified the credentials to use.  (Also you don't have anonymous access enabled)

From: https://www.jfrog.com/confluence/display/RTF/Maven+Repository#MavenRepository-ConfiguringAuthentication

Each <repository> and <mirror> element specified in the file must have a corresponding <server> element with a matching <id> that specifies the username and password.

Your mirror's id is test.  So you need to add another server entry for it:

<servers>
    <server>
        <username>USERNAME</username>
        <password>PASSWORD</password>
        <id>test-maven</id>
    </server>
    <server>
        <!-- credentials for mirror -->
        <username>USERNAME</username>
        <password>PASSWORD</password>
        <id>test</id>
    </server>
</servers>

It's a tad annoying that Artifactory's "Set me up" feature for creating settings.xml files doesn't add a <server> entry for mirrors automatically.


问:
Slow matrix inversion in C++
I'm currently trying to convert matlab code to C++ using armadillo.  I converted some matlab code by following the aramdillo documentation to C++. However the performance is disappointing compared to matlab.

In Matlab it takes about 0.1 sec to inverse a Matrix A of size (625x625) compared to over 3 seconds in C++.

In C++ I have tried both

```<code>solve()
</code>```

as well as

```<code>inv()
</code>```

I'm aware of the fact that inv produces less accurate results, thus I do not prefer to use it. Besides I really need the inverse of matrix A, as I use the diagonal elements later in the algorithm.

The code that's producing these results:

Matlab

```<code>x=A\b
invA = A\eye(size(A))
</code>```

C++

```<code>arma::mat x = solve(A,b)
arma::mat invA = solve(A,eye(625,625))
</code>```

The versions I'm using:

C++:

Visual Studio 2013

Armadillo 8.300.1

Intel MKL 2018.1.156

Matlab:

matlab 2016b

version -blas

Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for Intel(R) 64 architecture applications, CNR branch AVX2

version -lapack

Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for Intel(R) 64 architecture applications, CNR branch AVX2
Linear Algebra PACKage Version 3.5.0

Does anyone have an idea how to overcome this lack of speed in C++ using armadillo?

答: Have you tried : add to your code #ARMA_USE_LAPACK ? This allows your code to use more optimized version of .inv() function. Also check the documentation: http://arma.sourceforge.net/docs.html </p>

Title: Slow matrix inversion in C++

Body:
I'm currently trying to convert matlab code to C++ using armadillo.  I converted some matlab code by following the aramdillo documentation to C++. However the performance is disappointing compared to matlab.

In Matlab it takes about 0.1 sec to inverse a Matrix A of size (625x625) compared to over 3 seconds in C++.

In C++ I have tried both

solve()

as well as

inv()

I'm aware of the fact that inv produces less accurate results, thus I do not prefer to use it. Besides I really need the inverse of matrix A, as I use the diagonal elements later in the algorithm.

The code that's producing these results:

Matlab

x=A\b
invA = A\eye(size(A))

C++

arma::mat x = solve(A,b)
arma::mat invA = solve(A,eye(625,625))

The versions I'm using:

C++:

Visual Studio 2013

Armadillo 8.300.1

Intel MKL 2018.1.156

Matlab:

matlab 2016b

version -blas

Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for Intel(R) 64 architecture applications, CNR branch AVX2

version -lapack

Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for Intel(R) 64 architecture applications, CNR branch AVX2
Linear Algebra PACKage Version 3.5.0

Does anyone have an idea how to overcome this lack of speed in C++ using armadillo?


问:
Java program for permutation and combination
I was given a program with the below inputs

```<code>List of integers = {1,2,3}
int n = 5;
</code>```

The output should be the unique combination of the list elements which can be added to form the integer n.

The expected output = 5
because the unique combinations which can form 5 using the above array is

```<code>1,1,1,1,1
1,1,1,2
1,1,3
2,2,1
2,3
</code>```

The function I have created is like below

```<code>static void printAllCobinations(List<Integer> rooms,int t){
    int count = 0;
    for (int i=0;i<rooms.size();i++){
        int temp = t;
        while (temp>0){
            if((rooms.contains(temp))){
                count++;
            }
            temp-=rooms.get(i);
        }
    }
</code>```

Its giving the output as 6, as in addition to the above scenario its considering
3,2 also.

Actual expectation is if 2, 3 is considered no need to consider 3,2 .

How can i accomplish that ?

Note : the input array and n can change.

答:
Your task looks like the coin exchange problem, which is described here.
But instead of simply getting the amount of possible permutations you want to enumerate the results, so code needs to be changed.

For example my solution may look like the following in Java 8:

```<code>import java.util.*;
import java.util.stream.Collectors;

public class Solution {
    private List<Integer> rooms;
    private int numberToCheck;
    private Map<Integer, Set<List<Integer>>> cache;

    public Solution(List<Integer> rooms, int numberToCheck) {
        this.numberToCheck = numberToCheck;
        this.cache = new HashMap<>();
        this.rooms = rooms;
    }

    public Set<List<Integer>> solve() {
        return count(numberToCheck);
    }

    private Set<List<Integer>> count(int currentNumber) {
        if (currentNumber <= 0) {
            return Collections.emptySet();
        }

        if (cache.containsKey(currentNumber)) {
            return cache.get(currentNumber);
        }

        Set<List<Integer>> currentSolutions = new HashSet<>();
        cache.put(currentNumber, currentSolutions);
        for (Integer room : rooms) {
            if (currentNumber == room) {
                currentSolutions.add(Collections.singletonList(room));
            }

            Set<List<Integer>> previousSolutions = count(currentNumber - room);
            for (List<Integer> previousSolution : previousSolutions) {
                List<Integer> solution = new ArrayList<Integer>() {{
                    addAll(previousSolution);
                    add(room);
                }};
                Collections.sort(solution);
                currentSolutions.add(solution);
            }
        }
        return currentSolutions;
    }

    public static void main(String[] args) {
        List<Integer> rooms = new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
        }};

        int n = 5;

        Solution solution = new Solution(rooms, n);
        Set<List<Integer>> results = solution.solve();
        System.out.println("Total results: " + results.size());

        System.out.println("Simple results: " + results);
        List<List<Integer>> sortedResults = new ArrayList<List<Integer>>() {{
            addAll(results);
        }};

        sortedResults.sort((list1, list2) -> -Integer.compare(list1.size(), list2.size()));
        System.out.println("Sorted results: " + sortedResults);

        System.out.println("Line by line:");
        sortedResults.forEach(list -> {
            List<String> stringList = list.stream().map(Object::toString).collect(Collectors.toList());
            System.out.println(String.join(",", stringList));
        });
    }
}
</code>```

The output will be like:

```<code>Total results: 5
Simple results: [[1, 2, 2], [1, 1, 3], [2, 3], [1, 1, 1, 1, 1], [1, 1, 1, 2]]
Sorted results: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 2], [1, 1, 3], [2, 3]]
Line by line:
1,1,1,1,1
1,1,1,2
1,2,2
1,1,3
2,3
</code>```

This approach uses Dynamic programming technique (or memoization) to store intermediate results to avoid unneeded recomputation. Method count is computed only once for the unique number, and rooms are also enumerated only once at that time. So, assuming, that the number of rooms is k, the computation is called nk times. And if we needed only to count possible results, the algorithm complexity would be O(kn). So to compute the count of results for the given task it will require 3*5=15 iterations. Which is very fast.

But it is needed to enumerate all possible solutions, the number of which may combinatorically (according to the input) increase complexity in terms of consuming time and space, and there are some sort operations which add extra overhead, which can take to n! operations in worst case.

This approach is running very fast on my PC for n=200 with the same list of rooms {1,2,3}, and it takes several seconds to show the result.

Body:
I was given a program with the below inputs

List of integers = {1,2,3}
int n = 5;

The output should be the unique combination of the list elements which can be added to form the integer n.

The expected output = 5
because the unique combinations which can form 5 using the above array is

1,1,1,1,1
1,1,1,2
1,1,3
2,2,1
2,3

The function I have created is like below

static void printAllCobinations(List<Integer> rooms,int t){
    int count = 0;
    for (int i=0;i<rooms.size();i++){
        int temp = t;
        while (temp>0){
            if((rooms.contains(temp))){
                count++;
            }
            temp-=rooms.get(i);
        }
    }

Its giving the output as 6, as in addition to the above scenario its considering
3,2 also.

Actual expectation is if 2, 3 is considered no need to consider 3,2 .

How can i accomplish that ?

Note : the input array and n can change.

Body:
Your task looks like the coin exchange problem, which is described here.
But instead of simply getting the amount of possible permutations you want to enumerate the results, so code needs to be changed.

For example my solution may look like the following in Java 8:

import java.util.*;
import java.util.stream.Collectors;

public class Solution {
    private List<Integer> rooms;
    private int numberToCheck;
    private Map<Integer, Set<List<Integer>>> cache;

    public Solution(List<Integer> rooms, int numberToCheck) {
        this.numberToCheck = numberToCheck;
        this.cache = new HashMap<>();
        this.rooms = rooms;
    }

    public Set<List<Integer>> solve() {
        return count(numberToCheck);
    }

    private Set<List<Integer>> count(int currentNumber) {
        if (currentNumber <= 0) {
            return Collections.emptySet();
        }

        if (cache.containsKey(currentNumber)) {
            return cache.get(currentNumber);
        }

        Set<List<Integer>> currentSolutions = new HashSet<>();
        cache.put(currentNumber, currentSolutions);
        for (Integer room : rooms) {
            if (currentNumber == room) {
                currentSolutions.add(Collections.singletonList(room));
            }

            Set<List<Integer>> previousSolutions = count(currentNumber - room);
            for (List<Integer> previousSolution : previousSolutions) {
                List<Integer> solution = new ArrayList<Integer>() {{
                    addAll(previousSolution);
                    add(room);
                }};
                Collections.sort(solution);
                currentSolutions.add(solution);
            }
        }
        return currentSolutions;
    }

    public static void main(String[] args) {
        List<Integer> rooms = new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
        }};

        int n = 5;

        Solution solution = new Solution(rooms, n);
        Set<List<Integer>> results = solution.solve();
        System.out.println("Total results: " + results.size());

        System.out.println("Simple results: " + results);
        List<List<Integer>> sortedResults = new ArrayList<List<Integer>>() {{
            addAll(results);
        }};

        sortedResults.sort((list1, list2) -> -Integer.compare(list1.size(), list2.size()));
        System.out.println("Sorted results: " + sortedResults);

        System.out.println("Line by line:");
        sortedResults.forEach(list -> {
            List<String> stringList = list.stream().map(Object::toString).collect(Collectors.toList());
            System.out.println(String.join(",", stringList));
        });
    }
}

The output will be like:

Total results: 5
Simple results: [[1, 2, 2], [1, 1, 3], [2, 3], [1, 1, 1, 1, 1], [1, 1, 1, 2]]
Sorted results: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 2], [1, 1, 3], [2, 3]]
Line by line:
1,1,1,1,1
1,1,1,2
1,2,2
1,1,3
2,3

This approach uses Dynamic programming technique (or memoization) to store intermediate results to avoid unneeded recomputation. Method count is computed only once for the unique number, and rooms are also enumerated only once at that time. So, assuming, that the number of rooms is k, the computation is called nk times. And if we needed only to count possible results, the algorithm complexity would be O(kn). So to compute the count of results for the given task it will require 3*5=15 iterations. Which is very fast.

But it is needed to enumerate all possible solutions, the number of which may combinatorically (according to the input) increase complexity in terms of consuming time and space, and there are some sort operations which add extra overhead, which can take to n! operations in worst case.

This approach is running very fast on my PC for n=200 with the same list of rooms {1,2,3}, and it takes several seconds to show the result.


问:
What is the difference between Unit.type and Unit
I have the method below:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}
</code>```

It gives the following compiler error:

```<code>  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^
</code>```

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)
</code>```

What is going on here?

答: x.type is the singleton type of x: the type whose only two values are x and null. x must be a "stable identifier" of a value, such as the companion object of Unit.

Body:
I have the method below:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}

It gives the following compiler error:

  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)

What is going on here?


问:
Reading from an unaligned uint8_t recast as a uint32_t array - not getting all values
I am trying to cast a uint8_t array to uint32_t array. However, when i try to do this, I cant seem to be able to access every consecutive 4 bytes.

Let us say I have a uint8_t array with 8 bytes. I would like to access byte 2 -> 6 as one uint32_t.

These all get the same value *((uint32_t*)&uint8Array[0]), *((uint32_t*)&uint8Array[1]), *((uint32_t*)&uint8Array[2]), *((uint32_t*)&uint8Array[3])

While *((uint32_t*)&uint8Array[4]) gets the bytes 4 -> 8 as expected.

So it seem like I can not access 4 consecutive bytes from any address?

Is there any way that I can do this?

答:
As @DietrichEpp suggests, you'll have to make two loads; and as @tera suggests, you can combine these two loads generically for cheap even when the misalignment is not known in advance (i.e. when the initial address of uint8Array is arbitrary) using the prmt PTX instruction.

I'll offer a solution based on @tera's which will let you do:

```<code>value = read_unaligned(&uint8Array[offset]);
</code>```

safely and (relatively) efficiently. Also, it will only have one inline PTX assembly instruction, and an "unsafe" variant if you need it:

```<code>#include <cstdint>
#include <cuda_runtime_api.h>

__device__ __forceinline__ uint32_t prmt_forward_4_extract(
    uint32_t first_word,
    uint32_t second_word,
    uint32_t control_bits)
{
    uint32_t result;
    asm("prmt.b32.f4e %0, %1, %2, %3;"
        : "=r"(result)
        : "r"(first_word), "r"(second_word), "r"(control_bits) );
    return result;
}

/*
 * This unsafe, faster variant may read past the 32-bit naturally-aligned
 * word containing the last relevant byte
 */
__device__ inline uint32_t read_unaligned_unsafe(const uint32_t* __restrict__ ptr)
{
    /*
     *  Clear the bottom 2 bits of the address, making the result aligned
     *  for the purposes of reading a 32-bit (= 4-byte) value
     */
    auto aligned_ptr  = (uint32_t*) ((uint64_t) ptr & ~((uint64_t) 0x3));
    auto first_value  = *aligned_ptr;
    auto second_value = *(aligned_ptr + 1);

    auto lower_word_of_ptr = (uint32_t)((uint64_t)(ptr));

    return prmt_forward_4_extract(first_value, second_value, lower_word_of_ptr);
}

__device__ inline uint32_t read_unaligned(const uint32_t* __restrict__ ptr)
{
    auto ptr_is_already_aligned = ((uint64_t)(ptr) & 0x3 == 0);
    if (ptr_is_already_aligned) { return *ptr; }
    return read_unaligned_unsafe(ptr);
}
</code>```

Body:
As @DietrichEpp suggests, you'll have to make two loads; and as @tera suggests, you can combine these two loads generically for cheap even when the misalignment is not known in advance (i.e. when the initial address of uint8Array is arbitrary) using the prmt PTX instruction.

I'll offer a solution based on @tera's which will let you do:

value = read_unaligned(&uint8Array[offset]);

safely and (relatively) efficiently. Also, it will only have one inline PTX assembly instruction, and an "unsafe" variant if you need it:

#include <cstdint>
#include <cuda_runtime_api.h>

__device__ __forceinline__ uint32_t prmt_forward_4_extract(
    uint32_t first_word,
    uint32_t second_word,
    uint32_t control_bits)
{
    uint32_t result;
    asm("prmt.b32.f4e %0, %1, %2, %3;"
        : "=r"(result)
        : "r"(first_word), "r"(second_word), "r"(control_bits) );
    return result;
}

/*
 * This unsafe, faster variant may read past the 32-bit naturally-aligned
 * word containing the last relevant byte
 */
__device__ inline uint32_t read_unaligned_unsafe(const uint32_t* __restrict__ ptr)
{
    /*
     *  Clear the bottom 2 bits of the address, making the result aligned
     *  for the purposes of reading a 32-bit (= 4-byte) value
     */
    auto aligned_ptr  = (uint32_t*) ((uint64_t) ptr & ~((uint64_t) 0x3));
    auto first_value  = *aligned_ptr;
    auto second_value = *(aligned_ptr + 1);

    auto lower_word_of_ptr = (uint32_t)((uint64_t)(ptr));

    return prmt_forward_4_extract(first_value, second_value, lower_word_of_ptr);
}

__device__ inline uint32_t read_unaligned(const uint32_t* __restrict__ ptr)
{
    auto ptr_is_already_aligned = ((uint64_t)(ptr) & 0x3 == 0);
    if (ptr_is_already_aligned) { return *ptr; }
    return read_unaligned_unsafe(ptr);
}


问:
Converting Pandas DataFrame to tkinter object
I am trying to create a Pandas' DataFrame GUI in tkinter that would update the moment the user changes the value of the cell (each cell is an Entry). I thought that converting the DataFrame into tkinter variables (tk.StringVar,  tk.IntVar...) would be the best way to achieve that.

My problem:
I am not sure how to convert dataframe into those objects. I tried using the astype function, but it doesn't seem to convert the type.

My questions:
1) how to convert dataframe into tkinter variables?

2) is converting dataframe into ttkinter variables the best way to make the dataframe update instantly?

答:
I think pandas can't use StringVar as dtype.

You would have to get every element in dataframe and create separated var = StringVar(value=df[row,col]) (or var = StringVar() ; var.set(df[row,col]))) and keep them in standard list.

But you could put values directly to Entry, and bind() event to Entry which will execute function everytime something change in Entry or you press Enter.  This function could copy value from Entry to dataframe.

EDIT: example code

It changes value in dataframe when you click Enter (or Enter on keypad) in any Entry.

```<code>import pandas as pd
import tkinter as tk

df = pd.DataFrame([[1,2,3], [5,6,7], [101,102,103]])

# --- functions ---

def change(event, row, col):
    # get value from Entry
    value = event.widget.get()
    # set value in dataframe
    df.iloc[row,col] = value
    print(df)

# --- main --

root = tk.Tk()

# create entry for every element in dataframe

rows, cols = df.shape

for r in range(rows):
    for c in range(cols):
        e = tk.Entry(root)
        e.insert(0, df.iloc[r,c])
        e.grid(row=r, column=c)
        # ENTER
        e.bind('<Return>', lambda event, y=r, x=c: change(event,y,x))
        # ENTER on keypad
        e.bind('<KP_Enter>', lambda event, y=r, x=c: change(event,y,x))

# start program

root.mainloop()
</code>```

To change value in dataframe with every key press use <KeyRelease>

(it works when you press Ctrl+V too, so you can paste data from clipboard)

```<code>for r in range(rows):
    for c in range(cols):
        e = tk.Entry(root)
        e.insert(0, df.iloc[r,c])
        e.grid(row=r, column=c)
        e.bind('<KeyRelease>', lambda event, y=r, x=c: changed(event, y,x))
</code>```

EDIT: example as class DataFrameEdit(tk.Frame)

Body:
I think pandas can't use StringVar as dtype.

You would have to get every element in dataframe and create separated var = StringVar(value=df[row,col]) (or var = StringVar() ; var.set(df[row,col]))) and keep them in standard list.

But you could put values directly to Entry, and bind() event to Entry which will execute function everytime something change in Entry or you press Enter.  This function could copy value from Entry to dataframe.

EDIT: example code

It changes value in dataframe when you click Enter (or Enter on keypad) in any Entry.

import pandas as pd
import tkinter as tk

df = pd.DataFrame([[1,2,3], [5,6,7], [101,102,103]])

# --- functions ---

def change(event, row, col):
    # get value from Entry
    value = event.widget.get()
    # set value in dataframe
    df.iloc[row,col] = value
    print(df)

# --- main --

root = tk.Tk()

# create entry for every element in dataframe

rows, cols = df.shape

for r in range(rows):
    for c in range(cols):
        e = tk.Entry(root)
        e.insert(0, df.iloc[r,c])
        e.grid(row=r, column=c)
        # ENTER
        e.bind('<Return>', lambda event, y=r, x=c: change(event,y,x))
        # ENTER on keypad
        e.bind('<KP_Enter>', lambda event, y=r, x=c: change(event,y,x))

# start program

root.mainloop()

To change value in dataframe with every key press use <KeyRelease>

(it works when you press Ctrl+V too, so you can paste data from clipboard)

for r in range(rows):
    for c in range(cols):
        e = tk.Entry(root)
        e.insert(0, df.iloc[r,c])
        e.grid(row=r, column=c)
        e.bind('<KeyRelease>', lambda event, y=r, x=c: changed(event, y,x))

EDIT: example as class DataFrameEdit(tk.Frame)


问:
ICO takes forever to load
How do I tell a webpage that I don't want an ICO so it doesn't waste loadtime looking for it??

```<code><link rel="icon" type="images/png" href="" />
</code>```

If it's omitted, then it looks too!

答: Many browsers will simply look for http://yoursite.com/favicon.ico by default, without any prompt.  Unfortunately, there's not a lot you can do to stop browsers from requesting that file, since it's setting controlled by the user.</p>

Title: ICO takes forever to load

Body:
How do I tell a webpage that I don't want an ICO so it doesn't waste loadtime looking for it??

<link rel="icon" type="images/png" href="" />

If it's omitted, then it looks too!


问:
Change Response Header Encode .Net Core
I need help changing the encoding of the response header on .Net Core 1.1.

We're developing an application and we created a custom header called "X-Application-Error" where any error that happens at the backend of the aplication  returns a response code 500 and inside the header the message. This way I use the "app.UseExceptionHandler" to catch the errors, put it inside the header, and the front end, if it recieves and response code 500, displays the message sent at the header.

This is working as expected, the trouble that I'm having is that I need to send chacters like "é", "ã" and others, and the default encoding of the header is UTF-8, so it doesn't display those characters.

At the .net framework, we can use the "HttpResponse.HeaderEncoding" Property to change it (https://msdn.microsoft.com/en-us/library/system.web.httpresponse.headerencoding(v=vs.110).aspx)
but I can't find the equivalent for the .Net Core (1.1)

I found a similar question here (C# WebClient non-english request header value encoding) but no answer too.

答:
Ok, I have found a work around (and yes, it seems obvious to me now).

From what I understood .Net Core won't allow characters like "á", "ã" inside a header if they are not encoded. So I just used "WebUtility.UrlEncode(string)" and sent the message encoded. At the FrontEnd, Angular decoded the message automatically. The code is like:

```<code>app.UseExceptionHandler(
          builder =>
          {
              builder.Run(
                async context =>
                {
 //Some validations I make

                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        try
                        {
                            context.Response.Headers.Add("Application-Error", WebUtility.UrlEncode(error.Error.Message));
                        }catch(Exception e)
                        {
                            context.Response.Headers.Add("Application-Error", e.Message);
                        }

                        //the rest of the code
                    }
                });
          });
</code>```

Title: Change Response Header Encode .Net Core

Body:
Ok, I have found a work around (and yes, it seems obvious to me now).

From what I understood .Net Core won't allow characters like "á", "ã" inside a header if they are not encoded. So I just used "WebUtility.UrlEncode(string)" and sent the message encoded. At the FrontEnd, Angular decoded the message automatically. The code is like:

app.UseExceptionHandler(
          builder =>
          {
              builder.Run(
                async context =>
                {
 //Some validations I make

                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        try
                        {
                            context.Response.Headers.Add("Application-Error", WebUtility.UrlEncode(error.Error.Message));
                        }catch(Exception e)
                        {
                            context.Response.Headers.Add("Application-Error", e.Message);
                        }

                        //the rest of the code
                    }
                });
          });


问:
Is it possible to declare an array with config?
Or any similar data structure of dynamic length, which, can be cast easily to an array. The only workaround I have found is entering the array as a string and manually parsing it.

```<code>config var not_array: string = '[1,2,3,4,5]' ;

proc main() {
    // config array workaround
    writeln("I am string. Definitely not array ", not_array) ;

    // parse string
    not_array = not_array.replace(' ','') ;
    not_array = not_array.replace('[','') ;
    not_array = not_array.replace(']','') ;
    var still_not_array = not_array.split(',') ;

    // prepare array
    var dom = 0..#still_not_array.size ;
    var array: [dom] real ;

    // populate array
    for (i, x) in zip(dom, still_not_array) {
        array[i] = x:real ;
    }
    writeln("Ha! Tricked you, am actually array ", array) ;
}
</code>```

This works as intended, but is there a better way?

答:
Is it possible to declare an array with config?

No, this is not yet supported in Chapel as of Chapel 1.16.

That said, there are ways to work around this as you demonstrate.

As an alternative work-around, you can utilize IO calls to write the input string to memory and then read it in as an array, e.g.

```<code>config type  arrType = int;
config const arrSize = 3,
             arrString = '1 2 3';

var A : [1..arrSize] arrType;

// Create a memory buffer to write in
var f = openmem();

// Create a writer on the memory buffer and write the input string
var w = f.writer();
w.writeln(arrString);
w.close();

// Create a reader on the memory buffer and read the input string as an array
var r = f.reader();
r.readln(A);
r.close();

writeln(A);
</code>```

Note this requires the array size up front. I think you'd have to do some string processing like your original example to compute that on the fly.

Some resources:

IO.openmem()

IO.channel.readln()

Body:
Or any similar data structure of dynamic length, which, can be cast easily to an array. The only workaround I have found is entering the array as a string and manually parsing it.

config var not_array: string = '[1,2,3,4,5]' ;

proc main() {
    // config array workaround
    writeln("I am string. Definitely not array ", not_array) ;

    // parse string
    not_array = not_array.replace(' ','') ;
    not_array = not_array.replace('[','') ;
    not_array = not_array.replace(']','') ;
    var still_not_array = not_array.split(',') ;

    // prepare array
    var dom = 0..#still_not_array.size ;
    var array: [dom] real ;

    // populate array
    for (i, x) in zip(dom, still_not_array) {
        array[i] = x:real ;
    }
    writeln("Ha! Tricked you, am actually array ", array) ;
}

This works as intended, but is there a better way?

Body:
Is it possible to declare an array with config?

No, this is not yet supported in Chapel as of Chapel 1.16.

That said, there are ways to work around this as you demonstrate.

As an alternative work-around, you can utilize IO calls to write the input string to memory and then read it in as an array, e.g.

config type  arrType = int;
config const arrSize = 3,
             arrString = '1 2 3';

var A : [1..arrSize] arrType;

// Create a memory buffer to write in
var f = openmem();

// Create a writer on the memory buffer and write the input string
var w = f.writer();
w.writeln(arrString);
w.close();

// Create a reader on the memory buffer and read the input string as an array
var r = f.reader();
r.readln(A);
r.close();

writeln(A);

Note this requires the array size up front. I think you'd have to do some string processing like your original example to compute that on the fly.

Some resources:

IO.openmem()

IO.channel.readln()


问:
How to read multiple text files from a folder and append it to a new file in java using io package?
How to read multiple text files from a folder and append it to a new file in java using io package? In that folder there might be files other than text files, I have tried to solve the question it is working fine. Is there any easier method to do this instead of this long code, Please suggest if any
    package practice;</p>

```<code>import java.io.*;

public class ReadWriteFiles {

    public static void main(String args[]) throws IOException{
        String inpath="C:/Users/sr01407/Desktop/test";
        String outpath="C:/Users/sr01407/Desktop/numbers.txt";
        File Folder=new File(inpath);
        File Files[];
        Files=Folder.listFiles();
        /*for(int j=0;j<Files.length;j++){
            System.out.println(Files[j]);
        }*/
        File OutFile = new File(outpath);
        // if File doesn't exists, then create it
        if (!OutFile.exists()) {
            OutFile.createNewFile();
        }
     for(int i=0;i<Files.length;i++){
         String FileName=Files[i].getName();

         if(FileName.endsWith("txt")){
             // System.out.println(FileName);
    BufferedReader streamIn = new BufferedReader(new FileReader(Files[i].toString()));

    FileWriter filewriter = new FileWriter(OutFile.getAbsoluteFile(), true);
    BufferedWriter streamOut= new BufferedWriter(filewriter);
    String count;
    while ((count = streamIn.readLine()) != null) {
        streamOut.write(count);
        streamOut.newLine();
        }
        streamOut.flush();
        streamOut.close();
    }}

}
}
</code>```

答:
As the concrete Java version is not specified, let's assume it is Java 8. As you mentioned you have to use java.io package, let's assume it is not allowed to use fancy methods from classes like java.nio.file.Files or org.apache.commons.io.FileUtils. In this case I would propose a bit shorter way to do it.

```<code>public static void main(final String[] args) throws IOException {
    final File directory = new File("C:/Users/sr01407/Desktop/test");
    final File[] files = directory.listFiles((dir, name) -> name.endsWith(".txt"));
    if (files == null) {
        throw new IOException("the file " + directory + " is not a directory");
    }
    try (final BufferedWriter output = new BufferedWriter(new FileWriter("C:/Users/sr01407/Desktop/numbers.txt", true))) {
        for (final File file : files) {
            try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.write(line);
                    output.newLine();
                }
            }
        }
    }
}
</code>```

The main differences from what you proposed are the usage of the File#listFiles(FilenameFilter) to list and filter the files and the try-with-resources statement.

Body:
How to read multiple text files from a folder and append it to a new file in java using io package? In that folder there might be files other than text files, I have tried to solve the question it is working fine. Is there any easier method to do this instead of this long code, Please suggest if any
    package practice;

import java.io.*;

public class ReadWriteFiles {

    public static void main(String args[]) throws IOException{
        String inpath="C:/Users/sr01407/Desktop/test";
        String outpath="C:/Users/sr01407/Desktop/numbers.txt";
        File Folder=new File(inpath);
        File Files[];
        Files=Folder.listFiles();
        /*for(int j=0;j<Files.length;j++){
            System.out.println(Files[j]);
        }*/
        File OutFile = new File(outpath);
        // if File doesn't exists, then create it
        if (!OutFile.exists()) {
            OutFile.createNewFile();
        }
     for(int i=0;i<Files.length;i++){
         String FileName=Files[i].getName();

         if(FileName.endsWith("txt")){
             // System.out.println(FileName);
    BufferedReader streamIn = new BufferedReader(new FileReader(Files[i].toString()));

    FileWriter filewriter = new FileWriter(OutFile.getAbsoluteFile(), true);
    BufferedWriter streamOut= new BufferedWriter(filewriter);
    String count;
    while ((count = streamIn.readLine()) != null) {
        streamOut.write(count);
        streamOut.newLine();
        }
        streamOut.flush();
        streamOut.close();
    }}

}
}

Body:
As the concrete Java version is not specified, let's assume it is Java 8. As you mentioned you have to use java.io package, let's assume it is not allowed to use fancy methods from classes like java.nio.file.Files or org.apache.commons.io.FileUtils. In this case I would propose a bit shorter way to do it.

public static void main(final String[] args) throws IOException {
    final File directory = new File("C:/Users/sr01407/Desktop/test");
    final File[] files = directory.listFiles((dir, name) -> name.endsWith(".txt"));
    if (files == null) {
        throw new IOException("the file " + directory + " is not a directory");
    }
    try (final BufferedWriter output = new BufferedWriter(new FileWriter("C:/Users/sr01407/Desktop/numbers.txt", true))) {
        for (final File file : files) {
            try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.write(line);
                    output.newLine();
                }
            }
        }
    }
}

The main differences from what you proposed are the usage of the File#listFiles(FilenameFilter) to list and filter the files and the try-with-resources statement.