问:
sympy.MatrixSymbol : Problems with differentiation
I'm struggling with the fact that elements of sympy.MatrixSymbol don't seem to interact well with sympy's differentiation routines.

The fact that I'm trying to work with elements of sympy.MatrixSymbol rather than "normal" sympy symbols is beacause I want to autowrap a large function, and this seems that this is the only way to overcome argument limitations and enable input of a single array.

To give the reader a picture of the restrictions on possible solutions, I'll start with an overview of my intentions; however, the hasty reader might as well jump to the codeblocks below, which illustrate my problem.

Declare a vector or array of variables of some sort.

Build some expressions out of the elements of the former; these expressions are to make up the components of a vector valued function of said vector. In addition to this function, I'd like to obtain the Jacobian w.r.t. the vector.

Use autowrap (with the cython backend) to get numerical implementations of the vector function and its Jacobian. This puts some limitations on the former steps: (a) it is desired that the input of the function is given as a vector, rather than a list of symbols. (Both because there seems to be a limit to the number of inputs for an autwrapped function, and to ease interaction with scipy later on, i.e. avoid having to unpack numpy vectors to lists often).

On my journey, I ran into 2 issues:

Cython does not seem to like some sympy function, among them sympy.Max, upon which I heavily rely. The "helpers" kwarg of autowrap seems unable to handle multiple helpers at once.

This is by itself not a big deal, as I learned to circumvent it using abs() or sign(), which cython readily understands.

(see also this question on the above)

As stated before, autowrap/cython do not accept more than 509 arguments in form of symbols, at least not in my compiler setup. (See also here)

As I would prefer to give a vector rather than a list as input to the function anyways, I looked for a way to get the wrapped function to take a numpy array as input (comparable to DeferredVector + lambdify). It seems the natural way to do this is sympy.MatrixSymbol. (See thread linked above. I'm not sure there'd be an alternative, if so, suggestions are welcome.)

My latest problem then starts here: I realized that the elements of sympy.MatrixSymbol in many ways do not behave like "other" sympy symbols. One has to assign the properties real and commutative individually, which then seems to work fine though. However, my real trouble starts when trying to get the Jacobian; sympy seems not to get derivatives of the elements right out of the box:

```<code>import sympy

X= sympy.MatrixSymbol("X",10,1)

for element in X:
    element._assumptions.update({"real":True, "commutative":True})

X[0].diff(X[0])
Out[2]: Derivative(X[0, 0], X[0, 0])

X[1].diff(X[0])
Out[15]: Derivative(X[1, 0], X[0, 0])
</code>```

