问:
Caffe compiled fine with cudnn however runtest fails with error: CUDNN_STATUS_ARCH_MISMATCH
When running make runtest using caffe I get the following output, it all compiles fine with Cudnn no errors are provided, I have also included the output of build_release/tools/caffe device_query -gpu <0,1> for both NVidia Tesla GPUs running Cuda driver and runtime version 7.0. Could anyone help?</p>

```<code>[----------] 1 test from SolverTest/0, where TypeParam = caffe::CPUDevice<float>
[ RUN      ] SolverTest/0.TestInitTrainTestNets
F0907 18:53:28.279698   309 cudnn_softmax_layer.cpp:19] Check failed: status == CUDNN_STATUS_SUCCESS (6 vs. 0)  CUDNN_STATUS_ARCH_MISMATCH
*** Check failure stack trace: ***
    @     0x2b8a426cfdaa  (unknown)
    @     0x2b8a426cfce4  (unknown)
    @     0x2b8a426cf6e6  (unknown)
    @     0x2b8a426d2687  (unknown)
    @     0x2b8a4404b3c5  caffe::CuDNNSoftmaxLayer<>::LayerSetUp()
    @     0x2b8a440bf8a7  caffe::SoftmaxWithLossLayer<>::LayerSetUp()
    @     0x2b8a440eb9dd  caffe::Net<>::Init()
    @     0x2b8a440eca25  caffe::Net<>::Net()
    @     0x2b8a4410335a  caffe::Solver<>::InitTrainNet()
    @     0x2b8a44104354  caffe::Solver<>::Init()
    @     0x2b8a44104659  caffe::Solver<>::Solver()
    @           0x787e9c  caffe::SolverTest<>::InitSolverFromProtoString()
    @           0x785170  caffe::SolverTest_TestInitTrainTestNets_Test<>::TestBody()
    @           0x7e9943  testing::internal::HandleExceptionsInMethodIfSupported<>()
    @           0x7e0627  testing::Test::Run()
    @           0x7e06ce  testing::TestInfo::Run()
    @           0x7e07d5  testing::TestCase::Run()
    @           0x7e3b18  testing::internal::UnitTestImpl::RunAllTests()
    @           0x7e3da7  testing::UnitTest::Run()
    @           0x45552a  main
    @     0x2b8a44d70ec5  (unknown)
    @           0x45bd69  (unknown)
    @              (nil)  (unknown)
make: *** [runtest] Aborted (core dumped)

% ./build_release/tools/caffe device_query -gpu 0
I0907 18:55:04.830653   729 caffe.cpp:111] Querying GPUs 0
I0907 18:55:05.037142   729 common.cpp:168] Device id:                     0
I0907 18:55:05.037195   729 common.cpp:169] Major revision number:         2
I0907 18:55:05.037201   729 common.cpp:170] Minor revision number:         0
I0907 18:55:05.037207   729 common.cpp:171] Name:                          Tesla M2090
I0907 18:55:05.037214   729 common.cpp:172] Total global memory:           5636554752
I0907 18:55:05.037220   729 common.cpp:173] Total shared memory per block: 49152
I0907 18:55:05.037225   729 common.cpp:174] Total registers per block:     32768
I0907 18:55:05.037231   729 common.cpp:175] Warp size:                     32
I0907 18:55:05.037236   729 common.cpp:176] Maximum memory pitch:          2147483647
I0907 18:55:05.037241   729 common.cpp:177] Maximum threads per block:     1024
I0907 18:55:05.037246   729 common.cpp:178] Maximum dimension of block:    1024, 1024, 64
I0907 18:55:05.037253   729 common.cpp:181] Maximum dimension of grid:     65535, 65535, 65535
I0907 18:55:05.037258   729 common.cpp:184] Clock rate:                    1301000
I0907 18:55:05.037263   729 common.cpp:185] Total constant memory:         65536
I0907 18:55:05.037268   729 common.cpp:186] Texture alignment:             512
I0907 18:55:05.037272   729 common.cpp:187] Concurrent copy and execution: Yes
I0907 18:55:05.037278   729 common.cpp:189] Number of multiprocessors:     16
I0907 18:55:05.037283   729 common.cpp:190] Kernel execution timeout:      No

% ./build_release/tools/caffe device_query -gpu 1
I0907 18:55:15.162884   784 caffe.cpp:111] Querying GPUs 1
I0907 18:55:20.532964   784 common.cpp:168] Device id:                     1
I0907 18:55:20.533093   784 common.cpp:169] Major revision number:         2
I0907 18:55:20.533129   784 common.cpp:170] Minor revision number:         0
I0907 18:55:20.533161   784 common.cpp:171] Name:                          Tesla M2090
I0907 18:55:20.533193   784 common.cpp:172] Total global memory:           5636554752
I0907 18:55:20.533227   784 common.cpp:173] Total shared memory per block: 49152
I0907 18:55:20.533252   784 common.cpp:174] Total registers per block:     32768
I0907 18:55:20.533277   784 common.cpp:175] Warp size:                     32
I0907 18:55:20.533298   784 common.cpp:176] Maximum memory pitch:          2147483647
I0907 18:55:20.533323   784 common.cpp:177] Maximum threads per block:     1024
I0907 18:55:20.533345   784 common.cpp:178] Maximum dimension of block:    1024, 1024, 64
I0907 18:55:20.533371   784 common.cpp:181] Maximum dimension of grid:     65535, 65535, 65535
I0907 18:55:20.533404   784 common.cpp:184] Clock rate:                    1301000
I0907 18:55:20.533428   784 common.cpp:185] Total constant memory:         65536
I0907 18:55:20.533452   784 common.cpp:186] Texture alignment:             512
I0907 18:55:20.533476   784 common.cpp:187] Concurrent copy and execution: Yes
I0907 18:55:20.533500   784 common.cpp:189] Number of multiprocessors:     16
I0907 18:55:20.533524   784 common.cpp:190] Kernel execution timeout:      No
</code>```

答:
Firstly check type this command nvidia-smi using  the terminal.
Then go to this link and try to find your GPU in the table. You will probably find out that your gpu have lower compute capability than 3.0 which is not supported for cuDNN.

Based on your output and TESLA M2090 you probably have one of the following GPUs:

GeForce GTX 590, GeForce GTX 580, GeForce GTX 570, GeForce GTX 480,
  GeForce GTX 470, GeForce GTX 465, GeForce GTX 480M

And  the compute capability of above GPUs is 2.0. So my suggestion is  try to install caffe without cuDNN , and do not use it at least in current machine.

