问:
I want to reorder an array of strings
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

```<code>String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);
</code>```

答: Use SortedSet -- TreeSet is an implementation -- instead of the array. </p>

Title: I want to reorder an array of strings

Body:
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);


来源: stackexchange

问:
Selenium Python - Finding Elements by Class Name With Spaces
I'm writing a Python program that uses Selenium to navigate to and enter information into search boxes on an advanced search page. This website uses Javascript, and the IDs and Names for each search box change slightly each time the website is loaded, but the Class Names remain consistent. Class names are frequently reused though, so my goal is to use find_elements_by_class_name(classname) and then index through that list.

One box, for example, has the class name x-form-text x-form-field x-form-num-field x-form-empty-field, but I can't use this because selenium considers it a compound class name and throws an error. If I use just a portion of it, such as x-form-text, it can't find the element. My hope is to either find a way to allow the spaces or, if that can't be done, find a way to search for all elements whose class name contains a section of text without spaces, such as x-form-text.

Any help or thoughts would be greatly appreciated!

Edit:

I tried this code:

    quantminclass = 'x-form-text.x-form-field.x-form-num-field.x-form-empty-field'
    quantmin = '25'
    browser.find_elements_by_css_selector(quantminclass)[0].send_keys(quantmin)

But got an error that the list index was out of range, implying that it can't find anything. I inspected the element and that is definitely its class name, so I'm not sure how to proceed.

答:
Try converting class name to a CSS selector.

With a CSS selector, a class named x-form-text x-form-field x-form-num-field
turns into .x-form-text.x-form-field.x-form-num-field

So basically just replace spaces with dots and you're good to go.

ContentLicense: CC BY-SA 3.0


问:
External style sheets not applying styles
I have this page, to test a new layout for a category on a website at my new job:

```<code><!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />
  </head>
  <body>
    <div id="category-desc-grid" class="pure-g">

      <div class="pure-u">
        <p class="title"></p>

        <p class="details">
          Throw Style & Fitted Style<br>
          71 Fabric Color Choices<br>
          Fire resistant. Passes NFPA 701-2010<br>
          Full Color Dye Sublimation
        </p>

        <a href="#" class="button">Buy/View 24 Hour Tablecloths</a>
      </div>

      <div class="pure-u-1-2">
        <p class="title">Single Color Front Panel, Fitted Table Colors & Throws</p>

        <p class="details">
          4ft, 5ft, 6ft, 8ft<br>
          74 Fabric Color Choices,<br>
          including neon colors.<br>
          Fire resistant. Passes<br>
          NFPA 701-2010
        </p>

        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>

      <div class="pure-u-1-2">
        <p class="title">Full Color Print Front Panel</p>

        <p class="details">
          Additional Panel Print $99<br>
          Fitted & Throw Style<br>
          4ft, 5ft, 6ft, 8ft<br>
          71 Fabric Choices<br>
          F.R. - NFPA 701-2010
        </p>

        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>

    </div>

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

All of the stylesheets included are the mass that they have included in the head of the page that this code is to be inserted into, save for the last one, the Pure Grid. This is the one in question which will not apply any of its styles. As you can see I have the classes from that stylesheet in my HTML, but no styles are being attributed to them upon inspection. Styles from the stylesheets prior, however, are being applied.

Why

I've removed the grid stylesheet altogether and added one simple line: .display-grid .half { display: inline-block; width: 50%; max-width: 50%; } but it will only split into halves if I exclude the width rule. Unbelievable.

I just added the Bootstrap grid standalone.

答:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/js/tm/easylightbox/lightbox/css/lightbox.css" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/reset.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/boxes.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/styles.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/menu.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/widgets.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/aitpagecache.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/crimson/catalog/css/catalog.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/magmodules/snippets/snippets.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/magmodules/snippets/breadcrumbs.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/tm/easytabs.css" media="all" />
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />
 <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/base-min.css"/>
 <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/grids-min.css"/>

          Throw Style & Fitted Style

          71 Fabric Color Choices

          Fire resistant. Passes NFPA 701-2010

          Full Color Dye Sublimation

        Buy/View 24 Hour Tablecloths

Single Color Front Panel, Fitted Table Colors & Throws

          4ft, 5ft, 6ft, 8ft

          74 Fabric Color Choices,

          including neon colors.

          Fire resistant. Passes

          NFPA 701-2010

        Available in 1, 2, or 3 Day Production

Full Color Print Front Panel

          Additional Panel Print $99

          Fitted & Throw Style

          4ft, 5ft, 6ft, 8ft

          71 Fabric Choices

          F.R. - NFPA 701-2010

        Available in 1, 2, or 3 Day Production

```

Above you forgot to add two more files like- base-min.js and grids-min.js

Body:
I have this page, to test a new layout for a category on a website at my new job:

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />

          Throw Style & Fitted Style

          71 Fabric Color Choices

          Fire resistant. Passes NFPA 701-2010

          Full Color Dye Sublimation

        Buy/View 24 Hour Tablecloths

Single Color Front Panel, Fitted Table Colors & Throws

          4ft, 5ft, 6ft, 8ft

          74 Fabric Color Choices,

          including neon colors.

          Fire resistant. Passes

          NFPA 701-2010

        Available in 1, 2, or 3 Day Production

Full Color Print Front Panel

          Additional Panel Print $99

          Fitted & Throw Style

          4ft, 5ft, 6ft, 8ft

          71 Fabric Choices

          F.R. - NFPA 701-2010

        Available in 1, 2, or 3 Day Production

All of the stylesheets included are the mass that they have included in the head of the page that this code is to be inserted into, save for the last one, the Pure Grid. This is the one in question which will not apply any of its styles. As you can see I have the classes from that stylesheet in my HTML, but no styles are being attributed to them upon inspection. Styles from the stylesheets prior, however, are being applied.

Why

I've removed the grid stylesheet altogether and added one simple line: .display-grid .half { display: inline-block; width: 50%; max-width: 50%; } but it will only split into halves if I exclude the width rule. Unbelievable.

I just added the Bootstrap grid standalone.

Body:
<!DOCTYPE html>
<html>
  <head>

    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/js/tm/easylightbox/lightbox/css/lightbox.css" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/reset.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/boxes.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/styles.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/default/delivery/css/menu.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/widgets.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/aitpagecache.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/crimson/catalog/css/catalog.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/magmodules/snippets/snippets.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/magmodules/snippets/breadcrumbs.css" media="all" />
    <link rel="stylesheet" type="text/css" href="http://dev.premiertablelinens.com/skin/frontend/base/default/css/tm/easytabs.css" media="all" />
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />
 <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/base-min.css"/>
 <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/grids-min.css"/>
  </head>
  <body>
    <div id="category-desc-grid" class="pure-g">
      <div class="pure-u">
        <p class="title"></p>
        <p class="details">
          Throw Style &amp; Fitted Style<br>
          71 Fabric Color Choices<br>
          Fire resistant. Passes NFPA 701-2010<br>
          Full Color Dye Sublimation
        </p>
        <a href="#" class="button">Buy/View 24 Hour Tablecloths</a>
      </div>
      <div class="pure-u-1-2">
        <p class="title">Single Color Front Panel, Fitted Table Colors &amp; Throws</p>
        <p class="details">
          4ft, 5ft, 6ft, 8ft<br>
          74 Fabric Color Choices,<br>
          including neon colors.<br>
          Fire resistant. Passes<br>
          NFPA 701-2010
        </p>
        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>
      <div class="pure-u-1-2">
        <p class="title">Full Color Print Front Panel</p>
        <p class="details">
          Additional Panel Print $99<br>
          Fitted &amp; Throw Style<br>
          4ft, 5ft, 6ft, 8ft<br>
          71 Fabric Choices<br>
          F.R. - NFPA 701-2010
        </p>
        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>
    </div>
  </body>
</html>

Above you forgot to add two more files like- base-min.js and grids-min.js


问:
json-server middleware not working as expected
using node.js/Express/json-server

I am trying to check ( and modify) the request url sent to my API json-server. I wrote as stated the following middleware in my app server.js

```<code>//  API JSON-SERVER
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
...
apiServer.use((req, res, next) => {
  console.log('REQUEST: ', req)
  next() // Continue to JSON Server Router
})
...
apiRouter = jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json'))
app.use('/api', apiRouter)
</code>```

but I never get the request displayed
where am I wrong ?

答:
I looked here

https://github.com/typicode/json-server/issues/253

and it seems to me that you never want to instantiate the jsonServer, but only use the router.  Since you are using the express server, you should attach the middleware to that.