The following block is a minimal example of what I'd like to do, but here using normal symbols:
(I think it captures all I need, if I forgot something I'll add that later.)

```<code>import sympy
from sympy.utilities.autowrap import autowrap

X = sympy.symbols("X:2", real = True)
expr0 = X[1]*( (X[0] - abs(X[0]) ) /2)**2
expr1 = X[0]*( (X[1] - abs(X[1]) ) /2)**2
F = sympy.Matrix([expr0, expr1])
J = F.jacobian([X[0],X[1]])
J_num = autowrap(J, args = [X[0],X[1]], backend="cython")
</code>```

And here is my (currently) best guess using sympy.MatrixSymbol, which then of course fails because the Derivative-expressions within J:

```<code>X= sympy.MatrixSymbol("X",2,1)
for element in X:
    element._assumptions.update({"real":True, "commutative":True, "complex":False})
expr0 = X[1]*( (X[0] - abs(X[0]) ) /2)**2
expr1 = X[0]*( (X[1] - abs(X[1]) ) /2)**2
F = sympy.Matrix([expr0, expr1])
J = F.jacobian([X[0],X[1]])
J_num = autowrap(J, args = [X], backend="cython")
</code>```

Here is what Jlooks like after running the above:

```<code>J
Out[50]:
Matrix([
[(1 - Derivative(X[0, 0], X[0, 0])*X[0, 0]/Abs(X[0, 0]))*(-Abs(X[0, 0])/2 + X[0, 0]/2)*X[1, 0], (-Abs(X[0, 0])/2 + X[0, 0]/2)**2],
[(-Abs(X[1, 0])/2 + X[1, 0]/2)**2, (1 - Derivative(X[1, 0], X[1, 0])*X[1, 0]/Abs(X[1, 0]))*(-Abs(X[1, 0])/2 + X[1, 0]/2)*X[0, 0]]])
</code>```

Which, unsurprisingly, autowrap does not like:

```<code>[...]
wrapped_code_2.c(4): warning C4013: 'Derivative' undefined; assuming extern returning int
[...]
wrapped_code_2.obj : error LNK2001: unresolved external symbol Derivative
</code>```

How can I tell sympy that X[0].diff(X[0])=1 and X[0].diff(X[1])=0? And perhaps even that abs(X[0]).diff(X[0]) = sign(X[0]).

Or is there any way around using sympy.MatrixSymbol and still get a cythonized function, where the input is a single vector rather than a list of symbols?

Would be greatful for any input, might well be a workaround at any step of the process described above. Thanks for reading!

Edit:

One short remark: One solution I could come up with myself is this:
Construct F and J using normal symbols; then replace the symbols in both expressions by the elements of some sympy.MatrixSymbol. This seems to get the job done, but the replacement takes considerable time, as J can reach dimensions of ~1000x1000 and above. I therefore would prefer to avoid such an approach.

答:
After more extensive research, it seems the problem I was describing above is already fixed in the development/github version. After updating accordingly, all the Derivative terms involving MatrixElementare resolved correctly!

See here for reference.

Body:
I'm struggling with the fact that elements of sympy.MatrixSymbol don't seem to interact well with sympy's differentiation routines.

The fact that I'm trying to work with elements of sympy.MatrixSymbol rather than "normal" sympy symbols is beacause I want to autowrap a large function, and this seems that this is the only way to overcome argument limitations and enable input of a single array.

To give the reader a picture of the restrictions on possible solutions, I'll start with an overview of my intentions; however, the hasty reader might as well jump to the codeblocks below, which illustrate my problem.

Declare a vector or array of variables of some sort.

Build some expressions out of the elements of the former; these expressions are to make up the components of a vector valued function of said vector. In addition to this function, I'd like to obtain the Jacobian w.r.t. the vector.

Use autowrap (with the cython backend) to get numerical implementations of the vector function and its Jacobian. This puts some limitations on the former steps: (a) it is desired that the input of the function is given as a vector, rather than a list of symbols. (Both because there seems to be a limit to the number of inputs for an autwrapped function, and to ease interaction with scipy later on, i.e. avoid having to unpack numpy vectors to lists often).

On my journey, I ran into 2 issues:

Cython does not seem to like some sympy function, among them sympy.Max, upon which I heavily rely. The "helpers" kwarg of autowrap seems unable to handle multiple helpers at once.

This is by itself not a big deal, as I learned to circumvent it using abs() or sign(), which cython readily understands.

(see also this question on the above)

As stated before, autowrap/cython do not accept more than 509 arguments in form of symbols, at least not in my compiler setup. (See also here)

As I would prefer to give a vector rather than a list as input to the function anyways, I looked for a way to get the wrapped function to take a numpy array as input (comparable to DeferredVector + lambdify). It seems the natural way to do this is sympy.MatrixSymbol. (See thread linked above. I'm not sure there'd be an alternative, if so, suggestions are welcome.)

My latest problem then starts here: I realized that the elements of sympy.MatrixSymbol in many ways do not behave like "other" sympy symbols. One has to assign the properties real and commutative individually, which then seems to work fine though. However, my real trouble starts when trying to get the Jacobian; sympy seems not to get derivatives of the elements right out of the box:

import sympy

X= sympy.MatrixSymbol("X",10,1)

for element in X:
    element._assumptions.update({"real":True, "commutative":True})

X[0].diff(X[0])
Out[2]: Derivative(X[0, 0], X[0, 0])

X[1].diff(X[0])
Out[15]: Derivative(X[1, 0], X[0, 0])

The following block is a minimal example of what I'd like to do, but here using normal symbols:
(I think it captures all I need, if I forgot something I'll add that later.)

import sympy
from sympy.utilities.autowrap import autowrap

X = sympy.symbols("X:2", real = True)
expr0 = X[1]*( (X[0] - abs(X[0]) ) /2)**2
expr1 = X[0]*( (X[1] - abs(X[1]) ) /2)**2
F = sympy.Matrix([expr0, expr1])
J = F.jacobian([X[0],X[1]])
J_num = autowrap(J, args = [X[0],X[1]], backend="cython")

And here is my (currently) best guess using sympy.MatrixSymbol, which then of course fails because the Derivative-expressions within J:

X= sympy.MatrixSymbol("X",2,1)
for element in X:
    element._assumptions.update({"real":True, "commutative":True, "complex":False})
expr0 = X[1]*( (X[0] - abs(X[0]) ) /2)**2
expr1 = X[0]*( (X[1] - abs(X[1]) ) /2)**2
F = sympy.Matrix([expr0, expr1])
J = F.jacobian([X[0],X[1]])
J_num = autowrap(J, args = [X], backend="cython")

Here is what Jlooks like after running the above:

J
Out[50]:
Matrix([
[(1 - Derivative(X[0, 0], X[0, 0])*X[0, 0]/Abs(X[0, 0]))*(-Abs(X[0, 0])/2 + X[0, 0]/2)*X[1, 0], (-Abs(X[0, 0])/2 + X[0, 0]/2)**2],
[(-Abs(X[1, 0])/2 + X[1, 0]/2)**2, (1 - Derivative(X[1, 0], X[1, 0])*X[1, 0]/Abs(X[1, 0]))*(-Abs(X[1, 0])/2 + X[1, 0]/2)*X[0, 0]]])

Which, unsurprisingly, autowrap does not like:

[...]
wrapped_code_2.c(4): warning C4013: 'Derivative' undefined; assuming extern returning int
[...]
wrapped_code_2.obj : error LNK2001: unresolved external symbol Derivative

How can I tell sympy that X[0].diff(X[0])=1 and X[0].diff(X[1])=0? And perhaps even that abs(X[0]).diff(X[0]) = sign(X[0]).

Or is there any way around using sympy.MatrixSymbol and still get a cythonized function, where the input is a single vector rather than a list of symbols?

Would be greatful for any input, might well be a workaround at any step of the process described above. Thanks for reading!

Edit:

One short remark: One solution I could come up with myself is this:
Construct F and J using normal symbols; then replace the symbols in both expressions by the elements of some sympy.MatrixSymbol. This seems to get the job done, but the replacement takes considerable time, as J can reach dimensions of ~1000x1000 and above. I therefore would prefer to avoid such an approach.


来源: stackexchange

问:
Python won't let me use variable inside function
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?</p>

```<code>import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()
</code>```

答:
Add them as parameters?</p>

```<code>def run(display_w, display_h):
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?

import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()

Body:
Add them as parameters?

def run(display_w, display_h):


问:
Comprenhension doesn't return the same result as a normal for loop
In Python 2.7, I've got some code:

```<code>values = list()
for i in dict.keys():
    values.append( (i,)+dict[i] )
</code>```

That returns a values list which length is 2428.

The same, but with comprehension mode returns a list of length -> 1, each 2428 elements are nested 1 level deeper (len(values[0]) -> 2428):

```<code>values = list()
values.append( (i,)+dict[i] for i in dict.keys() )
</code>```

I simply wonder why. I must miss something.

答:
You've just appended a generator expression - a single object - to your list.

You can either extend the list with the gen. exp. which is an iterable:

```<code>values = list()
values.extend( (i,)+dct[i] for i in dct )
</code>```

Or use a list comprehension to build your list which is the more standard way:

```<code>values = [(k,)+v for k, v in dct.items()]
</code>```

Notice that I've used the items method of the dict to generate key-value pairs at a go, that .keys can be dropped when you're iterating on the dict and that dict is not a good name since it shadows the built-in dict.

You can read more about Generator expressions.

Body:
In Python 2.7, I've got some code:

values = list()
for i in dict.keys():
    values.append( (i,)+dict[i] )

That returns a values list which length is 2428.

The same, but with comprehension mode returns a list of length -> 1, each 2428 elements are nested 1 level deeper (len(values[0]) -> 2428):

values = list()
values.append( (i,)+dict[i] for i in dict.keys() )

I simply wonder why. I must miss something.

Body:
You've just appended a generator expression - a single object - to your list.

You can either extend the list with the gen. exp. which is an iterable:

values = list()
values.extend( (i,)+dct[i] for i in dct )

Or use a list comprehension to build your list which is the more standard way:

values = [(k,)+v for k, v in dct.items()]

Notice that I've used the items method of the dict to generate key-value pairs at a go, that .keys can be dropped when you're iterating on the dict and that dict is not a good name since it shadows the built-in dict.

You can read more about Generator expressions.


问:
How can I check if an element contains another element using $(this)?
I'm trying to check if an element contains an input element in the following function

```<code> $(document).on("click", ".edit_text", function() {
    if($(this).children().is("input")) {
      $(this).html("<input type='text'>")
    }
 })
</code>```

I can't figure a way of doing this as all the solutions point to using the selector such as $(".edit_text :contains(input)")

I need to use $(this) as I am using the function on elements that have a class and not on a specific element.

Is there any way of achieving this?

答:
```<code>$(this).find('input').length > 0
//or just
$(this).find('input').length
//since it is truthy.  or
$(this).find('> input').length
//if you only want to search one level deep
</code>```

Body:
I'm trying to check if an element contains an input element in the following function

 $(document).on("click", ".edit_text", function() {
    if($(this).children().is("input")) {
      $(this).html("<input type='text'>")
    }
 })

I can't figure a way of doing this as all the solutions point to using the selector such as $(".edit_text :contains(input)")

I need to use $(this) as I am using the function on elements that have a class and not on a specific element.

Is there any way of achieving this?


问:
Replacing items in list with multiple "keys" in one index
I am trying to change my list items to their actual values.  For example, this is how my data looks right now:

```<code>data = [
['student1', '"answer 1"', '"answer 2"', '"answer 3"'],
['student2', '"answer 10"', '"answer 2"', '"answer 3", "answer 4"']
</code>```

As seen in the last item in data[1], there can be multiple responses to a singular question.  My code right now is this:

```<code>def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            print (index)
            print (item)
            if index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
            print (replaced_element)
        replaced_data.append(replaced_element)
    return replaced_data
</code>```

It works fine except for the cases with multiple answers.  I was trying to use re.sub, but couldn't get it to work. (The answers I want to change the values to are stored in the dictionary answer_replacement)

答:
Ended up figuring it out a couple minutes after posting this.  Go figure.  Here's what I did:</p>

```<code>def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            if index == 5 or index == 7 or index == 8 or index == 10 or index == 12 or index == 15:
                newitem = item.split(',')
                temp = []
                for item in newitem:
                    item = item.strip()
                    temp.append(re.sub(item, answer_replacement[index][item], item))
                replaced_element.append(temp)
            elif index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
        replaced_data.append(replaced_element)
    return replaced_data
</code>```

Body:
I am trying to change my list items to their actual values.  For example, this is how my data looks right now:

data = [
['student1', '"answer 1"', '"answer 2"', '"answer 3"'],
['student2', '"answer 10"', '"answer 2"', '"answer 3", "answer 4"']

As seen in the last item in data[1], there can be multiple responses to a singular question.  My code right now is this:

def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            print (index)
            print (item)
            if index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
            print (replaced_element)
        replaced_data.append(replaced_element)
    return replaced_data

It works fine except for the cases with multiple answers.  I was trying to use re.sub, but couldn't get it to work. (The answers I want to change the values to are stored in the dictionary answer_replacement)

Body:
Ended up figuring it out a couple minutes after posting this.  Go figure.  Here's what I did:

def answer_replace(data):
    replaced_data = []
    for element in data:
        replaced_element = []
        for index, item in enumerate(element):
            if index == 5 or index == 7 or index == 8 or index == 10 or index == 12 or index == 15:
                newitem = item.split(',')
                temp = []
                for item in newitem:
                    item = item.strip()
                    temp.append(re.sub(item, answer_replacement[index][item], item))
                replaced_element.append(temp)
            elif index in answer_replacement:
                replaced_element.append(answer_replacement[index].get(item, item))
            else:  # no replacement available for this index
                replaced_element.append(item)
        replaced_data.append(replaced_element)
    return replaced_data


问:
Referencing symbols in other files using PPC assembly
How can you reference a symbol external to the current file in ppc assembly? I've tried looking at the .extern keyword as well as adding a new symbol in the linker file but with no success.

I have two ppc assembly files that are part of a larger project. I wish to reference a symbol (__head) in file1 from file2 in this way:

file1.S:

```<code>    .section ".head","ax"

    . = 0
.global __head
__head:
</code>```

file2.S:

```<code>    .section ".head","ax"
...
    LOAD_32(%r3, file2_symbol_name - __head)
</code>```

where LOAD_32 is

```<code>#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;
</code>```

...but am getting the following error:

```<code>file2.S: Assembler messages:
file2.S:113: Error: can't resolve `file2_symbol_name' {.head section} - `__head' {*UND* section}
file2.S:113: Error: expression too complex
</code>```

When used in file1 LOAD_32(%r3, file1_symbol_name - __head) works just fine so I know I'm not importing the symbol name correctly.  How can I do this?

EDIT:

I have reduced my problem to the bare minimum parts so that I am clear about the problem. Below is all of the code, linker file, Makefile, and the terminal output for "make quick".

NB: When I comment out line 9 of other.S the project compiles without error.

head.S:

```<code>#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

    . = 0x0

.global __head
__head:
    LOAD_32(%r3, file1_symbol_name - __head)
    b   .

file1_symbol_name:
    b   .
</code>```

other.S

```<code>#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

.global other
other:
    LOAD_32(%r3, file2_symbol_name)
    LOAD_32(%r3, file2_symbol_name - __head)
    b   .

file2_symbol_name:
    b   .
</code>```

asm-defines.h:

```<code>#ifndef ASM_DEFINES_H
#define ASM_DEFINES_H

/* Load an immediate 32-bit value into a register */
#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

#endif //ASM_DEFINES_H
</code>```

quick.lds

```<code>ENTRY(__head);
</code>```

Makefile

```<code>CC=$(CROSS)gcc
QFLAGS := -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib

quick:
    $(CC) $(QFLAGS) -T quick.lds head.S other.S -o quick.o
</code>```

$(CROSS) is a path to the cross compiler which I have omitted.
The CC is powerpc64le-buildroot-linux-gnu-gcc

Terminal

```<code>$ make quick
powerpc64le-buildroot-linux-gnu-gcc -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib -T quick.lds head.S other.S -o quick.o
other.S: Assembler messages:
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
make: *** [quick] Error 1
</code>```

答:
Regarding David's response, see https://sourceware.org/binutils/docs/as/Infix-Ops.html#Infix-Ops, where it specifies:  "Subtraction. If the right argument is absolute, the result has the section of the left argument. If both arguments are in the same section, the result is absolute. You may not subtract arguments from different sections."  The error message indicates that the assembler has no idea which section contains __head, which indeed it cannot, since the symbol and its section are not defined in filescope.

You might be able to get what you want by using the .weak and/or .weakref directives so that the symbol can be defined in two files, with the strong reference overriding the weak one at link time.  I haven't experimented with this.  See the manual (https://sourceware.org/binutils/docs/as/) and hunt for .weak.

Some background information on weak symbols is here:  https://en.wikipedia.org/wiki/Weak_symbol.

Body:
How can you reference a symbol external to the current file in ppc assembly? I've tried looking at the .extern keyword as well as adding a new symbol in the linker file but with no success.

I have two ppc assembly files that are part of a larger project. I wish to reference a symbol (__head) in file1 from file2 in this way:

file1.S:

    .section ".head","ax"

    . = 0
.global __head
__head:

file2.S:

    .section ".head","ax"
...
    LOAD_32(%r3, file2_symbol_name - __head)

where LOAD_32 is

#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

...but am getting the following error:

file2.S: Assembler messages:
file2.S:113: Error: can't resolve `file2_symbol_name' {.head section} - `__head' {*UND* section}
file2.S:113: Error: expression too complex

When used in file1 LOAD_32(%r3, file1_symbol_name - __head) works just fine so I know I'm not importing the symbol name correctly.  How can I do this?

EDIT:

I have reduced my problem to the bare minimum parts so that I am clear about the problem. Below is all of the code, linker file, Makefile, and the terminal output for "make quick".

NB: When I comment out line 9 of other.S the project compiles without error.

head.S:

#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

    . = 0x0

.global __head
__head:
    LOAD_32(%r3, file1_symbol_name - __head)
    b   .

file1_symbol_name:
    b   .

other.S

#include "asm-defines.h"

    .section ".head","ax"
    .align 0x10

.global other
other:
    LOAD_32(%r3, file2_symbol_name)
    LOAD_32(%r3, file2_symbol_name - __head)
    b   .

file2_symbol_name:
    b   .

asm-defines.h:

#ifndef ASM_DEFINES_H
#define ASM_DEFINES_H

/* Load an immediate 32-bit value into a register */
#define LOAD_32(r, e)           \
    lis     r,(e)@h;            \
    ori     r,r,(e)@l;

#endif //ASM_DEFINES_H

quick.lds

ENTRY(__head);

Makefile

CC=$(CROSS)gcc
QFLAGS := -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib

quick:
    $(CC) $(QFLAGS) -T quick.lds head.S other.S -o quick.o

$(CROSS) is a path to the cross compiler which I have omitted.
The CC is powerpc64le-buildroot-linux-gnu-gcc

Terminal

$ make quick
powerpc64le-buildroot-linux-gnu-gcc -Wl,--oformat,elf64-powerpc -pie -m64 -mbig-endian -nostdlib -T quick.lds head.S other.S -o quick.o
other.S: Assembler messages:
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
other.S:9: Error: can't resolve `.head' {.head section} - `__head' {*UND* section}
other.S:9: Error: expression too complex
make: *** [quick] Error 1


问:
System.Threading.Timer trying to make timer for same time every day
I am using System.Threading.Timer in a console service app, and trying to make timer for same time every day.

Initially I am good if I start the app prior to the time.  Like if my time is 10:05 and I start the app at 10:00 we are good. But if I start at 10:06 I dont know how to tell the timespan to go 24 hours ahead.

Thanks for any help!

```<code>public void SetUpTimer(TimeSpan alertTime)
{
    DateTime current = DateTime.Now;
    TimeSpan timeToGo = alertTime - current.TimeOfDay;

    if (timeToGo < TimeSpan.Zero)
    {
        EventLog.WriteEntry("MyApp", "Timer Passed  " );

        return;//time already passed
    }

    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    },  null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}
</code>```

答:
Here's one way to do it:</p>

```<code>public void SetUpTimer(TimeSpan alertTime)
{
    DateTime targetDateTime = DateTime.Today.Add(alertTime);
    if (targetDateTime < DateTime.Now)
    {
        targetDateTime = targetDateTime.AddDays(1);
    }
    TimeSpan timeToGo = targetDateTime - DateTime.Now;
    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    }, null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}
</code>```

Body:
I am using System.Threading.Timer in a console service app, and trying to make timer for same time every day.

Initially I am good if I start the app prior to the time.  Like if my time is 10:05 and I start the app at 10:00 we are good. But if I start at 10:06 I dont know how to tell the timespan to go 24 hours ahead.

Thanks for any help!

public void SetUpTimer(TimeSpan alertTime)
{
    DateTime current = DateTime.Now;
    TimeSpan timeToGo = alertTime - current.TimeOfDay;

    if (timeToGo < TimeSpan.Zero)
    {
        EventLog.WriteEntry("MyApp", "Timer Passed  " );

        return;//time already passed
    }

    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    },  null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}

Body:
Here's one way to do it:

public void SetUpTimer(TimeSpan alertTime)
{
    DateTime targetDateTime = DateTime.Today.Add(alertTime);
    if (targetDateTime < DateTime.Now)
    {
        targetDateTime = targetDateTime.AddDays(1);
    }
    TimeSpan timeToGo = targetDateTime - DateTime.Now;
    timer = new System.Threading.Timer(x =>
    {
        EventLog.WriteEntry("MhyApp", "Timer Set  " + timeToGo);

        this.MethodRunsAt();
    }, null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}


问:
Why do we wrap a SSL public key with a certificate?
With some research I know

how the public/private keys work

SSL certificate wraps the public key

given a Certificate Signing Requests (CSR), Certificate Authorities (CA) issues certificates

when an user first connects to an SSL-secured website, the user first verifies the certificate with a trusted third party

I read that SSL certificates promise users that they are connecting to the party which they think they are connecting to. What does this mean? What extra security does wrapping the public key provide us, as opposed to just having the public key itself? An example would be greatly appreciated.

E.g. If Facebook only gives me its public key, instead of an SSL certificate wrapping the public key, what dangers would I be exposed to? Is making sure the address bar reading https://www.facebook.com/ not enough?

答:
Is making sure the address bar reading https://www.facebook.com/ not enough?

A public key doesn't have a name, so you'd connect to a host, and it would give you a key, and that would be it.  If an attacker was able to intercept your request they'd just give you their own public key and you'd not have any way of knowing he wasn't facebook.com

what dangers would I be exposed to?

Man-in-the-middle is the main threat.  The defenses against it are all in the certificate:

The certificate SubjectAltNames extension or Subject value say what the intended property is for a certificate.

The certificate says who issued it.  So you can say "yeah? sez who?", and it says "Well, says VeriSign".

Then you can look to see if VeriSign is someone that you're comfortable with making the trust decision for you (that is, is VeriSign in your root trust list)

A CA can keep track of when a client has reported their key as stolen, so the CA can mark the certificate as revoked.

This means that even though it says it's good for facebook.com, the CA says it's good for nothing, and probably you're talking to the person who stole it, not with facebook.com.


问:
How to use SignalR with aspnetcore 2.0.0 preview
I am trying to use SignalR with aspnetcore 2.0.0 preview. The preview version is supposed to have support for signalR as per the release notes and I can add references to the "Microsoft.aspnetcoreSignalR" package.

However, I am unable to find the MapSignalR extension method or something like useSignalR() on the IApplicationBuilder.

Googling around for this gives lots of examples of the UseAppBuilder extension method. However, I still get stuck at MapSignalR with the below code:

```<code>using Microsoft.AspNetCore.Builder;

using Microsoft.Owin.Mapping;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Builder;
using Owin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyNamespace
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public static class SignalRExtensions
    {

        public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    configure(appBuilder);

                    return appBuilder.Build<AppFunc>();
                });
            });

            return app;
        }

        public static void UseSignalR2(this IApplicationBuilder app)
        {
            app.UseAppBuilder(appBuilder => appBuilder.MapSignalR());
        }
    }
}
</code>```

This is unable to find the MapSignalR extension method. Any thoughts on if I can find this some nuget package that will work with aspnetcore? Or is there a different mechanism to initialize signalR with aspnetcore 2.0.0 preview?
I am using visual studio 2017 preview 15.3 with .Net core 2.0 preview installed.

答: I basically hada the wrong set of nugget references. If I only have aspnetcore 2.0.0 preview 1 and the corresponding Microsoft.aspnetcore.signalR 1.0.0 preview package, there is already a UseSignalR() method available as an extension method for IApplicationBuilder and we don't need any of the above code.

Body:
I am trying to use SignalR with aspnetcore 2.0.0 preview. The preview version is supposed to have support for signalR as per the release notes and I can add references to the "Microsoft.aspnetcoreSignalR" package.

However, I am unable to find the MapSignalR extension method or something like useSignalR() on the IApplicationBuilder.

Googling around for this gives lots of examples of the UseAppBuilder extension method. However, I still get stuck at MapSignalR with the below code:

using Microsoft.AspNetCore.Builder;

using Microsoft.Owin.Mapping;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Builder;
using Owin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyNamespace
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public static class SignalRExtensions
    {

        public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    configure(appBuilder);

                    return appBuilder.Build<AppFunc>();
                });
            });

            return app;
        }

        public static void UseSignalR2(this IApplicationBuilder app)
        {
            app.UseAppBuilder(appBuilder => appBuilder.MapSignalR());
        }
    }
}