Body:
When running make runtest using caffe I get the following output, it all compiles fine with Cudnn no errors are provided, I have also included the output of build_release/tools/caffe device_query -gpu <0,1> for both NVidia Tesla GPUs running Cuda driver and runtime version 7.0. Could anyone help?

[----------] 1 test from SolverTest/0, where TypeParam = caffe::CPUDevice<float>
[ RUN      ] SolverTest/0.TestInitTrainTestNets
F0907 18:53:28.279698   309 cudnn_softmax_layer.cpp:19] Check failed: status == CUDNN_STATUS_SUCCESS (6 vs. 0)  CUDNN_STATUS_ARCH_MISMATCH
*** Check failure stack trace: ***
    @     0x2b8a426cfdaa  (unknown)
    @     0x2b8a426cfce4  (unknown)
    @     0x2b8a426cf6e6  (unknown)
    @     0x2b8a426d2687  (unknown)
    @     0x2b8a4404b3c5  caffe::CuDNNSoftmaxLayer<>::LayerSetUp()
    @     0x2b8a440bf8a7  caffe::SoftmaxWithLossLayer<>::LayerSetUp()
    @     0x2b8a440eb9dd  caffe::Net<>::Init()
    @     0x2b8a440eca25  caffe::Net<>::Net()
    @     0x2b8a4410335a  caffe::Solver<>::InitTrainNet()
    @     0x2b8a44104354  caffe::Solver<>::Init()
    @     0x2b8a44104659  caffe::Solver<>::Solver()
    @           0x787e9c  caffe::SolverTest<>::InitSolverFromProtoString()
    @           0x785170  caffe::SolverTest_TestInitTrainTestNets_Test<>::TestBody()
    @           0x7e9943  testing::internal::HandleExceptionsInMethodIfSupported<>()
    @           0x7e0627  testing::Test::Run()
    @           0x7e06ce  testing::TestInfo::Run()
    @           0x7e07d5  testing::TestCase::Run()
    @           0x7e3b18  testing::internal::UnitTestImpl::RunAllTests()
    @           0x7e3da7  testing::UnitTest::Run()
    @           0x45552a  main
    @     0x2b8a44d70ec5  (unknown)
    @           0x45bd69  (unknown)
    @              (nil)  (unknown)
make: *** [runtest] Aborted (core dumped)

% ./build_release/tools/caffe device_query -gpu 0
I0907 18:55:04.830653   729 caffe.cpp:111] Querying GPUs 0
I0907 18:55:05.037142   729 common.cpp:168] Device id:                     0
I0907 18:55:05.037195   729 common.cpp:169] Major revision number:         2
I0907 18:55:05.037201   729 common.cpp:170] Minor revision number:         0
I0907 18:55:05.037207   729 common.cpp:171] Name:                          Tesla M2090
I0907 18:55:05.037214   729 common.cpp:172] Total global memory:           5636554752
I0907 18:55:05.037220   729 common.cpp:173] Total shared memory per block: 49152
I0907 18:55:05.037225   729 common.cpp:174] Total registers per block:     32768
I0907 18:55:05.037231   729 common.cpp:175] Warp size:                     32
I0907 18:55:05.037236   729 common.cpp:176] Maximum memory pitch:          2147483647
I0907 18:55:05.037241   729 common.cpp:177] Maximum threads per block:     1024
I0907 18:55:05.037246   729 common.cpp:178] Maximum dimension of block:    1024, 1024, 64
I0907 18:55:05.037253   729 common.cpp:181] Maximum dimension of grid:     65535, 65535, 65535
I0907 18:55:05.037258   729 common.cpp:184] Clock rate:                    1301000
I0907 18:55:05.037263   729 common.cpp:185] Total constant memory:         65536
I0907 18:55:05.037268   729 common.cpp:186] Texture alignment:             512
I0907 18:55:05.037272   729 common.cpp:187] Concurrent copy and execution: Yes
I0907 18:55:05.037278   729 common.cpp:189] Number of multiprocessors:     16
I0907 18:55:05.037283   729 common.cpp:190] Kernel execution timeout:      No

% ./build_release/tools/caffe device_query -gpu 1
I0907 18:55:15.162884   784 caffe.cpp:111] Querying GPUs 1
I0907 18:55:20.532964   784 common.cpp:168] Device id:                     1
I0907 18:55:20.533093   784 common.cpp:169] Major revision number:         2
I0907 18:55:20.533129   784 common.cpp:170] Minor revision number:         0
I0907 18:55:20.533161   784 common.cpp:171] Name:                          Tesla M2090
I0907 18:55:20.533193   784 common.cpp:172] Total global memory:           5636554752
I0907 18:55:20.533227   784 common.cpp:173] Total shared memory per block: 49152
I0907 18:55:20.533252   784 common.cpp:174] Total registers per block:     32768
I0907 18:55:20.533277   784 common.cpp:175] Warp size:                     32
I0907 18:55:20.533298   784 common.cpp:176] Maximum memory pitch:          2147483647
I0907 18:55:20.533323   784 common.cpp:177] Maximum threads per block:     1024
I0907 18:55:20.533345   784 common.cpp:178] Maximum dimension of block:    1024, 1024, 64
I0907 18:55:20.533371   784 common.cpp:181] Maximum dimension of grid:     65535, 65535, 65535
I0907 18:55:20.533404   784 common.cpp:184] Clock rate:                    1301000
I0907 18:55:20.533428   784 common.cpp:185] Total constant memory:         65536
I0907 18:55:20.533452   784 common.cpp:186] Texture alignment:             512
I0907 18:55:20.533476   784 common.cpp:187] Concurrent copy and execution: Yes
I0907 18:55:20.533500   784 common.cpp:189] Number of multiprocessors:     16
I0907 18:55:20.533524   784 common.cpp:190] Kernel execution timeout:      No


来源: stackexchange

问:
Hover state for active row in ui-datepicker
I'm trying to add a 'current week' indicator to the jQuery UI datepicker. I have a custom event which triggers after the datepicker is shown. It half works, but there's a sort of lag when moving up and down quickly (even though the hover class is cleared).  I have no idea why the border is still applied to the trs after the mouse leaves the row.

