问:
python scipy installation failure
Good morning:
I'm trying to install scipy in my system, and am getting the below error. Can anyone help me to fix this issue ?

PS C:\Windows> pip install scipy
Collecting scipy
  Downloading scipy-0.19.0.zip (15.3MB)
    100% |████████████████████████████████| 15.3MB 97kB/s
Installing collected packages: scipy
  Running setup.py install for scipy ... error
    Complete output from command "c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Te
mp\pip-build-vewzf1v9\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exe
c'))" install --record C:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile:

```<code>Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

lapack_opt_info:
lapack_mkl_info:
  libraries mkl_rt not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

openblas_lapack_info:
  libraries openblas not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-bui
</code>```

lder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)

      NOT AVAILABLE

```<code>atlas_3_10_info:
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  self.calc_info()
lapack_info:
  libraries lapack not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  self.calc_info()
lapack_src_info:
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  self.calc_info()
  NOT AVAILABLE

Running from scipy source directory.
non-existing path in 'scipy\\integrate': 'quadpack.h'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 416, in <module>
    setup_package()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 412, in setup_package
    setup(**metadata)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
    config = configuration()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 336, in configuration
    config.add_subpackage('scipy')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\setup.py", line 15, in configuration
    config.add_subpackage('linalg')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\linalg\setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------
</code>```

Command ""c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\
scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C
:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\asekha
r\AppData\Local\Temp\pip-build-vewzf1v9\scipy\

答:
The easiest way to get packages like this installed on Windows is to download Anaconda:

https://www.continuum.io/downloads

It will install SciPy along with many other useful packages for scientific computing in Python.  I've never had an issue with installing Anaconda on Windows and have almost always had issues trying to pip install scipy.

Title: python scipy installation failure

Body:
Good morning:
I'm trying to install scipy in my system, and am getting the below error. Can anyone help me to fix this issue ?

PS C:\Windows> pip install scipy
Collecting scipy
  Downloading scipy-0.19.0.zip (15.3MB)
    100% |████████████████████████████████| 15.3MB 97kB/s
Installing collected packages: scipy
  Running setup.py install for scipy ... error
    Complete output from command "c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Te
mp\pip-build-vewzf1v9\scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exe
c'))" install --record C:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile:

Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

lapack_opt_info:
lapack_mkl_info:
  libraries mkl_rt not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

openblas_lapack_info:
  libraries openblas not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:1051: UserWarning: Specified path C:\projects\numpy-wheels\windows-wheel-bui

lder\atlas-builds\atlas-3.10.1-sse2-32\lib is invalid.
      pre_dirs = system_info.get_paths(self, section, key)

      NOT AVAILABLE

atlas_3_10_info:
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  self.calc_info()
lapack_info:
  libraries lapack not found in ['c:\\program files (x86)\\python36-32\\lib', 'C:\\', 'c:\\program files (x86)\\python36-32\\libs']
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  self.calc_info()
lapack_src_info:
  NOT AVAILABLE

c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\system_info.py:572: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  self.calc_info()
  NOT AVAILABLE

Running from scipy source directory.
non-existing path in 'scipy\\integrate': 'quadpack.h'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 416, in <module>
    setup_package()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 412, in setup_package
    setup(**metadata)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\core.py", line 135, in setup
    config = configuration()
  File "C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\scipy\setup.py", line 336, in configuration
    config.add_subpackage('scipy')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\setup.py", line 15, in configuration
    config.add_subpackage('linalg')
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in add_subpackage
    caller_level = 2)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 970, in get_subpackage
    caller_level = caller_level + 1)
  File "c:\program files (x86)\python36-32\lib\site-packages\numpy\distutils\misc_util.py", line 907, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy\linalg\setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------

Command ""c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\asekhar\AppData\Local\Temp\pip-build-vewzf1v9\
scipy\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C
:\Users\asekhar\AppData\Local\Temp\pip-02ml9lzd-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\asekha
r\AppData\Local\Temp\pip-build-vewzf1v9\scipy\


来源: stackexchange

问:
Android QR Scanner: How to quit ZXingScannerView.ResultHandler to get back to where I came from
In my first steps in exploring Android I now start with QR scanning.

Works all pretty well. But I am not able to come back from the ResultHandler after read the QR successfully to my MainActivity.

```<code>public class MainActivity extends AppCompatActivity implements
        ZXingScannerView.ResultHandler
{

  private ZXingScannerView mScannerView
  ....

  @Override
  public void handleResult(Result rawResult)
  {
   // my results are ok in rawResult
   // the scanner does not scan anymore but it is still there

   // how to go back to my main activity???
  }

  public void ClickButton (View view)
  {
       mScannerView = new ZXingScannerView(this);

       setContentView(mScannerView);
       mScannerView.setResultHandler(this);
       mScannerView.startCamera();
   }
}
</code>```

}

I tried

```<code>mScannerview.stopCameraPreview

mScannerView.stopCamera

this.finish

setContentView(R.layout.activity_main);  // shows my activity_main
             // but I can not click anything
</code>```

Thanks!!

EDIT

I added some code to describe it a bit better. The idea is from

https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/

答:
I too was stuck with this problem for an hour, just like you. And later realised..

To solve this problem DON NOT implementing the ZXingScannerView in the same activity or fragment. Instead start a new activity when you click the button and this activity is just for the ZXingScannerView

Once the Scan is done finish and pass the data back to your activity or fragment

ContentLicense: CC BY-SA 3.0

Body:
In my first steps in exploring Android I now start with QR scanning.

Works all pretty well. But I am not able to come back from the ResultHandler after read the QR successfully to my MainActivity.

public class MainActivity extends AppCompatActivity implements
        ZXingScannerView.ResultHandler
{

  private ZXingScannerView mScannerView
  ....

  @Override
  public void handleResult(Result rawResult)
  {
   // my results are ok in rawResult
   // the scanner does not scan anymore but it is still there

   // how to go back to my main activity???
  }

  public void ClickButton (View view)
  {
       mScannerView = new ZXingScannerView(this);

       setContentView(mScannerView);
       mScannerView.setResultHandler(this);
       mScannerView.startCamera();
   }
}

}

I tried

mScannerview.stopCameraPreview

mScannerView.stopCamera

this.finish

setContentView(R.layout.activity_main);  // shows my activity_main
             // but I can not click anything

Thanks!!

EDIT

I added some code to describe it a bit better. The idea is from

https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/


问:
C - pointer to pointer array
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

```<code>double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}
</code>```

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?

答:
In C, functions will have to return a value/variable of the same type as the function. In this example, tr would be a double pointer, which is pointing to the first row.

When using double pointers to create 2D arrays, you're actually creating an pointer that points to an array of pointers, with the pointers within the array pointing to strings/values stored in each row. The double pointer would be pointing to the first pointer in the pointer array, which will point to the first element in the first row.

You can access values in 2D arrays using bracket notation such as
tr[row][column], or as *(*(tr + row) + column). For the second notation, *(tr + row) will access the pointer pointing to the row you want, which you can then reference the value by using *(found_row + column), giving you the element in the column you want.

Title: C - pointer to pointer array

Body:
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?


问:
Layouting a small table with HTML and CSS
I'm very novice to HTML and CSS and have not yet "gotten it" how it all works.
I am trying to achieve a table made of two rows, in which the first row only has one column and spans over the two columns of the second row.

In the first row I have an input box and I'd like the row to conform to the height of this input box. On the bottom left I have a button with its own style and I'd like the row (and cell) to conform to the size of the button. On the bottom right I have an image and I'd like the image to scale (preserving its aspect ratio) such that it either fills the height of the row (and floats to the right) or the width of the cell and centers vertically.