```<code>const express = require('express')
const jsonServer = require('json-server')

const app = express()

app.use((req, res, next) => {
 console.log('REQUEST: ', req)
 next() // Continue to JSON Server Router
})

app.use('/api', jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json')))
</code>```

Body:
using node.js/Express/json-server

I am trying to check ( and modify) the request url sent to my API json-server. I wrote as stated the following middleware in my app server.js

//  API JSON-SERVER
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
...
apiServer.use((req, res, next) => {
  console.log('REQUEST: ', req)
  next() // Continue to JSON Server Router
})
...
apiRouter = jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json'))
app.use('/api', apiRouter)

but I never get the request displayed
where am I wrong ?

Body:
I looked here

https://github.com/typicode/json-server/issues/253

and it seems to me that you never want to instantiate the jsonServer, but only use the router.  Since you are using the express server, you should attach the middleware to that.

const express = require('express')
const jsonServer = require('json-server')

const app = express()

app.use((req, res, next) => {
 console.log('REQUEST: ', req)
 next() // Continue to JSON Server Router
})

app.use('/api', jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json')))


问:
Pop-up modal dialog with grey background
I want to make classic a modal Window with dark background.

I don't know why this is so hard to make it. I tried a lot way to do it, however it just doesn't fit with my needs.

I have 10+ modal Windows and they are customized Forms which contain grids, charts, etc.

They are not 'OK, No, Cancel' stuff.

My code basically creates another Form with black background between parent Form and modal Form:

```<code>Form f = new Form();
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = this.StartPosition;
f.Opacity = 0.6;
f.Show();
notificationSGA nsga = new notificationSGA(Cursor.Position);
nsga.ShowDialog();
f.Dispose();
f.Close();
</code>```

Above code works perfectly fine. However if I move the parent (master) Form to somewhere instead of center of the screen, the black Form still appears at the center of the screen, not centered to the parent Form.

How can I solve my issue?

Note: This is not duplicated topic with below question:

How to show a pop up message with dark background

答:
Change the .StartPosition to .Manual so that you can set .Location to where your reference form is.

Also, change the owner in the .Show() method for both new Forms.

```<code>Form f = new Form();
//(...)
f.Size = this.Size;
f.StartPosition = FormStartPosition.Manual;
f.Location = this.Location;
//(...)

f.Show(this);

using (var nsga = new notificationSGA(Cursor.Position)) {
    nsga.StartPosition = FormStartPosition.CenterParent;
    nsga.ShowDialog(f);
}
f.Dispose();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to make classic a modal Window with dark background.

I don't know why this is so hard to make it. I tried a lot way to do it, however it just doesn't fit with my needs.

I have 10+ modal Windows and they are customized Forms which contain grids, charts, etc.

They are not 'OK, No, Cancel' stuff.

My code basically creates another Form with black background between parent Form and modal Form:

Form f = new Form();
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = this.StartPosition;
f.Opacity = 0.6;
f.Show();
notificationSGA nsga = new notificationSGA(Cursor.Position);
nsga.ShowDialog();
f.Dispose();
f.Close();

Above code works perfectly fine. However if I move the parent (master) Form to somewhere instead of center of the screen, the black Form still appears at the center of the screen, not centered to the parent Form.

How can I solve my issue?

Note: This is not duplicated topic with below question:

How to show a pop up message with dark background

Body:
Change the .StartPosition to .Manual so that you can set .Location to where your reference form is.

Also, change the owner in the .Show() method for both new Forms.

Form f = new Form();
//(...)
f.Size = this.Size;
f.StartPosition = FormStartPosition.Manual;
f.Location = this.Location;
//(...)

f.Show(this);

using (var nsga = new notificationSGA(Cursor.Position)) {
    nsga.StartPosition = FormStartPosition.CenterParent;
    nsga.ShowDialog(f);
}
f.Dispose();


问:
Changing all the values in a string to 'm'
I'm just beginning to toy with masm. I don't understand why this code isn't working.

```<code>.data
MsgBoxCaption  db "Iczelion Tutorial No.2",0
MsgBoxText       db "Win32 Assembly is Great!",0
savedAddr DWORD ?

.code
start:
mov eax, 10
mov savedAddr, OFFSET MsgBoxText

lab:
inc MsgBoxText
MOV MsgBoxText, 'm'
cmp eax, 0
dec eax
jnz lab

invoke MessageBox, NULL, savedAddr, addr MsgBoxCaption, MB_OK
invoke ExitProcess, NULL
end start
</code>```

Edit: I expect to see the first 10 characters in MsgBoxText be 'm's. Instead, only the first letter is an 'm'. I assume that inc MsgBoxText increments a pointer.

答:
At first glance it seems like this code should do nothing except change the 'W' of Win32 to an 'a' and then to a single 'm'.

You are incrementing the word in memory at MsgBoxText, the same word, in each loop iteration.

To clobber the string using the 'm' characters, a better strategy would be to load the address of the string into a register, start storing 'm' bytes, and then increment the value in the register, as well as decrementing the counter.

Update: Ok, to answer the question in the comment, change the loop to:

```<code>  lea esi, MsgBoxText
  mov bl, 'm'
lab:
  mov [esi], bl
  inc esi
  cmp eax, 0
  dec eax
  jnz lab
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm just beginning to toy with masm. I don't understand why this code isn't working.

.data
MsgBoxCaption  db "Iczelion Tutorial No.2",0
MsgBoxText       db "Win32 Assembly is Great!",0
savedAddr DWORD ?

.code
start:
mov eax, 10
mov savedAddr, OFFSET MsgBoxText

lab:
inc MsgBoxText
MOV MsgBoxText, 'm'
cmp eax, 0
dec eax
jnz lab

invoke MessageBox, NULL, savedAddr, addr MsgBoxCaption, MB_OK
invoke ExitProcess, NULL
end start

Edit: I expect to see the first 10 characters in MsgBoxText be 'm's. Instead, only the first letter is an 'm'. I assume that inc MsgBoxText increments a pointer.

Body:
At first glance it seems like this code should do nothing except change the 'W' of Win32 to an 'a' and then to a single 'm'.

You are incrementing the word in memory at MsgBoxText, the same word, in each loop iteration.

To clobber the string using the 'm' characters, a better strategy would be to load the address of the string into a register, start storing 'm' bytes, and then increment the value in the register, as well as decrementing the counter.

Update: Ok, to answer the question in the comment, change the loop to:

  lea esi, MsgBoxText
  mov bl, 'm'
lab:
  mov [esi], bl
  inc esi
  cmp eax, 0
  dec eax
  jnz lab


问:
Newton method in python for multivariables (system of equations)
My code is running fine for first iteration but after that it outputs the following error:

```<code>ValueError: matrix must be 2-dimensional
</code>```

To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me in this problem.

```<code>from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv

#initial guesses
x = -2
y = -2.5
i1 = 0

while i1<5:
    F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
    theta = np.sum(F)
    J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
    Jinv = inv(J)
    xn = np.array([[x],[y]])
    xn_1 = xn - (Jinv*F)
    x = xn_1[0]
    y = xn_1[1]
    #~ print theta
    print xn
    i1 = i1+1
</code>```

答:
xn_1 is a numpy matrix, so it's elements are accessed with the item() method, not like an array. (with []s)

So just change

```<code>x = xn_1[0]
y = xn_1[1]
</code>```

to

```<code>x = xn_1.item(0)
y = xn_1.item(1)
</code>```

Body:
My code is running fine for first iteration but after that it outputs the following error:

ValueError: matrix must be 2-dimensional

To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me in this problem.

from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv

#initial guesses
x = -2
y = -2.5
i1 = 0

while i1<5:
    F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
    theta = np.sum(F)
    J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
    Jinv = inv(J)
    xn = np.array([[x],[y]])
    xn_1 = xn - (Jinv*F)
    x = xn_1[0]
    y = xn_1[1]
    #~ print theta
    print xn
    i1 = i1+1

Body:
xn_1 is a numpy matrix, so it's elements are accessed with the item() method, not like an array. (with []s)

So just change

x = xn_1[0]
y = xn_1[1]

to

x = xn_1.item(0)
y = xn_1.item(1)


问:
How to do bulk insert from text file into sql table
I saw a few examples here, but I could not find the right solution.

I have a .txt file with a comma separated data that looks like this:

I have the following logic to bulk insert it into the table:

```<code>SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\n'',TABLOCK)'
EXEC (@cmd)
</code>```

This is the table structure:

.

After the execution, everything is in one row.

I need to insert everything from the file into the table, so each line from the file will be on a separate row.
Later on I will need to extract the data and move it into different tables based on certain conditions.

How can I correctly insert the data?

答:
You probably have your ROWTERMINATOR set incorrectly. Try this:

```<code>SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\r\n'',TABLOCK)'
EXEC (@cmd)
</code>```

Body:
I saw a few examples here, but I could not find the right solution.

I have a .txt file with a comma separated data that looks like this:

I have the following logic to bulk insert it into the table:

SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\n'',TABLOCK)'
EXEC (@cmd)