function addCalendarHover(){
    $('.ui-datepicker-calendar').on('mousemove', 'tr', function () {
        $(this)
            .addClass('week-hover')
            .find('td a').addClass('ui-state-hover');
    });
    $('.ui-datepicker-calendar').on('mouseleave', 'tr', function () {
        $(this)
            .removeClass('week-hover')
            .find('td a').removeClass('ui-state-hover');
    });
}
// add 'afterShow' event for jQUI date picker
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
    $.datepicker._updateDatepicker = function(inst) {
        $.datepicker._updateDatepicker_original(inst);
        var afterShow = this._get(inst, 'afterShow');
        if (afterShow)
            afterShow.apply((inst.input ? inst.input[0] : null));  // trigger custom callback
}
$('#date1').datepicker({
    changeMonth: true,
    changeYear: true,
        afterShow: function(date) {
            addCalendarHover();
        }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ui-datepicker-calendar > tbody > tr {
    border: 1px solid white;
}
    .ui-datepicker-calendar > tbody > tr.week-hover {
        /*border: 1px solid #ffaf46;*/
        border: 1px solid #ffaf46;
    } </code>```

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

Date Picker on input field: <input type="text" id="date1" name="date1"/>
```

https://jsfiddle.net/Echilon/5y0wampc/

答:
You can achieve what you want using just css, and you will not have that problem, no need for js in this case

See code snippet:

function addCalendarHover() {
  /* $('.ui-datepicker-calendar').on('mousemove', 'tr', function () {
        $(this)
            .addClass('week-hover')
            .find('td a').addClass('ui-state-hover');
    });
    $('.ui-datepicker-calendar').on('mouseleave', 'tr', function () {
        $(this)
            .removeClass('week-hover')
            .find('td a').removeClass('ui-state-hover');
    });*/
}
// add 'afterShow' event for jQUI date picker
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
  $.datepicker._updateDatepicker_original(inst);
  var afterShow = this._get(inst, 'afterShow');
  if (afterShow)
    afterShow.apply((inst.input ? inst.input[0] : null)); // trigger custom callback
}
$('#date1').datepicker({
  changeMonth: true,
  changeYear: true,
  afterShow: function(date) {
    addCalendarHover();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ui-datepicker-calendar>tbody>tr {
  border: 1px solid white;
}

.ui-datepicker-calendar>tbody>tr:hover td a:not(.ui-state-highlight) {

  font-weight: normal;
  color: #555555;
  border: 1px solid #999999;
}

.ui-datepicker-calendar>tbody>tr:hover td {
  border-top: 1px solid #ffaf46;
  border-bottom: 1px solid #ffaf46;
}

.ui-datepicker-calendar>tbody>tr:hover td:first-child {
  border-left: 1px solid #ffaf46;
}

.ui-datepicker-calendar>tbody>tr:hover td:last-child {
  border-right: 1px solid #ffaf46;
}</code>```

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />

Date Picker on input field: <input type="text" id="date1" name="date1" />
```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to add a 'current week' indicator to the jQuery UI datepicker. I have a custom event which triggers after the datepicker is shown. It half works, but there's a sort of lag when moving up and down quickly (even though the hover class is cleared).  I have no idea why the border is still applied to the trs after the mouse leaves the row.

function addCalendarHover(){
    $('.ui-datepicker-calendar').on('mousemove', 'tr', function () {
        $(this)
            .addClass('week-hover')
            .find('td a').addClass('ui-state-hover');
    });
    $('.ui-datepicker-calendar').on('mouseleave', 'tr', function () {
        $(this)
            .removeClass('week-hover')
            .find('td a').removeClass('ui-state-hover');
    });
}
// add 'afterShow' event for jQUI date picker
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
    $.datepicker._updateDatepicker = function(inst) {
        $.datepicker._updateDatepicker_original(inst);
        var afterShow = this._get(inst, 'afterShow');
        if (afterShow)
            afterShow.apply((inst.input ? inst.input[0] : null));  // trigger custom callback
}
$('#date1').datepicker({
    changeMonth: true,
    changeYear: true,
        afterShow: function(date) {
            addCalendarHover();
        }
});

.ui-datepicker-calendar > tbody > tr {
    border: 1px solid white;
}
    .ui-datepicker-calendar > tbody > tr.week-hover {
        /*border: 1px solid #ffaf46;*/
        border: 1px solid #ffaf46;
    }

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

Date Picker on input field: <input type="text" id="date1" name="date1"/>

https://jsfiddle.net/Echilon/5y0wampc/

Body:
You can achieve what you want using just css, and you will not have that problem, no need for js in this case

See code snippet:

function addCalendarHover() {
  /* $('.ui-datepicker-calendar').on('mousemove', 'tr', function () {
        $(this)
            .addClass('week-hover')
            .find('td a').addClass('ui-state-hover');
    });
    $('.ui-datepicker-calendar').on('mouseleave', 'tr', function () {
        $(this)
            .removeClass('week-hover')
            .find('td a').removeClass('ui-state-hover');
    });*/
}
// add 'afterShow' event for jQUI date picker
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
  $.datepicker._updateDatepicker_original(inst);
  var afterShow = this._get(inst, 'afterShow');
  if (afterShow)
    afterShow.apply((inst.input ? inst.input[0] : null)); // trigger custom callback
}
$('#date1').datepicker({
  changeMonth: true,
  changeYear: true,
  afterShow: function(date) {
    addCalendarHover();
  }
});

.ui-datepicker-calendar>tbody>tr {
  border: 1px solid white;
}

.ui-datepicker-calendar>tbody>tr:hover td a:not(.ui-state-highlight) {

  font-weight: normal;
  color: #555555;
  border: 1px solid #999999;
}

.ui-datepicker-calendar>tbody>tr:hover td {
  border-top: 1px solid #ffaf46;
  border-bottom: 1px solid #ffaf46;
}

.ui-datepicker-calendar>tbody>tr:hover td:first-child {
  border-left: 1px solid #ffaf46;
}

.ui-datepicker-calendar>tbody>tr:hover td:last-child {
  border-right: 1px solid #ffaf46;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
Date Picker on input field: <input type="text" id="date1" name="date1" /> <br/>


问:
3d visualize tools in WPF
I am getting the surface shown in the picture that i am attaching below ,I want triangle with the same color and texture Could you please guide me on the same.
and one more thing ,This is because the triangles are not oriented consistently which only makes sense if the output is a true oriented surface without any artifact.if any one suggest me which visualization tool where it shows the triangles without considering orientation in WPF, i have used helix toolkit in WPF but it gives same result this is 3d model:

答: You can either try to fix the orientation of the triangles or define the BackMaterial of your GeometryModel3D to be the same as the Material.

ContentLicense: CC BY-SA 4.0

Title: 3d visualize tools in WPF


问:
Sending an array as a server tag's property
I am wondering if it's possible to send an array of strings to a tag's property

```<code><SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>
</code>```

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

答:
Better off doing this in code behind</p>

```<code><SampleTag:Form runat="server" ID="sampleform1"></SampleTag:Form>

sampleform1.Items = new { item1, item2, item3, item4 };
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am wondering if it's possible to send an array of strings to a tag's property

<SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

Body:
Better off doing this in code behind

<SampleTag:Form runat="server" ID="sampleform1"></SampleTag:Form>

sampleform1.Items = new { item1, item2, item3, item4 };


问:
Upload json file to elastic search using python
I try to upload JSON file with 2 documents to ES.
I got the following error

```<code>ValueError: Invalid control character at: line 1 column 24 (char 23)
</code>```

I'm using this python code:

```<code>import json
import os, sys

from elasticsearch import Elasticsearch

ES_CLUSTER = 'http://localhost:9200/' # Need PW and User name
ES_INDEX = 'test'
ES_TYPE = 'doc'

es = Elasticsearch(
    ['localhost'],
    http_auth=('elastic', 'changeme'),
    port=9200
)
es = Elasticsearch(ES_CLUSTER)
with open("C:\Users\office\Desktop\Elasticsearch data\E-commerce.json") as json_file:
    json_docs = json.load(json_file)
es.bulk(ES_INDEX, ES_TYPE, json_docs)
</code>```

答: Try using json.loads instead of json.load that might work

Body:
I try to upload JSON file with 2 documents to ES.
I got the following error

ValueError: Invalid control character at: line 1 column 24 (char 23)

I'm using this python code:

import json
import os, sys

from elasticsearch import Elasticsearch

ES_CLUSTER = 'http://localhost:9200/' # Need PW and User name
ES_INDEX = 'test'
ES_TYPE = 'doc'

es = Elasticsearch(
    ['localhost'],
    http_auth=('elastic', 'changeme'),
    port=9200
)
es = Elasticsearch(ES_CLUSTER)
with open("C:\Users\office\Desktop\Elasticsearch data\E-commerce.json") as json_file:
    json_docs = json.load(json_file)
es.bulk(ES_INDEX, ES_TYPE, json_docs)


问:
This is the error that I am getting while executing from sklearn import preprocessing, cross_validation, svm
```<code>Traceback (most recent call last):
  File "C:/Python27/12.py", line 4, in <module>
    from sklearn import preprocessing, cross_validation, svm
  File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Python27\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
ImportError: No module named scipy
</code>```

Please help me resolve this.

答:
Install this package using:

```<code>easy_install scipy
</code>```

or

```<code>sudo apt-get install python-scipy
</code>```

or

```<code>pip install scipy
</code>```

or

```<code>conda install scikit-learn
</code>```

if you are using windows refer:

https://stackoverflow.com/a/39577864/6633975

https://stackoverflow.com/a/32064281/6633975

Body:
Traceback (most recent call last):
  File "C:/Python27/12.py", line 4, in <module>
    from sklearn import preprocessing, cross_validation, svm
  File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Python27\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
ImportError: No module named scipy

Please help me resolve this.

Body:
Install this package using:

easy_install scipy

or

sudo apt-get install python-scipy

or

pip install scipy

or

conda install scikit-learn

if you are using windows refer:

https://stackoverflow.com/a/39577864/6633975

https://stackoverflow.com/a/32064281/6633975


问:
How to select specific row column pairs in numpy array which have specific value?
I am trying to have a numpy array with random numbers from 0 to 1:

```<code>import numpy as np
x = np.random.random((3,3))
</code>```

yields

```<code>[[ 0.11874238  0.71885484  0.33656161]
 [ 0.69432263  0.25234083  0.66118676]
 [ 0.77542651  0.71230397  0.76212491]]
</code>```

And, from this array, I need the row,column combinations which have values bigger than 0.3. So the expected output should look like:

```<code>(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)
</code>```

To be able to extract the item (the values of x[row][column]),and tried to write the output to a file. I tried the following command:

```<code>with open('newfile.txt', 'w') as fd:
    for row in x:
        for item in row:
            if item > 0.3:
                print(item)
                for row in item:
                    for col in item:
                        print(row,column,'\n')
                        fd.write(row,column,'\n')
</code>```

However, it raises an error :

```<code>TypeError: 'numpy.float64' object is not iterable
</code>```

Also, I searched but could not find how to start the numpy index from 1 instead of 0. For example, the expected output would look like this:

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

Do you know how to get these outputs?

答:
Get the indices along first two axes that match that criteria with np.nonzero/np.where on the mask of comparisons and then simply index with integer array indexing -

```<code>r,c = np.nonzero(x>0.3)
out = x[r,c]
</code>```

If you are looking to get those indices a list of tuples, zip those indices -

```<code>zip(r,c)
</code>```

To get those starting from 1, add 1 and then zip -

```<code>zip(r+1,c+1)
</code>```

On Python 3.x, you would need to wrap it with list() : list(zip(r,c)) and list(zip(r+1,c+1)).

Sample run -

```<code>In [9]: x
Out[9]:
array([[ 0.11874238,  0.71885484,  0.33656161],
       [ 0.69432263,  0.25234083,  0.66118676],
       [ 0.77542651,  0.71230397,  0.76212491]])

In [10]: r,c = np.nonzero(x>0.3)

In [14]: zip(r,c)
Out[14]: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]

In [18]: zip(r+1,c+1)
Out[18]: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]

In [13]: x[r,c]
Out[13]:
array([ 0.71885484,  0.33656161,  0.69432263,  0.66118676,  0.77542651,
        0.71230397,  0.76212491])
</code>```

Writing indices to file -

Use np.savetxt with int format, like so -

```<code>In [69]: np.savetxt("output.txt", np.argwhere(x>0.3), fmt="%d", comments='')

In [70]: !cat output.txt
0 1
0 2
1 0
1 2
2 0
2 1
2 2
</code>```

With the 1 based indexing, add 1 to np.argwhere output -

```<code>In [71]: np.savetxt("output.txt", np.argwhere(x>0.3)+1, fmt="%d", comments='')

In [72]: !cat output.txt
1 2
1 3
2 1
2 3
3 1
3 2
3 3
</code>```

Body:
I am trying to have a numpy array with random numbers from 0 to 1:

import numpy as np
x = np.random.random((3,3))

yields

[[ 0.11874238  0.71885484  0.33656161]
 [ 0.69432263  0.25234083  0.66118676]
 [ 0.77542651  0.71230397  0.76212491]]

And, from this array, I need the row,column combinations which have values bigger than 0.3. So the expected output should look like:

(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)

To be able to extract the item (the values of x[row][column]),and tried to write the output to a file. I tried the following command:

with open('newfile.txt', 'w') as fd:
    for row in x:
        for item in row:
            if item > 0.3:
                print(item)
                for row in item:
                    for col in item:
                        print(row,column,'\n')
                        fd.write(row,column,'\n')

However, it raises an error :

TypeError: 'numpy.float64' object is not iterable

Also, I searched but could not find how to start the numpy index from 1 instead of 0. For example, the expected output would look like this:

 (1,2),(1,3),(2,1),(2,3),(3,1),(3,2),(3,3)

Do you know how to get these outputs?

Body:
Get the indices along first two axes that match that criteria with np.nonzero/np.where on the mask of comparisons and then simply index with integer array indexing -

r,c = np.nonzero(x>0.3)
out = x[r,c]

If you are looking to get those indices a list of tuples, zip those indices -

zip(r,c)

To get those starting from 1, add 1 and then zip -

zip(r+1,c+1)

On Python 3.x, you would need to wrap it with list() : list(zip(r,c)) and list(zip(r+1,c+1)).

Sample run -

In [9]: x
Out[9]:
array([[ 0.11874238,  0.71885484,  0.33656161],
       [ 0.69432263,  0.25234083,  0.66118676],
       [ 0.77542651,  0.71230397,  0.76212491]])

In [10]: r,c = np.nonzero(x>0.3)

In [14]: zip(r,c)
Out[14]: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]

In [18]: zip(r+1,c+1)
Out[18]: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]

In [13]: x[r,c]
Out[13]:
array([ 0.71885484,  0.33656161,  0.69432263,  0.66118676,  0.77542651,
        0.71230397,  0.76212491])

Writing indices to file -

Use np.savetxt with int format, like so -

In [69]: np.savetxt("output.txt", np.argwhere(x>0.3), fmt="%d", comments='')

In [70]: !cat output.txt
0 1
0 2
1 0
1 2
2 0
2 1
2 2

With the 1 based indexing, add 1 to np.argwhere output -

In [71]: np.savetxt("output.txt", np.argwhere(x>0.3)+1, fmt="%d", comments='')

In [72]: !cat output.txt
1 2
1 3
2 1
2 3
3 1
3 2
3 3


问:
Get Payment dates in a list
I have a payment check application, in that I get 2 strings:

```<code>String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
</code>```

Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.

Is there any optimal way to do that using the Java 8 nice features?

I started here:

```<code>    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    System.out.println(contractStart);
    System.out.println(contractStop);
    List<LocalDate> payCheck= new ArrayList<>();
    for (int i = 0; i < args.length; i++) {
        payCheck.add(...) ??
    }
</code>```

答:
I am not sure about your args array. But If you want to get every last friday of month between the contract start and end date. I would do as follow :

```<code>    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));

    List<LocalDate> payCheck = new ArrayList<>();
    LocalDate payCheckDate = contractStart;

    while (payCheckDate.isBefore(contractStop)) {
        payCheckDate = payCheckDate
                .with(lastDayOfMonth())
                .with(previousOrSame(DayOfWeek.FRIDAY));
        payCheck.add(payCheckDate);
        payCheckDate = payCheckDate.with(TemporalAdjusters.firstDayOfNextMonth());

    }

    payCheck.forEach(System.out::println);