The table will fill its container (a div) horizontally.

Can anyone give me hints?

I don't necessarily need a table element, just something that achieves the effect without me having to specify pixel sizes to keep everything scalable.

Here is what I have now (some garbage may still be in there...):

table {
  display: table;
  table-layout: auto;
  width: 100%;
}

tr {
  display: table-row;
  width: auto;
  clear: both;
}

input {
  font-size: 16px;
}

input[name="text"] {
  line-height:1.875;
  display:table-cell;
  width:100%;
}

input[type="submit"] {
  border: 0;
  border-radius: 0;
  background: #d7b221;
  box-shadow: none;
  color: white;
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
  padding: 1.4em 1.6em 1.2em;
}

img {
  width: auto;
  height: 52px;
}

a {
  display: block;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<table>
<tr>
<td colspan="2">
<input name="text" placeholder="Enter some text here"/>
</td>
</tr>
<tr>
<td><input type="submit" value="Click Here"/></td>
<td><img src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/car.svg"/></td>
</tr>
</table>
</form></code>```

I guess it ultimately boils down to this:

```<code>#container {
  border:1px solid red;
}

#main_img {
  height: 30px;
  width: 30px;
}

#dep_img {
  max-width: 100%;
  max-height: 100%;
}

<div id="container">
    <img id="main_img" src="http://i.stack.imgur.com/xkF9Q.jpg">
    <img id="dep_img" src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
</code>```

Is there any way in which the size (height) of the main image can dictate the size (height) of the dep image?

答:
Why are you using a table to layout in the first place when you can do all that with just CSS.
Learn CSS from this site: http://learnlayout.com/</p>

Body:
I'm very novice to HTML and CSS and have not yet "gotten it" how it all works.
I am trying to achieve a table made of two rows, in which the first row only has one column and spans over the two columns of the second row.

In the first row I have an input box and I'd like the row to conform to the height of this input box. On the bottom left I have a button with its own style and I'd like the row (and cell) to conform to the size of the button. On the bottom right I have an image and I'd like the image to scale (preserving its aspect ratio) such that it either fills the height of the row (and floats to the right) or the width of the cell and centers vertically.

The table will fill its container (a div) horizontally.

Can anyone give me hints?

I don't necessarily need a table element, just something that achieves the effect without me having to specify pixel sizes to keep everything scalable.

Here is what I have now (some garbage may still be in there...):

table {
  display: table;
  table-layout: auto;
  width: 100%;
}

tr {
  display: table-row;
  width: auto;
  clear: both;
}

input {
  font-size: 16px;
}

input[name="text"] {
  line-height:1.875;
  display:table-cell;
  width:100%;
}

input[type="submit"] {
  border: 0;
  border-radius: 0;
  background: #d7b221;
  box-shadow: none;
  color: white;
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
  padding: 1.4em 1.6em 1.2em;
}

img {
  width: auto;
  height: 52px;
}

a {
  display: block;
  float: right;
}

<form>

<input name="text" placeholder="Enter some text here"/>

<input type="submit" value="Click Here"/>

</form>

I guess it ultimately boils down to this:

#container {
  border:1px solid red;
}

#main_img {
  height: 30px;
  width: 30px;
}

#dep_img {
  max-width: 100%;
  max-height: 100%;
}

Is there any way in which the size (height) of the main image can dictate the size (height) of the dep image?


问:
Get option value from select tag in jQuery
I have a select tag on my page. I want to get the value 1 from <option value="1"> here using jquery to process an ajax request. How can I get so?

Here is a sample code

```<code><select name="duration">
    <option value='01'>This is Value 1</option>
    <option value='02'>This is Value 2</option>
    <option value='03'>This is Value 3</option>
    <option value='04'>This is Value 4</option>
</select>
</code>```

I want to get the 01, 02, 03 or 04 (whichever is selected in case) from the select tag. How can I do so?

I tried using $("select[name='duration'] option:selected").text() but this returns me This is Value 1 instead of 01 (the actual field value). Please help.

答:
```<code>    <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(function(){
$('.duration').change(function(){
var a = $("select[name='duration'] option:selected").text();
var b = $("select[name='duration'] option:selected").val();

});

});
</script>
<select class="duration" name="duration">
    <option value='01'>This is Value 1</option>
    <option value='02'>This is Value 2</option>
    <option value='03'>This is Value 3</option>
    <option value='04'>This is Value 4</option>
</select>
</html>
</code>```

Body:
I have a select tag on my page. I want to get the value 1 from <option value="1"> here using jquery to process an ajax request. How can I get so?

Here is a sample code

<select name="duration">
    <option value='01'>This is Value 1</option>
    <option value='02'>This is Value 2</option>
    <option value='03'>This is Value 3</option>
    <option value='04'>This is Value 4</option>
</select>

I want to get the 01, 02, 03 or 04 (whichever is selected in case) from the select tag. How can I do so?

I tried using $("select[name='duration'] option:selected").text() but this returns me This is Value 1 instead of 01 (the actual field value). Please help.


问:
Resusing select subquery/result
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

```<code>Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)
</code>```

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?

答:
Without a concrete example it's difficult to help, but try a WITH statement, something like:

```<code>WITH csq(x,y,z) AS (
  <complex subquery>
)
Select * from
 csq
join table1 t1 on (cq.id=t1.id)
union
Select * from
 csq