This is unable to find the MapSignalR extension method. Any thoughts on if I can find this some nuget package that will work with aspnetcore? Or is there a different mechanism to initialize signalR with aspnetcore 2.0.0 preview?
I am using visual studio 2017 preview 15.3 with .Net core 2.0 preview installed.


答:
This isn't totally clear what you're doing, but the modifications to your code below should get you going in the right direction:</p>

```<code>$(document).on("click", ".edit_text", function() {
    // search for an 'input' element within the context of the clicked element
    // .length will be > 0 if any are found
    if( $('input', this).length ) {
      $(this).html("<input type='text'>")
    }
});
</code>```

Title: How can I check if an element contains another element using $(this)?

Body:
This isn't totally clear what you're doing, but the modifications to your code below should get you going in the right direction:

$(document).on("click", ".edit_text", function() {
    // search for an 'input' element within the context of the clicked element
    // .length will be > 0 if any are found
    if( $('input', this).length ) {
      $(this).html("<input type='text'>")
    }
});


问:
First steps in python: how to combine two lists
So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".

No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.

Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.

I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.

It just gives me the two names first and then the two ages.

Is anyone happy to help me with this beginner problem?

Thanks in advance

```<code>catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
          nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for name in catNames:
            print(" " + name)
        for age in catAges:
            print(" " + age)
        break
    catNames = catNames + [name]
    catAges = catAges + [age]
</code>```

