问:
Python Optimized Comparison Between List of Dict
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

```<code>    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))
</code>```

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]

答:
(This answer deals with simple optimisations and Python style; it works with the existing algorithm, teaching some points of optimisation, rather than replacing it with a more efficient one.)

Here are some points to start with to make the code easier to read and understand:

Iterate over sList, not over range(len(sList)). for i in range(len(sList)) becomes for i in sList and sList[i] becomes i.

No need for that tmpRad; put it inline.

Instead of if a: if b: if c: use if a and b and c.

Now we're at this:

```<code>filteredList = []
for i in sList:
    minx = i['x'] - i['radius']
    maxx = i['x'] + i['radius']
    miny = i['y'] - i['radius']
    maxy = i['y'] + i['radius']
    minz = i['z'] - i['radius']
    maxz = i['z'] + i['radius']

    for j in nList:
        if minx <= j['x'] <= maxx and miny <= j['y'] <= maxy and minz <= j['z'] <= maxz and findRadius(i,j) <= i['radius']:
            filteredList.append(int(j['num']))
</code>```

(PEP 8 would recommend splitting that long line to lines of no more than 80 characters; PEP 8 would also recommend filtered_list and s_list and n_list rather than filteredList, sList and nList.)

I've put the findRadius(i, j) <= i['radius'] first for style and because it looks like it might be more likely to evaluate to false, speeding up calculations. Then I've also inlined the minx etc. variables:

```<code>filteredList = []
for i in sList:
    for j in nList:
        if findRadius(i, j) <= i['radius'] \
        and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] \
        and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius'] \
        and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']:
            filteredList.append(int(j['num']))
</code>```

One thing to think about is that i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] could be simplified; try things like subtracting i['x'] from all three parts.

You can shorten this even more with a list comprehension.

```<code>filteredList = [int(j['num']) for j in nList for i in sList
        if findRadius(i, j) <= i['radius']
        and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius']
        and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius']
        and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']]
</code>```

And finally, named tuples (this has the side-effect of making them immutable, too, which is probably desired? Also note it's Python 2.6 only, read the page for how you could do it with older versions of Python):

```<code>from collections import namedtuple

node = namedtuple('node', 'x y z num')
sphere = namedtuple('sphere', 'x y z radius')

nList = [
        node(x=0.0, y=0.0, z=0.0, num=1.0),
        node(x=1.0, y=0.0, z=0.0, num=2.0),
        node(x=2.0, y=0.0, z=0.0, num=3.0),
        node(x=3.0, y=0.0, z=0.0, num=4.0),
        node(x=4.0, y=0.0, z=0.0, num=5.0),
        node(x=5.0, y=0.0, z=0.0, num=6.0),
        node(x=6.0, y=0.0, z=0.0, num=7.0),
        node(x=7.0, y=0.0, z=0.0, num=8.0),
        node(x=8.0, y=0.0, z=0.0, num=9.0),
        node(x=9.0, y=0.0, z=0.0, num=10.0)]

sList = [
        sphere(x=25.0, y=18.0, z=26.0, radius=0.0056470000000000001),
        sphere(x=23.0, y=29.0, z=45.0, radius=0.0066280000000000002),
        sphere(x=29.0, y=46.0, z=13.0, radius=0.014350999999999999),
        sphere(x=20.0, y=0.0, z=25.0, radius=0.014866000000000001),
        sphere(x=31.0, y=27.0, z=18.0, radius=0.018311999999999998),
        sphere(x=36.0, y=10.0, z=46.0, radius=0.024702000000000002),
        sphere(x=13.0, y=27.0, z=48.0, radius=0.027300999999999999),
        sphere(x=1.0, y=14.0, z=13.0, radius=0.033889000000000002),
        sphere(x=20.0, y=31.0, z=11.0, radius=0.034118999999999997),
        sphere(x=28.0, y=23.0, z=8.0, radius=0.036683)]
</code>```

Then, instead of sphere['radius'] you can do sphere.radius. This makes the code neater:

```<code>filteredList = [int(j.num) for j in nList for i in sList
        if findRadius(i, j) <= i.radius
        and i.x - i.radius <= j.x <= i.x + i.radius
        and i.y - i.radius <= j.y <= i.y + i.radius
        and i.z - i.radius <= j.z <= i.z + i.radius]
</code>```

Or, without the list comprehension,

```<code>filteredList = []
for i in sList:
    for j in nList:
        if findRadius(i, j) <= i.radius \
        and i.x - i.radius <= j.x <= i.x + i.radius \
        and i.y - i.radius <= j.y <= i.y + i.radius \
        and i.z - i.radius <= j.z <= i.z + i.radius:
            filteredList.append(int(j.num))
</code>```

Finally, choose nicer names; [style changed slightly as per comments, putting findRadius at the end as it's more likely to be computationally expensive - you're the best judge of that, though]

```<code>filteredList = [int(n.num) for n in nodes for s in spheres
        if s.x - s.radius <= n.x <= s.x + s.radius and
            s.y - s.radius <= n.y <= s.y + s.radius and
            s.z - s.radius <= n.z <= s.z + s.radius and
            findRadius(s, n) <= s.radius]
</code>```

Or,

```<code>filteredList = []
for s in spheres:
    for n in nodes:
        if (s.x - s.radius <= n.x <= s.x + s.radius and
            s.y - s.radius <= n.y <= s.y + s.radius and
            s.z - s.radius <= n.z <= s.z + s.radius and
            findRadius(s, n) <= s.radius):
            filteredList.append(int(n.num))
</code>```

(You could put srad = s.radius in the outer loop for a probable slight performance gain if desired.)

Body:
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]

Body:
(This answer deals with simple optimisations and Python style; it works with the existing algorithm, teaching some points of optimisation, rather than replacing it with a more efficient one.)

Here are some points to start with to make the code easier to read and understand:

Iterate over sList, not over range(len(sList)). for i in range(len(sList)) becomes for i in sList and sList[i] becomes i.

No need for that tmpRad; put it inline.

Instead of if a: if b: if c: use if a and b and c.

Now we're at this:

filteredList = []
for i in sList:
    minx = i['x'] - i['radius']
    maxx = i['x'] + i['radius']
    miny = i['y'] - i['radius']
    maxy = i['y'] + i['radius']
    minz = i['z'] - i['radius']
    maxz = i['z'] + i['radius']

    for j in nList:
        if minx <= j['x'] <= maxx and miny <= j['y'] <= maxy and minz <= j['z'] <= maxz and findRadius(i,j) <= i['radius']:
            filteredList.append(int(j['num']))

(PEP 8 would recommend splitting that long line to lines of no more than 80 characters; PEP 8 would also recommend filtered_list and s_list and n_list rather than filteredList, sList and nList.)

I've put the findRadius(i, j) <= i['radius'] first for style and because it looks like it might be more likely to evaluate to false, speeding up calculations. Then I've also inlined the minx etc. variables:

filteredList = []
for i in sList:
    for j in nList:
        if findRadius(i, j) <= i['radius'] \
        and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] \
        and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius'] \
        and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']:
            filteredList.append(int(j['num']))

One thing to think about is that i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] could be simplified; try things like subtracting i['x'] from all three parts.

You can shorten this even more with a list comprehension.