join table2 t2 on (cq.id=t2.id)
</code>```

it sometimes speeds things up no end

ContentLicense: CC BY-SA 2.5

Title: Resusing select subquery/result

Body:
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?

Body:
Without a concrete example it's difficult to help, but try a WITH statement, something like:

WITH csq(x,y,z) AS (
  <complex subquery>
)
Select * from
 csq
join table1 t1 on (cq.id=t1.id)
union
Select * from
 csq
join table2 t2 on (cq.id=t2.id)

it sometimes speeds things up no end


问:
identical word alignment using for loop
I'm trying to align words from two list

```<code>sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']
</code>```

and this is my codes :

```<code>def identicalWordsIndex(self, sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
            if sentence2[j] == sentence1[i]:
                idenNew2 = [j,i]
                identical_index.append(idenNew2)
    return identical_index
</code>```

what i'm trying to do is get the index number of align words from sentence1 and sentence2.

1st is the aligned words index from sentence1 towards sentence2.
2nd is the aligned words index from sentence2 towards sentence1.

but the result from the codes above is like this :

```<code>1st : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
2nd : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
</code>```

what I expect from the result is like this :

```<code>1st : [[0,1],[2,2],[3,4]]
2nd : [[1,0],[2,2],[3,0],[4,3],[5,3]]
</code>```

anyone can solve? thanks

答:
You just need to add breaks. Try this:

```<code>sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']
identical_index = []

def identicalWordsIndex( sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
                break
    return identical_index

print (identicalWordsIndex(sentence1, sentence2))
print (identicalWordsIndex(sentence2, sentence1))
</code>```

Prints:

[[0, 1], [2, 2], [3, 4]]

[[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]

Title: identical word alignment using for loop

Body:
I'm trying to align words from two list

sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']

and this is my codes :

def identicalWordsIndex(self, sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
            if sentence2[j] == sentence1[i]:
                idenNew2 = [j,i]
                identical_index.append(idenNew2)
    return identical_index

what i'm trying to do is get the index number of align words from sentence1 and sentence2.

1st is the aligned words index from sentence1 towards sentence2.
2nd is the aligned words index from sentence2 towards sentence1.

but the result from the codes above is like this :

1st : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
2nd : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]

what I expect from the result is like this :

1st : [[0,1],[2,2],[3,4]]
2nd : [[1,0],[2,2],[3,0],[4,3],[5,3]]

anyone can solve? thanks

Body:
You just need to add breaks. Try this:

sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']
identical_index = []

def identicalWordsIndex( sentence1, sentence2):
    identical_index = []
    for i in xrange(len(sentence1)):
        for j in xrange(len(sentence2)):
            if sentence1[i] == sentence2[j]:
                idenNew1 = [i,j]
                identical_index.append(idenNew1)
                break
    return identical_index

print (identicalWordsIndex(sentence1, sentence2))
print (identicalWordsIndex(sentence2, sentence1))

Prints:

[[0, 1], [2, 2], [3, 4]]

[[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]


答:
Alright.

First, we need to define what a conversation is: a pair of  (sender_id, recipient_id) exchanging messages. Determining the first message in a conversation is a bit tricky. We could do this:

```<code>SELECT sender_id, recipient_id, min(created_at) FROM messages
GROUP BY sender_id, recipient_id
</code>```

However, this will give us the first two messages of each conversation instead. We still don't know who started it and who replied without looking at the date, but the data we get is all we need to answer the question. And it is likely to be fast, since I will assume an index on (sender_id, recipient_id, created_at).

Now, I see two ways to solve this. First one:

```<code>SELECT least(sender_id,recipient_id),
       greatest(sender_id,recipient_id),
       max(created_at) <= DATE_ADD( min(created_at), INTERVAL 1 DAY )
FROM (
    SELECT sender_id, recipient_id, min(created_at) FROM messages
    GROUP BY sender_id, recipient_id
) foo
GROUP BY least(sender_id,recipient_id),
       greatest(sender_id,recipient_id)
HAVING count(*)=2;
</code>```

least() and greatest() allow to create one id for each conversation from the sender and receiver ids. max() and min() will return the first message and its reply, since we have only 2 rows per conversation. And the having will remove messages without reply.

We could also use a temp table:

```<code>CREATE TEMPORARY TABLE foo (
    sender_id     INT NOT NULL,
    recipient_id  INT NOT NULL,
    createdèat    DATETIME NOT NULL
);

INSERT INTO foo
SELECT sender_id, recipient_id, min(created_at) FROM messages
GROUP BY sender_id, recipient_id

ALTER TABLE foo ADD PRIMARY KEY (sender_id,recipient_id);

SELECT ... substract a.created_at and b.created_at to get your 24h limit
FROM foo a
JOIN foo b ON (    a.sender_id=b.recipient_id
               AND a.recipient_id=b.sender_id
               AND a.created_at < b.created_at)
</code>```

By joining the temp table to itself, we put together the first message and its reply in a single query, and we can compare their dates.

Title: Get users who replied the first message of the conversation within 24hours

Body:
I need to find the users who replied the first message of the conversation (one to one conversation) within 24hours. I have a messages table where all data are stored.

Table: messages

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01
5  | 1002      | 500          | Hi there     | 2017-03-22 10:10:10
6  | 1002      | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 500       | 1002         | Yes          | 2017-03-22 10:20:30
8  | 1003      | 600          | Hello world  | 2017-03-23 01:00:00
9  | 1004      | 700          | Hi           | 2017-03-23 08:10:10
10 | 700       | 1004         | hello        | 2017-03-26 22:00:00

Expected result:

users
256
500

Example: Conversation between user 1001 and 256.

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01

Here 2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10 is the first replied message of the conversation and its replied within 24 hours.

Body:
Alright.

First, we need to define what a conversation is: a pair of  (sender_id, recipient_id) exchanging messages. Determining the first message in a conversation is a bit tricky. We could do this:

SELECT sender_id, recipient_id, min(created_at) FROM messages
GROUP BY sender_id, recipient_id

However, this will give us the first two messages of each conversation instead. We still don't know who started it and who replied without looking at the date, but the data we get is all we need to answer the question. And it is likely to be fast, since I will assume an index on (sender_id, recipient_id, created_at).

Now, I see two ways to solve this. First one:

SELECT least(sender_id,recipient_id),
       greatest(sender_id,recipient_id),
       max(created_at) <= DATE_ADD( min(created_at), INTERVAL 1 DAY )
FROM (
    SELECT sender_id, recipient_id, min(created_at) FROM messages
    GROUP BY sender_id, recipient_id
) foo
GROUP BY least(sender_id,recipient_id),
       greatest(sender_id,recipient_id)
HAVING count(*)=2;

least() and greatest() allow to create one id for each conversation from the sender and receiver ids. max() and min() will return the first message and its reply, since we have only 2 rows per conversation. And the having will remove messages without reply.

We could also use a temp table:

CREATE TEMPORARY TABLE foo (
    sender_id     INT NOT NULL,
    recipient_id  INT NOT NULL,
    createdèat    DATETIME NOT NULL
);

INSERT INTO foo
SELECT sender_id, recipient_id, min(created_at) FROM messages
GROUP BY sender_id, recipient_id

ALTER TABLE foo ADD PRIMARY KEY (sender_id,recipient_id);

SELECT ... substract a.created_at and b.created_at to get your 24h limit
FROM foo a
JOIN foo b ON (    a.sender_id=b.recipient_id
               AND a.recipient_id=b.sender_id
               AND a.created_at < b.created_at)

By joining the temp table to itself, we put together the first message and its reply in a single query, and we can compare their dates.


问:
jQuery check 2 checkboxes in a PHP foreach's loop
I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.

I get the values from a databases thanks to a php's foreach loop. Here is my test code:

```<code>    <?php
            //checkboxes
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
           //script
           foreach($host1 as $row){ ?>
            <script type="text/javascript">
           var $checkboxes = $("input[type=checkbox][name='list[]'][value='<?php echo $row['table']?>']");
                $checkboxes.on("click", function() {
                var checkedState = this.checked
                $checkboxes.each(function() {
                    this.checked = checkedState;
            });
           });
            </script>
<?php    }
</code>```

If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.

Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.

Any ideas where is my mistake ?

Thank you ;)

答:
You should try this. I think this is what you want</p>

```<code><?php
//checkboxes
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
//script
?>
<script type = "text/javascript">
    $(document).ready(function () {

        $(".my_cb").on("click", function () {
            var val = $(this).val();
            var checkboxes = $("input[type=checkbox][name='list[]'][value='"+val+"']");
            var checkedState = this.checked;
            checkboxes.each(function () {
                this.checked = checkedState;
            });

        });
    });
</script>
</code>```

Body:
I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.

I get the values from a databases thanks to a php's foreach loop. Here is my test code:

    <?php
            //checkboxes
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
           //script
           foreach($host1 as $row){ ?>

<?php    }

If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.

Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.

Any ideas where is my mistake ?

Thank you ;)

Body:
You should try this. I think this is what you want

<?php
//checkboxes
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
//script
?>
<script type = "text/javascript">
    $(document).ready(function () {

        $(".my_cb").on("click", function () {
            var val = $(this).val();
            var checkboxes = $("input[type=checkbox][name='list[]'][value='"+val+"']");
            var checkedState = this.checked;
            checkboxes.each(function () {
                this.checked = checkedState;
            });

        });
    });
</script>


问:
Redis matching keys using SCAN with Glob pattern to get collection of items within a namespace
I have a redis data structure like so:

```<code>practice:1:patient:{UUID}:reports:{UUID}
practice:1:patient:{UUID}:reports:{UUID}:notes:{id}
practice:1:patient:{UUID}:reports:{UUID}:notes:{id}:fieldValue:{id}
practice:1:patient:{UUID}
practice:1:patient:{UUID}:variables
practice:1:patient:{UUID}:documents
</code>```

I'm trying to query for specifically patient:{UUID} keys but it's proving difficult with glob pattern matching.

Should I create a set practice:1:patients with the patient keys added to it?

Is there a valid glob pattern that would isolate that namespace?

Is there a better way to query for collections (e.g. to also apply to the reports, notes, etc.) / would I have to create a set for every namespace that contains the keys for that collection?

答: Scanning the entire keyspace to retrieve a few keys is inefficient - use a different data structure to store the patient data (e.g. a Hash) and/or Sets (your 1 and 3) to perform fast lookups.</p>

Body:
I have a redis data structure like so:

practice:1:patient:{UUID}:reports:{UUID}
practice:1:patient:{UUID}:reports:{UUID}:notes:{id}
practice:1:patient:{UUID}:reports:{UUID}:notes:{id}:fieldValue:{id}
practice:1:patient:{UUID}
practice:1:patient:{UUID}:variables
practice:1:patient:{UUID}:documents

I'm trying to query for specifically patient:{UUID} keys but it's proving difficult with glob pattern matching.

Should I create a set practice:1:patients with the patient keys added to it?

Is there a valid glob pattern that would isolate that namespace?

Is there a better way to query for collections (e.g. to also apply to the reports, notes, etc.) / would I have to create a set for every namespace that contains the keys for that collection?


问:
Why does map over an iterable return a one-shot iterable?
Why does map when called with an object which can be iterated over multiple times not return an object which can also be iterated multiple times? I think the latter is much more reasonable.

My use case is that I have a lot of data, such that it can only be iterated over. map is (in theory) perfect for operations on data, since it is lazy. However in the following example I would expect that the length is both times the same.

```<code>iterable = [1,2,3,4]  # this can be iterated repeatedly
m = map(lambda x:x**2, iterable) # this again should be iterable repeatedly
print(len(list(m))) # 4
print(len(list(m))) # 0
</code>```

How can I map over an iterable structure and get an iterable structure back?

Edit:
This is an example of how it imho should work, demonstrating the lazy evaluation:

```<code>def g():
    print('g() called')

data = [g, g]

# map is lazy, so nothing is called
m = map(lambda g: g(), data)
print('m: %s' % len(list(m))) # g() is called here
print('m: %s' % len(list(m))) # this should work, but doesnt

# this imap returns an iterable
class imap(object):
    def __init__(self, fnc, iterable):
        self.fnc = fnc
        self.iterable = iterable
    def __iter__(self):
        return map(self.fnc, self.iterable)

# imap is lazy, so nothing is called
im = imap(lambda g: g(), data)
print('im: %s' % len(list(im))) # g() is called here
print('im: %s' % len(list(im))) # works as expected
</code>```

答:
Why does map when called with an object which can be iterated over multiple times not return an object which can also be iterated multiple times?

Because there is no interface to tell whether an object can be iterated over repeatedly. map has no way to tell whether the thing it's iterating over supports repeat iteration, and unless map manages to determine this information somehow and invents an API to expose it to its users, map users would have no way to tell whether their map object supports repeat iteration.

Also, with repeat iteration comes the need to either repeat the function evaluations or cache the results (but if you're going to cache the results, why redesign map to return an iterator at all?). Repeated function evaluations are inefficient, potentially dangerous, and usually not what users want. It's better to have users explicitly repeat the map call or explicitly call list if they want to iterate again.

It's simpler if map objects are always just iterators.

Body:
Why does map when called with an object which can be iterated over multiple times not return an object which can also be iterated multiple times? I think the latter is much more reasonable.

My use case is that I have a lot of data, such that it can only be iterated over. map is (in theory) perfect for operations on data, since it is lazy. However in the following example I would expect that the length is both times the same.

iterable = [1,2,3,4]  # this can be iterated repeatedly
m = map(lambda x:x**2, iterable) # this again should be iterable repeatedly
print(len(list(m))) # 4
print(len(list(m))) # 0

How can I map over an iterable structure and get an iterable structure back?

Edit:
This is an example of how it imho should work, demonstrating the lazy evaluation:

def g():
    print('g() called')

data = [g, g]

# map is lazy, so nothing is called
m = map(lambda g: g(), data)
print('m: %s' % len(list(m))) # g() is called here
print('m: %s' % len(list(m))) # this should work, but doesnt

# this imap returns an iterable
class imap(object):
    def __init__(self, fnc, iterable):
        self.fnc = fnc
        self.iterable = iterable
    def __iter__(self):
        return map(self.fnc, self.iterable)

# imap is lazy, so nothing is called
im = imap(lambda g: g(), data)
print('im: %s' % len(list(im))) # g() is called here
print('im: %s' % len(list(im))) # works as expected


问:
.Net Multiline Regex expression to restrict to integers
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

```<code>Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);
</code>```

I want the following examples to be valid:

```<code>1

1\\n

1\\n2\\n3
</code>```

I want the following to be invalid

```<code>A

A1\\n2

1\\n2\\nA3
</code>```

Thanks in advance.

答:
You can match digits and newlines with:

```<code>Regex regExpr = new Regex("[\d\n]*", RegexOptions.Multiline)
</code>```

This will match any number of digits and newlines.  If you just want to make sure that the entered text doesn't have a NON digit, then use

```<code>Regex regExpr = new Regex("[\D\S]", RegexOptions.Multiline)
</code>```

and if it matches, then you have an illegal entry.

Body:
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);

I want the following examples to be valid:

1

1\\n

1\\n2\\n3

I want the following to be invalid

A

A1\\n2

1\\n2\\nA3

Thanks in advance.

Body:
You can match digits and newlines with:

Regex regExpr = new Regex("[\d\n]*", RegexOptions.Multiline)

This will match any number of digits and newlines.  If you just want to make sure that the entered text doesn't have a NON digit, then use

Regex regExpr = new Regex("[\D\S]", RegexOptions.Multiline)

and if it matches, then you have an illegal entry.


答:
You can try this solution using for loops:

```<code>a = ['boy','motorcycle','people','play']
b = ['run','boy','people','boy','play','play']

def align_ab(a, b):
    indexed = []
    for k,v in enumerate(a):
        try:
            i = b.index(v)
            indexed.append([k,i])
        except ValueError:
            pass

    return indexed
# Align a words from b
print(align_ab(a,b))
# Align b words from a
print(align_ab(b,a))
</code>```

Output:

```<code>>>> [[0, 1], [2, 2], [3, 4]]
>>> [[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]
</code>```

Title: identical word alignment using for loop

Body:
You can try this solution using for loops:

a = ['boy','motorcycle','people','play']
b = ['run','boy','people','boy','play','play']

def align_ab(a, b):
    indexed = []
    for k,v in enumerate(a):
        try:
            i = b.index(v)
            indexed.append([k,i])
        except ValueError:
            pass

    return indexed
# Align a words from b
print(align_ab(a,b))
# Align b words from a
print(align_ab(b,a))

Output:

>>> [[0, 1], [2, 2], [3, 4]]
>>> [[1, 0], [2, 2], [3, 0], [4, 3], [5, 3]]


问:
DevExteme Cancel button stays on navigating away from component
I am having a very weird problem, using a the DevExtreme library I have built a cell editable datagrid and implemented validation on it. On an error for a particular field a red Revert Button appears. The same Revert button  does not go away when user navigates to another page particularly using routing. However, when you navigate to another component which is dynamically generated it is can be removed using cancelEditData() funtion exposed by DevExtreme's datagrid instance. Here is a plunker that demonstrates the problem, try the below steps to replicate the issue.

Clear up the value for the Column Name field in the first row and click outside which would give you the red revert button

Now, click on the top lavel "My Component" menu item and you would see that the button stays on that screen

But, when you do that by clicking in the Child 2 side bar menu link it disappears as both Child 1 and Child 2 are generated dynamically and not via routing.

Any help would be greatly appreciated. I already contacted DevExtreme support and they are saying this is a problem with the Angular 2 framework, but why that beats me.

Code of interest is on src/parent.ts

```<code>onItemClick( event ) {
    // this works as this is invoked before I create the new component
    if (this.currentComponentHolder.instance.gridInstance)
      this.currentComponentHolder.instance.gridInstance.cancelEditData();

    let item = event.itemData;
    this.setContent( item.component );
}

// this is the piece which is not working. Also, noteworthy is the fact that the above working code also does not work when i put it in the ngOnDestroy of Child1 component.
ngOnDestroy() {
    if (this.currentComponentHolder.instance.gridInstance)
        this.currentComponentHolder.instance.gridInstance.cancelEditData();
}
</code>```

答:
I wasn't able to run the Plunker, getting tons of console error messages

However, looking at parent.ts, I see that you have no implement OnDestroy here:

```<code>export class Parent implements OnInit
</code>```

You need to also import OnDestroy. Try that and let me know!

Body:
I am having a very weird problem, using a the DevExtreme library I have built a cell editable datagrid and implemented validation on it. On an error for a particular field a red Revert Button appears. The same Revert button  does not go away when user navigates to another page particularly using routing. However, when you navigate to another component which is dynamically generated it is can be removed using cancelEditData() funtion exposed by DevExtreme's datagrid instance. Here is a plunker that demonstrates the problem, try the below steps to replicate the issue.

Clear up the value for the Column Name field in the first row and click outside which would give you the red revert button

Now, click on the top lavel "My Component" menu item and you would see that the button stays on that screen

But, when you do that by clicking in the Child 2 side bar menu link it disappears as both Child 1 and Child 2 are generated dynamically and not via routing.

Any help would be greatly appreciated. I already contacted DevExtreme support and they are saying this is a problem with the Angular 2 framework, but why that beats me.

Code of interest is on src/parent.ts

onItemClick( event ) {
    // this works as this is invoked before I create the new component
    if (this.currentComponentHolder.instance.gridInstance)
      this.currentComponentHolder.instance.gridInstance.cancelEditData();

    let item = event.itemData;
    this.setContent( item.component );
}

// this is the piece which is not working. Also, noteworthy is the fact that the above working code also does not work when i put it in the ngOnDestroy of Child1 component.
ngOnDestroy() {
    if (this.currentComponentHolder.instance.gridInstance)
        this.currentComponentHolder.instance.gridInstance.cancelEditData();
}

Body:
I wasn't able to run the Plunker, getting tons of console error messages

However, looking at parent.ts, I see that you have no implement OnDestroy here:

export class Parent implements OnInit

You need to also import OnDestroy. Try that and let me know!


问:
Android MediaPlayer Stop and Play
I'm creating Android application contains 2 buttons, on click on each button play a mp3 file.
The problem is when I play button1 it plays sound1, when I click button2 it plays sound2.

I check on each button the other player if it's working and I stop it and play the clicked one

But If I click on same button twice it's keep first audio playing in the background and play another one again

I tried to check isPlaying() and to stop it, but it doesn't work!

I want If I click on button1 it play sound1 and if clicked on it again it stop it and play it again from beginning.

My code:

```<code>package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b= (Button) findViewById(R.id.button1);
        Button b2= (Button) findViewById(R.id.button2);
        final TextView t= (TextView) findViewById(R.id.textView1);

        final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
        final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp1.isPlaying()) {

                    mp1.stop();
                }

                mp.start();
            }

        });

        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {

                    mp.stop();
                }
                mp1.start();
            }
        });
    }
}
</code>```

Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.

答:
just in case someone comes to this question, I have the easier version.</p>

```<code>public static MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button);
        Button b2 = (Button) findViewById(R.id.button2);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mp = MediaPlayer.create(MainActivity.this, R.raw.game);
                mp.start();
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
               // mp.start();
            }
        });
    }