This is the table structure:

.

After the execution, everything is in one row.

I need to insert everything from the file into the table, so each line from the file will be on a separate row.
Later on I will need to extract the data and move it into different tables based on certain conditions.

How can I correctly insert the data?

Body:
You probably have your ROWTERMINATOR set incorrectly. Try this:

SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\r\n'',TABLOCK)'
EXEC (@cmd)


问:
VSTS v.Next Build Definitions Multiple Branches
I've recently transitioned from XAML builds to v.Next builds.  I've always kept one build definition per branch but I see the new system has the ability for a single build definition to trigger on multiple branches and pull requests.

Is this a good idea?  What are things to watch out for and the best ways to set this up?

The first couple concerns that come to mind are:

1) Version numbers.   How would I handle scenarios such as an old maintenance branch versioning as 1.0.,  master versioning as 2.0. and a dev build as say 0.2.*  so I don't confuse build artifacts?  Is there a better way?

2) What if the repos tree has changed?  What if master expects to build a .sln in one folder but a dev branch has since moved it to another folder?

Any other concerns and resolutions?

答:
This part,

Is this a good idea? What are things to watch out for and the best ways to set this up?

is off-topic (too broad/primarily opinion based), so I'm ignoring it and answering the two concrete scenarios you outlined.

Not really sure what you're asking. Release definition environments can be set to trigger on branches (artifact triggers), so if you have different release requirements for older branches, you can have different release definitions or simply an alternate pipeline within a single release definition.