filteredList = [int(j['num']) for j in nList for i in sList
        if findRadius(i, j) <= i['radius']
        and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius']
        and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius']
        and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']]

And finally, named tuples (this has the side-effect of making them immutable, too, which is probably desired? Also note it's Python 2.6 only, read the page for how you could do it with older versions of Python):

from collections import namedtuple

node = namedtuple('node', 'x y z num')
sphere = namedtuple('sphere', 'x y z radius')

nList = [
        node(x=0.0, y=0.0, z=0.0, num=1.0),
        node(x=1.0, y=0.0, z=0.0, num=2.0),
        node(x=2.0, y=0.0, z=0.0, num=3.0),
        node(x=3.0, y=0.0, z=0.0, num=4.0),
        node(x=4.0, y=0.0, z=0.0, num=5.0),
        node(x=5.0, y=0.0, z=0.0, num=6.0),
        node(x=6.0, y=0.0, z=0.0, num=7.0),
        node(x=7.0, y=0.0, z=0.0, num=8.0),
        node(x=8.0, y=0.0, z=0.0, num=9.0),
        node(x=9.0, y=0.0, z=0.0, num=10.0)]

sList = [
        sphere(x=25.0, y=18.0, z=26.0, radius=0.0056470000000000001),
        sphere(x=23.0, y=29.0, z=45.0, radius=0.0066280000000000002),
        sphere(x=29.0, y=46.0, z=13.0, radius=0.014350999999999999),
        sphere(x=20.0, y=0.0, z=25.0, radius=0.014866000000000001),
        sphere(x=31.0, y=27.0, z=18.0, radius=0.018311999999999998),
        sphere(x=36.0, y=10.0, z=46.0, radius=0.024702000000000002),
        sphere(x=13.0, y=27.0, z=48.0, radius=0.027300999999999999),
        sphere(x=1.0, y=14.0, z=13.0, radius=0.033889000000000002),
        sphere(x=20.0, y=31.0, z=11.0, radius=0.034118999999999997),
        sphere(x=28.0, y=23.0, z=8.0, radius=0.036683)]

Then, instead of sphere['radius'] you can do sphere.radius. This makes the code neater:

filteredList = [int(j.num) for j in nList for i in sList
        if findRadius(i, j) <= i.radius
        and i.x - i.radius <= j.x <= i.x + i.radius
        and i.y - i.radius <= j.y <= i.y + i.radius
        and i.z - i.radius <= j.z <= i.z + i.radius]

Or, without the list comprehension,

filteredList = []
for i in sList:
    for j in nList:
        if findRadius(i, j) <= i.radius \
        and i.x - i.radius <= j.x <= i.x + i.radius \
        and i.y - i.radius <= j.y <= i.y + i.radius \
        and i.z - i.radius <= j.z <= i.z + i.radius:
            filteredList.append(int(j.num))

Finally, choose nicer names; [style changed slightly as per comments, putting findRadius at the end as it's more likely to be computationally expensive - you're the best judge of that, though]

filteredList = [int(n.num) for n in nodes for s in spheres
        if s.x - s.radius <= n.x <= s.x + s.radius and
            s.y - s.radius <= n.y <= s.y + s.radius and
            s.z - s.radius <= n.z <= s.z + s.radius and
            findRadius(s, n) <= s.radius]

Or,

filteredList = []
for s in spheres:
    for n in nodes:
        if (s.x - s.radius <= n.x <= s.x + s.radius and
            s.y - s.radius <= n.y <= s.y + s.radius and
            s.z - s.radius <= n.z <= s.z + s.radius and
            findRadius(s, n) <= s.radius):
            filteredList.append(int(n.num))

(You could put srad = s.radius in the outer loop for a probable slight performance gain if desired.)


来源: stackexchange

问:
After installing CanCanCan development does not work anymore
I am developing a Rails app and of course on my computer in development mode, so if there is an error, Rails returns a nice error page with all details.

Since I installed and started to use CanCanCan I get the erro message

We're sorry, but something went wrong.

Which is supposed to be for production mode. And the erro details disappeared.
I did not change anything in my configurations.

Does anyone know what happened?

答:
Im not 100% sure what you are asking, but it might be that your new CanCanCan rules are actually triggering AccessDenied but that is leading to a new error that Rails can't get a trace on. For example, an error in 400.html

You could try:

https://github.com/ryanb/cancan/wiki/exception-handling

Something like:

```<code>class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im not 100% sure what you are asking, but it might be that your new CanCanCan rules are actually triggering AccessDenied but that is leading to a new error that Rails can't get a trace on. For example, an error in 400.html

You could try:

https://github.com/ryanb/cancan/wiki/exception-handling

Something like:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end


问:
How do I mock a class without an interface?
I am working on .NET 4.0 using C# in Windows 7.

I want to test the communication between some methods using mock. The only problem is that I want to do it without implementing an interface. Is that possible?

I just read a lot of topics and some tutorials about mock objects, but all of them used to mock interfaces, and not the classes. I tried to use Rhino and Moq frameworks.

答:
If you cannot change the class under test, then the only option I can suggest is using MS Fakes https://msdn.microsoft.com/en-us/library/hh549175.aspx.
However, MS Fakes works only in a few editions of Visual Studio.</p>

ContentLicense: CC BY-SA 4.0


问:
Changing entry text in tkinter, if the entry is created from list
I created 12 Entry boxes using a for loop with a default value of N/A. Any change in the text of entry is detected through .trace method.

I want to use reset button to make all the text on the Entry Boxes back to N/A

```<code>from tkinter import *

root = Tk()

t_diesel_price_EnF_variable = ["JanVar", "FebVar", "MarVar", "AprVar","MayVar","JuneVar","JulyVar","AugVar","SeptVar", "OctVar", "NovVar", "DecVar"]
t_diesel_price_EnF_values = ["N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A"]

def EnFChanging(*events):
    for EnF in range(0,len(t_diesel_price_EnF_variable)):
        t_diesel_price_EnF_values[EnF]=t_diesel_price_EnF_variable[EnF].get()
        try:
            t_diesel_price_EnF_values[EnF] = float(t_diesel_price_EnF_values[EnF])
        except ValueError:
            pass
    print(t_diesel_price_EnF_values)

for EnF in range(0,len(t_diesel_price_EnF_values)):
    t_diesel_price_EnF_variable[EnF] = StringVar(root , value = "N/A")
    t_diesel_price = Entry(root , textvariable =  t_diesel_price_EnF_variable[EnF], width = 10).pack()
    t_diesel_price_EnF_variable[EnF].trace("w",EnFChanging)

def ChangeText():
    for EnF in range(0, len(t_diesel_price_EnF_values)):
        t_diesel_price[EnF].delete(0,END)
        t_diesel_price[EnF].insert(0,"N/A")

    return

b1 = Button(root, text = "Reset" , command = ChangeText).pack()

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

When I press the button it gives an error t_diesel_price[EnF].delete(0,END)
TypeError: 'NoneType' object is not subscriptable

What should I do now, Please ignore the basic errors of programming as I am a Mechanical Engineer with not a programming back ground. And I have to make a lot of other boxes too for my energy calculator.

答:
You trying treat t_diesel_price as an Entry (and as a list) when your variable is None.
First of all I suggest you to install some IDE (e.g. PyCharm) and place break points to see whats wrong with variable!

Your problem occures because you create and pack your widget in one line! So t_diesel_price is None because pack() always returns None (link).
Just split your declaration and packing to:

```<code>t_diesel_price = Entry(root , textvariable =  t_diesel_price_EnF_variable[EnF], width = 10)
t_diesel_price.pack()
</code>```

After that it's works for me, except this fact that t_diesel_price is last created entry and the value changes only in it. So I assume that you need another list to iterate over entries:

```<code>...
# another fresh list
t_diesel_price_EnF_entries = list()
...
    # declare entry
    t_diesel_price = Entry(root, textvariable=t_diesel_price_EnF_variable[EnF], width=10)
    # pack entry
    t_diesel_price.pack()
    # append entry to list
    t_diesel_price_EnF_entries.append(t_diesel_price)
...
def ChangeText():
    # iterate over entries
    for diesel_price in t_diesel_price_EnF_entries:
        diesel_price.delete(0,END)
        diesel_price.insert(0,"N/A")
...
</code>```

Alternatively you can iterate over StringVar's if you don't wanna store your entries at all:

```<code>def ChangeText():
    # iterate over stringvars
    for EnF in range(len(t_diesel_price_EnF_variable)):
        t_diesel_price_EnF_variable[EnF].set('N/A')
</code>```

And you can make it more readable as in example with entry iterating:

```<code>def ChangeText():
    # iterate over stringvars
    for string_var in t_diesel_price_EnF_variable:
        string_var.set('N/A')
</code>```

Cheers!

Body:
I created 12 Entry boxes using a for loop with a default value of N/A. Any change in the text of entry is detected through .trace method.

I want to use reset button to make all the text on the Entry Boxes back to N/A

from tkinter import *

root = Tk()

t_diesel_price_EnF_variable = ["JanVar", "FebVar", "MarVar", "AprVar","MayVar","JuneVar","JulyVar","AugVar","SeptVar", "OctVar", "NovVar", "DecVar"]
t_diesel_price_EnF_values = ["N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A","N/A", "N/A"]

def EnFChanging(*events):
    for EnF in range(0,len(t_diesel_price_EnF_variable)):
        t_diesel_price_EnF_values[EnF]=t_diesel_price_EnF_variable[EnF].get()
        try:
            t_diesel_price_EnF_values[EnF] = float(t_diesel_price_EnF_values[EnF])
        except ValueError:
            pass
    print(t_diesel_price_EnF_values)

for EnF in range(0,len(t_diesel_price_EnF_values)):
    t_diesel_price_EnF_variable[EnF] = StringVar(root , value = "N/A")
    t_diesel_price = Entry(root , textvariable =  t_diesel_price_EnF_variable[EnF], width = 10).pack()
    t_diesel_price_EnF_variable[EnF].trace("w",EnFChanging)

def ChangeText():
    for EnF in range(0, len(t_diesel_price_EnF_values)):
        t_diesel_price[EnF].delete(0,END)
        t_diesel_price[EnF].insert(0,"N/A")

    return

b1 = Button(root, text = "Reset" , command = ChangeText).pack()

root.mainloop()

When I press the button it gives an error t_diesel_price[EnF].delete(0,END)
TypeError: 'NoneType' object is not subscriptable

What should I do now, Please ignore the basic errors of programming as I am a Mechanical Engineer with not a programming back ground. And I have to make a lot of other boxes too for my energy calculator.

Body:
You trying treat t_diesel_price as an Entry (and as a list) when your variable is None.
First of all I suggest you to install some IDE (e.g. PyCharm) and place break points to see whats wrong with variable!

Your problem occures because you create and pack your widget in one line! So t_diesel_price is None because pack() always returns None (link).
Just split your declaration and packing to:

t_diesel_price = Entry(root , textvariable =  t_diesel_price_EnF_variable[EnF], width = 10)
t_diesel_price.pack()

After that it's works for me, except this fact that t_diesel_price is last created entry and the value changes only in it. So I assume that you need another list to iterate over entries:

...
# another fresh list
t_diesel_price_EnF_entries = list()
...
    # declare entry
    t_diesel_price = Entry(root, textvariable=t_diesel_price_EnF_variable[EnF], width=10)
    # pack entry
    t_diesel_price.pack()
    # append entry to list
    t_diesel_price_EnF_entries.append(t_diesel_price)
...
def ChangeText():
    # iterate over entries
    for diesel_price in t_diesel_price_EnF_entries:
        diesel_price.delete(0,END)
        diesel_price.insert(0,"N/A")
...

Alternatively you can iterate over StringVar's if you don't wanna store your entries at all:

def ChangeText():
    # iterate over stringvars
    for EnF in range(len(t_diesel_price_EnF_variable)):
        t_diesel_price_EnF_variable[EnF].set('N/A')

And you can make it more readable as in example with entry iterating:

def ChangeText():
    # iterate over stringvars
    for string_var in t_diesel_price_EnF_variable:
        string_var.set('N/A')

Cheers!


问:
iisnode encountered an error when processing the request. HTTP status: 500
iisnode encountered an error when processing the request.

HRESULT: 0x2
HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error

This is a fairly simple node/express application which we cannot get to run under iisnode.

We are seeing errors in the ETW trace such as:
iisnode request processing failed for reasons unrecognized by iisnode
iisnode was unable to establish named pipe connection to the node.exe process

The last thing seen in the node output is:
server Express http server listening on port \.\pipe\15524b7e-249a-4464-b41a-eddab028342e

Where can we look to find out what is happening?

1) the node application works correctly from the command line in the folder, by typing node server.js.
2) There is seemingly nothing "thrown" in the javascript, we have this code:

```<code>process.on('uncaughtException', function (err) {
    console.log(err);
    fs.writeFileSync("exception.txt", err, "utf8");
})
</code>```

3) the web.config is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.webServer>
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="NodeLog">
          <action type="Rewrite" url="iisnode{REQUEST_URI}"/>
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
          <add segment="node_modules"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
    -->
    <!--<iisnode watchedFiles="web.config;*.js"/>-->
    <defaultDocument enabled="true">
      <files>
        <add value="server.js" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>
</code>```

The server.js is pretty simple:

```<code>var fs = require('fs');
var express = require('express');
var path = require('path');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override'); // Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.

var routes = require('./routes/index');

var http = require('http');
var https = require('https');
var options = {
    pfx: fs.readFileSync(path.join(__dirname, 'sslcert') + '/web.local.pfx'),
    passphrase: ''
}

var app = express();

//app.engine("ejs", ejsEngine); // templating engine

// must set up environment before controllers establish routes

// all environments
// set default port if not set
//app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));

// opt into services
app.use(express.static(path.join(__dirname, 'public')));

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());
app.use(methodOverride());

/* api access */
app.get('/api', function (req, res) {
    res.send('api is up and running');
});

//app.get('*', function (req, res) {
//    res.render('index.html');
//});

var port = process.env.PORT || 3000;

// start the web server
http.createServer(app).listen(app.get(port), function () {
//http.createServer(app).listen(2025, function () {
    console.log('server', 'Express http server listening on port' + port);
});

https.createServer(options, app).listen(8443, function () {
    console.log('server', 'Express https server listening on port 8443');
});

module.exports = app;
</code>```

答:
I had the same issue with IISNode and spent far too much time trying to fix it. I tried adding different permissions for different users (IIS_USRS, IUSRS, Everyone, IIS AppPool/domainname) through Windows explorer with no luck.

I finally found the solution in the setupexamples.bat script, provided with the iisnode examples. Simple run the following script on the folder containing your app code:

```<code>icacls (folder_name) /grant IIS_IUSRS:(OI)(CI)F /t
</code>```

Body:
iisnode encountered an error when processing the request.

HRESULT: 0x2
HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error

This is a fairly simple node/express application which we cannot get to run under iisnode.

We are seeing errors in the ETW trace such as:
iisnode request processing failed for reasons unrecognized by iisnode
iisnode was unable to establish named pipe connection to the node.exe process

The last thing seen in the node output is:
server Express http server listening on port \.\pipe\15524b7e-249a-4464-b41a-eddab028342e

Where can we look to find out what is happening?

1) the node application works correctly from the command line in the folder, by typing node server.js.
2) There is seemingly nothing "thrown" in the javascript, we have this code:

process.on('uncaughtException', function (err) {
    console.log(err);
    fs.writeFileSync("exception.txt", err, "utf8");
})

3) the web.config is as follows:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.webServer>
    <handlers>

      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="NodeLog">
          <action type="Rewrite" url="iisnode{REQUEST_URI}"/>
        </rule>

        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
          <add segment="node_modules"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough" />

    <defaultDocument enabled="true">
      <files>
        <add value="server.js" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>

The server.js is pretty simple:

var fs = require('fs');
var express = require('express');
var path = require('path');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override'); // Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.

var routes = require('./routes/index');

var http = require('http');
var https = require('https');
var options = {
    pfx: fs.readFileSync(path.join(__dirname, 'sslcert') + '/web.local.pfx'),
    passphrase: ''
}

var app = express();

//app.engine("ejs", ejsEngine); // templating engine

// must set up environment before controllers establish routes

// all environments
// set default port if not set
//app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));

// opt into services
app.use(express.static(path.join(__dirname, 'public')));

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());
app.use(methodOverride());

/* api access */
app.get('/api', function (req, res) {
    res.send('api is up and running');
});

//app.get('*', function (req, res) {
//    res.render('index.html');
//});

var port = process.env.PORT || 3000;

// start the web server
http.createServer(app).listen(app.get(port), function () {
//http.createServer(app).listen(2025, function () {
    console.log('server', 'Express http server listening on port' + port);
});

https.createServer(options, app).listen(8443, function () {
    console.log('server', 'Express https server listening on port 8443');
});

module.exports = app;

Body:
I had the same issue with IISNode and spent far too much time trying to fix it. I tried adding different permissions for different users (IIS_USRS, IUSRS, Everyone, IIS AppPool/domainname) through Windows explorer with no luck.

I finally found the solution in the setupexamples.bat script, provided with the iisnode examples. Simple run the following script on the folder containing your app code:

icacls (folder_name) /grant IIS_IUSRS:(OI)(CI)F /t


问:
navbar icons jumping down when the window get smaller
I use bootstrap.my navbar icons jumping down when the window get smaller.when it is too small the menu goes to 3line icon bar.
How I can set my icons to appear in one line in small window?

here is my navbar code,

```<code>  <nav class="navbar navbar-inverse navbar-fixed-top ">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>

                </button>
                <a class="navbar-brand" href="#">
                    <img id="brand-image" alt="" src="../image/fullLogo.png"/>
                </a>

            </div>

            <div class=" col-md-offset-2">
                <div class="collapse navbar-collapse" id="myNavbar">
                    <ul class="nav navbar-nav">

                        <li>
                            <a href="../MainPages/avayejavid.html"    class="header-style">
                                <i class="fa fa-home li-header-style" aria-hidden="true" ></i>

                                خانه
                            </a>
                        </li>

                        <li class="dropdown ">
                            <a data-toggle="dropdown" href="#" class="header-style">
                                <i class="fa fa-file-o li-header-style" aria-hidden="true"></i>

                                معرفی <span class="caret "></span>
                            </a>
                            <ul class="dropdown-menu" style=" background-color: #9D763C">
                                <li>
                                    <a href="../MainPages/bio.html" class="header-style">بیوگرافی</a>
                                </li>
                                <li>
                                    <a href="../MainPages/ava-members.html" class="header-style">اعضای گروه</a>
                                </li>

                            </ul>
                        </li>

                        <li>
                            <a href="../MainPages/gallery.html" class="header-style">
                                <i class="fa fa-picture-o li-header-style" aria-hidden="true" ></i>

                                گالری

                            </a>
                        </li>

                        <li class="dropdown">
                            <a data-toggle="dropdown" href="#" class="header-style">
                                <i class="fa fa-file-o li-header-style" aria-hidden="true"></i>

                                ویدئو <span class="caret "></span>
                            </a>
                            <ul class="dropdown-menu" style=" background-color: #9D763C">
                                <li>

                                    <a href="../MainPages/training.html" class="header-style">آموزش</a>
                                </li>
                                <li>

                                    <a href="../MainPages/tasnif1.html" class="header-style">تصنیف خوانی</a>
                                </li>

                                <li>
                                    <a href="../MainPages/saz-va-avaz1.html" class="header-style"> ساز و آواز</a>
                                </li>

                            </ul>
                        </li>

                        <li>
                            <a href="../MainPages/Articles.html" class="header-style">
                                <i class="fa fa-shopping-cart li-header-style" aria-hidden="true"></i>

                                مقالات

                            </a>
                        </li>

                        <li>
                            <a href="../MainPages/movie.html" class="header-style">
                                <i class="fa fa-shopping-cart li-header-style" aria-hidden="true"></i>

                                خرید

                            </a>
                        </li>

                        <li>
                            <a href="#" class="header-style">
                                <i class="fa fa-comments li-header-style" aria-hidden="true"></i>

                                تماس با ما

                            </a>
                        </li>

                    </ul>

                </div>

            </div>

        </div>

    </nav>
</code>```

and here is my CSS:

```<code> .header-style{
           padding-top:20px !important;
           background-image:url(../images/icon.png);
            background-size: 100% 100% !important;
            padding-left:40px !important;
            padding-right:40px !important;
       }
       .li-header-style{
           color:#ffe766
       }
.navbar-fixed-top .nav {
    padding: 15px 0;
}

@media (max-width:767px) {
    .navbar-brand {
        padding: 0;
    }

   .navbar-brand img {
        margin-top: 1px;
        margin-left: 1px;
    }
}

 .navbar-nav li a {
  height:80px;

}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

        .navbar .nav > li.dropdown.open.active > a:hover,
        .navbar .nav > li.dropdown.open > a {
            color: #ffe766 !important;
            background-color: transparent !important;
            border-color: #ffe766 !important;
        }
         #brand-image
        {
            height:100px;

        }