</code>```

Title: Android MediaPlayer Stop and Play

Body:
I'm creating Android application contains 2 buttons, on click on each button play a mp3 file.
The problem is when I play button1 it plays sound1, when I click button2 it plays sound2.

I check on each button the other player if it's working and I stop it and play the clicked one

But If I click on same button twice it's keep first audio playing in the background and play another one again

I tried to check isPlaying() and to stop it, but it doesn't work!

I want If I click on button1 it play sound1 and if clicked on it again it stop it and play it again from beginning.

My code:

package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b= (Button) findViewById(R.id.button1);
        Button b2= (Button) findViewById(R.id.button2);
        final TextView t= (TextView) findViewById(R.id.textView1);

        final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
        final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp1.isPlaying()) {

                    mp1.stop();
                }

                mp.start();
            }

        });

        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {

                    mp.stop();
                }
                mp1.start();
            }
        });
    }
}

Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.

Body:
just in case someone comes to this question, I have the easier version.

public static MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button);
        Button b2 = (Button) findViewById(R.id.button2);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mp = MediaPlayer.create(MainActivity.this, R.raw.game);
                mp.start();
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
               // mp.start();
            }
        });
    }


问:
PHP/Ajax/jquery action not working after pagination click
I have a single php page that loads a table with pagination using jquery/ajax. I am unable to get the rows to redirect to a different page once any page in the pagination is clicked (other than the initial page)

Here is simplified code of my generated html for the table. I know the html is generated correctly each time pagination page is changed.

```<code><tr class="table-row" data-myredirect="http://example.com/page">
<td>blah blah</td>
</tr>
</code>```

Upon success of loading the table data (only run once after user runs a query), i run the following (simplified):

```<code>success:function(result){
         //display table data (not shown)
$(".table-row").click(function() {
         //redirect
        window.document.location = $(this).data("myredirect");
    });
}
</code>```

When user selects a different page from the pagination links, the following is run:

```<code>//executes code below when user click on pagination links
    $("#results").on( "click", ".pagination a", function (e){
        e.preventDefault();
        $(".loading-div").show(); //show loading element
        var page = $(this).attr("data-page"); //get page number from link
        $("#results").load("test.php",{"page":page, "myparam":searchItemOne}, function(){ //get content from PHP page
            $(".loading-div").hide(); //once done, hide loading element
            //fixes scrolling up bug
            $('html, body').animate({
        scrollTop: $("#results").offset().top
     }, 0);
        });

    });