</code>```

This gives you every last friday of each month.

Title: Get Payment dates in a list

Body:
I have a payment check application, in that I get 2 strings:

String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";

Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.

Is there any optimal way to do that using the Java 8 nice features?

I started here:

    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    System.out.println(contractStart);
    System.out.println(contractStop);
    List<LocalDate> payCheck= new ArrayList<>();
    for (int i = 0; i < args.length; i++) {
        payCheck.add(...) ??
    }

Body:
I am not sure about your args array. But If you want to get every last friday of month between the contract start and end date. I would do as follow :

    String contractBegin = "01-01-2018";
    String contractEnd = "31-12-2018";

    LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));

    List<LocalDate> payCheck = new ArrayList<>();
    LocalDate payCheckDate = contractStart;

    while (payCheckDate.isBefore(contractStop)) {
        payCheckDate = payCheckDate
                .with(lastDayOfMonth())
                .with(previousOrSame(DayOfWeek.FRIDAY));
        payCheck.add(payCheckDate);
        payCheckDate = payCheckDate.with(TemporalAdjusters.firstDayOfNextMonth());

    }

    payCheck.forEach(System.out::println);

This gives you every last friday of each month.


问:
Xamarin iOS storyboard localization
I'm developing an ios app with xamarin in Visual Studio.
I'm trying to add localization to my Main.storyboard file and to default LaunchScreen.xib file but I can't make it work.

I've follow the documentation here and I've also executed the sample app (which is working fine). I've copied the structure of the project and I've checked files many times but I'm not be able to see my strings localized inside the storyboard or xib files (LaunchScreen.xib).

This is my Info.plist:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDisplayName</key>
    <string>MyApp</string>
    <key>CFBundleIdentifier</key>
    <string>it.company.myapp</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>MinimumOSVersion</key>
    <string>9.0</string>
    <key>UIDeviceFamily</key>
    <array>
        <integer>1</integer>
        <integer>2</integer>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIMainStoryboardFile~ipad</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>CFBundleDevelopmentRegion</key>
    <string>it</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
    </array>
</dict>
</plist>
</code>```