</code>```

答:
The problem is the icons are taking up too much space for the designated break-point.

I would advise reading the bootstrap documentation more thoroughly (especially the grid system): http://getbootstrap.com/css/#grid-media-queries

To fix your problem you would need to increase the .navbar breakpoint. This is explained very well here: https://coderwall.com/p/wpjw4w/change-the-bootstrap-navbar-breakpoint.

You can also look at this previous answer to help you: Change bootstrap navbar collapse breakpoint without using LESS

Body:
I use bootstrap.my navbar icons jumping down when the window get smaller.when it is too small the menu goes to 3line icon bar.
How I can set my icons to appear in one line in small window?

here is my navbar code,

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>

                                خانه

                                معرفی

                                    بیوگرافی

                                    اعضای گروه

                                گالری

                                ویدئو

                                    آموزش

                                    تصنیف خوانی

                                     ساز و آواز

                                مقالات

                                خرید

                                تماس با ما

and here is my CSS:

 .header-style{
           padding-top:20px !important;
           background-image:url(../images/icon.png);
            background-size: 100% 100% !important;
            padding-left:40px !important;
            padding-right:40px !important;
       }
       .li-header-style{
           color:#ffe766
       }
.navbar-fixed-top .nav {
    padding: 15px 0;
}

@media (max-width:767px) {
    .navbar-brand {
        padding: 0;
    }

   .navbar-brand img {
        margin-top: 1px;
        margin-left: 1px;
    }
}

 .navbar-nav li a {
  height:80px;

}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

        .navbar .nav > li.dropdown.open.active > a:hover,
        .navbar .nav > li.dropdown.open > a {
            color: #ffe766 !important;
            background-color: transparent !important;
            border-color: #ffe766 !important;
        }
         #brand-image
        {
            height:100px;

        }


问:
Who sent you?
I have a series of input forms, all of them take a different form action. Each of those validates input. If ok, they go to different success pages. If fail, I want the form action/validation pages to set $_SESSION['error_messages'] and go to a common page which displays the errors and has a "resubmit" button.

Question ... how to get error form the resubmit button back to one of many possible input forms?

Edit: I don't see how $_SERVER['HTTP_REFERER'] is going to work. Again: form --> validation --> error_page

So, I guess that validation has to set  a session variable from $_SERVER['HTTP_REFERER']

答:
Using $_SERVER['HTTP_REFERER'].

But, as per http://php.net/manual/en/reserved.variables.server.php

The address of the page (if any)
  which referred the user agent to the
  current page. This is set by the user
  agent. Not all user agents will set
  this, and some provide the ability to
  modify HTTP_REFERER as a feature. In
  short, it cannot really be trusted.

So, like Neal Donnan has suggested, passing the module_name in a hidden field and then resubmitting to http://project/'.$_POST['module_name'] would be best

ContentLicense: CC BY-SA 2.5

Title: Who sent you?


问:
WSO2 - iteration through xml response
I manged to do similar with JSON response but now I'm stuck.
I have a data service that returns XML. I created end point and now I want to go over response and call another endpoint to write custom MQ message.

result from Dataservice is like

```<code><VINS xmlns="http://ws.wso2.org/dataservice">
<VIN>
<TransactionDate>2017-03-01-06:00</TransactionDate>
<VIN>5TDXZ3XXXXXX</VIN>
<DealerCode>YYYY</DealerCode>
</VIN>
</code>```

and my API looks like :

```<code><resource methods="GET" uri-template="/{dlrcode}">
<inSequence>
<log level="custom">
<property expression="fn:concat(' DLR code ',get-property('uri.var.dlrcode'))" name="Allocation GET api  method is called for"/>
</log>
<property description="DLR Code" expression="get-property('uri.var.dlrcode')" name="dlrCode" scope="default" type="STRING"/>
<call>
<endpoint key="getAllocationVehicles"/>
</call>
<log level="custom">
<property name="call status " value="ok"/>
</log>
<iterate continueParent="true" expression="//VINS" id="MyIterator" xmlns:ns="http://ws.wso2.org/dataservice" sequential="true">
<target>
<sequence>
<log level="custom">
<property name="iteration " value="working..."/>
</log>
<property description="VIN" expression="//VINS/VIN" name="vin" scope="default" type="STRING"/>
<property description="TransactionDate" expression="//VINS/DealerCode" name="trsDate" scope="default" type="STRING"/>
<property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/>
<property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
<property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
<payloadFactory description="VIN message" media-type="json">
<format>{"DLRCode":"$1","VIN":"$2","TrDate":"$3"}</format>
<args>
<arg evaluator="xml" expression="$ctx:dlrCode"/>
<arg evaluator="xml" expression="$ctx:vin"/>
<arg evaluator="xml" expression="$ctx:trsDate"/>
</args>
</payloadFactory>
<call>
<endpoint>
<address uri="jms:/LocalQueue2?transport.jms.Destination=LocalQueue2">
<timeout>
<duration>5</duration>
<responseAction>fault</responseAction>
</timeout>
</address>
</endpoint>
</call>
</sequence>
</target>
</iterate>
<respond/>
</inSequence>
<outSequence>
<log level="full"/>
</outSequence>
<faultSequence/>
</resource>
</code>```

in log I see that call to Data service is done because I'm getting

Allocation GET api method is called for = DLR code ABC

and

call status = ok

BUT it looks that I'm not getting into iteration because there is no message

iteration = working...

Im guesting thet my issue is on iteration declaration but i don't see it ..

thanks to Jeam-Michel I want to put correct iteration for clarity

```<code><iterate continueParent="true" expression="//ns:VINS/ns:VIN" id="MyIterator" sequential="true" xmlns:ns="http://ws.wso2.org/dataservice">
                <target>
                    <sequence>
                        <property description="VIN" expression="//ns:VIN/text()" name="vin" scope="default" type="STRING"/>
                        <property description="TransactionDate" expression="//ns:TransactionDate/text()" name="trsDate" scope="default" type="STRING"/>
                        <property description="Dlr code for Veh" expression="//ns:DealerCode/text()" name="trsDLR" scope="default" type="STRING"/>
                        <property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/>
                        <property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
                        <property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
                        <payloadFactory description="VIN message" media-type="json">
                            <format>{"DLRCode":"$1","VIN":"$2","TrDate":"$3"}</format>
                            <args>
                                <arg evaluator="xml" expression="$ctx:trsDLR"/>
                                <arg evaluator="xml" expression="$ctx:vin"/>
                                <arg evaluator="xml" expression="$ctx:trsDate"/>
                            </args>
                        </payloadFactory>
                        <call>
                            <endpoint>
                                <address uri="jms:/LocalQueue2?transport.jms.Destination=LocalQueue2">
                                    <timeout>
                                        <duration>5</duration>
                                        <responseAction>fault</responseAction>
                                    </timeout>
                                </address>
                            </endpoint>
                        </call>
                    </sequence>
                </target>
            </iterate>