</code>```

What might be causing the action to no longer work once I navigate to the next pagination page? I can include more code upon request.

答:
i think it's because your .table-row is rendered after the javascript code ( after you load the html via AJAX the second time) so the redirection code doesn't know the new table-row .

try to put the redirection code

```<code>$(".table-row").click(function() {
         //redirect
        window.document.location = $(this).data("myredirect");
    });
</code>```

in your php file so it reloads with the new html
.

Body:
I have a single php page that loads a table with pagination using jquery/ajax. I am unable to get the rows to redirect to a different page once any page in the pagination is clicked (other than the initial page)

Here is simplified code of my generated html for the table. I know the html is generated correctly each time pagination page is changed.

blah blah

Upon success of loading the table data (only run once after user runs a query), i run the following (simplified):

success:function(result){
         //display table data (not shown)
$(".table-row").click(function() {
         //redirect
        window.document.location = $(this).data("myredirect");
    });
}

When user selects a different page from the pagination links, the following is run:

//executes code below when user click on pagination links
    $("#results").on( "click", ".pagination a", function (e){
        e.preventDefault();
        $(".loading-div").show(); //show loading element
        var page = $(this).attr("data-page"); //get page number from link
        $("#results").load("test.php",{"page":page, "myparam":searchItemOne}, function(){ //get content from PHP page
            $(".loading-div").hide(); //once done, hide loading element
            //fixes scrolling up bug
            $('html, body').animate({
        scrollTop: $("#results").offset().top
     }, 0);
        });

    });

What might be causing the action to no longer work once I navigate to the next pagination page? I can include more code upon request.

Body:
i think it's because your .table-row is rendered after the javascript code ( after you load the html via AJAX the second time) so the redirection code doesn't know the new table-row .

try to put the redirection code

$(".table-row").click(function() {
         //redirect
        window.document.location = $(this).data("myredirect");
    });

in your php file so it reloads with the new html
.


问:
Java - Loop through all inputs with input mask xxxxxxx where x = 0 or 1
So I am trying to create an AList of AClass(es) with a 7-switch String parameter where each character is either on [1] or off [0], E.g: 0011010.

```<code>ArrayList<AClass> AList = new ArrayList<AClass>();