And this is a screenshot of my project structure:

I've seen that storyboard localization ids should be like "kId-c2-rCX". This is true for my LaunchScreen.xib file but not for Main.storyboard file which has simple numerical ids like "192", "193" ecc. Could this be the problem?

What am I missing?

答:
I know this is old question, but I want to tell my solution for problem.

Here is my localization structure:

In my solution i have renamed Main.strings -file to same name that my storyboard.

Now change you ui item localization id to string. In my project that makes the different. Here is image to show what I mean.

Open your storyboard in text mode and replace those id numbers to text.

Now open your Main.strings and type your item there.

More info from: https://developer.xamarin.com/guides/ios/advanced_topics/localization_and_internationalization/

Title: Xamarin iOS storyboard localization

Body:
I'm developing an ios app with xamarin in Visual Studio.
I'm trying to add localization to my Main.storyboard file and to default LaunchScreen.xib file but I can't make it work.

I've follow the documentation here and I've also executed the sample app (which is working fine). I've copied the structure of the project and I've checked files many times but I'm not be able to see my strings localized inside the storyboard or xib files (LaunchScreen.xib).

This is my Info.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDisplayName</key>
    <string>MyApp</string>
    <key>CFBundleIdentifier</key>
    <string>it.company.myapp</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>MinimumOSVersion</key>
    <string>9.0</string>
    <key>UIDeviceFamily</key>
    <array>
        <integer>1</integer>
        <integer>2</integer>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIMainStoryboardFile~ipad</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>CFBundleDevelopmentRegion</key>
    <string>it</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
    </array>