</code>```

It works like a charm

答:
All the nodes in your result belongs to namespace http://ws.wso2.org/dataservice

You've just defined this namespace in your iterate, but you need to specify it inside the xpath :

```<code><iterate continueParent="true" expression="//ds:VINS" id="MyIterator" xmlns:ds="http://ws.wso2.org/dataservice" sequential="true">
</code>```

Title: WSO2 - iteration through xml response

Body:
I manged to do similar with JSON response but now I'm stuck.
I have a data service that returns XML. I created end point and now I want to go over response and call another endpoint to write custom MQ message.

result from Dataservice is like

<VINS xmlns="http://ws.wso2.org/dataservice">
<VIN>
<TransactionDate>2017-03-01-06:00</TransactionDate>
<VIN>5TDXZ3XXXXXX</VIN>
<DealerCode>YYYY</DealerCode>
</VIN>

and my API looks like :

<resource methods="GET" uri-template="/{dlrcode}">
<inSequence>
<log level="custom">
<property expression="fn:concat(' DLR code ',get-property('uri.var.dlrcode'))" name="Allocation GET api  method is called for"/>
</log>
<property description="DLR Code" expression="get-property('uri.var.dlrcode')" name="dlrCode" scope="default" type="STRING"/>
<call>
<endpoint key="getAllocationVehicles"/>
</call>
<log level="custom">
<property name="call status " value="ok"/>
</log>
<iterate continueParent="true" expression="//VINS" id="MyIterator" xmlns:ns="http://ws.wso2.org/dataservice" sequential="true">
<target>
<sequence>
<log level="custom">
<property name="iteration " value="working..."/>
</log>
<property description="VIN" expression="//VINS/VIN" name="vin" scope="default" type="STRING"/>
<property description="TransactionDate" expression="//VINS/DealerCode" name="trsDate" scope="default" type="STRING"/>
<property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/>
<property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
<property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
<payloadFactory description="VIN message" media-type="json">
<format>{"DLRCode":"$1","VIN":"$2","TrDate":"$3"}</format>
<args>
<arg evaluator="xml" expression="$ctx:dlrCode"/>
<arg evaluator="xml" expression="$ctx:vin"/>
<arg evaluator="xml" expression="$ctx:trsDate"/>
</args>
</payloadFactory>
<call>
<endpoint>
<address uri="jms:/LocalQueue2?transport.jms.Destination=LocalQueue2">
<timeout>
<duration>5</duration>
<responseAction>fault</responseAction>
</timeout>
</address>
</endpoint>
</call>
</sequence>
</target>
</iterate>
<respond/>
</inSequence>
<outSequence>
<log level="full"/>
</outSequence>
<faultSequence/>
</resource>

in log I see that call to Data service is done because I'm getting

Allocation GET api method is called for = DLR code ABC

and

call status = ok

BUT it looks that I'm not getting into iteration because there is no message

iteration = working...

Im guesting thet my issue is on iteration declaration but i don't see it ..

thanks to Jeam-Michel I want to put correct iteration for clarity

<iterate continueParent="true" expression="//ns:VINS/ns:VIN" id="MyIterator" sequential="true" xmlns:ns="http://ws.wso2.org/dataservice">
                <target>
                    <sequence>
                        <property description="VIN" expression="//ns:VIN/text()" name="vin" scope="default" type="STRING"/>
                        <property description="TransactionDate" expression="//ns:TransactionDate/text()" name="trsDate" scope="default" type="STRING"/>
                        <property description="Dlr code for Veh" expression="//ns:DealerCode/text()" name="trsDLR" scope="default" type="STRING"/>
                        <property name="FORCE_SC_ACCEPTED" scope="axis2" type="STRING" value="true"/>
                        <property action="remove" name="TRANSPORT_HEADERS" scope="axis2"/>
                        <property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
                        <payloadFactory description="VIN message" media-type="json">
                            <format>{"DLRCode":"$1","VIN":"$2","TrDate":"$3"}</format>
                            <args>
                                <arg evaluator="xml" expression="$ctx:trsDLR"/>
                                <arg evaluator="xml" expression="$ctx:vin"/>
                                <arg evaluator="xml" expression="$ctx:trsDate"/>
                            </args>
                        </payloadFactory>
                        <call>
                            <endpoint>
                                <address uri="jms:/LocalQueue2?transport.jms.Destination=LocalQueue2">
                                    <timeout>
                                        <duration>5</duration>
                                        <responseAction>fault</responseAction>
                                    </timeout>
                                </address>
                            </endpoint>
                        </call>
                    </sequence>
                </target>
            </iterate>

It works like a charm

Body:
All the nodes in your result belongs to namespace http://ws.wso2.org/dataservice

You've just defined this namespace in your iterate, but you need to specify it inside the xpath :

<iterate continueParent="true" expression="//ds:VINS" id="MyIterator" xmlns:ds="http://ws.wso2.org/dataservice" sequential="true">


问:
(Excel add-in) When setting a large number to Range.value, the resulting number in the spreadsheet is different
When setting a large number as the value for a Range (cell), the number that is written to the spreadsheet is different than the original number. E.g.

If I set 42300000000, the number in excel becomes -649672960. This doesn't happen with smaller numbers

I tested it with the basic project sample from Visual Studio. Just replaced the original loadSampleData function with:

```<code>function loadSampleData() {

     var values = [
                    [4230, 42300, 423000],
                    [4230000, 42300000, 423000000],
                    [4230000000, 42300000000, 423000000000]
    ];

    // Run a batch operation against the Excel object model
    Excel.run(function (ctx) {
        // Create a proxy object for the active sheet
        var sheet = ctx.workbook.worksheets.getActiveWorksheet();
        // Queue a command to write the sample data to the worksheet
        sheet.getRange("B3:D5").values = values;

        // Run the queued-up commands, and return a promise to indicate task completion
        return ctx.sync();
    })
    .catch(errorHandler);
}
</code>```

When I run the add-in, I get this in Excel:

```<code>4230         42300      423000
4230000      42300000   423000000
-64967296   -649672960  2093204992
</code>```

Is this some kind of overflow? Am I doing something wrong?

Thanks!

答:
When I explore this bug I get the following results

9876543210 and 9876543210.0 give 1286608618 - fail

9876543210.9 gives 9876543210.9 - works

'9876543210' and "9876543210" - do not result in a string (I would consider that a bug but maybe this is just a JS type confusion nasty) but give
9876543210 as a number (so a possible hack bypass to the original bug)

"'9876543210" gives '9876543210 which excel recognises as a string -
correct

using the following code with 1704.8017.1000

```<code>async function setValue() {
    try {
        await Excel.run(async (context) => {
            let sheet = context.workbook.worksheets.getActiveWorksheet();

            let range = sheet.getRange("C3");
            range.values = [[ 9876543210.0 ]];
            range.format.autofitColumns();

            await context.sync();
        });

        console.log("Done!");
    }
    catch (error) {
        OfficeHelpers.Utilities.log(error);
    }
}
</code>```

Body:
When setting a large number as the value for a Range (cell), the number that is written to the spreadsheet is different than the original number. E.g.

If I set 42300000000, the number in excel becomes -649672960. This doesn't happen with smaller numbers

I tested it with the basic project sample from Visual Studio. Just replaced the original loadSampleData function with:

function loadSampleData() {

     var values = [
                    [4230, 42300, 423000],
                    [4230000, 42300000, 423000000],
                    [4230000000, 42300000000, 423000000000]
    ];

    // Run a batch operation against the Excel object model
    Excel.run(function (ctx) {
        // Create a proxy object for the active sheet
        var sheet = ctx.workbook.worksheets.getActiveWorksheet();
        // Queue a command to write the sample data to the worksheet
        sheet.getRange("B3:D5").values = values;

        // Run the queued-up commands, and return a promise to indicate task completion
        return ctx.sync();
    })
    .catch(errorHandler);
}

When I run the add-in, I get this in Excel:

4230         42300      423000
4230000      42300000   423000000
-64967296   -649672960  2093204992

Is this some kind of overflow? Am I doing something wrong?

Thanks!

Body:
When I explore this bug I get the following results

9876543210 and 9876543210.0 give 1286608618 - fail

9876543210.9 gives 9876543210.9 - works

'9876543210' and "9876543210" - do not result in a string (I would consider that a bug but maybe this is just a JS type confusion nasty) but give
9876543210 as a number (so a possible hack bypass to the original bug)

"'9876543210" gives '9876543210 which excel recognises as a string -
correct

using the following code with 1704.8017.1000

async function setValue() {
    try {
        await Excel.run(async (context) => {
            let sheet = context.workbook.worksheets.getActiveWorksheet();

            let range = sheet.getRange("C3");
            range.values = [[ 9876543210.0 ]];
            range.format.autofitColumns();

            await context.sync();
        });

        console.log("Done!");
    }
    catch (error) {
        OfficeHelpers.Utilities.log(error);
    }
}


问:
Why getting null in the request parameter
Below is my API.

```<code>public HttpResponseMessage Delete(IEnumerable<int> customerIds)
{
    //api stuff
}
</code>```

But when this API is hit I am getting customerIds as null.

This is how I am calling the API via Postman.

```<code>{
 "customerIds" : [69,50]
}

Content-Type = application/json
</code>```

However, if I update the API as below, values are caught.

```<code>public HttpResponseMessage Delete(CustomerTO customerIds)
{
    //api stuff
}
public class CustomerTO
{
   public IEnumerable<int> CustomerIds
}
</code>```

If I do so, I think its an overhead.

Any help/suggestion highly appreciated.

答:
For the first one I think you might need to do it like this:</p>

```<code>([FromBody] IEnumerable<int> customerIds)
</code>```

Body:
Below is my API.

public HttpResponseMessage Delete(IEnumerable<int> customerIds)
{
    //api stuff
}

But when this API is hit I am getting customerIds as null.

This is how I am calling the API via Postman.

{
 "customerIds" : [69,50]
}

Content-Type = application/json

However, if I update the API as below, values are caught.

public HttpResponseMessage Delete(CustomerTO customerIds)
{
    //api stuff
}
public class CustomerTO
{
   public IEnumerable<int> CustomerIds
}

If I do so, I think its an overhead.

Any help/suggestion highly appreciated.

Body:
For the first one I think you might need to do it like this:

([FromBody] IEnumerable<int> customerIds)


问:
How to parse RESTful API params with Dropwizard
Let's say I have:

```<code>@GET
public UserList fetch(@PathParam("user") String userId) {
    // Do stuff here
}
</code>```

Now, let's say I have my own type for userId, let's call it UserId. Is it possible to parse that String to UserId when it is passed into the fetch method, i.e.:

```<code>@GET
public UserList fetch(@PathParam("user") UserId userId) {
    // Do stuff here
}
</code>```

I realize I can parse the String once I am inside the method, but it would be more convenient that my method gets the type I want.

答:
Dropwizard is using Jersey for HTTP<->Java POJO marshalling. You could use the various annotations from Jersey @*Param (@FormParam, @QueryParam, etc.) for some of the parameters.

If you need to use map/marshall to/from Java POJOs take a look at the test cases in Dropwizard:

```<code>@Path("/valid/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ValidatingResource {
    @POST
    @Path("foo")
    @Valid
    public ValidRepresentation blah(@NotNull @Valid ValidRepresentation representation, @QueryParam("somethingelse") String xer) {
        return new ValidRepresentation();
    }
</code>```

This defines an API endpoint responding to HTTP POST method which expects ValidRepresentation object and "somethingelse" as HTTP method query parameter. The endpoint WILL respond ONLY when supplied with JSON parameters and will return only JSON objects (@Produces and @Consumes on the class level). The @NotNull requires that object to be mandatory for the call to succeed and @Valid instructs Dropwizard to call Hibernate validator to validate the object before calling the endpoint.

The ValidRepresentation class is here:

```<code>package io.dropwizard.jersey.validation;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

public class ValidRepresentation {
    @NotEmpty
    private String name;

    @JsonProperty
    public String getName() {
        return name;
    }

    @JsonProperty
    public void setName(String name) {
        this.name = name;
    }
}
</code>```

The POJO is using Jackson annotations to define how JSON representation of this object should look like. @NotEmtpy is annotation from Hibernate validator.

Dropwizard, Jersey and Jackson take care of the details. So for the basic stuff this is all that you need.

Body:
Let's say I have:

@GET
public UserList fetch(@PathParam("user") String userId) {
    // Do stuff here
}

Now, let's say I have my own type for userId, let's call it UserId. Is it possible to parse that String to UserId when it is passed into the fetch method, i.e.:

@GET
public UserList fetch(@PathParam("user") UserId userId) {
    // Do stuff here
}

I realize I can parse the String once I am inside the method, but it would be more convenient that my method gets the type I want.

Body:
Dropwizard is using Jersey for HTTP<->Java POJO marshalling. You could use the various annotations from Jersey @*Param (@FormParam, @QueryParam, etc.) for some of the parameters.

If you need to use map/marshall to/from Java POJOs take a look at the test cases in Dropwizard:

@Path("/valid/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ValidatingResource {
    @POST
    @Path("foo")
    @Valid
    public ValidRepresentation blah(@NotNull @Valid ValidRepresentation representation, @QueryParam("somethingelse") String xer) {
        return new ValidRepresentation();
    }

This defines an API endpoint responding to HTTP POST method which expects ValidRepresentation object and "somethingelse" as HTTP method query parameter. The endpoint WILL respond ONLY when supplied with JSON parameters and will return only JSON objects (@Produces and @Consumes on the class level). The @NotNull requires that object to be mandatory for the call to succeed and @Valid instructs Dropwizard to call Hibernate validator to validate the object before calling the endpoint.

The ValidRepresentation class is here:

package io.dropwizard.jersey.validation;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

public class ValidRepresentation {
    @NotEmpty
    private String name;

    @JsonProperty
    public String getName() {
        return name;
    }

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

The POJO is using Jackson annotations to define how JSON representation of this object should look like. @NotEmtpy is annotation from Hibernate validator.

Dropwizard, Jersey and Jackson take care of the details. So for the basic stuff this is all that you need.


问:
How do i connect an SQL file to my Bluej application?
I really am new at this, and I don't really know what I'm doing so please be gentle. I have a blueJ program and an SQL database to connect it to. I have a .jar library to connect it but where exactly do I save the library and where exactly is that location stored? here, right?

```<code>    try
    {
        String user = "root";
        String pass = "12345";
        String url = "jdbc:mysql://localhost/mydb";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(url, user, pass);
        System.out.println ("Database connection established");
    }
</code>```

But in

String url = "jdbc:mysql://localhost/mydb";

The location is different from where I currently have my sql file and jar library stored, so I need to change this line to the location of the file and library? Is that right?

To be a numskull here, if I just saved it to the C drive (for the sake of easy understanding) how would I rewrite that line to point there?

Thanks. Whew.

答:
```<code>import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
    System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "jdbctutorial";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "root";
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      conn.close();
      System.out.println("Disconnected from database");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
</code>```

Body:
I really am new at this, and I don't really know what I'm doing so please be gentle. I have a blueJ program and an SQL database to connect it to. I have a .jar library to connect it but where exactly do I save the library and where exactly is that location stored? here, right?

    try
    {
        String user = "root";
        String pass = "12345";
        String url = "jdbc:mysql://localhost/mydb";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(url, user, pass);
        System.out.println ("Database connection established");
    }

But in

String url = "jdbc:mysql://localhost/mydb";

The location is different from where I currently have my sql file and jar library stored, so I need to change this line to the location of the file and library? Is that right?

To be a numskull here, if I just saved it to the C drive (for the sake of easy understanding) how would I rewrite that line to point there?

Thanks. Whew.


问:
Is it possible to include static properties in a functional representation of a React component?
With ES6, it is possible to represent a React Component as a function.

So, the following component

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

  render() {
    <div>Hi</div>
  }

}
</code>```

could also be represented as such

```<code>const MyComponent = (props) => (
   <div>Hi</div>
)
</code>```

My question is whether the functional representation also allows for static properties. So, I'm wondering whether it is possible to represent the following component somehow as a function as well:

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

  static myProperty = {'hello': 'world'}

  render() {
    <div>Hi</div>
  }

}
</code>```

答:
```<code>const MyComponent = (props) => (
   <div>Hi</div>
)