public BClass() {
    // I believe there is 128 unique ways to arrange between 0000000 and 1111111
    for (int i = 0; i < ?; i++) {
        // I assume I would need to create the String some how here and use that.
        String str;
        AList.add(new AClass("0000000"));

        / * Each loop would create a new one, you get the idea.
        AList.add(new AClass("1000000"));
        AList.add(new AClass("1100000"));
        AList.add(new AClass("1110000"));
        ...
        ...
        AList.add(new AClass("1001010"));
        ...
        ...
        AList.add(new AClass("1111111"));
        */
    }
}
</code>```

What is the most efficient way to create all 128 unique parameter AClass(es)?

Edited: Mistakenly started at 0000001 instead of 1000000

答:
You can use Integer.toBinaryString(int i) and String.format to complete your String with 0 in left:

```<code>for (int i = 0; i < 128; i++) {
    System.out.println(String.format("%07d", Integer.parseInt(Integer.toBinaryString(i))));
}
</code>```

This will show you :

```<code>0000000
0000001
...
...
1111110
1111111
</code>```

Body:
So I am trying to create an AList of AClass(es) with a 7-switch String parameter where each character is either on [1] or off [0], E.g: 0011010.

ArrayList<AClass> AList = new ArrayList<AClass>();

public BClass() {
    // I believe there is 128 unique ways to arrange between 0000000 and 1111111
    for (int i = 0; i < ?; i++) {
        // I assume I would need to create the String some how here and use that.
        String str;
        AList.add(new AClass("0000000"));

        / * Each loop would create a new one, you get the idea.
        AList.add(new AClass("1000000"));
        AList.add(new AClass("1100000"));
        AList.add(new AClass("1110000"));
        ...
        ...
        AList.add(new AClass("1001010"));
        ...
        ...
        AList.add(new AClass("1111111"));
        */
    }
}

What is the most efficient way to create all 128 unique parameter AClass(es)?

Edited: Mistakenly started at 0000001 instead of 1000000

Body:
You can use Integer.toBinaryString(int i) and String.format to complete your String with 0 in left:

for (int i = 0; i < 128; i++) {
    System.out.println(String.format("%07d", Integer.parseInt(Integer.toBinaryString(i))));
}

This will show you :

0000000
0000001
...
...
1111110
1111111


问:
Convert text Amount to decimal - ssis
In my source file I have amount column with values

eg:

```<code>Amount
380.00
2,435.00
</code>```

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.

答:
In SSIS, you can do the following.

Add a Derived Column

Add one of these conversions

Round: (DT_I4)Amount

Ceiling: (DT_I4)CEILING(((DT_DECIMAL,2)Amount))

Floor: (DT_I4)FLOOR(((DT_I4)(DT_DECIMAL,2)Amount))

Note: While I chose to add as new column you can Replace that column as well.

Title: Convert text Amount to decimal - ssis

Body:
In my source file I have amount column with values

eg:

Amount
380.00
2,435.00

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.


答:
Here is a solution using binary representation:

```<code>/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        for (int i = 0; i < 128; i++) {
            System.out.println(padLeft(Integer.toBinaryString(i), 8));
        }
    }

    // borrowed from http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java
    public static String padLeft(String s, int n) {
        return String.format("%1$" + n + "s", s).replace(' ', '0');
    }
}
</code>```

demo

Title: Java - Loop through all inputs with input mask xxxxxxx where x = 0 or 1

Body:
Here is a solution using binary representation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        for (int i = 0; i < 128; i++) {
            System.out.println(padLeft(Integer.toBinaryString(i), 8));
        }
    }

    // borrowed from http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java
    public static String padLeft(String s, int n) {
        return String.format("%1$" + n + "s", s).replace(' ', '0');
    }
}

demo


问:
Jasmine-node expect not executed
I started testing today with Jasmine, which is new to me. Since I am working with a GraphQL-server, developed with NodeJS, I am using jasmine-node.

The following is my first spec I write myself, and I thought it was working:

```<code>const request = require('request');
const config = require('../sources/config');

const base_url = `http://localhost:${config.graphqlPort}/${config.graphqlRoute}`;

describe("GraphQLServer.", () => {
it("Should expect something.", () => {
    expect(1).not.toEqual(2);
    expect(1).toEqual(1);
    expect(true).toBe(true);
    expect(false).not.toBe(true);
});

describe('When request is made.', () => {
    it('Returns statuscode 200.', () => {
        request.get(base_url, (error, response, body) => {
            console.log('Error: ', error);
            console.log(base_url);
            console.log('StatusCode: ', response && response.statusCode);
            console.log('Body:', body);
            expect(true).toBe(true);
            expect(true).toBe(false);
            expect(response.statusCode).toBe(200);
            expect(response.statusCode).toBe(400);
            done();
            });
        });
    });
});
</code>```

This gives the following result:

```<code>    ..

Finished in 0.018 seconds
2 tests, 4 assertions, 0 failures, 0 skipped

Error:  null
http://localhost:8000/graphql
StatusCode:  400
Body: {"errors":[{"message":"Must provide query string."}]}
</code>```

A lot of this is exactly what I expect. I do a request without a query-string, so the errors in body are expected.

The problem is: the 4 useless (obvious) expects inside it("Should expect something") are working just fine. Those are the 4 assertions in the result. The other 4 expect's inside it("Returns statuscode 200.") are simply not in the result (they don't fail and they don't pass), but the console.log's are.

Every example I find online seems to do exactly what I do right here, yet I don't manage to get this to work.

答:
I forget the exact syntax in Jasmine to suggest a fix, but I believe I know the answer: This is a classic case of testing with promises.  The result is coming back after the test is done, so your expect calls are not happening in a context where they can affect the test anymore.

One difference I noticed between your code and the jasmine-node docs is that the function being passed to it should take done as a parameter, but you have () => instead of (done) =>.  That might cause the behaviour you're seeing.

ContentLicense: CC BY-SA 4.0

Title: Jasmine-node expect not executed

Body:
I started testing today with Jasmine, which is new to me. Since I am working with a GraphQL-server, developed with NodeJS, I am using jasmine-node.

The following is my first spec I write myself, and I thought it was working:

const request = require('request');
const config = require('../sources/config');

const base_url = `http://localhost:${config.graphqlPort}/${config.graphqlRoute}`;

describe("GraphQLServer.", () => {
it("Should expect something.", () => {
    expect(1).not.toEqual(2);
    expect(1).toEqual(1);
    expect(true).toBe(true);
    expect(false).not.toBe(true);
});

describe('When request is made.', () => {
    it('Returns statuscode 200.', () => {
        request.get(base_url, (error, response, body) => {
            console.log('Error: ', error);
            console.log(base_url);
            console.log('StatusCode: ', response && response.statusCode);
            console.log('Body:', body);
            expect(true).toBe(true);
            expect(true).toBe(false);
            expect(response.statusCode).toBe(200);
            expect(response.statusCode).toBe(400);
            done();
            });
        });
    });
});