</dict>
</plist>

And this is a screenshot of my project structure:

I've seen that storyboard localization ids should be like "kId-c2-rCX". This is true for my LaunchScreen.xib file but not for Main.storyboard file which has simple numerical ids like "192", "193" ecc. Could this be the problem?

What am I missing?


问:
Java convert String of byte array to byte array
I got a byte array sent from javascript by ajax looking like this:

```<code>"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."
</code>```

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

```<code>    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }
</code>```

答:
here is a simple solution with JAVA :</p>

```<code>        String bytes="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08";
        String []tab=bytes.split(",");
        Integer []b = new Integer[tab.length];
        for(int i = 0 ; i < tab.length ; i++){
             if(tab[i].matches("[-+]?\\d*\\.?\\d+"))
                 b[i]=Integer.parseInt(tab[i]);
             else
                 b[i]=Integer.parseInt(tab[i],16);

        }
</code>```

Body:
I got a byte array sent from javascript by ajax looking like this:

"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }

Body:
here is a simple solution with JAVA :

        String bytes="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08";
        String []tab=bytes.split(",");
        Integer []b = new Integer[tab.length];
        for(int i = 0 ; i < tab.length ; i++){
             if(tab[i].matches("[-+]?\\d*\\.?\\d+"))
                 b[i]=Integer.parseInt(tab[i]);
             else
                 b[i]=Integer.parseInt(tab[i],16);

        }


问:
Add column to table and then update it inside transaction
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

```<code>BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END
</code>```

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

答:
GO is not a T-SQL command. Is a batch delimiter. The client tool (SSM, sqlcmd, osql etc) uses it to effectively cut the file at each GO and send to the server the individual batches. So obviously you cannot use GO inside IF, nor can you expect variables to span scope across batches.

Also, you cannot catch exceptions without checking for the XACT_STATE() to ensure the transaction is not doomed.

Using GUIDs for IDs is always at least suspicious.

Using NOT NULL constraints and providing a default 'guid' like '{00000000-0000-0000-0000-000000000000}' also cannot be correct.

Updated:

Separate the ALTER and UPDATE into two batches.

Use sqlcmd extensions to break the script on error. This is supported by SSMS when sqlcmd mode is on, sqlcmd, and is trivial to support it in client libraries too: dbutilsqlcmd.

use XACT_ABORT to force error to interrupt the batch. This is frequently used in maintenance scripts (schema changes). Stored procedures and application logic scripts in general use TRY-CATCH blocks instead, but with proper care: Exception handling and nested transactions.

example script:

```<code>:on error exit

set xact_abort on;
go

begin transaction;
go

if columnproperty(object_id('Code'), 'ColorId', 'AllowsNull') is null
begin
    alter table Code add ColorId uniqueidentifier null;
end
go

update Code
  set ColorId = '...'
  where ...
go

commit;
go
</code>```

Only a successful script will reach the COMMIT. Any error will abort the script and rollback.

I used COLUMNPROPERTY to check for column existance, you could use any method you like instead (eg. lookup sys.columns).

Body:
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

Body:
GO is not a T-SQL command. Is a batch delimiter. The client tool (SSM, sqlcmd, osql etc) uses it to effectively cut the file at each GO and send to the server the individual batches. So obviously you cannot use GO inside IF, nor can you expect variables to span scope across batches.

Also, you cannot catch exceptions without checking for the XACT_STATE() to ensure the transaction is not doomed.

Using GUIDs for IDs is always at least suspicious.

Using NOT NULL constraints and providing a default 'guid' like '{00000000-0000-0000-0000-000000000000}' also cannot be correct.

Updated:

Separate the ALTER and UPDATE into two batches.

Use sqlcmd extensions to break the script on error. This is supported by SSMS when sqlcmd mode is on, sqlcmd, and is trivial to support it in client libraries too: dbutilsqlcmd.

use XACT_ABORT to force error to interrupt the batch. This is frequently used in maintenance scripts (schema changes). Stored procedures and application logic scripts in general use TRY-CATCH blocks instead, but with proper care: Exception handling and nested transactions.

example script:

:on error exit

set xact_abort on;
go

begin transaction;
go

if columnproperty(object_id('Code'), 'ColorId', 'AllowsNull') is null
begin
    alter table Code add ColorId uniqueidentifier null;
end
go

update Code
  set ColorId = '...'
  where ...
go

commit;
go

Only a successful script will reach the COMMIT. Any error will abort the script and rollback.

I used COLUMNPROPERTY to check for column existance, you could use any method you like instead (eg. lookup sys.columns).


问:
Uploader in Create action - Asp.net MVC
I'm working on an asp.net Mvc Project.
I want to implement a File up_loader to upload images. my File up_loader should create the correct address and fill the imgURL field of database.
my view looks like this

here is my view

```<code>@using (Html.BeginForm())
 {
 @Html.AntiForgeryToken()

 <div class="form-horizontal">
    <h4>Hotel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.StateId, "StateId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("StateId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.HotelRate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.HotelRate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.HotelRate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.HotelName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.HotelName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.HotelName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ImageURL, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @*@Html.EditorFor(model => model.ImageURL, new { htmlAttributes = new { @class = "form-control" } })*@
            <label for="file">Filename:</label>
            <input type="file" name="file" id="file" />

            @Html.ValidationMessageFor(model => model.ImageURL, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
     </div>
  </div>
 }
</code>```

and here is my controller:

```<code> [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,StateId,HotelRate,HotelName,Description,ImageURL")] Hotel hotel,HttpPostedFileBase file)
    {
        if (file != null)
        {

                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/img/hotel"), fileName);
                file.SaveAs(path);
                hotel.ImageURL = path;

        }
        if (ModelState.IsValid)
        {
            db.Hotels.Add(hotel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.StateId = new SelectList(db.States, "Id", "StateName", hotel.StateId);
        return View(hotel);
    }
</code>```

after saving data everything will be save correctly except ImgURL. its data is null after saving and also even before code comes t this command if (ModelState.IsValid){...}.

答:
I suppose whole part

```<code>if (file != null)
{
//...
}
</code>```

Not working

You should use

```<code>Html.BeginForm("", "", FormMethod.Post, new { enctype="multipart/form-data"})
</code>```

You don't have file becouse on POST selected file data is not been serialized without enctype="multipart/form-data" attribute on form tag.

Title: Uploader in Create action - Asp.net MVC

Body:
I'm working on an asp.net Mvc Project.
I want to implement a File up_loader to upload images. my File up_loader should create the correct address and fill the imgURL field of database.
my view looks like this