答:
In general you would use dictionaries for this kind of task.

But if you were to use lists for your problem, it could be implemented like this:

```<code>catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for i in range(len(catNames)):
            print("Cat number",i, "has the name", catNames[i], "and is", catAges[i], "years old")
        break

    catNames = catNames + [name]
    catAges = catAges + [age]
</code>```

Body:
So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".

No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.

Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.

I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.

It just gives me the two names first and then the two ages.

Is anyone happy to help me with this beginner problem?

Thanks in advance

catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
          nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for name in catNames:
            print(" " + name)
        for age in catAges:
            print(" " + age)
        break
    catNames = catNames + [name]
    catAges = catAges + [age]

Body:
In general you would use dictionaries for this kind of task.

But if you were to use lists for your problem, it could be implemented like this:

catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for i in range(len(catNames)):
            print("Cat number",i, "has the name", catNames[i], "and is", catAges[i], "years old")
        break

    catNames = catNames + [name]
    catAges = catAges + [age]


问:
Why use JS for Image Rollovers When I can use CSS?
I am making my way through Lynda.com's JS tutorial, and they have a whole chapter on image rollevers for buttons.  Why would I use JS when I could just use CSS-- to create image rollevers?</p>

答:
At the time of those writings, the :hover pseudo class did not exist and/or was not supported by all browsers. Therefore, javascript was the preferred method of achieving the rollover effect.

Nowadays the CSS :hover pseudo class exists and is supported in all major browsers; therefore, the CSS method is preferred.

ContentLicense: CC BY-SA 2.5


问:
How to save file under different name in vi
I am frequently editting a file in vi and I want to save it under a different name than the name that I opened it under.

I have tried saving like this:  :w >> new_file_name but I ALWAYS get E212: Can't open file for writing.

What is the correct way around this?

答:
```<code>:w filename
</code>```

Will save to filename

Body:
:w filename

Will save to filename


问:
REST API: Design API to let user submit POST something and GET some value other than created Id in response
It's bit lengthy but simple to understand so please read it.

We have a feedback form where the user fills the complaint/suggestions. To fill a complaint, the user needs to fill his/her {Name, Mobile Number, ZipCode}. As a response to this complaint, we show our nearest call center number based on user's pin code.

Once the user submits the feedback [name, mobile, zip code], the complete process is:

The user sees nearest customer care contact number upfront on the screen.

New Complaint is registered in the database.