This gives the following result:

    ..

Finished in 0.018 seconds
2 tests, 4 assertions, 0 failures, 0 skipped

Error:  null
http://localhost:8000/graphql
StatusCode:  400
Body: {"errors":[{"message":"Must provide query string."}]}

A lot of this is exactly what I expect. I do a request without a query-string, so the errors in body are expected.

The problem is: the 4 useless (obvious) expects inside it("Should expect something") are working just fine. Those are the 4 assertions in the result. The other 4 expect's inside it("Returns statuscode 200.") are simply not in the result (they don't fail and they don't pass), but the console.log's are.

Every example I find online seems to do exactly what I do right here, yet I don't manage to get this to work.


问:
would change process priority frequently have side effect
I am doing embedded system programming.
our process is set as higher priority by default, however for some actions like invoking shell command, write file. I was thinking to lower its priority and then up it again. so it's kind of like a pair of function calling: "setdefaultpriority" and "improve priority".

And there are lots of shell command calling in our process. In one file, I may need to call tens of pair of "setdefault..." and "improve.."

My question, would so many priority operation in one process have any bad effect ?

答:
setpriority in a non-root process can only go up (decrease priority), never down.

What you can do is decrease process priority in the child process, before it execs the shell command.

```<code>//errror checks ommited
#include <sys/resource.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <sys/wait.h>

int main()
{
    pid_t pid;
    pid=fork();
    assert(pid>=0);
    if (!pid){
        execlp("nice", "nice", (char*)0);
        _exit(1);
    }
    wait(0);
    pid=fork();
    if (!pid){
        setpriority(PRIO_PROCESS, 0, 10);
        execlp("nice", "nice", (char*)0);
        _exit(1);
    }

}
/* should print:
    0
    10
*/
</code>```

The performance overhead of a system call as simple as setpriority should be negligible compared to the cost of fork and exec*.

Body:
setpriority in a non-root process can only go up (decrease priority), never down.

What you can do is decrease process priority in the child process, before it execs the shell command.

//errror checks ommited
#include <sys/resource.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <sys/wait.h>

int main()
{
    pid_t pid;
    pid=fork();
    assert(pid>=0);
    if (!pid){
        execlp("nice", "nice", (char*)0);
        _exit(1);
    }
    wait(0);
    pid=fork();
    if (!pid){
        setpriority(PRIO_PROCESS, 0, 10);
        execlp("nice", "nice", (char*)0);
        _exit(1);
    }

}
/* should print:
    0
    10
*/

The performance overhead of a system call as simple as setpriority should be negligible compared to the cost of fork and exec*.


问:
How to create a Form dynamically?
I want to create, dynamically, forms depending a type of user. For example:
I want, if it is an administrator, to create the form or the buttons, for this user specifically.
 In the code of my login there is a validation that identifies the type of user.
But I only did that when it identifies the user to send it to the corresponding screen with its buttons already set, but what I want is that when identifying the user type, generate the buttons that the user should have access to;
The user has a type of user and that type of user has 1 or more permissions, then, depending on how many permissions that user has, create the buttons. Each permission is a button.
Example:
The user Alfonso is type of sales and has permissions to invoice and sell, then when it initiates session the "invoice" and "sell" buttons will be generated.</p>

答:
Create a "UserType" table:

```<code>|   id   |   userType      |
|--------------------------|
|   1    |   Administrator |
|   2    |   Sales         |
</code>```

Create a "Menu" or "options" table:

```<code>|   id   |   option   |
|---------------------|
|   1    |   Invoice  |
|   2    |   Sell     |
</code>```

Create a Permissions by user type Table(with the list of options)

```<code>|   idUserType   |   idOption   |  allow   |
|----------------|--------------|----------|
|         2      |        1     |  true    |
|         2      |        2     |  true    |
</code>```

Create ALL the options in your aplication [dynamical] (create the buttons with the options from the database)

When Login get all the permissions for the user type

Change the visible attribute to false for all the buttons, except the ones on the Permissions by user type Table

Thats my idea, all configurable from the DataBase

Title: How to create a Form dynamically?

Body:
Create a "UserType" table:

|   id   |   userType      |
|--------------------------|
|   1    |   Administrator |
|   2    |   Sales         |

Create a "Menu" or "options" table:

|   id   |   option   |
|---------------------|
|   1    |   Invoice  |
|   2    |   Sell     |

Create a Permissions by user type Table(with the list of options)

|   idUserType   |   idOption   |  allow   |
|----------------|--------------|----------|
|         2      |        1     |  true    |
|         2      |        2     |  true    |

Create ALL the options in your aplication [dynamical] (create the buttons with the options from the database)

When Login get all the permissions for the user type

Change the visible attribute to false for all the buttons, except the ones on the Permissions by user type Table

Thats my idea, all configurable from the DataBase


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答:
F# will behave the same as C# for calculations (since it is all just IL). Just sure to represent your vector as a struct - since you will be constructing many of those objects which are short lived.

Units of measure has zero impact on performance, in fact at compile time the units of measure information is removed entirely. So you actually cannot tell that your F# code has units of measure on it.

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Chris Smith


问:
problem with unix date util running in emacs shell
here's a oddity.

on Cygwin bash on Windows Vista, i can get date like this:

```<code>$ date
2010-11-30  4:40:48 AM PST

xah@xah-PC ~
$ date +%s
1291120855
</code>```

but in emacs “shell”, running the same date command, i get this:

```<code>c:\Users\xah\web\xahlee_org\comp>which date
which date
/usr/bin/date

c:\Users\xah\web\xahlee_org\comp>date
date
The current date is: 2010-11-30
Enter the new date: (yy-mm-dd)

c:\Users\xah\web\xahlee_org\comp>date +%s
date +%s
The system cannot accept the date entered.
Enter the new date: (yy-mm-dd)
</code>```

any idea what's going on?

答: You're hitting cmd.exe's date builtin, which is in no way like POSIX date(1). You could work around this by typing in the full path to the date command that you want.</p>

Body:
here's a oddity.

on Cygwin bash on Windows Vista, i can get date like this:

$ date
2010-11-30  4:40:48 AM PST

xah@xah-PC ~
$ date +%s
1291120855

but in emacs “shell”, running the same date command, i get this:

c:\Users\xah\web\xahlee_org\comp>which date
which date
/usr/bin/date

c:\Users\xah\web\xahlee_org\comp>date
date
The current date is: 2010-11-30
Enter the new date: (yy-mm-dd)

c:\Users\xah\web\xahlee_org\comp>date +%s
date +%s
The system cannot accept the date entered.
Enter the new date: (yy-mm-dd)

any idea what's going on?


问:
Return value larger than X with INDEX(MATCH)
Please some help with the following:

In Excel, I have this table:

And I have this formula to lookup the combination of "Cores per host" and "GHz per host" that it satisfies the values of "Required cores per host" and "Required GHz per host"

```<code>=(INDEX(CPUData;MATCH(1;(CoresHost>C66)*(ghzHost>C36/C8);0);1))
</code>```

Where CPUData is the table without headers, CoresHost and ghzHost are the defined names of the columns containing the values in the table above.

The formula is working, but the problem is that instead of returning the value larger than what is required, it's returning the value that is smaller.

For example, if the processor that matches the requirement or exactly exceeds it is the E52630, it will return the E52643 instead.

I have tried using -1 and 0, but any combination of those I've tried it gives me either an error or a completely wrong value.

How can I get it to return the processor that it exactly meets or exceeds the requirement?

答:
Assuming you are using an Excel Table (i.e. ListObject). If so, instead of using Defined Names, use the "BuiltIn Names" of the ListObject.