here is my view

@using (Html.BeginForm())
 {
 @Html.AntiForgeryToken()

Hotel

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.StateId, "StateId", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("StateId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.HotelRate, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.HotelRate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.HotelRate, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.HotelName, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.HotelName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.HotelName, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.ImageURL, htmlAttributes: new { @class = "control-label col-md-2" })

            @*@Html.EditorFor(model => model.ImageURL, new { htmlAttributes = new { @class = "form-control" } })*@
            Filename:
            <input type="file" name="file" id="file" />

            @Html.ValidationMessageFor(model => model.ImageURL, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

 }

and here is my controller:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,StateId,HotelRate,HotelName,Description,ImageURL")] Hotel hotel,HttpPostedFileBase file)
    {
        if (file != null)
        {

                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/img/hotel"), fileName);
                file.SaveAs(path);
                hotel.ImageURL = path;

        }
        if (ModelState.IsValid)
        {
            db.Hotels.Add(hotel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.StateId = new SelectList(db.States, "Id", "StateName", hotel.StateId);
        return View(hotel);
    }

after saving data everything will be save correctly except ImgURL. its data is null after saving and also even before code comes t this command if (ModelState.IsValid){...}.

Body:
I suppose whole part

if (file != null)
{
//...
}

Not working

You should use

Html.BeginForm("", "", FormMethod.Post, new { enctype="multipart/form-data"})

You don't have file becouse on POST selected file data is not been serialized without enctype="multipart/form-data" attribute on form tag.


问:
create a display alert function globally and call it from any view controller
```<code>func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())
</code>```

<p>it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is. </p>

答:
You're passing a new instance of the validateOTPViewController to the displayalert function.

Change it to:

```<code>displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:self)
</code>```

This will pass the current view controller to the function instead of a new one that hasn't been presented.

Body:
func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())

it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is.

Body:
You're passing a new instance of the validateOTPViewController to the displayalert function.

Change it to:

displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:self)

This will pass the current view controller to the function instead of a new one that hasn't been presented.


问:
Makemagrations - django.db.utils.ProgrammingError: column does not exist
I can't understand what is wrong. I can't add new fields to a model, every time I run makemigrations I get this error:

```<code>django.db.utils.ProgrammingError: column "..." does not exist
</code>```

Yes the column doesn't exist. That is why I want to run a migration.

```<code>'ENGINE': 'django.contrib.gis.db.backends.postgis',
</code>```

答:
try to make a rollback:

Go into the migrations folder in your django app.

Look for the migration file where you would like to go back to. (for example 0012_post_category.py)

go in the terminal write: ./manage.py migrate yourAppName 0012 (this is just the example number) and hit enter

if everything goes well. Delete the other migrations which came after this number in your migrations folder.

or try with python manage.py syncdb

Body:
I can't understand what is wrong. I can't add new fields to a model, every time I run makemigrations I get this error:

django.db.utils.ProgrammingError: column "..." does not exist

Yes the column doesn't exist. That is why I want to run a migration.

'ENGINE': 'django.contrib.gis.db.backends.postgis',


问:
How to handle keyboard events on a document level in ReacJS
I want to implement keyboard shortcuts in a React App. I am quite new to React. How do we do this? I don't want to use any plugins.

Let's say I want to close a Modal on Esc.

```<code>class Modal extends React.Component{

componentWillMount(){
    document.addEventListener("keydown",closeModal);//creating problems
}
componentWillUnMount(){
    document.removeEventListener("keydown",closeModal);
 }
closeModal(){
   //closing code
}

render(){
   //render code
}
}
</code>```

Now how to listen to Esc event and call closeModal when that happens? Adding a event listener for document in componentWillMount is creating problems as it is changing "this" value to "document"

答:
Bind correct context (this) to the passed event handlers:

document.addEventListener("keydown", this.closeModal.bind(this));
```

<p>This is simple example. You probably want to bind your methods in constructor so that you will be able to remove event listener. E.g.:</p>

<pre class="lang-js prettyprint-override"><code>class Modal extends React.Component{

    constructor(props, ctx) {
        super(props, ctx);
        this.closeModal = this.closeModal.bind(this);
    }

    componentWillMount(){
        document.addEventListener("keydown", this.closeModal);
    }

    componentWillUnMount(){
        document.removeEventListener("keydown", this.closeModal);
    }

    closeModal(){
        //closing code
    }

}
</code>```

Body:
I want to implement keyboard shortcuts in a React App. I am quite new to React. How do we do this? I don't want to use any plugins.

Let's say I want to close a Modal on Esc.

class Modal extends React.Component{

componentWillMount(){
    document.addEventListener("keydown",closeModal);//creating problems
}
componentWillUnMount(){
    document.removeEventListener("keydown",closeModal);
 }
closeModal(){
   //closing code
}

render(){
   //render code
}
}

Now how to listen to Esc event and call closeModal when that happens? Adding a event listener for document in componentWillMount is creating problems as it is changing "this" value to "document"

Body:
Bind correct context (this) to the passed event handlers:

document.addEventListener("keydown", this.closeModal.bind(this));

This is simple example. You probably want to bind your methods in constructor so that you will be able to remove event listener. E.g.:

class Modal extends React.Component{

    constructor(props, ctx) {
        super(props, ctx);
        this.closeModal = this.closeModal.bind(this);
    }

    componentWillMount(){
        document.addEventListener("keydown", this.closeModal);
    }

    componentWillUnMount(){
        document.removeEventListener("keydown", this.closeModal);
    }

    closeModal(){
        //closing code
    }

}


问:
How can I make my html td elements fit to changing window sizes?
```<code>**THIS IS MY HTML**

<div class="table">
<table>
<tr>
<td><a href="otherpage.html">Home</a></td>
<td><a href="otherpage.html">About us</a></td>
<td><a href="otherpage.html">Testimonials</a></td>
<td><a href="otherpage.html">Contact us</a></td>
<tr>
</table>
</div>
</code>```

THIS IS MY CSS

```<code>html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}
</code>```

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:

答:
Try adding the following code to your CSS:
td a { white-space: nowrap; }

Body:
**THIS IS MY HTML**

Home
About us
Testimonials
Contact us

THIS IS MY CSS

html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:


答:
I would suggest doing this using cross apply:

```<code>select t.id, v.*
from t cross apply
     (values ('make', t.make),
             ('model', t.model)
     ) v(fieldname, fieldvalue);
</code>```

SQL Server also offers unpivot and union all which can be used for this purpose.  However, lateral joins (the technical name for what apply does) are quite powerful and efficient.

Title: Transpose columns in SQL

Body:
I'm trying to take the following data;

|-----------------|-----------------|-----------------|
|        ID       |       Make      |       Model     |
|-----------------|-----------------|-----------------|
|        A1       |       Ford      |       Fiesta    |
|-----------------|-----------------|-----------------|
|        A2       |       Peugeot   |       106       |
|-----------------|-----------------|-----------------|

And transpose it so that it looks like so;

|-----------------|-----------------|-----------------|
|        ID       |     FieldName   |    FieldValue   |
|-----------------|-----------------|-----------------|
|        A1       |       Make      |       Ford      |
|-----------------|-----------------|-----------------|
|        A1       |       Model     |       Fiesta    |
|-----------------|-----------------|-----------------|
|        A2       |       Make      |       Peugeot   |
|-----------------|-----------------|-----------------|
|        A2       |       Model     |       106       |
|-----------------|-----------------|-----------------|

Is this possible within SQL?

Body:
I would suggest doing this using cross apply:

select t.id, v.*
from t cross apply
     (values ('make', t.make),
             ('model', t.model)
     ) v(fieldname, fieldvalue);

SQL Server also offers unpivot and union all which can be used for this purpose.  However, lateral joins (the technical name for what apply does) are quite powerful and efficient.


问:
WTForm "OR" conditional validator? (Either email or phone)
```<code>class ContactForm(Form):
  name = StringField('Name',
                     validators=[DataRequired(), Length(max=255)])
  email = StringField('Email',
                      validators=[Optional(), Email(), Length(max=255)])
  phone = StringField('Phone number',
                      validators=[Optional(), NumberRange(min=8, max=14)])
  comment = TextAreaField(u'Comment',
                          validators=[DataRequired()])
</code>```

Is there anyway to specify a validator such that either email or phone is required?

答:
Thank you @reptilicus. I had minor changes to the answer for it to work.

Had to check for data field self.email.data and self.phone.data

Also had to return valid at the end of the validate() method instead of else condition.

```<code>def validate(self):
    valid = True
    if not Form.validate(self):
        valid = False
    if not self.email and not self.phone:
        self.email.errors.append("Email or phone required")
        valid = False
    return valid
</code>```

Body:
class ContactForm(Form):
  name = StringField('Name',
                     validators=[DataRequired(), Length(max=255)])
  email = StringField('Email',
                      validators=[Optional(), Email(), Length(max=255)])
  phone = StringField('Phone number',
                      validators=[Optional(), NumberRange(min=8, max=14)])
  comment = TextAreaField(u'Comment',
                          validators=[DataRequired()])

Is there anyway to specify a validator such that either email or phone is required?

Body:
Thank you @reptilicus. I had minor changes to the answer for it to work.

Had to check for data field self.email.data and self.phone.data

Also had to return valid at the end of the validate() method instead of else condition.

def validate(self):
    valid = True
    if not Form.validate(self):
        valid = False
    if not self.email and not self.phone:
        self.email.errors.append("Email or phone required")
        valid = False
    return valid


问:
didSelectRowAtIndexPath in TableViewCell not working
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

CallHistoryTableViewCell.h

```<code>@interface CallHistoryTableViewCell : UITableViewCell
@property(nonatomic, strong) IBOutlet UILabel *contactName;
@property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end
</code>```

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

```<code>@interface CallHistoryVC : UIViewController
@end
</code>```

CallHistoryVC.m

```<code>@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}

@implementation CallHistoryVC

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard         storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}
</code>```

Everything works fine but in didSelectRowAtIndexPath indexPath.row is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

答:
Don't add the UISwipeGestureRecognizer to Cell. Add it to UITableView and handle the like given below. In that action method you will get the indexpath of user touch area.

```<code>func handleSwipe(sender: UISwipeGestureRecognizer){
    if longPress.state == UIGestureRecognizerState.Began {
        let touchPoint = longPress.locationInView(self.view)
        if let indexPath = yourTableView.indexPathForRowAtPoint(touchPoint) {
            // your code here, get the row for the indexPath or do whatever you want
        }
    }
}
</code>```

In this scenario didSelectRowAtIndexPath will call without fail

Body:
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

CallHistoryTableViewCell.h

@interface CallHistoryTableViewCell : UITableViewCell
@property(nonatomic, strong) IBOutlet UILabel *contactName;
@property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

@interface CallHistoryVC : UIViewController
@end

CallHistoryVC.m

@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}

@implementation CallHistoryVC

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard         storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}