You can specify wildcards in the Visual Studio Build step so you can specify, for example, **/*.sln. That will find any .sln file under any folder.


问:
How do I pass text input from one JTextField to a variable in another class?
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

```<code>import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}
</code>```

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!

答:
You're talking about data binding.  I recently posted a demo that shows how to do what you need as an answer to this question: Switching JPanels moves content diagonally

Essentially, the GUI passes information to the model and vice-versa by events, typically Property Change Events but there are lots of options you could choose.  The process would look like this:

User enters a value in a field

The field fires a property change event for the property "value" when it looses focus

The GUI (or controller class) listens for the property change event and fires another event, such as a Vetoable Change Event.

The Model (or controller) listens for the Vetoable change and validates the value, saving the "state" in the correct place. If the validation fails, it fires an exception.

The GUI checks for the veto exception and reverts the field if required.

A similar approach can allow the model to send property change requests to the GUI to update the value of fields.

The benefit of using these events is that it keeps the GUI simple, separates the model from the representation and makes it easier to replace/duplicate the GUI with another technology rather easily.

Body:
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;

import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {

public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}

    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){

          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call
   //acgMemberModel

          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }

 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;

public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}

public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name,
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!


问:
AVD hardware buttons not enabled
I just downloaded and installed the new Android SDK. When I start the emulator, on the emulator screen it says "Hardward Buttons not enabled in AVD". There are Home, Menu, etc are all disabled. How do I make these buttons enabled?

答:
The accepted answer is kind of deprecated now, because the android emulator interface changed a little bit.

If you need to display hardware buttons on your android emulator you have to uncheck this toggle inside your android emulator setings -> hardware profile:

Title: AVD hardware buttons not enabled


问:
How to animate a dynamically changing div when a button is clicked
A snippet of code for a portfolio showing projects using specified languages. The returning divs INSTANTLY change but I want an animation effect when they are changed.  Heres my HTML:

```<code>                <div>
                    <button class="waves-effect waves-light btn-large" onclick="checkProjects('python');">Python</button>
                </div>
                <div>
                    <button class="waves-effect waves-light btn-large" onclick="checkProjects('javascript');">Javascript</button>

                </div>

            <div class="col s6 project-list">
                <div class = "project1 col s12">
                    <div id="project1Title" class="project-title col s12"></div>
                    <img id="project1Pic" class="project-picture col s6" src="">
                    <div id ="project1Caption" class="col s6"></div>
                </div>
                <div class="project2 col s12">
                    <div id="project2Title" class="project-title col s12"></div>
                    <img id="project2Pic" class="project-picture col s6" src="">
                    <div id ="project2Caption" class="project-caption col s6"></div>
                </div>
            </div>
</code>```

I would like an animation everytime project1...project2...etc is changed.

答:
There are essentially two basic ways I can think of to accomplish what you're trying to do.

You can either

Add / remove a class to transition to whatever styles you want.

Manually animate the transition using javascript or jquery.

It sounds like your animation is more complex, and it may be best to use jquery.

```<code>// When the user clicks on a project
$('.project').on('click',function() {

  // Animate the project element
  $(this).animate({
    opacity:1
  },{duration:200,queue:false})

  // To access this specific project's child
  // elements (ie, title, picture, caption) you will
  // need to use .children
  $(this).children('.project-title').animate({
    opacity:1,
    top:'50px'
  },{duration:200,queue:false})
})
</code>```

Jquery's animation functionality can be very useful for complex, multi-element animations, check here for more info

Body:
A snippet of code for a portfolio showing projects using specified languages. The returning divs INSTANTLY change but I want an animation effect when they are changed.  Heres my HTML:

                    <button class="waves-effect waves-light btn-large" onclick="checkProjects('python');">Python</button>

                    <button class="waves-effect waves-light btn-large" onclick="checkProjects('javascript');">Javascript</button>

I would like an animation everytime project1...project2...etc is changed.

Body:
There are essentially two basic ways I can think of to accomplish what you're trying to do.

You can either

Add / remove a class to transition to whatever styles you want.

Manually animate the transition using javascript or jquery.

It sounds like your animation is more complex, and it may be best to use jquery.

// When the user clicks on a project
$('.project').on('click',function() {

  // Animate the project element
  $(this).animate({
    opacity:1
  },{duration:200,queue:false})

  // To access this specific project's child
  // elements (ie, title, picture, caption) you will
  // need to use .children
  $(this).children('.project-title').animate({
    opacity:1,
    top:'50px'
  },{duration:200,queue:false})
})

Jquery's animation functionality can be very useful for complex, multi-element animations, check here for more info


问:
Aliasing between C++ struct and std:vector element--why?
In C++, csi is a structure with integer fields:

```<code>struct CentScanInfo
{
    int runId;
...
};
</code>```

The following code processes a vector of csi structures:

```<code>// Create vector of csi structures
CentScanInfo csi; std::vector<CentScanInfo> csiv;
for(j = 0; j < n; j++)
{
    // ... code to store values into a csi structure
    csiv.push_back(csi);
}

// Sort the vector, then process entries
if(csiv.size() > 0)
{
    sort(csiv.begin(), csiv.end(), CsiSortCriterion);
    // BEFORE: csiv[n-2] = 3605406551, which is correct
    csi.pFI->runId = -99;
    // AFTER: csiv[n-2] = -99, which is wrong
    ...
}
</code>```

I do not expect changing the variable csi to affect any element of the vector csiv. Why does this happen, and how should the code be changed so it does not occur?

Visual Studio 2017 15.4.5; 64-bit Windows 7 Pro

答:
The aliasing is taking place via the pFI pointer. In the first loop, where the vector is populated, each csi has a unique pFI. Thus, when csi is used following the sort, csi.pFI is the same as the final element of the vector (before sorting).

The fix is to add another FI object, and set its pFI field, before changing runId:

```<code>CFileInfo sentinel; csi.pFI = &sentinel;
</code>```

This should have been obvious, but obviously it wasn't!

Body:
In C++, csi is a structure with integer fields:

struct CentScanInfo
{
    int runId;
...
};

The following code processes a vector of csi structures:

// Create vector of csi structures
CentScanInfo csi; std::vector<CentScanInfo> csiv;
for(j = 0; j < n; j++)
{
    // ... code to store values into a csi structure
    csiv.push_back(csi);
}

// Sort the vector, then process entries
if(csiv.size() > 0)
{
    sort(csiv.begin(), csiv.end(), CsiSortCriterion);
    // BEFORE: csiv[n-2] = 3605406551, which is correct
    csi.pFI->runId = -99;
    // AFTER: csiv[n-2] = -99, which is wrong
    ...
}

I do not expect changing the variable csi to affect any element of the vector csiv. Why does this happen, and how should the code be changed so it does not occur?

Visual Studio 2017 15.4.5; 64-bit Windows 7 Pro

Body:
The aliasing is taking place via the pFI pointer. In the first loop, where the vector is populated, each csi has a unique pFI. Thus, when csi is used following the sort, csi.pFI is the same as the final element of the vector (before sorting).

The fix is to add another FI object, and set its pFI field, before changing runId:

CFileInfo sentinel; csi.pFI = &sentinel;

This should have been obvious, but obviously it wasn't!


问:
All connections are active in Tomcat datasource pool with Spring
My Spring Boot application uses JDBCTemplate to send SQL queries to a PostgreSQL Database. It seems that each time a connection is got from the pool by the template, the connection is never released. The number of active connections (datasource.primary.active) is always increasing.

In the logs, after SQL Query using JDBCTemplate, I can see :

```<code>DEBUG o.s.j.d.DataSourceUtils - Returning JDBC Connection to DataSource
</code>```

But the count of idle connection stay with the same value and the count of active connections is not decreasing. When the maximum value is reached, it becomes impossible to retrieve a connection to execute a query.

So, I think there is no return of the connection to the datasource pool, any idea please ?

Here is the datasource configuration got with Actuator :

```<code>  "dataSource": {
        "prefix": "spring.datasource.tomcat",
        "properties": {
            "connectionProperties": null,
            "propagateInterruptState": false,
            "validator": null,
            "useDisposableConnectionFacade": true,
            "defaultCatalog": null,
            "validationInterval": 3000,
            "jmxEnabled": true,
            "ignoreExceptionOnPreLoad": false,
            "logAbandoned": false,
            "commitOnReturn": false,
            "password": "******",
            "maxIdle": 100,
            "testWhileIdle": false,
            "removeAbandoned": false,
            "poolProperties": {
                "dbProperties": {
                    "user": "postgres",
                    "password": "******"
                },
                "url": "jdbc:postgresql://localhost:5432/tvir",
                "driverClassName": "org.postgresql.Driver",
                "defaultAutoCommit": null,
                "defaultReadOnly": null,
                "defaultTransactionIsolation": -1,
                "defaultCatalog": null,
                "connectionProperties": null,
                "initialSize": 10,
                "maxActive": 100,
                "maxIdle": 100,
                "minIdle": 10,
                "maxWait": 30000,
                "validationQuery": "SELECT 1",
                "validationQueryTimeout": -1,
                "validatorClassName": null,
                "validator": null,
                "testOnBorrow": true,
                "testOnReturn": false,
                "testWhileIdle": false,
                "timeBetweenEvictionRunsMillis": 5000,
                "numTestsPerEvictionRun": 0,
                "minEvictableIdleTimeMillis": 60000,
                "accessToUnderlyingConnectionAllowed": true,
                "removeAbandoned": false,
                "removeAbandonedTimeout": 60,
                "logAbandoned": false,
                "name": "Tomcat Connection Pool[1-574817798]",
                "password": "******",
                "username": "postgres",
                "validationInterval": 3000,
                "jmxEnabled": true,
                "initSQL": null,
                "testOnConnect": false,
                "jdbcInterceptors": null,
                "fairQueue": true,
                "useEquals": true,
                "abandonWhenPercentageFull": 0,
                "maxAge": 0,
                "useLock": false,
                "suspectTimeout": 0,
                "dataSource": null,
                "dataSourceJNDI": null,
                "alternateUsernameAllowed": false,
                "commitOnReturn": false,
                "rollbackOnReturn": false,
                "useDisposableConnectionFacade": true,
                "logValidationErrors": false,
                "propagateInterruptState": false,
                "ignoreExceptionOnPreLoad": false,
                "useStatementFacade": true
            },
</code>```

And the code used to query the db :

```<code>JdbcTemplate jdbcTemplate = appCtx.getBean(JdbcTemplate.class);

ResultSet columns = jdbcTemplate.getDataSource().getConnection().getMetaData().getColumns(null, null, source.getTable().toLowerCase(), null);

String selectList = "";

while (columns.next())
{

    String colName = columns.getString("COLUMN_NAME");
    String colType = columns.getString("DATA_TYPE");

    if(!selectList.equals("")) {
        selectList += ", ";
    }

    if((""+java.sql.Types.INTEGER).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.DOUBLE).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.BIGINT).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.FLOAT).equalsIgnoreCase(colType) ) {
        selectList += "SUM(" + colName + ")";
    } else {
        selectList += "MAX(" + colName + ")";
    }

    selectList += " AS "+colName;
}

            String sql = "SELECT "+selectList+" FROM "+source.getTable()+" "+
                            "WHERE "+source.getDateColumn()+" >= ? "+
                            "AND "+source.getDateColumn()+" <= ? ";

List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, Date.valueOf(startDate), Date.valueOf(endDate));
</code>```

答:
Spring boot let you configure how you want your datasource to behave.
You will find a full list on the official doc.
check the following properties for your case : </p>

```<code>spring.datasource.maxActive
spring.datasource.maxIdle
</code>```

<p>Depending on what connection pool you are using you can also tune it using spring boot properties (everything is in the doc) . </p>

Body:
My Spring Boot application uses JDBCTemplate to send SQL queries to a PostgreSQL Database. It seems that each time a connection is got from the pool by the template, the connection is never released. The number of active connections (datasource.primary.active) is always increasing.

In the logs, after SQL Query using JDBCTemplate, I can see :

DEBUG o.s.j.d.DataSourceUtils - Returning JDBC Connection to DataSource

But the count of idle connection stay with the same value and the count of active connections is not decreasing. When the maximum value is reached, it becomes impossible to retrieve a connection to execute a query.

So, I think there is no return of the connection to the datasource pool, any idea please ?

Here is the datasource configuration got with Actuator :

  "dataSource": {
        "prefix": "spring.datasource.tomcat",
        "properties": {
            "connectionProperties": null,
            "propagateInterruptState": false,
            "validator": null,
            "useDisposableConnectionFacade": true,
            "defaultCatalog": null,
            "validationInterval": 3000,
            "jmxEnabled": true,
            "ignoreExceptionOnPreLoad": false,
            "logAbandoned": false,
            "commitOnReturn": false,
            "password": "******",
            "maxIdle": 100,
            "testWhileIdle": false,
            "removeAbandoned": false,
            "poolProperties": {
                "dbProperties": {
                    "user": "postgres",
                    "password": "******"
                },
                "url": "jdbc:postgresql://localhost:5432/tvir",
                "driverClassName": "org.postgresql.Driver",
                "defaultAutoCommit": null,
                "defaultReadOnly": null,
                "defaultTransactionIsolation": -1,
                "defaultCatalog": null,
                "connectionProperties": null,
                "initialSize": 10,
                "maxActive": 100,
                "maxIdle": 100,
                "minIdle": 10,
                "maxWait": 30000,
                "validationQuery": "SELECT 1",
                "validationQueryTimeout": -1,
                "validatorClassName": null,
                "validator": null,
                "testOnBorrow": true,
                "testOnReturn": false,
                "testWhileIdle": false,
                "timeBetweenEvictionRunsMillis": 5000,
                "numTestsPerEvictionRun": 0,
                "minEvictableIdleTimeMillis": 60000,
                "accessToUnderlyingConnectionAllowed": true,
                "removeAbandoned": false,
                "removeAbandonedTimeout": 60,
                "logAbandoned": false,
                "name": "Tomcat Connection Pool[1-574817798]",
                "password": "******",
                "username": "postgres",
                "validationInterval": 3000,
                "jmxEnabled": true,
                "initSQL": null,
                "testOnConnect": false,
                "jdbcInterceptors": null,
                "fairQueue": true,
                "useEquals": true,
                "abandonWhenPercentageFull": 0,
                "maxAge": 0,
                "useLock": false,
                "suspectTimeout": 0,
                "dataSource": null,
                "dataSourceJNDI": null,
                "alternateUsernameAllowed": false,
                "commitOnReturn": false,
                "rollbackOnReturn": false,
                "useDisposableConnectionFacade": true,
                "logValidationErrors": false,
                "propagateInterruptState": false,
                "ignoreExceptionOnPreLoad": false,
                "useStatementFacade": true
            },

And the code used to query the db :

JdbcTemplate jdbcTemplate = appCtx.getBean(JdbcTemplate.class);

ResultSet columns = jdbcTemplate.getDataSource().getConnection().getMetaData().getColumns(null, null, source.getTable().toLowerCase(), null);

String selectList = "";

while (columns.next())
{

    String colName = columns.getString("COLUMN_NAME");
    String colType = columns.getString("DATA_TYPE");

    if(!selectList.equals("")) {
        selectList += ", ";
    }

    if((""+java.sql.Types.INTEGER).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.DOUBLE).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.BIGINT).equalsIgnoreCase(colType) ||
            (""+java.sql.Types.FLOAT).equalsIgnoreCase(colType) ) {
        selectList += "SUM(" + colName + ")";
    } else {
        selectList += "MAX(" + colName + ")";
    }

    selectList += " AS "+colName;
}

            String sql = "SELECT "+selectList+" FROM "+source.getTable()+" "+
                            "WHERE "+source.getDateColumn()+" >= ? "+
                            "AND "+source.getDateColumn()+" <= ? ";

List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, Date.valueOf(startDate), Date.valueOf(endDate));

Body:
Spring boot let you configure how you want your datasource to behave.
You will find a full list on the official doc.
check the following properties for your case :

spring.datasource.maxActive
spring.datasource.maxIdle

Depending on what connection pool you are using you can also tune it using spring boot properties (everything is in the doc) .


问:
Jersey - resource variables null value despite non-null initialization
I have a resource in my Jersey REST api that has a private instance variable:

```<code>@Path("test")
public class TestResource implements ServletContextListener
{
    private String someString;

    @GET
    public void test()
    {
        System.out.println("someString " + someString);
    }

    @Override
    public void contextDestroyed(ServletContextEvent ctxt) {
        System.out.println("Destroying context");
    }

    @Override
    public void contextInitialized(ServletContextEvent ctxt) {
        System.out.println("TestResource initialized!");

        someString = "SET";
        System.out.println("someString has been set. someString: " + someString);
    }
}
</code>```

On server startup/restart the instance variable someString is initialized during contextInitialized() and is correctly printed out. However when I set a GET request to http://localhost:8080/myapp/api/test (i.e. invoke the test() method above) the variable someString is null.

How can I prevent that?

答:
From the JAX-RS specification:

By default a new resource class instance is created for each request to that resource.

So, any state you set on your resource class instance is meaningless, since the instance is never used again.  If you want to persist a value, place it in the ServletContext’s attributes:

```<code>// All classes in the web app share a ServletContext, so attribute names
// need to start with package names to prevent collisions.
private static final String SOME_ATTRIBUTE = TestResource.class.getName() + ".someAttribute";

@Override
public void contextInitialized(ServletContextEvent ctxt) {
    System.out.println("TestResource initialized!");

    String someString = "SET";
    System.out.println("someString has been set. someString: " + someString);

    ctxt.getServletContext().setAttribute(SOME_ATTRIBUTE, someString);
}

@GET
public void test(@Context ServletContext context) {
    System.out.println("someString " + context.getAttribute(SOME_ATTRIBUTE));
}
</code>```

Storing values in static fields will require you to implement thread safety and will not work in a distributed production environment.

Body:
I have a resource in my Jersey REST api that has a private instance variable:

@Path("test")
public class TestResource implements ServletContextListener
{
    private String someString;

    @GET
    public void test()
    {
        System.out.println("someString " + someString);
    }

    @Override
    public void contextDestroyed(ServletContextEvent ctxt) {
        System.out.println("Destroying context");
    }

    @Override
    public void contextInitialized(ServletContextEvent ctxt) {
        System.out.println("TestResource initialized!");

        someString = "SET";
        System.out.println("someString has been set. someString: " + someString);
    }
}

On server startup/restart the instance variable someString is initialized during contextInitialized() and is correctly printed out. However when I set a GET request to http://localhost:8080/myapp/api/test (i.e. invoke the test() method above) the variable someString is null.

How can I prevent that?

Body:
From the JAX-RS specification:

By default a new resource class instance is created for each request to that resource.

So, any state you set on your resource class instance is meaningless, since the instance is never used again.  If you want to persist a value, place it in the ServletContext’s attributes:

// All classes in the web app share a ServletContext, so attribute names
// need to start with package names to prevent collisions.
private static final String SOME_ATTRIBUTE = TestResource.class.getName() + ".someAttribute";

@Override
public void contextInitialized(ServletContextEvent ctxt) {
    System.out.println("TestResource initialized!");

    String someString = "SET";
    System.out.println("someString has been set. someString: " + someString);

    ctxt.getServletContext().setAttribute(SOME_ATTRIBUTE, someString);
}

@GET
public void test(@Context ServletContext context) {
    System.out.println("someString " + context.getAttribute(SOME_ATTRIBUTE));
}

Storing values in static fields will require you to implement thread safety and will not work in a distributed production environment.


问:
Pandas: Coloumn with mixed datatype; how to find the exceptions
I have a large dataframe, and when reading it, it gives me this message:
DtypeWarning: Columns (0,8) have mixed types. Specify dtype upon import or set low_memory=False.

It is supposed to be a column of floats, but I suspect a few strings snuck in there. I would like to identify them, and possibly remove them.

I tried
df.apply(lambda row: isinstance(row.AnnoyingColumn, (int, float)), 1)

But that gave me an out of memory error.

I assume there must be a better way.

答:
This will give you True if float:

```<code>df.some_column.apply(lambda x: isinstance(x, float))
</code>```

This will give you True if int or string:

```<code>df.some_column.apply(lambda x: isinstance(x, (int,str)))
</code>```

So, to remove strings:

```<code>mask = df.some_column.apply(lambda x: isinstance(x, str))
df = df[~mask]
</code>```

Example that removes floats and strings:

```<code>$ df = pd.DataFrame({'a': [1,2.0,'hi',4]})
$ df
    a
0   1
1   2
2   hi
3   4

$ mask = df.a.apply(lambda x: isinstance(x, (float,str)))
$ mask
0    False
1    False
2     True
3    False
Name: a, dtype: bool

$ df = df[~mask]
$ df
    a
0   1
3   4
</code>```

Body:
This will give you True if float:

df.some_column.apply(lambda x: isinstance(x, float))

This will give you True if int or string:

df.some_column.apply(lambda x: isinstance(x, (int,str)))

So, to remove strings:

mask = df.some_column.apply(lambda x: isinstance(x, str))
df = df[~mask]

Example that removes floats and strings:

$ df = pd.DataFrame({'a': [1,2.0,'hi',4]})
$ df
    a
0   1
1   2
2   hi
3   4

$ mask = df.a.apply(lambda x: isinstance(x, (float,str)))
$ mask
0    False
1    False
2     True
3    False
Name: a, dtype: bool

$ df = df[~mask]
$ df
    a
0   1
3   4


问:
ES6 avoid that/self
I am trying to avoid "const that = this", "const self = this" etc. using es6.
However I am struggling with some constructs in combination of vue js and highcharts where you got something like this:

```<code>data () {
  let that = this
  return {
    highchartsConfiguration: {
      ... big configuration ...
      formatter: function () {
        return this.point.y + that.unit
      }
    }
  }
}
</code>```

I'd like to have the that defined just in formatter object if possible. Using arrow syntax () => {} would me allow to use this from data scope, but i would lose the power of giving the function an extra scope.

I do not want to modify the used libraries.

答: If you need the this that the formatter method is called on, there is no way around an extra variable (that, self, whatever).

Title: ES6 avoid that/self

Body:
I am trying to avoid "const that = this", "const self = this" etc. using es6.
However I am struggling with some constructs in combination of vue js and highcharts where you got something like this:

data () {
  let that = this
  return {
    highchartsConfiguration: {
      ... big configuration ...
      formatter: function () {
        return this.point.y + that.unit
      }
    }
  }
}

I'd like to have the that defined just in formatter object if possible. Using arrow syntax () => {} would me allow to use this from data scope, but i would lose the power of giving the function an extra scope.

I do not want to modify the used libraries.


问:
Making a local scope inside a for loop, into a global scope
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach? </p>

```<code> var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'
</code>```

答:
var in javascript have function scope. So even if you define it inside for loop they will be available outside the loop. If you do console.log before the loop, the value will be undefined and if you do it after the loop, the value will be last value available inside the loop. To make things block scoped ( local scope inside the loop ), use let & const. They are available in ES6 and with all the major browsers support them.

Hope this will help

Happy Learning

Vatsal

Body:
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach?

 var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'


问:
Hide Nav Bar on Main Page - Xamarin Forms
I want to hide Nav bar on the main-start page of my app. but want to make it display with a title and back button on the second page. This is something I did, but it appears on the main page too.

In App.xaml.cs, I used this:

```<code> MainPage = new NavigationPage(new MainPage());
</code>```

In corresponding login page, I created this:

```<code>private async void LoginPage_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new LoginPage());
    }
</code>```

When the user will click it'll take to the second page(login page).

Also, how can I change the color of the nav bar?

答:
In App.cs use

```<code>MainPage = new YourProjectNamespace.MainPage();
</code>```

This will hide your navigation bar on your first page

Body:
I want to hide Nav bar on the main-start page of my app. but want to make it display with a title and back button on the second page. This is something I did, but it appears on the main page too.

In App.xaml.cs, I used this:

 MainPage = new NavigationPage(new MainPage());

In corresponding login page, I created this:

private async void LoginPage_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new LoginPage());
    }

When the user will click it'll take to the second page(login page).

Also, how can I change the color of the nav bar?

Body:
In App.cs use

MainPage = new YourProjectNamespace.MainPage();

This will hide your navigation bar on your first page


问:
Angular bootstrap returning setIsOpen is not a function
We've got the following HTML:

```<code><div class="btn-group search-dropdown" dropdown is-open="gender.isopen">
  <button type="button" class="btn btn-default dropdown-toggle" dropdown-toggle>
    {{sex_temp=='F'?'Female':'Male'}} <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li ng-class="{'dropdown-selected':sex_temp=='F'}">
                    <a ng-click="sex_temp='F'">Female</a>
    </li>
    <li ng-class="{'dropdown-selected':sex_temp=='M'}">
                    <a ng-click="sex_temp='M'">Male</a>
    </li>
  </ul>
</div>
</code>```

In the console, we're getting the following error:

```<code>Error: setIsOpen is not a function @http://127.0.0.1/lib/bootstrap-ui/ui-bootstrap-tpls-0.12.1.js:1734:5
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://127.0.0.1/lib/AngularJS/angular.js:12406:23
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://127.0.0.1/lib/AngularJS/angular.js:12679:13
done@http://127.0.0.1/lib/AngularJS/angular.js:8279:34
completeRequest@http://127.0.0.1/lib/AngularJS/angular.js:8484:7
createHttpBackend/</xhr.onreadystatechange@http://127.0.0.1/lib/AngularJS/angular.js:8423:1 @debugger eval code:1:1
consoleLog/<@http://127.0.0.1/lib/AngularJS/angular.js:10062:18
$ExceptionHandlerProvider/this.$get</<@http://127.0.0.1/lib/AngularJS/angular.js:7363:7
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://127.0.0.1/lib/AngularJS/angular.js:12426:19
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://127.0.0.1/lib/AngularJS/angular.js:12679:13
done@http://127.0.0.1/lib/AngularJS/angular.js:8279:34
completeRequest@http://127.0.0.1/lib/AngularJS/angular.js:8484:7
createHttpBackend/</xhr.onreadystatechange@http://127.0.0.1/lib/AngularJS/angular.js:8423:1
</code>```

We're using ui-bootstrap-tpls-0.12.1.js

I have tried adding $scope.gender={isopen:false} but that didn't help.

Any idea on what might be the problem here?  The dropdown is working perfectly. I just want to get rid of these errors in the console.

答: This is 2 years later, but updating your ui-bootstrap would fix this problem if you're using an older version (example 0.13 instead of 2.5)</p>

Body:
We've got the following HTML:

  <button type="button" class="btn btn-default dropdown-toggle" dropdown-toggle>
    {{sex_temp=='F'?'Female':'Male'}}
  </button>

                    Female

                    Male

In the console, we're getting the following error:

Error: setIsOpen is not a function @http://127.0.0.1/lib/bootstrap-ui/ui-bootstrap-tpls-0.12.1.js:1734:5
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://127.0.0.1/lib/AngularJS/angular.js:12406:23
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://127.0.0.1/lib/AngularJS/angular.js:12679:13
done@http://127.0.0.1/lib/AngularJS/angular.js:8279:34
completeRequest@http://127.0.0.1/lib/AngularJS/angular.js:8484:7
createHttpBackend/</xhr.onreadystatechange@http://127.0.0.1/lib/AngularJS/angular.js:8423:1 @debugger eval code:1:1
consoleLog/<@http://127.0.0.1/lib/AngularJS/angular.js:10062:18
$ExceptionHandlerProvider/this.$get</<@http://127.0.0.1/lib/AngularJS/angular.js:7363:7
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://127.0.0.1/lib/AngularJS/angular.js:12426:19
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://127.0.0.1/lib/AngularJS/angular.js:12679:13
done@http://127.0.0.1/lib/AngularJS/angular.js:8279:34
completeRequest@http://127.0.0.1/lib/AngularJS/angular.js:8484:7
createHttpBackend/</xhr.onreadystatechange@http://127.0.0.1/lib/AngularJS/angular.js:8423:1

We're using ui-bootstrap-tpls-0.12.1.js

I have tried adding $scope.gender={isopen:false} but that didn't help.

Any idea on what might be the problem here?  The dropdown is working perfectly. I just want to get rid of these errors in the console.


问:
Declare array of lambdas in Java
I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:

```<code>private interface I0 {
    int interface0(int a, int b);
}

private interface I1 {
    int interface1(double d);
}
</code>```

Now, how can I declare a list which can contain both I0 and I1?

```<code>List<Object> test = Arrays.asList(
        (int a, int b) -> a + b,
        (double d) -> d * 2
);
</code>```

Obviously Object does not work.

答:
From what I gather, you're trying to do something like this:

```<code>public static void main(String... args){
    List<Object> lambdas = Arrays.asList(
            (IntBinaryOperator) (int a, int b) -> a + b,
            (DoubleToIntFunction) (double d) -> (int)(d * 2)
    );
    for(int i=0;i<args.length;i++){
        // Apply lambdas.get(i) to args[i]
    }
}
</code>```

That comment is a pretty big deal, though; how would you implement it?

You could check the type during each round:

```<code>    for(int i=0;i<args.length;i++){
        if(lambdas.get(i) instanceof IntBinaryOperator){
            processedArgs[i] =
                    ((IntBinaryOperator) lambdas.get(i)).applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[i]));
        }else{
            // All your other cases (may take a while)
        }
    }
</code>```

Validating each possible type is a huge pain, and if it's position-dependent, it's only going to run once anyway, so it's overkill.

My recommendation depends on if this is going to be static (your code runs only on one specific set of arguments ever) or dynamic (it needs to run on all kinds of arguments).  For static code, I'd just apply the lambdas without a loop:

```<code>public static void main(String... args){
    processedArgs = new int[args.length];
    IntBinaryOperator op1 = (int a, int b) -> a + b;
    DoubleToIntFunction op2 =  (double d) -> (int)(d * 2);

    processedArgs[0] = op1.applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[0]));
    processedArgs[1] = op2.applyAsInt(Double.parseDouble(args[1]));
}
</code>```

For a dynamic solution, I'd recommend switching to a single functional interface.  I would go with the maximum requirement and fill in dummy values where not needed:

```<code>public static void main(String... args){
    processedArgs = new int[args.length];
    List<DoubleBinaryOperator> ops = Arrays.asList(
            (a, b) -> a + b,
            (d, ignore) -> (d * 2)
    );
    for(int i=0;i<args.length;i++){
        processedArgs[i] = (int)ops.get(i).applyAsDouble(Double.parseDouble(args[i]), MAGIC_NUMBER);
    }
}
</code>```

Or, preferably, if you can simplify your lambdas:

```<code>public static void main(String... args){
    processedArgs = new int[args.length];
    List<DoubleToIntFunction> ops = Arrays.asList(
            (d) -> (int)(d + MAGIC_NUMBER),
            (d) -> (int)(d * 2)
    );
    for(int i=0;i<args.length;i++){
        processedArgs[i] = ops.get(i).applyAsInt(Double.parseDouble(args[i]));
    }
}
</code>```

I feel like your solution ultimately is less complicated than any of these.  Just trying to help point you in the right direction.

Title: Declare array of lambdas in Java

Body:
I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:

private interface I0 {
    int interface0(int a, int b);
}

private interface I1 {
    int interface1(double d);
}

Now, how can I declare a list which can contain both I0 and I1?

List<Object> test = Arrays.asList(
        (int a, int b) -> a + b,
        (double d) -> d * 2
);

Obviously Object does not work.

Body:
From what I gather, you're trying to do something like this:

public static void main(String... args){
    List<Object> lambdas = Arrays.asList(
            (IntBinaryOperator) (int a, int b) -> a + b,
            (DoubleToIntFunction) (double d) -> (int)(d * 2)
    );
    for(int i=0;i<args.length;i++){
        // Apply lambdas.get(i) to args[i]
    }
}

That comment is a pretty big deal, though; how would you implement it?

You could check the type during each round:

    for(int i=0;i<args.length;i++){
        if(lambdas.get(i) instanceof IntBinaryOperator){
            processedArgs[i] =
                    ((IntBinaryOperator) lambdas.get(i)).applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[i]));
        }else{
            // All your other cases (may take a while)
        }
    }

Validating each possible type is a huge pain, and if it's position-dependent, it's only going to run once anyway, so it's overkill.

My recommendation depends on if this is going to be static (your code runs only on one specific set of arguments ever) or dynamic (it needs to run on all kinds of arguments).  For static code, I'd just apply the lambdas without a loop:

public static void main(String... args){
    processedArgs = new int[args.length];
    IntBinaryOperator op1 = (int a, int b) -> a + b;
    DoubleToIntFunction op2 =  (double d) -> (int)(d * 2);

    processedArgs[0] = op1.applyAsInt(MAGIC_NUMBER, Integer.parseInt(args[0]));
    processedArgs[1] = op2.applyAsInt(Double.parseDouble(args[1]));
}

For a dynamic solution, I'd recommend switching to a single functional interface.  I would go with the maximum requirement and fill in dummy values where not needed:

public static void main(String... args){
    processedArgs = new int[args.length];
    List<DoubleBinaryOperator> ops = Arrays.asList(
            (a, b) -> a + b,
            (d, ignore) -> (d * 2)
    );
    for(int i=0;i<args.length;i++){
        processedArgs[i] = (int)ops.get(i).applyAsDouble(Double.parseDouble(args[i]), MAGIC_NUMBER);
    }
}

Or, preferably, if you can simplify your lambdas:

public static void main(String... args){
    processedArgs = new int[args.length];
    List<DoubleToIntFunction> ops = Arrays.asList(
            (d) -> (int)(d + MAGIC_NUMBER),
            (d) -> (int)(d * 2)
    );
    for(int i=0;i<args.length;i++){
        processedArgs[i] = ops.get(i).applyAsInt(Double.parseDouble(args[i]));
    }
}

I feel like your solution ultimately is less complicated than any of these.  Just trying to help point you in the right direction.


问:
Php price asc function is not working
I'm trying to do price ascending or descending filter in php, but it is not working. Could some one help to fix it? Thanks </p>

```<code><select name='sort'>
<option value='ASC'> Price Low to High </option>
<option value='DESC'> Price High to Low </option>

</select>
<?php
$query = 'SELECT prd_price FROM products ORDER BY '.$_REQUEST['sort'];
$run_query = mysqli_query($con,$query);

$row = mysqli_fetch_array($run_query);
?>
</code>```

答:
You can't do it like this. Cause your select is not processed.

When you read the php docs about $_REQUEST you see that it only processes the values of $_POST, $_GET and $_COOKIE.

If you would like to make this working, you could do something like this:

```<code><form method="post">
    <select name="sort">
        <option value="asc">Price Low to High</option>
        <option value="desc">Prive High to Low</option>
    </select>
    <input type="submit" value="Sort">
</form>
<?php
// check if the server recieved a post:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (isset($_POST['sort'])) {
        if ($_POST['sort'] == "asc") {
            $query = "SELECT prd_price FROM products ORDER BY prd_price ASC";
        } else {
            $query = "SELECT prd_price FROM products ORDER BY prd_price DESC";
        }
    }
    // execute query here.
}
?>
</code>```

And try to avoid using $_REQUEST

Title: Php price asc function is not working

Body:
I'm trying to do price ascending or descending filter in php, but it is not working. Could some one help to fix it? Thanks

<select name='sort'>
<option value='ASC'> Price Low to High </option>
<option value='DESC'> Price High to Low </option>

</select>
<?php
$query = 'SELECT prd_price FROM products ORDER BY '.$_REQUEST['sort'];
$run_query = mysqli_query($con,$query);

$row = mysqli_fetch_array($run_query);
?>

Body:
You can't do it like this. Cause your select is not processed.

When you read the php docs about $_REQUEST you see that it only processes the values of $_POST, $_GET and $_COOKIE.

If you would like to make this working, you could do something like this:

<form method="post">
    <select name="sort">
        <option value="asc">Price Low to High</option>
        <option value="desc">Prive High to Low</option>
    </select>
    <input type="submit" value="Sort">
</form>
<?php
// check if the server recieved a post:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (isset($_POST['sort'])) {
        if ($_POST['sort'] == "asc") {
            $query = "SELECT prd_price FROM products ORDER BY prd_price ASC";
        } else {
            $query = "SELECT prd_price FROM products ORDER BY prd_price DESC";
        }
    }
    // execute query here.
}
?>

And try to avoid using $_REQUEST


问:
gradle project sync failed even after upgrading gradle plugin
Gradle project sync failed and did not get answers from other related questions.  Here are the details of my situation.

Initial sync attempt yielded the following error message:

```<code>Unsupported method: BaseConfig.getApplicationIdSuffix().
The version of Gradle you connect to does not support that method.
To resolve the problem you can change/upgrade the target version of Gradle you connect to.
Alternatively, you can ignore this exception and read other information from the model.
</code>```

I have Android Studio 3.0.  The build.gradle file includes the following dependency:

```<code>classpath 'com.android.tools.build:gradle-experimental:0.2.1'

  The gradle-wrapper.properties file includes the following distribution URL:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip
</code>```

According to https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#update_gradle I need to make some changes.

First, update the Gradle version for Android Studio 3.0 in gradle-wrapper.properties:

distributionUrl=\
  https://services.gradle.org/distributions/gradle-4.1-all.zip
(I believe the backslash right after the equal sign is an error and did not make that change.)

Second, add the following buildscript repository to build.gradle:

google()

Third, change the build.gradle dependency:

classpath 'com.android.tools.build:gradle:3.0.1'

The second and third changes apply the latest version of the Android plug-in.

When I try to sync after these changes it fails again with the following new error:

Plugin with id 'com.android.model.application' not found.

The error refers to the first line of build.gradle:

apply plugin: 'com.android.model.application'

What is happening and why?  I recently added NDK to Android Studio.  The project I'm trying to sync includes C code.  I'm not completely certain I added NDK correctly.  I wonder if that could be part of the problem.

答:
First, the gradle-wrapper.properties is incorrect. You must include \ in it. It should be something like this:

```<code>#Sat Jun 17 17:47:18 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

Then, add the experimental classpath to project build.gradle. Something like this:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle-experimental:0.7.0-alpha4"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

Check the Experimental Plugin User Guide for details.

Body:
Gradle project sync failed and did not get answers from other related questions.  Here are the details of my situation.

Initial sync attempt yielded the following error message:

Unsupported method: BaseConfig.getApplicationIdSuffix().
The version of Gradle you connect to does not support that method.
To resolve the problem you can change/upgrade the target version of Gradle you connect to.
Alternatively, you can ignore this exception and read other information from the model.

I have Android Studio 3.0.  The build.gradle file includes the following dependency:

classpath 'com.android.tools.build:gradle-experimental:0.2.1'

  The gradle-wrapper.properties file includes the following distribution URL:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip

According to https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#update_gradle I need to make some changes.

First, update the Gradle version for Android Studio 3.0 in gradle-wrapper.properties:

distributionUrl=\
  https://services.gradle.org/distributions/gradle-4.1-all.zip
(I believe the backslash right after the equal sign is an error and did not make that change.)

Second, add the following buildscript repository to build.gradle:

google()

Third, change the build.gradle dependency:

classpath 'com.android.tools.build:gradle:3.0.1'

The second and third changes apply the latest version of the Android plug-in.

When I try to sync after these changes it fails again with the following new error:

Plugin with id 'com.android.model.application' not found.

The error refers to the first line of build.gradle:

apply plugin: 'com.android.model.application'

What is happening and why?  I recently added NDK to Android Studio.  The project I'm trying to sync includes C code.  I'm not completely certain I added NDK correctly.  I wonder if that could be part of the problem.

Body:
First, the gradle-wrapper.properties is incorrect. You must include \ in it. It should be something like this:

#Sat Jun 17 17:47:18 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Then, add the experimental classpath to project build.gradle. Something like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle-experimental:0.7.0-alpha4"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Check the Experimental Plugin User Guide for details.


问:
How to get row data using angular material?
I have angular4 with materialize table Api so I am trying to get row data when user click on the row but its not passing data, How can i pass data to component from view any help will be appreciated ?

app.component.html

```<code><div class="table-container">
<mat-table>
       <ng-container matColumnDef="eventType">
            <mat-header-cell *matHeaderCellDef> Event Type </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.eventType}} </mat-cell>
          </ng-container>
          <!--<button (click)="newMessage()" class="button">New Message</button>-->
          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="highlight(row._id,$event)"></mat-row>
        </mat-table>
      </div>
</code>```

app.component.ts

```<code>highlight(id,event){
        console.log('Event',event);
    }
</code>```

答:
Change to following in your template app.component.html

```<code><mat-row *matRowDef="let row; columns: displayedColumns;" (click)="highlight(row,$event)"></mat-row>
</code>```

and you should write your click handler in your component app.component.ts

```<code>highlight(row,evt) :void{
   //console.log(row,evt);
}
</code>```

Remove ._id from (click)="highlight(row._id,$event)" from your code.refer this

Body:
I have angular4 with materialize table Api so I am trying to get row data when user click on the row but its not passing data, How can i pass data to component from view any help will be appreciated ?

app.component.html

<mat-table>
       <ng-container matColumnDef="eventType">
            <mat-header-cell *matHeaderCellDef> Event Type </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.eventType}} </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="highlight(row._id,$event)"></mat-row>
        </mat-table>

app.component.ts

highlight(id,event){
        console.log('Event',event);
    }

Body:
Change to following in your template app.component.html

<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="highlight(row,$event)"></mat-row>

and you should write your click handler in your component app.component.ts

highlight(row,evt) :void{
   //console.log(row,evt);
}

Remove ._id from (click)="highlight(row._id,$event)" from your code.refer this


问:
Identify my dotnet version
How can I check from a c# application itself, what version of dotnet being used by application?</p>

答:
In your Visual Studio,
go to Tools->Nutget Package Management->Package Manager Console
Type in dotnet --version
And here you go!

Title: Identify my dotnet version


问:
Rails static assets not caching with CloudFlare
I have a Rails 4.2.10 site on Heroku with CloudFlare activated. However, CloudFlare keeps reporting a MISS on my static assets. CloudFlare has been no help. Any ideas?

Website: https://www.eventingvolunteers.com/

```<code>Request URL:https://www.eventingvolunteers.com/assets/application-c5697db660693224e57f66260130bdeb07762900fb1b56009477833c84c6c589.js
Request Method:GET
Status Code:200  (from memory cache)
Remote Address:104.27.157.140:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
cache-control:public, max-age=31536000
cf-cache-status:MISS
cf-ray:3c3d502a79045735-IAD
content-encoding:br
content-type:application/javascript
date:Sun, 26 Nov 2017 13:49:48 GMT
expires:Mon, 26 Nov 2018 13:49:48 GMT
last-modified:Sun, 26 Nov 2017 13:47:31 GMT
server:cloudflare-nginx
status:200
vary:Accept-Encoding
via:1.1 vegur
Request Headers
Provisional headers are shown
</code>```

答:
This js file was served from your browser cache, hence CF cache status is MISS

Disable cache in browser an reload, cf-cache-status will be HIT

Body:
I have a Rails 4.2.10 site on Heroku with CloudFlare activated. However, CloudFlare keeps reporting a MISS on my static assets. CloudFlare has been no help. Any ideas?

Website: https://www.eventingvolunteers.com/

Request URL:https://www.eventingvolunteers.com/assets/application-c5697db660693224e57f66260130bdeb07762900fb1b56009477833c84c6c589.js
Request Method:GET
Status Code:200  (from memory cache)
Remote Address:104.27.157.140:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
cache-control:public, max-age=31536000
cf-cache-status:MISS
cf-ray:3c3d502a79045735-IAD
content-encoding:br
content-type:application/javascript
date:Sun, 26 Nov 2017 13:49:48 GMT
expires:Mon, 26 Nov 2018 13:49:48 GMT
last-modified:Sun, 26 Nov 2017 13:47:31 GMT
server:cloudflare-nginx
status:200
vary:Accept-Encoding
via:1.1 vegur
Request Headers
Provisional headers are shown


问:
VBA Compare times correctly
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

```<code>if dataArr(v1) = rowArr(v2) Then
</code>```

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

```<code>dataArr(v1) - rowArr(v2)
</code>```

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

```<code>CStr(dataArr(v1)) = CStr(rowArr(v2))
</code>```

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!

答: Sometimes floating point inaccuracies creep in.  If you want to compare then take the Absolute Value (ABS) of the subtraction and see if it is below a tolerance level, say, 1E-7 (a millionth).</p>

Title: VBA Compare times correctly

Body:
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

if dataArr(v1) = rowArr(v2) Then

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

dataArr(v1) - rowArr(v2)

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

CStr(dataArr(v1)) = CStr(rowArr(v2))

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!


问:
Python how convert single quotes to double quotes to format as json string
I have a file where on each line I have text like this (representing cast of a film):

```<code>[{'cast_id': 23, 'character': "Roger 'Verbal' Kint", 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast_id': 27, 'character': 'Edie's Finneran', 'credit_id': '52fe4260c3a36847f8019b07', 'gender': 1, 'id': 2179, 'name': 'Suzy Amis', 'order': 6, 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]
</code>```

I need to convert it in a valid json string, thus converting only the necessary single quotes to double quotes (e.g. the single quotes around word Verbal must not be converted, eventual apostrophes in the text also should not be converted).

I am using python 3.x. I need to find a regular expression which will convert only the right single quotes to double quotes, thus the whole text resulting in a valid json string. Any idea?

答:
Here is the code to get desired output

```<code>import ast
def getJson(filepath):
    fr = open(filepath, 'r')
    lines = []
    for line in fr.readlines():
        line_split = line.split(",")
        set_line_split = []
        for i in line_split:
            i_split = i.split(":")
            i_set_split = []
            for split_i in i_split:
                set_split_i = ""
                rev = ""
                i = 0
                for ch in split_i:
                    if ch in ['\"','\'']:
                        set_split_i += ch
                        i += 1
                        break
                    else:
                        set_split_i += ch
                        i += 1
                i_rev = (split_i[i:])[::-1]
                state = False
                for ch in i_rev:
                    if ch in ['\"','\''] and state == False:
                        rev += ch
                        state = True
                    elif ch in ['\"','\''] and state == True:
                        rev += ch+"\\"
                    else:
                        rev += ch
                i_rev = rev[::-1]
                set_split_i += i_rev
                i_set_split.append(set_split_i)
            set_line_split.append(":".join(i_set_split))
        line_modified = ",".join(set_line_split)
        lines.append(ast.literal_eval(str(line_modified)))
    return lines
lines = getJson('test.txt')
for i in lines:
    print(i)
</code>```

Body:
I have a file where on each line I have text like this (representing cast of a film):

[{'cast_id': 23, 'character': "Roger 'Verbal' Kint", 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast_id': 27, 'character': 'Edie's Finneran', 'credit_id': '52fe4260c3a36847f8019b07', 'gender': 1, 'id': 2179, 'name': 'Suzy Amis', 'order': 6, 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]

I need to convert it in a valid json string, thus converting only the necessary single quotes to double quotes (e.g. the single quotes around word Verbal must not be converted, eventual apostrophes in the text also should not be converted).

I am using python 3.x. I need to find a regular expression which will convert only the right single quotes to double quotes, thus the whole text resulting in a valid json string. Any idea?

Body:
Here is the code to get desired output

import ast
def getJson(filepath):
    fr = open(filepath, 'r')
    lines = []
    for line in fr.readlines():
        line_split = line.split(",")
        set_line_split = []
        for i in line_split:
            i_split = i.split(":")
            i_set_split = []
            for split_i in i_split:
                set_split_i = ""
                rev = ""
                i = 0
                for ch in split_i:
                    if ch in ['\"','\'']:
                        set_split_i += ch
                        i += 1
                        break
                    else:
                        set_split_i += ch
                        i += 1
                i_rev = (split_i[i:])[::-1]
                state = False
                for ch in i_rev:
                    if ch in ['\"','\''] and state == False:
                        rev += ch
                        state = True
                    elif ch in ['\"','\''] and state == True:
                        rev += ch+"\\"
                    else:
                        rev += ch
                i_rev = rev[::-1]
                set_split_i += i_rev
                i_set_split.append(set_split_i)
            set_line_split.append(":".join(i_set_split))
        line_modified = ",".join(set_line_split)
        lines.append(ast.literal_eval(str(line_modified)))
    return lines
lines = getJson('test.txt')
for i in lines:
    print(i)