This process needs to be integrated across platforms (Mobile, Desktop, Apps) and we need to design Restful APIs for this. Few choices:

GET /api/complaint/?mobile={mobile}&name={name}&zip={zipcode}. This API would send back nearest call center number in response, save record in complaint table. But this does not look restful as we are adding database records with GET request.

POST /api/complaint/ with {mobile},{name},{zipcode} in the request body. This too can do all above things but the problem here is that as per rest where we send back new created object in POST response, here we would send back nearest customer call center number which has nothing to do with complaint record creation in the database.

Create two separate APIs, first POST /api/complaint/ with {mobile},{name} that would insert a record in the complaint table. And second, create GET /api/callcenter/?zip={zipcode} which returns back the customer care number of that zipcode. There are few problems here like two APIs are decoupled so what if POST is unsuccessful while GET is executed OR vice versa? Also, hitting these two sequentially would be slow?

Which of these 3 is correct OR is there any 4th way to solve this problem?

答: I actually like the 3rd option. A failed post shouldn't affect the ability to get the nearest call center right? A failed post would be a problem in the second option as well. These call centers should already be in database. I'm sure you'll have some code/subroutine to calculate the shortest distance between any given zip code and all of the call centers. And in the third option, even though a complaint wouldn't be filed in a failed post, at least the user could get the number of the nearest call center to continue to get help</p>


问:
Is this failing radio button feature test a Capybara syntax issue?
I have a form with a radio button for a boolean attr prev_cover, displays Yes or No in browser with param values of true or false and saved in db as true or false as data type boolean. I am trying to:

a) model test presence of a selection of the radio buttons

b) feature test the creation of a whole quote record.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('No') } the create_quote_spec test fails, model quote.rb test passes.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('Yes') } the create_quote_spec test passes, model quote.rb test passes.

In actual manual browser testing the db record is created when either Yes or No is selected.

When I remove presence validation of prev_cover from quote.rb the create_quote_spec passes with with prev_cover Yes or No selected, but of course the model quote_spec.rb test fails.

I cannot see where the problem is here, is it something to do with the capybara within(".quote_prev_cover") { choose('No') } syntax perhaps? (it finds that css element just fine)

Here's form element of new.html.erb

```<code><div class='container'>
    <div class='row'>
        <div class='col-md-6'>
            <%= simple_form_for @quote do |f| %>
                <%= f.input :prev_cover, as: :radio_buttons, label: "Previous cover" %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>
        </div>
    </div>
</div>
</code>```

Here's quote.rb validation;

```<code>validates :prev_cover, inclusion: { in: [true, false] }
</code>```

Here's prev_cover element of the called NewQuoteFrom.new being created by Capybara;

```<code>within(".quote_prev_cover") { choose('No') }
</code>```

Here's test that fails if chooses prev_cover 'No' and passes if chooses 'Yes', create_quote_spec.rb

```<code>feature 'creating quote request' do
let(:user) { FactoryGirl.create(:user) }
let(:new_quote_form) { NewQuoteForm.new }

before do
    login_as(user, :scope => :user)
end

scenario 'completing quote data' do
    new_quote_form.visit_page.fill_in_with().submit
    expect(page).to have_content('Quote request created')
end
</code>```

here's the model test that passes whilst model validation is present, quote_spec.rb;

```<code>    context 'previous cover' do
        it 'must be true or false' do
            quote = Quote.new(prev_cover: nil)
            quote.valid?
            expect(quote.errors[:prev_cover]).not_to be_empty
        end
    end
</code>```

Failing test message:

```<code>1) creating quote request completing quote data
 Failure/Error: expect(page).to have_content('Quote request created')
   expected to find text "Quote request created" in "Toggle navigation QuoteEngine My Quotes My Account Sign out Complete the below to get a quote * GLA Previous coverYesNois not included in the list * Company name * Company number * Postcode * Industry Financial services Architect Business consultancy Lives overseasYesNo Scheme start date 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 January February March April May June July August September October November December 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Payment frequency Annually Monthly Commission level"
 # ./spec/features/create_quote_spec.rb:14:in `block (2 levels) in <top (required)>'
</code>```

Note the YesNois not included in the list in the error message, using any variation of true or false in the Capybara instruction does not work either.

Even specifying:

```<code><%= f.input :prev_cover, as: :radio_buttons, :collection => [['Yes', true],
                                    ['No', false]], label: "Previous cover" %>
</code>```

in the simpl_form_for in the new.html.erb view still results in the failure with the validation giving Previous coverYesNois not included in the list!?

Even within(".quote_prev_cover") { choose('quote_prev_cover_false') } still fails with the same Previous coverYesNois not included in the list.

It passes if told to choose Yes within(".quote_prev_cover") { choose('Yes') }, almost asif I hadn't already changed from presence: to inclusion: which I most certainly have done.

Actual HTML from firefox inspector:

```<code><div class="form-group radio_buttons optional quote_prev_cover">
  <label class="control-label radio_buttons optional">Previous cover</label>
    <input name="quote[prev_cover]" value="" type="hidden">
        <span class="radio">
            <label for="quote_prev_cover_true">
                <input class="radio_buttons optional" value="true" name="quote[prev_cover]" id="quote_prev_cover_true" type="radio">Yes</label>
        </span>
        <span class="radio">
            <label for="quote_prev_cover_false">
                <input class="radio_buttons optional" readonly="readonly" value="false" name="quote[prev_cover]" id="quote_prev_cover_false" type="radio">No</label>
        </span>
    </div>
</code>```

答:
The issue causing the failure of this Capybara test trying to create a quote record was that it was unable to select the No/false value of a boolean radio button, which due to a simple_form bug had readonly="readonly" set. There are two solutions, courtesy of this post here

1) Within config/initializers/simple_form_bootstrap.rb comment out b.optional :readonly within the :vertical_radio_and_checkboxes wrapper.

2) set your simple form arguments as below:

```<code><%= f.input :prev_cover, as: :radio_buttons, collection: [['Yes', true],
                        ['No', false]], readonly: nil %>
</code>```

Though option 2 still has Capybara giving you a warning when you run your tests of; Attempt to set readonly element with value: true * This will raise an exception in a future version of Capybara

Thanks to #ThomasWalpole helping me along the way and to platformatec maintainers.

Body:
I have a form with a radio button for a boolean attr prev_cover, displays Yes or No in browser with param values of true or false and saved in db as true or false as data type boolean. I am trying to:

a) model test presence of a selection of the radio buttons

b) feature test the creation of a whole quote record.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('No') } the create_quote_spec test fails, model quote.rb test passes.

With validation of prev_cover in place, I tell capybara to within(".quote_prev_cover") { choose('Yes') } the create_quote_spec test passes, model quote.rb test passes.

In actual manual browser testing the db record is created when either Yes or No is selected.

When I remove presence validation of prev_cover from quote.rb the create_quote_spec passes with with prev_cover Yes or No selected, but of course the model quote_spec.rb test fails.

I cannot see where the problem is here, is it something to do with the capybara within(".quote_prev_cover") { choose('No') } syntax perhaps? (it finds that css element just fine)

Here's form element of new.html.erb

            <%= simple_form_for @quote do |f| %>
                <%= f.input :prev_cover, as: :radio_buttons, label: "Previous cover" %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>

Here's quote.rb validation;

validates :prev_cover, inclusion: { in: [true, false] }

Here's prev_cover element of the called NewQuoteFrom.new being created by Capybara;

within(".quote_prev_cover") { choose('No') }

Here's test that fails if chooses prev_cover 'No' and passes if chooses 'Yes', create_quote_spec.rb

feature 'creating quote request' do
let(:user) { FactoryGirl.create(:user) }
let(:new_quote_form) { NewQuoteForm.new }

before do
    login_as(user, :scope => :user)
end

scenario 'completing quote data' do
    new_quote_form.visit_page.fill_in_with().submit
    expect(page).to have_content('Quote request created')
end

here's the model test that passes whilst model validation is present, quote_spec.rb;

    context 'previous cover' do
        it 'must be true or false' do
            quote = Quote.new(prev_cover: nil)
            quote.valid?
            expect(quote.errors[:prev_cover]).not_to be_empty
        end
    end

Failing test message:

1) creating quote request completing quote data
 Failure/Error: expect(page).to have_content('Quote request created')
   expected to find text "Quote request created" in "Toggle navigation QuoteEngine My Quotes My Account Sign out Complete the below to get a quote * GLA Previous coverYesNois not included in the list * Company name * Company number * Postcode * Industry Financial services Architect Business consultancy Lives overseasYesNo Scheme start date 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 January February March April May June July August September October November December 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Payment frequency Annually Monthly Commission level"
 # ./spec/features/create_quote_spec.rb:14:in `block (2 levels) in <top (required)>'