MyComponent.myProperty = {'hello': 'world'};
</code>```

Body:
With ES6, it is possible to represent a React Component as a function.

So, the following component

class MyComponent extends React.Component {

  render() {

Hi

  }

}

could also be represented as such

const MyComponent = (props) => (

Hi

)

My question is whether the functional representation also allows for static properties. So, I'm wondering whether it is possible to represent the following component somehow as a function as well:

class MyComponentWithStaticProperty extends React.Component {

  static myProperty = {'hello': 'world'}

  render() {

Hi

  }

}


问:
Is there a combination available between AWS SQS and SES?
We are planning to use AWS SES with SQS. The idea is to push the email content to SQS then SES fetch the queue item and send the emails. We are using PHP.
We just want the idea to implement this without hampering the webserver performance.</p>

答:
SES cannot fetch stuff from SQS.
You will have to have a compute tier in between (either on EC2 or Lambda or some other server), which could poll the SQS and then call SES.

Scheduled Lambda can be ideal for this use case.

Out of curiosity, who is putting the message in SQS and do tou have any specific use case for putting the message in SQS. Why can't the routine that places the message on SQS, simply call the SES and get the email sent


问:
one decimal for string format
I have below digits. I want to show one digit after to decimal. How to format it?

```<code>2.85
2
1.99
</code>```

I was using ("{0:0.0}". But data showing like

```<code>2.9 //It should be 2.8
2.0 //It should be 2
2.0 //It should be 1.9
</code>```

答:
Try using "{0:0.#}" as the format string. However, that will only fix the .0. To fix the  rounding to always round down, you might want to use:

```<code>string s = (Math.Floor(value * 10) / 10).ToString("0.#");
</code>```

Title: one decimal for string format

Body:
I have below digits. I want to show one digit after to decimal. How to format it?

2.85
2
1.99

I was using ("{0:0.0}". But data showing like

2.9 //It should be 2.8
2.0 //It should be 2
2.0 //It should be 1.9

Body:
Try using "{0:0.#}" as the format string. However, that will only fix the .0. To fix the  rounding to always round down, you might want to use:

string s = (Math.Floor(value * 10) / 10).ToString("0.#");


问:
Crash when opening - neo4j 3.1.2 Community Edition
I am totally new to neo4j. I have downloaded de software and installed it, but when I open it, it crashes immediately.

Below is the error I get. I have shorten the error text because its incredibly long.

Any ideas? I tried to reinstall, restart etc. but no luck.

Thank you in advance,

Cristina

```<code>>Process:               JavaApplicationStub [877]
Path:                  /Applications/Neo4j Community Edition 3.1.2.app/Contents/MacOS/JavaApplicationStub
Identifier:            com.install4j.8478-6373-2628-9929.24
Version:               3.1.2 (3.1.2)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           JavaApplicationStub [877]
User ID:               502

>Date/Time:             2017-03-28 13:43:24.705 +0200
OS Version:            Mac OS X 10.10.5 (14F27)
Report Version:        11
Anonymous UUID:        9E54842F-ADA5-86BD-C792-F5A255A236CE

>Time Awake Since Boot: 760 seconds

>Crashed Thread:        0  AppKit Thread  Dispatch queue: com.apple.main->thread

>Exception Type:        EXC_BAD_ACCESS (SIGABRT)
>Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000303620

>VM Regions Near 0x303620:
>-->
    __TEXT                 0000000100000000-000000010000a000 [   40K] r-x/rwx SM=COW  /Applications/Neo4j Community Edition 3.1.2.app/Contents/MacOS/JavaApplicationStub

>Application Specific Information:
abort() called