Try this formula instead:

```<code>=(INDEX(CPUData,MATCH(1,
(CPUData[Cores per Host]>C66)*(CPUData[GHz per host]>(C36/C8)),0),1))
</code>```

Or this variation which limits the index to the Processor column instead of referencing the entire Table:

```<code>=(INDEX(CPUData[Processor],
MATCH(1,(CPUData[Cores per Host]>C66)*(CPUData[GHz per host]>(C36/C8)),0),1))
</code>```

It returns E52630E (2,2GHz, 10Cores) with the following values:
C66 = 144; C36 = 144 & C8 = 5

This works regardless of the blank record at beginning of the table.

Body:
Please some help with the following:

In Excel, I have this table:

And I have this formula to lookup the combination of "Cores per host" and "GHz per host" that it satisfies the values of "Required cores per host" and "Required GHz per host"

=(INDEX(CPUData;MATCH(1;(CoresHost>C66)*(ghzHost>C36/C8);0);1))

Where CPUData is the table without headers, CoresHost and ghzHost are the defined names of the columns containing the values in the table above.

The formula is working, but the problem is that instead of returning the value larger than what is required, it's returning the value that is smaller.

For example, if the processor that matches the requirement or exactly exceeds it is the E52630, it will return the E52643 instead.

I have tried using -1 and 0, but any combination of those I've tried it gives me either an error or a completely wrong value.

How can I get it to return the processor that it exactly meets or exceeds the requirement?

Body:
Assuming you are using an Excel Table (i.e. ListObject). If so, instead of using Defined Names, use the "BuiltIn Names" of the ListObject.

Try this formula instead:

=(INDEX(CPUData,MATCH(1,
(CPUData[Cores per Host]>C66)*(CPUData[GHz per host]>(C36/C8)),0),1))

Or this variation which limits the index to the Processor column instead of referencing the entire Table:

=(INDEX(CPUData[Processor],
MATCH(1,(CPUData[Cores per Host]>C66)*(CPUData[GHz per host]>(C36/C8)),0),1))

It returns E52630E (2,2GHz, 10Cores) with the following values:
C66 = 144; C36 = 144 & C8 = 5

This works regardless of the blank record at beginning of the table.


问:
Using Storm in Cloudera
I have been looking to use Storm which is available with Hortonworks 2.1 installation but in order to avoid installing Hortonworks in addition to a Cloudera installation (which has Spark in it), I tried to find a way to use Storm in Cloudera.

If one can use both Storm and Spark on a single platform then it will save additional resources required to have both Cloudera and Hortonworks installations on a machine.

答:
You can install Apache Storm on Cloudera VM.
For a basic setup and test run, follow below link:

https://github.com/vrmorusu/StormOnClouderaVM/wiki/Apache-Storm-on-Cloudera-VM

This should get you started on developing Storm applications on Cloudera VM.

Title: Using Storm in Cloudera


问:
How can I debug JavaScript with PhpStorm without loading a new tab each time?
I'm all setup to debug JavaScript in PhpStorm, however, clicking the 'Debug' button in PhpStorm each time stinks. Is there anyway, maybe a Chrome extension, that I can use to enable debugging with from within the browser? (Just like you would while Xdebug debugging with the Chrome Xdebug helper?)

For example.. I'm working on a large project and need to debug site.com/some/thing/here, PhpStorm JavaScript debugging is setup for my site url (site.com), I have to click 'Debug' in PhpStorm, and a new Chrome tab opens to site.com. I then need to navigate to the page in question before my breakpoint will trigger; and I end up with a ton of tabs in Chrome. That workflow stinks :(

I'd much rather stay in one tab, navigate to the page in question, enable 'debugging mode', set my breakpoint in PhpStorm, and do a JS action or refresh the page to start debugging (just as you would with Xdebug).

I use the Chrome step-through debugger a lot, but I really want to move to using PhpStorm so I'm able to set breakpoints and edit my code in the same place / with the same workflow I use to debug PHP.

Any ideas? Suggestions? Thank you!!

答:
In the URL box, just enter the URL of the page you're debugging (e.g. http://example.com/some/thing/here)

When you click the debug button it will navigate to that page. You can then just refresh the same page


问:
Catching child process exceptions on windows
i'm developing a multi-platform C++ fuzzing application. The app spawns a child process and checks whether it stopped unexpectedly. I've already managed to do this on linux, however, windows exception handling mechanism is making things hard for me.

My code right now does the following:
- Call CreateProcess to spawn the process.
- WaitForSingleObject to wait for it to terminate.
- Then call GetExitCodeProcess and check if the exit code corresponds to an exception.

Everything works as it should, i've tested it with a null dereferencing test application, and i can catch the exception gracefully. However, each time i test this, a Windows error message box spawns telling me to Send or Not Send the error report. Since the fuzzer is supposed to be an automatic testing application, i'd need to somehow disable this notification, so that even if an exception is caught, the fuzzer can continue testing.

I've already tried installing a SEH handler, but had no luck(apparently these handlers aren't inherited by child processes). I've read something about using vectored exception handling, but suppose it would be the same, i believe vector handlers aren't inherited.

Could anybody help me with this problem? I don't know what to search for, i've already googled a lot and haven't found anyhing.

Thanks!

答: Debug API is one option. Here is a starting point in MSDN.</p>


问:
Dynamic value in where clause
I want to select a photo based on user that has opened the window form.

If I put a number in the where clause, "where id=36", it shows only the photo of ID 34 (its static). How can I make it dynamic? Every user has its own photo, so it should be loaded. Code below.

```<code> cmd = new SqlCommand("select profilepic from users where id=@Id", con);
        cmd.Parameters.Add("@ID", SqlDbType.Int);
        cmd.Parameters["@ID"].Value = profilePic;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["profilepic"]);
            pictureBox1.Image = new Bitmap(ms);
        }
</code>```

答:
You should use a Parameter object to add that instead of dynamically creating a SQL statement. It is usually safer and does not really penalize in terms of performance</p>

```<code>var con = new SqlConnection();
var cmd = new SqlCommand("select profilepic from users where id=@id", con);
cmd.Parameters.AddWithValue("@id", 36);
var pic = cmd.ExecuteScalar();
</code>```

Title: Dynamic value in where clause

Body:
I want to select a photo based on user that has opened the window form.

If I put a number in the where clause, "where id=36", it shows only the photo of ID 34 (its static). How can I make it dynamic? Every user has its own photo, so it should be loaded. Code below.

 cmd = new SqlCommand("select profilepic from users where id=@Id", con);
        cmd.Parameters.Add("@ID", SqlDbType.Int);
        cmd.Parameters["@ID"].Value = profilePic;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["profilepic"]);
            pictureBox1.Image = new Bitmap(ms);
        }

Body:
You should use a Parameter object to add that instead of dynamically creating a SQL statement. It is usually safer and does not really penalize in terms of performance

var con = new SqlConnection();
var cmd = new SqlCommand("select profilepic from users where id=@id", con);
cmd.Parameters.AddWithValue("@id", 36);
var pic = cmd.ExecuteScalar();


问:
mongoose query same field with different values
Is there a way to user mongoose.find({title:'some title'}) to query the same field with multiple values? For example something like this  mongoose.find({title:'some title', title:'some other title'}) sends back only documents matching title:'some other title is there a way to accomplish this ?

答:
The mongodb text search {"title":"some thing"} will return any document that has the word "some", or the word "thing" in it. I won't do an exact match to the phrase "some thing".

Therefore, if you wanted to find all titles that contained any series of words, you would just do {"title":"word one two three four something dog cat last word"} and it would return any document that has any of those words in it.

If you want to do exact phrase matching, then you would have to change your original query.