Note the YesNois not included in the list in the error message, using any variation of true or false in the Capybara instruction does not work either.

Even specifying:

<%= f.input :prev_cover, as: :radio_buttons, :collection => [['Yes', true],
                                    ['No', false]], label: "Previous cover" %>

in the simpl_form_for in the new.html.erb view still results in the failure with the validation giving Previous coverYesNois not included in the list!?

Even within(".quote_prev_cover") { choose('quote_prev_cover_false') } still fails with the same Previous coverYesNois not included in the list.

It passes if told to choose Yes within(".quote_prev_cover") { choose('Yes') }, almost asif I hadn't already changed from presence: to inclusion: which I most certainly have done.

Actual HTML from firefox inspector:

  Previous cover
    <input name="quote[prev_cover]" value="" type="hidden">

                <input class="radio_buttons optional" value="true" name="quote[prev_cover]" id="quote_prev_cover_true" type="radio">Yes

                <input class="radio_buttons optional" readonly="readonly" value="false" name="quote[prev_cover]" id="quote_prev_cover_false" type="radio">No

Body:
The issue causing the failure of this Capybara test trying to create a quote record was that it was unable to select the No/false value of a boolean radio button, which due to a simple_form bug had readonly="readonly" set. There are two solutions, courtesy of this post here

1) Within config/initializers/simple_form_bootstrap.rb comment out b.optional :readonly within the :vertical_radio_and_checkboxes wrapper.

2) set your simple form arguments as below:

<%= f.input :prev_cover, as: :radio_buttons, collection: [['Yes', true],
                        ['No', false]], readonly: nil %>

Though option 2 still has Capybara giving you a warning when you run your tests of; Attempt to set readonly element with value: true * This will raise an exception in a future version of Capybara

Thanks to #ThomasWalpole helping me along the way and to platformatec maintainers.


问:
Error on npm -install package.json not found
Error message:

https://ibb.co/m00A2a -

This is the error I am getting every time and idk how to say this, but some times after 5 min of waiting a node_modules folder is created and I have the library/framework in there and some times it doesn't happen.

答:
For anyone that has the same error this how you fix it

```<code>npm install bower -g
</code>```

this installs bower and then in your project folder instead of typing
npm install jquery you type bower install jquery

Body:
For anyone that has the same error this how you fix it

npm install bower -g

this installs bower and then in your project folder instead of typing
npm install jquery you type bower install jquery


问:
socialmedia status comment system
I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:

---POST MESSAGE----

-----comments-----

Here is the code I used:

```<code><?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];

$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");

while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
    $status= $r['post'];
    $date=$r['date'];
    $com=$r['comment'];
    $pid=$r['id'];
    $poster=$r['poster'];
    if(count($pid) > 1){

    }

    echo $status.'|'.$pid.'|'.$date.'<br>'.$poster.':'.$com.'<hr>';

}

?>
</code>```

It seems to duplicate the post for each comment for same post.

Not sure am making sense, but i will appreciate an answer.

答:
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)

```<code>... ORDER BY post.date, post.id, post_comments.date
</code>```

Then keep track of the post id as you go. Echo the post information only when the post id changes.

```<code>$id = null;   // initialize to null

while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {

    $pid = $r['id'];
    $status = $r['post'];
    $date = $r['date'];
    $com = $r['comment'];
    $poster = $r['poster'];

    if ($pid !== $id) {
        echo $status.'|'.$pid.'|'.$date.'<br>';    // new post, so echo post info here
        $id = $pid;                                // $id becomes new post id
    }
    if ($com) {
        echo $poster.':'.$com.'<br>';              // echo comment if present
    }
}
</code>```

One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.

Title: socialmedia status comment system

Body:
I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:

---POST MESSAGE----

-----comments-----

Here is the code I used:

<?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];

$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");

while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
    $status= $r['post'];
    $date=$r['date'];
    $com=$r['comment'];
    $pid=$r['id'];
    $poster=$r['poster'];
    if(count($pid) > 1){

    }

    echo $status.'|'.$pid.'|'.$date.'
'.$poster.':'.$com.'
';

}

?>

It seems to duplicate the post for each comment for same post.

Not sure am making sense, but i will appreciate an answer.

Body:
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)

... ORDER BY post.date, post.id, post_comments.date

Then keep track of the post id as you go. Echo the post information only when the post id changes.

$id = null;   // initialize to null

while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {

    $pid = $r['id'];
    $status = $r['post'];
    $date = $r['date'];
    $com = $r['comment'];
    $poster = $r['poster'];

    if ($pid !== $id) {
        echo $status.'|'.$pid.'|'.$date.'<br>';    // new post, so echo post info here
        $id = $pid;                                // $id becomes new post id
    }
    if ($com) {
        echo $poster.':'.$com.'<br>';              // echo comment if present
    }
}

One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.


问:
Python - remove a word or matching string from a text file
I am trying to remove a word from a text file and found a code that seems to be working.

However, it doesn't match an exact word, instead removes all matching letters.

```<code>fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')
</code>```

input.txt

```<code>http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt
</code>```

Result for trying to remove http:// (only) is as following-

output.txt

```<code>www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m
</code>```

答:
I just started coding so don't know how ugly is this solution looks, but re module seems fine.

```<code>from re import sub
with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    file[i] = sub(r'http[s]?://', '', file[i])
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])
</code>```

or if you don't want to use re module, you can use if statement instead

```<code>with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    if file[i].startswith('https://'):
        link = file[i]
        file[i] = link[8:]
    elif file[i].startswith('http://'):
        link = file[i]
        file[i] = link[7:]
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])
</code>```

Body:
I am trying to remove a word from a text file and found a code that seems to be working.

However, it doesn't match an exact word, instead removes all matching letters.

fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')

input.txt

http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt

Result for trying to remove http:// (only) is as following-

output.txt

www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m

Body:
I just started coding so don't know how ugly is this solution looks, but re module seems fine.

from re import sub
with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    file[i] = sub(r'http[s]?://', '', file[i])
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])

or if you don't want to use re module, you can use if statement instead

with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    if file[i].startswith('https://'):
        link = file[i]
        file[i] = link[8:]
    elif file[i].startswith('http://'):
        link = file[i]
        file[i] = link[7:]
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])


问:
create sql database from sql express database
I am working on asp.net membership website. I created the membership provider automatically, and now its stored in sql express database within the solution. I want to move all the tables to sql database instead of sql express. Last night I attached the sql express database to the sql server management studio, and I was able to see all the objects. Then, I run my solution in visual studio, and I got error: LOGIN FAILED for the sql express database, and the solution wasn't running.
I have two questions.
1. Why is that happening?
2. If I create the same database in sql server with the same objects, and then point to the sql server database instead of sql express database, will I have problems with the membershop provider?
Thanks in advance.</p>

答:
Attaching a database to a new server does not automatically create the necessary logins.

run exec sp_change_users_login  'Report' from within SSMS on your database.

If it comes back with anything in the result set, you'll need to run exec sp_change_users_login 'Auto_Fix', '<username>'

where  is the username from the first result set.


问:
How to transfer materials with a scene created in Blender to unity
I have created a scene in Blender with multiple objects, and each object has a material/texture. When I save the scene in my assets of my Unity project, I am able to use the scene, but all of the objects are white and have lost the materials I created and added to them in Blender. Is there a way to save my scene in Blender so that the materials will also be saved to the objects for when I use the scene in Unity? Or do I need to save all the materials from Blender separately into a file and also put that in my assets folder? </p>