>Thread 0 Crashed:: AppKit Thread  Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff937d2286 __pthread_kill + 10
1   libsystem_c.dylib               0x00007fff94d9a9b3 abort + 129
2   libjvm.dylib                    0x0000000104482beb os::abort(bool) + 25
3   libjvm.dylib                    0x00000001045a6a2a VMError::report_and_die() + 2304
4   libjvm.dylib                    0x0000000104484816 JVM_handle_bsd_signal + 1131
5   libjvm.dylib                    0x0000000104480a7b signalHandler(int, __siginfo*, void*) + 47
6   libsystem_platform.dylib        0x00007fff8b907f1a _sigtramp + 26
7   libsystem_c.dylib               0x00007fff94d3dfb2 strlen + 18
8   com.apple.CoreFoundation        0x00007fff942c8a3c __CFStringAppendFormatCore + 8524
9   com.apple.CoreFoundation        0x00007fff943be3a0 _CFStringCreateWithFormatAndArgumentsAux2 + 256
10  com.apple.Foundation            0x00007fff973f5701 -[NSPlaceholderString initWithFormat:locale:arguments:] + 153
11  com.apple.Foundation            0x00007fff9740eef9 +[NSString stringWithFormat:] + 174
12  com.apple.java.JavaRuntimeSupport   0x000000011c276fce -[JRSInputMethodController availableInputMethodLocales] + 253
13  libawt_lwawt.dylib              0x000000011d21907f __Java_sun_lwawt_macosx_CInputMethodDescriptor_nativeGetAvailableLocales_block_invoke_1 + 124
14  com.apple.Foundation            0x00007fff9747ddd0 __NSThreadPerformPerform + 293
15  com.apple.CoreFoundation        0x00007fff9430aa01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16  com.apple.CoreFoundation        0x00007fff942fcb8d __CFRunLoopDoSources0 + 269
17  com.apple.CoreFoundation        0x00007fff942fc1bf __CFRunLoopRun + 927
18  com.apple.CoreFoundation        0x00007fff942fbbd8 CFRunLoopRunSpecific + 296
19  com.apple.HIToolbox             0x00007fff8d1cf56f RunCurrentEventLoopInMode + 235
20  com.apple.HIToolbox             0x00007fff8d1cf2ea ReceiveNextEventCommon + 431
21  com.apple.HIToolbox             0x00007fff8d1cf12b _BlockUntilNextEventMatchingListInModeWithFilter + 71
22  com.apple.AppKit                0x00007fff92a118ab _DPSNextEvent + 978
23  com.apple.AppKit                0x00007fff92a10e58 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 346
24  libosxapp.dylib                 0x000000011cf6a3aa -[NSApplicationAWT nextEventMatchingMask:untilDate:inMode:dequeue:] + 124
25  com.apple.AppKit                0x00007fff92a06af3 -[NSApplication run] + 594
26  libosxapp.dylib                 0x000000011cf6a14d +[NSApplicationAWT runAWTLoopWithApp:] + 156
27  libawt_lwawt.dylib              0x000000011d23f517 -[AWTStarter starter:] + 905
28  com.apple.Foundation            0x00007fff9747ddd0 __NSThreadPerformPerform + 293
29  com.apple.CoreFoundation        0x00007fff9430aa01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
30  com.apple.CoreFoundation        0x00007fff942fcb8d __CFRunLoopDoSources0 + 269
31  com.apple.CoreFoundation        0x00007fff942fc1bf __CFRunLoopRun + 927
32  com.apple.CoreFoundation        0x00007fff942fbbd8 CFRunLoopRunSpecific + 296
33  com.oracle.java.8u60.jdk        0x00000001000f28fb CreateExecutionEnvironment + 871
34  com.oracle.java.8u60.jdk        0x00000001000ee644 JLI_Launch + 1952
35  com.install4j.8478-6373-2628-9929.24    0x0000000100006cf4 -[Launcher launch] + 836
36  com.install4j.8478-6373-2628-9929.24    0x0000000100007381 launcher_main + 625
37  com.install4j.8478-6373-2628-9929.24    0x00000001000074f2 main + 34
38  com.install4j.8478-6373-2628-9929.24    0x0000000100001154 start + 52
</code>```

答:
The issue is caused by a crash in [JRSInputMethodController availableInputMethodLocales], which is related to the relatively old version of OSX that you're using (10.10.5).

It's ultimately a problem inside the version of Java that Apple ships with that OS version, and according to this post, the issue was fixed in 10.11.

That post also suggests that you can use the Java SE 6 installer found here, which supposedly contains a fix for the problem.

FWIW, you're not the only one with this problem, there is an (as yet unresolved) issue for Neo4j posted here.

Body:
I am totally new to neo4j. I have downloaded de software and installed it, but when I open it, it crashes immediately.

Below is the error I get. I have shorten the error text because its incredibly long.

Any ideas? I tried to reinstall, restart etc. but no luck.

Thank you in advance,

Cristina

>Process:               JavaApplicationStub [877]
Path:                  /Applications/Neo4j Community Edition 3.1.2.app/Contents/MacOS/JavaApplicationStub
Identifier:            com.install4j.8478-6373-2628-9929.24
Version:               3.1.2 (3.1.2)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           JavaApplicationStub [877]
User ID:               502

>Date/Time:             2017-03-28 13:43:24.705 +0200
OS Version:            Mac OS X 10.10.5 (14F27)
Report Version:        11
Anonymous UUID:        9E54842F-ADA5-86BD-C792-F5A255A236CE

>Time Awake Since Boot: 760 seconds

>Crashed Thread:        0  AppKit Thread  Dispatch queue: com.apple.main->thread

>Exception Type:        EXC_BAD_ACCESS (SIGABRT)
>Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000303620

>VM Regions Near 0x303620:
>-->
    __TEXT                 0000000100000000-000000010000a000 [   40K] r-x/rwx SM=COW  /Applications/Neo4j Community Edition 3.1.2.app/Contents/MacOS/JavaApplicationStub

>Application Specific Information:
abort() called

>Thread 0 Crashed:: AppKit Thread  Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff937d2286 __pthread_kill + 10
1   libsystem_c.dylib               0x00007fff94d9a9b3 abort + 129
2   libjvm.dylib                    0x0000000104482beb os::abort(bool) + 25
3   libjvm.dylib                    0x00000001045a6a2a VMError::report_and_die() + 2304
4   libjvm.dylib                    0x0000000104484816 JVM_handle_bsd_signal + 1131
5   libjvm.dylib                    0x0000000104480a7b signalHandler(int, __siginfo*, void*) + 47
6   libsystem_platform.dylib        0x00007fff8b907f1a _sigtramp + 26
7   libsystem_c.dylib               0x00007fff94d3dfb2 strlen + 18
8   com.apple.CoreFoundation        0x00007fff942c8a3c __CFStringAppendFormatCore + 8524
9   com.apple.CoreFoundation        0x00007fff943be3a0 _CFStringCreateWithFormatAndArgumentsAux2 + 256
10  com.apple.Foundation            0x00007fff973f5701 -[NSPlaceholderString initWithFormat:locale:arguments:] + 153
11  com.apple.Foundation            0x00007fff9740eef9 +[NSString stringWithFormat:] + 174
12  com.apple.java.JavaRuntimeSupport   0x000000011c276fce -[JRSInputMethodController availableInputMethodLocales] + 253
13  libawt_lwawt.dylib              0x000000011d21907f __Java_sun_lwawt_macosx_CInputMethodDescriptor_nativeGetAvailableLocales_block_invoke_1 + 124
14  com.apple.Foundation            0x00007fff9747ddd0 __NSThreadPerformPerform + 293
15  com.apple.CoreFoundation        0x00007fff9430aa01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16  com.apple.CoreFoundation        0x00007fff942fcb8d __CFRunLoopDoSources0 + 269
17  com.apple.CoreFoundation        0x00007fff942fc1bf __CFRunLoopRun + 927
18  com.apple.CoreFoundation        0x00007fff942fbbd8 CFRunLoopRunSpecific + 296
19  com.apple.HIToolbox             0x00007fff8d1cf56f RunCurrentEventLoopInMode + 235
20  com.apple.HIToolbox             0x00007fff8d1cf2ea ReceiveNextEventCommon + 431
21  com.apple.HIToolbox             0x00007fff8d1cf12b _BlockUntilNextEventMatchingListInModeWithFilter + 71
22  com.apple.AppKit                0x00007fff92a118ab _DPSNextEvent + 978
23  com.apple.AppKit                0x00007fff92a10e58 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 346
24  libosxapp.dylib                 0x000000011cf6a3aa -[NSApplicationAWT nextEventMatchingMask:untilDate:inMode:dequeue:] + 124
25  com.apple.AppKit                0x00007fff92a06af3 -[NSApplication run] + 594
26  libosxapp.dylib                 0x000000011cf6a14d +[NSApplicationAWT runAWTLoopWithApp:] + 156
27  libawt_lwawt.dylib              0x000000011d23f517 -[AWTStarter starter:] + 905
28  com.apple.Foundation            0x00007fff9747ddd0 __NSThreadPerformPerform + 293
29  com.apple.CoreFoundation        0x00007fff9430aa01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
30  com.apple.CoreFoundation        0x00007fff942fcb8d __CFRunLoopDoSources0 + 269
31  com.apple.CoreFoundation        0x00007fff942fc1bf __CFRunLoopRun + 927
32  com.apple.CoreFoundation        0x00007fff942fbbd8 CFRunLoopRunSpecific + 296
33  com.oracle.java.8u60.jdk        0x00000001000f28fb CreateExecutionEnvironment + 871
34  com.oracle.java.8u60.jdk        0x00000001000ee644 JLI_Launch + 1952
35  com.install4j.8478-6373-2628-9929.24    0x0000000100006cf4 -[Launcher launch] + 836
36  com.install4j.8478-6373-2628-9929.24    0x0000000100007381 launcher_main + 625
37  com.install4j.8478-6373-2628-9929.24    0x00000001000074f2 main + 34
38  com.install4j.8478-6373-2628-9929.24    0x0000000100001154 start + 52


问:
How a userdefined functions saved under Table valued function in sql server 2014
Im not sure whether im in right place to ask this question.
But I wonder How a function that i created fall under the table valued function? why cant it be inside scalar function?

I have the below function recorded in a Database.

```<code>IF OBJECT_ID (N'dbo.ufnGetTVP', N'FN') IS NOT NULL
    DROP FUNCTION ufnGetTVP;
GO
CREATE FUNCTION dbo.ufnGetTVP(@input varchar(50))
returns @mt table (a nvarchar(60))
AS
-- Returns the stock level for the product.
BEGIN
declare @output varchar(1)
declare @len int=(select len(@input))
while(@len>0)
begin
set @output =substring(@input,0,2)

set @input=substring(@input,charindex(@output,@input)+2,len(@input))
SET @len=len(@input)

insert into @mt
Select @OUTPUT
end
return
END;
GO
</code>```

if a function will be saved as TVF how a scalar function can created?
Please share your thoughts.

答:
As I wrote in my comment - the difference between a Scalar function and a Table valued function is only the return type of the function.

A scalar valued function is a function that returns a scalar (or single) value such as int, varchar, bit etc`, while a table valued function is a function that returns a table.

The basic syntax of creating a scalar functions is the same as the one for creating a table function:

```<code>CREATE FUNCTION <name>
(
<parameters list>
)
RETURNS <scalar type>
AS
BEGIN
    -- function code goes here
END;
</code>```

Body:
Im not sure whether im in right place to ask this question.
But I wonder How a function that i created fall under the table valued function? why cant it be inside scalar function?

I have the below function recorded in a Database.

IF OBJECT_ID (N'dbo.ufnGetTVP', N'FN') IS NOT NULL
    DROP FUNCTION ufnGetTVP;
GO
CREATE FUNCTION dbo.ufnGetTVP(@input varchar(50))
returns @mt table (a nvarchar(60))
AS
-- Returns the stock level for the product.
BEGIN
declare @output varchar(1)
declare @len int=(select len(@input))
while(@len>0)
begin
set @output =substring(@input,0,2)

set @input=substring(@input,charindex(@output,@input)+2,len(@input))
SET @len=len(@input)

insert into @mt
Select @OUTPUT
end
return
END;
GO

if a function will be saved as TVF how a scalar function can created?
Please share your thoughts.

Body:
As I wrote in my comment - the difference between a Scalar function and a Table valued function is only the return type of the function.