Everything works fine but in didSelectRowAtIndexPath indexPath.row is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

Body:
Don't add the UISwipeGestureRecognizer to Cell. Add it to UITableView and handle the like given below. In that action method you will get the indexpath of user touch area.

func handleSwipe(sender: UISwipeGestureRecognizer){
    if longPress.state == UIGestureRecognizerState.Began {
        let touchPoint = longPress.locationInView(self.view)
        if let indexPath = yourTableView.indexPathForRowAtPoint(touchPoint) {
            // your code here, get the row for the indexPath or do whatever you want
        }
    }
}

In this scenario didSelectRowAtIndexPath will call without fail


问:
How to use Type Script 1.8 in Visual Studio 2017 for legacy project
I have recently installed visual studio 2017 and tried to run my project in it. It is causing TypeScript error. I think VS 2017 is using Typescript 2.1.5 but my application was writted for TypeScript 1.8.

How can I make VS 17 use TypeScript 1.8. I already have VS 2015 and the solution is working fine on it. But I really want to use 2017(without making changes to code)

The odd thing is:
The TypeScript version mentioned in .csproj is 1.8

```<code><TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>
</code>```

But if I edit the .csproj the TypeScriptToolsVersion to something else and then back to 1.8, the solution compiles properly. However, after consecutive compiles, the TypeScript resurfaces.

答:
I noticed the compile errors disappeared when you "force" a downgrade of TypeScript by applying nuget package Microsoft.TypeScript.MSBuild.1.8.11.

That way the solution/project seems to use the package version instead of the built in version.

Body:
I have recently installed visual studio 2017 and tried to run my project in it. It is causing TypeScript error. I think VS 2017 is using Typescript 2.1.5 but my application was writted for TypeScript 1.8.

How can I make VS 17 use TypeScript 1.8. I already have VS 2015 and the solution is working fine on it. But I really want to use 2017(without making changes to code)

The odd thing is:
The TypeScript version mentioned in .csproj is 1.8

<TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>

But if I edit the .csproj the TypeScriptToolsVersion to something else and then back to 1.8, the solution compiles properly. However, after consecutive compiles, the TypeScript resurfaces.