答: As Hellium said, if your textures are in separate archives (.png) you can create materials in unity and add those png textures as albedo</p>


问:
Color coding html table cell based on SQL flag value
So I finally have a SQL query working to take 3 conditions from my DB table and set a flag based on them.

Here is the Statement:

```<code>UPDATE staging
SET  `miuFlag` =1
WHERE  `lowSideMIUNumArriv` =    `lowSideMIUNumDepart`
AND  `miu` =  "No"
</code>```

Now my database table has a column called 'miuFlag' with either ones or zeroes. Based on this value, I want one of my html table values to be red or green (0=red, 1=green).

Here is the affected html table row:

```<code>        <td><? echo $row['miu'];?> </td>
</code>```

I know I can color this row's font by using style inside of the td element, but how exactly would I create the condition to style one color for miuFlag = 0 and another for miuFlag = 1?

答:
I think it would be something like this:</p>

```<code><td class="<? echo ($row['miu'] == 0) ? "redstyle" : "greenstyle"); ?>"> </td>
</code>```

Body:
So I finally have a SQL query working to take 3 conditions from my DB table and set a flag based on them.

Here is the Statement:

UPDATE staging
SET  `miuFlag` =1
WHERE  `lowSideMIUNumArriv` =    `lowSideMIUNumDepart`
AND  `miu` =  "No"

Now my database table has a column called 'miuFlag' with either ones or zeroes. Based on this value, I want one of my html table values to be red or green (0=red, 1=green).

Here is the affected html table row:

        <? echo $row['miu'];?>

I know I can color this row's font by using style inside of the td element, but how exactly would I create the condition to style one color for miuFlag = 0 and another for miuFlag = 1?

Body:
I think it would be something like this:

<td class="<? echo ($row['miu'] == 0) ? "redstyle" : "greenstyle"); ?>">&nbsp;</td>


问:
Add to ArrayList from different WebForms
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

```<code>    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }
</code>```

```<code>    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }
</code>```

答:
There were a number of issues in that code. When the user clicks Add, first thing is retrieving the list from session, not storing into session. After adding an item to the list, we need to update session.

WebForm1

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray = (ArrayList)Session["FullNameApplicantArray"] ?? new ArrayList();
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");

    foreach (var item in FullNameApplicantArray)
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
    Session["FullNameApplicantArray"] = FullNameApplicantArray;
}

protected void Button2_Click(object sender, EventArgs e)
{
    Response.Redirect("~/WebForm2.aspx");
}
</code>```

WebForm2

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray = (ArrayList)Session["FullNameApplicantArray"] ?? new ArrayList();
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");

    foreach (var item in FullNameApplicantArray)
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
    Session["FullNameApplicantArray"] = FullNameApplicantArray;
}
</code>```

Also take into account that the output window for Debug.Write(item) depends on how VS is configured.

Body:
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

Body:
There were a number of issues in that code. When the user clicks Add, first thing is retrieving the list from session, not storing into session. After adding an item to the list, we need to update session.

WebForm1

protected void Button1_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray = (ArrayList)Session["FullNameApplicantArray"] ?? new ArrayList();
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");

    foreach (var item in FullNameApplicantArray)
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
    Session["FullNameApplicantArray"] = FullNameApplicantArray;
}

protected void Button2_Click(object sender, EventArgs e)
{
    Response.Redirect("~/WebForm2.aspx");
}

WebForm2

protected void Button1_Click(object sender, EventArgs e)
{
    ArrayList FullNameApplicantArray = (ArrayList)Session["FullNameApplicantArray"] ?? new ArrayList();
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");

    foreach (var item in FullNameApplicantArray)
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
    Session["FullNameApplicantArray"] = FullNameApplicantArray;
}

Also take into account that the output window for Debug.Write(item) depends on how VS is configured.


问:
Python socket slow to connect for SMTP after multiple successful connections
I have a script that is emailing out PDFs to our clients and am having an issue where when I start the script, it sends up to three PDFs and then it starts to take 1-2 minutes for each subsequent email to send out. I can halt the script and start over in a few minutes, allowing the same result where three go out and the rest are molasses.

I've narrowed it down to a server problem, with near certainty, but I don't know what it could be. I have two servers, one from an old AWS account, and that one can send emails quickly over and over again. The new AWS account server can do three. When I interrupt the program, I know that it is stuck connecting because this is the trace:

```<code>Traceback (most recent call last):
  File "./test_reports.py", line 202, in <module>
    send_email(advertiser_email, sales_email, emailSubject, emailBody, fname, sendEmail=True)
  File "./test_reports.py", line 158, in send_email
    smtp = smtplib.SMTP('email-smtp.us-east-1.amazonaws.com')
  File "/usr/lib64/python3.5/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib64/python3.5/smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib64/python3.5/smtplib.py", line 306, in _get_socket
    self.source_address)
  File "/usr/lib64/python3.5/socket.py", line 702, in create_connection
    sock.connect(sa)
KeyboardInterrupt
</code>```

If I run strace on the python process while it is trying to send, I get this:

```<code>connect(4, {sa_family=AF_INET, sin_port=htons(25), sin_addr=inet_addr("54.243.225.221")}, 16)
</code>```

I now have a test script where it only sends an email, and I notice I can run that three times as well before it takes forever to send. I am thinking it is some sort of rate limit on the server, but I'm not sure where to look now.

答: It ended up being the repeated establishment of the connection. I established the connection near my global variables and just passed it in to send_email() instead of establishing each time. I had tried this earlier and it didn't work, but I think it was because it was inside of a loop.</p>

Body:
I have a script that is emailing out PDFs to our clients and am having an issue where when I start the script, it sends up to three PDFs and then it starts to take 1-2 minutes for each subsequent email to send out. I can halt the script and start over in a few minutes, allowing the same result where three go out and the rest are molasses.

I've narrowed it down to a server problem, with near certainty, but I don't know what it could be. I have two servers, one from an old AWS account, and that one can send emails quickly over and over again. The new AWS account server can do three. When I interrupt the program, I know that it is stuck connecting because this is the trace:

Traceback (most recent call last):
  File "./test_reports.py", line 202, in <module>
    send_email(advertiser_email, sales_email, emailSubject, emailBody, fname, sendEmail=True)
  File "./test_reports.py", line 158, in send_email
    smtp = smtplib.SMTP('email-smtp.us-east-1.amazonaws.com')
  File "/usr/lib64/python3.5/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib64/python3.5/smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib64/python3.5/smtplib.py", line 306, in _get_socket
    self.source_address)
  File "/usr/lib64/python3.5/socket.py", line 702, in create_connection
    sock.connect(sa)
KeyboardInterrupt

If I run strace on the python process while it is trying to send, I get this:

connect(4, {sa_family=AF_INET, sin_port=htons(25), sin_addr=inet_addr("54.243.225.221")}, 16)

I now have a test script where it only sends an email, and I notice I can run that three times as well before it takes forever to send. I am thinking it is some sort of rate limit on the server, but I'm not sure where to look now.


问:
How to call java objects and functions from CPython?
I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?

It would be nice to be able to use some java objects too.

Jython is not an option. I must run the python part in CPython.

答:
If you don't want to go the write your own JNI/C route.

The other option is to use jpype which for me is always what I use to access Oracle databases becuase installing the oracle c drivers on a PC is a pita.
You can do stuff like (from docs):

```<code> from jpype import *
 startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") # or path to your jvm
 java.lang.System.out.println("hello world")
 shutdownJVM()
</code>```

It hasn't been updated in a while and there isn't much in the way of documentation but it does work reasonably well.

homepage

docs

OwnerDisplayName: nosklo

Body:
If you don't want to go the write your own JNI/C route.

The other option is to use jpype which for me is always what I use to access Oracle databases becuase installing the oracle c drivers on a PC is a pita.
You can do stuff like (from docs):

 from jpype import *
 startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") # or path to your jvm
 java.lang.System.out.println("hello world")
 shutdownJVM()

It hasn't been updated in a while and there isn't much in the way of documentation but it does work reasonably well.

homepage