A scalar valued function is a function that returns a scalar (or single) value such as int, varchar, bit etc`, while a table valued function is a function that returns a table.

The basic syntax of creating a scalar functions is the same as the one for creating a table function:

CREATE FUNCTION <name>
(
<parameters list>
)
RETURNS <scalar type>
AS
BEGIN
    -- function code goes here
END;


问:
nodemailer not sending and returning error
I'm trying to setup a simple contact form using nodemailer. All i'm trying to do is send an email to my email from the contact form. My email is "myemail@mac.com"

When I do my axios post I get an error in the data object saying:  550 5.7.0 From address is not one of your addresses. but yet the status:200 and statusText:"OK"

When I use the same from email as the icloud email "myemail@mac.com" then it works ? I dont see anything where it says you have to use the same from address as the service address ?

Axios post:

```<code>  const request = axios.post('http://localhost:3002/send', {'name':John Doe,'email':meme@gmail.com'});
  request.then((result)=>{
      console.log("request = ", result);
  });
</code>```

Error message from console.log("request = ", result);

```<code>error:{
 code:"EMESSAGE",
 command:"DATA",
 response:"550 5.7.0 From address is not one of your addresses.",
 responseCode:550
}
</code>```

nodemailer is my node.js

```<code>const transporter = nodemailer.createTransport({
  service: "iCloud",
  auth: {
    user: "myemail@mac.com",
    pass: "myemailpassword"
  }
})

    app.use('/send', function(req, res){
      var message = {
        from: req.body.email,
        to: 'myemail@mac.com',
        subject: 'Message From Portfolio Contact Form',
        //text: 'Plaintext version of the message',
        html: '<p>'+req.body.description+'</p>'
      };
      transporter.sendMail(message, function(error, info){
        if(error){
          res.json({error: error});
        }else{
          res.json({success: info.response});
        };
      });
    })
</code>```

答:
You configure nodemailer transport with iCloud Service and you are trying to send a mail with a gmail adresse.

```<code>from: req.body.email, // meme@gmail.com
to: 'myemail@mac.com'
</code>```

Which logically produces the error:

response:"550 5.7.0 From address is not one of your addresses."

You probably want to do the inverse.

Body:
I'm trying to setup a simple contact form using nodemailer. All i'm trying to do is send an email to my email from the contact form. My email is "myemail@mac.com"

When I do my axios post I get an error in the data object saying:  550 5.7.0 From address is not one of your addresses. but yet the status:200 and statusText:"OK"

When I use the same from email as the icloud email "myemail@mac.com" then it works ? I dont see anything where it says you have to use the same from address as the service address ?

Axios post:

  const request = axios.post('http://localhost:3002/send', {'name':John Doe,'email':meme@gmail.com'});
  request.then((result)=>{
      console.log("request = ", result);
  });

Error message from console.log("request = ", result);

error:{
 code:"EMESSAGE",
 command:"DATA",
 response:"550 5.7.0 From address is not one of your addresses.",
 responseCode:550
}

nodemailer is my node.js

const transporter = nodemailer.createTransport({
  service: "iCloud",
  auth: {
    user: "myemail@mac.com",
    pass: "myemailpassword"
  }
})

    app.use('/send', function(req, res){
      var message = {
        from: req.body.email,
        to: 'myemail@mac.com',
        subject: 'Message From Portfolio Contact Form',
        //text: 'Plaintext version of the message',
        html: '
'+req.body.description+'
'
      };
      transporter.sendMail(message, function(error, info){
        if(error){
          res.json({error: error});
        }else{
          res.json({success: info.response});
        };
      });
    })

Body:
You configure nodemailer transport with iCloud Service and you are trying to send a mail with a gmail adresse.

from: req.body.email, // meme@gmail.com
to: 'myemail@mac.com'

Which logically produces the error:

response:"550 5.7.0 From address is not one of your addresses."

You probably want to do the inverse.


问:
jquery hover div and show another div then keep that div open
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}</code>```

home

about

contact

```

https://jsfiddle.net/7okx2Lrx/7/

答:
Change below code

```<code>$('.navigation-dropdown').toggleClass('visible');
</code>```

to

```<code>$('.navigation-dropdown').addClass('visible');
</code>```

Body:
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});

.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}

home

about

contact

https://jsfiddle.net/7okx2Lrx/7/

Body:
Change below code

$('.navigation-dropdown').toggleClass('visible');

to

$('.navigation-dropdown').addClass('visible');


问:
Cannot stop or even kill tomcat process
I started a tomcat service through ./catalina.sh start and now that I want to stop/kill it - it won't do so.

When I started it with the script, I had 2 processes:

```<code>my-user   2728   2.2  0.8  4480236 138448 s001  S     9:52AM   0:01.82 "some -Djava configurations and executables"
my-user   2737   0.0  0.0  2434840    800 s001  S+    9:53AM   0:00.00 grep tomcat
</code>```

When I run ./catalina.sh stop (or ./shutdown.sh) - it will stop only the first process. Then for the other one I try pkill -9 -f tomcat but it doesn't do the trick. And the process changes its PID basically every second, so I can't try to kill it by PID either.

Trying to shut it down through the shutdown scripts again throws an exception:

```<code>SEVERE: Catalina.stop:
java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at org.apache.catalina.startup.Catalina.stopServer(Catalina.java:450)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.stopServer(Bootstrap.java:400)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:487)
</code>```

答:
You can try using below command

    sudo kill -9 $(ps aux | grep '[c]atalina' | awk '{print $2}')

Let me know if it helps

Title: Cannot stop or even kill tomcat process

Body:
I started a tomcat service through ./catalina.sh start and now that I want to stop/kill it - it won't do so.

When I started it with the script, I had 2 processes:

my-user   2728   2.2  0.8  4480236 138448 s001  S     9:52AM   0:01.82 "some -Djava configurations and executables"
my-user   2737   0.0  0.0  2434840    800 s001  S+    9:53AM   0:00.00 grep tomcat

When I run ./catalina.sh stop (or ./shutdown.sh) - it will stop only the first process. Then for the other one I try pkill -9 -f tomcat but it doesn't do the trick. And the process changes its PID basically every second, so I can't try to kill it by PID either.

Trying to shut it down through the shutdown scripts again throws an exception:

SEVERE: Catalina.stop:
java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at org.apache.catalina.startup.Catalina.stopServer(Catalina.java:450)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.stopServer(Bootstrap.java:400)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:487)


问:
How to flip a byte in python?
I'm trying to decode a file that's a collection of reversed bytes.
Currently, my code reads and copies the file, but I want to edit some of the bytes before I write out the copy. After printing the file's binary in string format, it looks like:

b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00

...and so on. I would like to flip the bytes that read out as \x** like so:

\x01 → \x10 , \x81 → \x18 , \x40 → \x04 , \xae → \xea

答:
You want to swap the 4 first bits with the 4 last bits of the byte. Just rebuild the bytes array in a list comprehension with some shifting & masking:

```<code>>>> b = b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00'

>>> bytes(((x<<4 & 0xF0) + (x >> 4)) for x in b)
b"'\x00\x00\x00`\x00\x05\x00A\x00\x01\x00\xe0\x00\x05\x00Q\x00\x92s\x8f\x97\x82\xd3\x82\xbd\x82\xe8\x80\x00"
</code>```

Title: How to flip a byte in python?

Body:
You want to swap the 4 first bits with the 4 last bits of the byte. Just rebuild the bytes array in a list comprehension with some shifting & masking:

>>> b = b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00'

>>> bytes(((x<<4 & 0xF0) + (x >> 4)) for x in b)
b"'\x00\x00\x00`\x00\x05\x00A\x00\x01\x00\xe0\x00\x05\x00Q\x00\x92s\x8f\x97\x82\xd3\x82\xbd\x82\xe8\x80\x00"


问:
Yii2 REST: How to customize Error response?
For first I use this solution - http://www.yiiframework.com/doc-2.0/guide-rest-error-handling.html
But, I want to customize two types error.

When model validation wrong.

When something wrong (Exceptiin)

If model validation wrong i get response, like that:

```<code>{
    "success": false,
    "data": [
        {
            "field": "country_id",
            "message": "Country Id cannot be blank."
        },
        {
            "field": "currency_id",
            "message": "Currency Id cannot be blank."
        },
        {
            "field": "originator_id",
            "message": "Originator Id cannot be blank."
        }
    ]
}
</code>```

But i want like that:

```<code>{
    "success": false,
    "data": [
"errors": [
{
            "field": "country_id",
            "message": "Country Id cannot be blank."
        },
        {
            "field": "currency_id",
            "message": "Currency Id cannot be blank."
        },
        {
            "field": "originator_id",
            "message": "Originator Id cannot be blank."
        }
]

    ]
}
</code>```

Second type error i get

```<code>{
    "success": false,
    "data": {
        "name": "Exception",
        "message": "Invalid request arguments",
        "code": 0,
        "type": "yii\\base\\InvalidParamException",
        ]
    }
}
</code>```

But i Want:

```<code>{
    "success": false,
    "data": {
        "errors" : 1, <----------------
        "name": "Exception",
        "message": "Invalid request arguments",
        "code": 0,
        "type": "yii\\base\\InvalidParamException",
        ]
    }
}
</code>```

Because in anyway user get 200 Response and they don know about error or mistake.

答:
If you are using default yii/rest/Controller model with error send 422.
Use yii/rest/Controller or yii/rest/ActiveController  or extend it.
Or use own Serializer

http://www.yiiframework.com/doc-2.0/yii-rest-serializer.html

Body:
For first I use this solution - http://www.yiiframework.com/doc-2.0/guide-rest-error-handling.html
But, I want to customize two types error.

When model validation wrong.

When something wrong (Exceptiin)

If model validation wrong i get response, like that:

{
    "success": false,
    "data": [
        {
            "field": "country_id",
            "message": "Country Id cannot be blank."
        },
        {
            "field": "currency_id",
            "message": "Currency Id cannot be blank."
        },
        {
            "field": "originator_id",
            "message": "Originator Id cannot be blank."
        }
    ]
}

But i want like that:

{
    "success": false,
    "data": [
"errors": [
{
            "field": "country_id",
            "message": "Country Id cannot be blank."
        },
        {
            "field": "currency_id",
            "message": "Currency Id cannot be blank."
        },
        {
            "field": "originator_id",
            "message": "Originator Id cannot be blank."
        }
]

    ]
}

Second type error i get

{
    "success": false,
    "data": {
        "name": "Exception",
        "message": "Invalid request arguments",
        "code": 0,
        "type": "yii\\base\\InvalidParamException",
        ]
    }
}

But i Want:

{
    "success": false,
    "data": {
        "errors" : 1, <----------------
        "name": "Exception",
        "message": "Invalid request arguments",
        "code": 0,
        "type": "yii\\base\\InvalidParamException",
        ]
    }
}

Because in anyway user get 200 Response and they don know about error or mistake.