docs

OwnerDisplayName: Ravi


问:
Pandas dataframe boolean mask on multiple columns
I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns:

```<code>   A    B    dA      dB
0 -1    3    0.31    0.08
1  2   -4    0.263   0.357
2  5    5    0.382   0.397
3 -4   -0.5  0.33    0.115
</code>```

I apply a function to find values in the measurement columns that are valid according to my definition

```<code>df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)
</code>```

This will return a boolean array:

```<code>     A          B
0    False      True
1    True       True
2    True       True
3    True       False
</code>```

I would like to use this array to select rows in dataframe for which the condition is true within a single column, e.g. A -> row 1-3, and also find rows where the condition is true for all the input columns, e.g. row 1 and 2.
Is there an efficient way to do this with pandas?

答:
You can use the results of your apply statement to boolean index select from the original dataframe:

```<code>results = df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)
</code>```

Which returns your boolean array above:

```<code>       A      B
0  False   True
1   True   True
2   True   True
3   True  False
</code>```

Now, you can use this array to select rows from your original datafame as follows:

Select where A is True:

```<code>df[results.A]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115
</code>```

Select where either A or B are true:

```<code>df[results.any(axis=1)]

   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115
</code>```

Select where all the columns true:

```<code>df[results.all(axis=1)]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
</code>```

Body:
I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns:

   A    B    dA      dB
0 -1    3    0.31    0.08
1  2   -4    0.263   0.357
2  5    5    0.382   0.397
3 -4   -0.5  0.33    0.115

I apply a function to find values in the measurement columns that are valid according to my definition

df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)

This will return a boolean array:

     A          B
0    False      True
1    True       True
2    True       True
3    True       False

I would like to use this array to select rows in dataframe for which the condition is true within a single column, e.g. A -> row 1-3, and also find rows where the condition is true for all the input columns, e.g. row 1 and 2.
Is there an efficient way to do this with pandas?

Body:
You can use the results of your apply statement to boolean index select from the original dataframe:

results = df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)

Which returns your boolean array above:

       A      B
0  False   True
1   True   True
2   True   True
3   True  False

Now, you can use this array to select rows from your original datafame as follows:

Select where A is True:

df[results.A]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

Select where either A or B are true:

df[results.any(axis=1)]

   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

Select where all the columns true:

df[results.all(axis=1)]

   A    B     dA     dB
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397


答:
HTML:

```<code><td class="<?php echo (int)$row['miu']?'red':''?>"><? echo $row['miu'];?> </td>
</code>```

CSS

```<code>.red{
    color:red;
}
</code>```

Title: Color coding html table cell based on SQL flag value

Body:
HTML:

<td class="<?php echo (int)$row['miu']?'red':''?>"><? echo $row['miu'];?>&nbsp;</td>

CSS

.red{
    color:red;
}


问:
Python Range Error in While Loop
I am trying to write a python program that will take any string of lowercase letters and return the longest alphabetical substring within it. Below is a segment of the code. </p>

```<code>s="abc"                                            #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) >= 1+shift+expan:                     #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        while s[0+shift+expan] <= s[1+shift+expan]:  #while alphabetical
            expan += 1                               #checks next letter
        anslist += s[0+shift:2+shift+expan]       #adds substring to ans
        expan = 0                                  #resets expansion
</code>```

<p>When I run the code, the line containing
while s[0+shift+expan] <= s[1+shift+expan]:
creates an error that the string index is outside of the range. I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this? I appreciate any help. </p>

答:
First, why your code doesn't work:

You aren't protecting your inner loop against running off the end of the string

your indexes are off when "saving" the substring

you += onto anslist, which is not how you add strings to a list

you don't increment the shift after processing a substring, so when it clears expan it starts over at the same index and loops forever

Fixed code (inline comments explain changes):

```<code>s="abckdefghacbde"                                 #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) > 1+shift+expan:                      #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        # Added guard for end of string
        while len(s) > 1 + shift + expan and       # While still valid
              s[0+shift+expan] <= s[1+shift+expan]:# While alphabetical
            expan += 1                             #checks next letter
        # Fixed string sublength and append instead of +=
        anslist.append(s[0+shift:1+shift+expan])   #adds substring to ans
        # Continue to next possible substring
        shift += expan                             # skip inner substrings
        expan = 0
print anslist
</code>```

Results in:

```<code>['abck', 'defgh', 'ac', 'bde']
</code>```

So the last step would be to find the one with the longest length, which I'll leave up to you, since this looks like homework.

To answer the question:

I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this?

It protects against your starting substring index from going off, but not your expansion. You must protect against both possibilities.

Title: Python Range Error in While Loop

Body:
I am trying to write a python program that will take any string of lowercase letters and return the longest alphabetical substring within it. Below is a segment of the code.

s="abc"                                            #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) >= 1+shift+expan:                     #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        while s[0+shift+expan] <= s[1+shift+expan]:  #while alphabetical
            expan += 1                               #checks next letter
        anslist += s[0+shift:2+shift+expan]       #adds substring to ans
        expan = 0                                  #resets expansion

When I run the code, the line containing
while s[0+shift+expan] <= s[1+shift+expan]:
creates an error that the string index is outside of the range. I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this? I appreciate any help.

Body:
First, why your code doesn't work:

You aren't protecting your inner loop against running off the end of the string

your indexes are off when "saving" the substring

you += onto anslist, which is not how you add strings to a list

you don't increment the shift after processing a substring, so when it clears expan it starts over at the same index and loops forever

Fixed code (inline comments explain changes):

s="abckdefghacbde"                                 #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) > 1+shift+expan:                      #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        # Added guard for end of string
        while len(s) > 1 + shift + expan and       # While still valid
              s[0+shift+expan] <= s[1+shift+expan]:# While alphabetical
            expan += 1                             #checks next letter
        # Fixed string sublength and append instead of +=
        anslist.append(s[0+shift:1+shift+expan])   #adds substring to ans
        # Continue to next possible substring
        shift += expan                             # skip inner substrings
        expan = 0
print anslist

Results in:

['abck', 'defgh', 'ac', 'bde']

So the last step would be to find the one with the longest length, which I'll leave up to you, since this looks like homework.

To answer the question:

I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this?

It protects against your starting substring index from going off, but not your expansion. You must protect against both possibilities.


问:
POST request not working in Google Cloud
I have a MEAN app deployed on Google Cloud (GAE). POST requests work locally but not in the cloud. Anything I need to do, specifically, to get this working on GAE?

GETs work fine.

Thanks.

ERROR that I get when hit from Postman:

```<code><html>
    <head>
        <title>502 Bad Gateway</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>502 Bad Gateway</h1>
        </center>
        <hr>
        <center>nginx</center>
    </body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
</code>```

Not using NGINX locally, which is why it probably works fine.

答:
What response do you get?

GAE is pretty strict and requires Content-Length on POST.

Body:
I have a MEAN app deployed on Google Cloud (GAE). POST requests work locally but not in the cloud. Anything I need to do, specifically, to get this working on GAE?

GETs work fine.

Thanks.

ERROR that I get when hit from Postman:

        <title>502 Bad Gateway</title>

502 Bad Gateway

        nginx

Not using NGINX locally, which is why it probably works fine.


问:
How to retrieve usage on Amazon S3 based on tags?
We are only implement one bucket for all data stored in S3, there are many data from different organization. Can we retrieve usage from 'foo' organization or 'bar' organization by its 'foo' or 'bar' tag?

Usecase :

We deploy a mobile app for our client called 'foo' and 'bar', this app used to upload file (images and videos) contains 'foo' tag, and 'bar' tag based on organization. We use the same API for the app, and same bucket in S3. So I just want to get the metrics like total storage used by 'foo' tag or 'bar' tag. So i can monitor that 'foo' or 'bar' already use N GB.

答:
You could create a Lambda function that executes on upload events in s3 that can records the metadata about the object into a database like Dynamodb or mysql. And then a separate lambda function on delete events in the s3 bucket. Then you can run analytics on the database instead of trying to use a lot of API calls to s3.

http://docs.aws.amazon.com/lambda/latest/dg/with-s3.html