问:
SQL statement in php variable?
Ok so I realized this probably looks crazy to good programers but I'm a noob and just trying to figure out the basics.  I'm trying to build a simple question/answer site.  I can submit a question to the db just fine but when I direct a user to answer I need to put the correct question id (q_id) as it's a foreign key in my answers table.  I cant find anything online to solve this problem.  I'm sure I'll get "dont use mysqli_query" or something but if anyone can just help me understand how to get the correct value passed into q_id it would be a great help.  Seeing my php code below it will probably make sense what I'm attempting to do:</p>

```<code>//set up connection credentials
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "ask";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//gather the data from the form
$answer = $_POST["answer"];
$q_id = mysqli_query($conn,"select q_id from questions order by q_id
desc limit 1");

 $sql = "INSERT INTO answers (answer, q_id)  VALUES ('$answer',
  '$q_id')";
 if (mysqli_query($conn, $sql)) {

 echo "answer submitted";

} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}

?>
</code>```

答:
When you open the page that display question, you already use the q_id, just use it again.

Like the stackoverflow URL, question ID is on the URL:
https://stackoverflow.com/questions/44896448/sql-statement-in-php-variable

Because you do not know re-write yet so you can use $_GET method to get q_id.

EDITED:

User insert_id; to get last id after question submitted then you got the id for the question

```<code>if (mysqli_query($conn, $sql)) {
 $last_id = $conn->insert_id;
 echo "answer submitted, id is ".$last_id;

} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}

?>
</code>```

Title: SQL statement in php variable?

Body:
Ok so I realized this probably looks crazy to good programers but I'm a noob and just trying to figure out the basics.  I'm trying to build a simple question/answer site.  I can submit a question to the db just fine but when I direct a user to answer I need to put the correct question id (q_id) as it's a foreign key in my answers table.  I cant find anything online to solve this problem.  I'm sure I'll get "dont use mysqli_query" or something but if anyone can just help me understand how to get the correct value passed into q_id it would be a great help.  Seeing my php code below it will probably make sense what I'm attempting to do:

//set up connection credentials
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "ask";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//gather the data from the form
$answer = $_POST["answer"];
$q_id = mysqli_query($conn,"select q_id from questions order by q_id
desc limit 1");

 $sql = "INSERT INTO answers (answer, q_id)  VALUES ('$answer',
  '$q_id')";
 if (mysqli_query($conn, $sql)) {

 echo "answer submitted";

} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);}

?>

Body:
When you open the page that display question, you already use the q_id, just use it again.

Like the stackoverflow URL, question ID is on the URL:
https://stackoverflow.com/questions/44896448/sql-statement-in-php-variable

Because you do not know re-write yet so you can use $_GET method to get q_id.

EDITED:

User insert_id; to get last id after question submitted then you got the id for the question

if (mysqli_query($conn, $sql)) {
 $last_id = $conn->insert_id;
 echo "answer submitted, id is ".$last_id;

} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}

?>


来源: stackexchange

问:
Php: How to pull a value from an array in a single field in MySQL
In my database I have a table named posts. In it, the columns are:

Postid - 1

PostBody - my first post

Likers - 1,2,3,4,5,

Now what am trying to do is, in the likers field, am trying to pull the individual number without pulling all the data on the field. So if I want to retrieve likers No.3, I want the output to be 3 when I echo it out.

I have tried FIND_IN_SET(), and strstr(). All I get is the whole array, 1-5,  being echoed. And because of that, I cannot match it with other variables(I.e. $var = 3;) which have the matching number.

Is there a way of doing this?

Thanx

答:
If you really want to do it this way (read my comment first), what you can do is retrieve the comma-seperated data, explode it into a php array, and then use the array_search built-in function:

```<code>$likers_attribute_data = '1,2,3,4,5,';
$likers_array = explode(',', $likers_attribute_data);
// check if user 3 is a liker:
if (array_search('3', $likers_array) {
    // he has :)
} else {
    // he hasn't :(
}
</code>```

Again, this is a very sloppy and inefficient way of doing business. Please just go with the solution in my comment!

ContentLicense: CC BY-SA 3.0

Body:
If you really want to do it this way (read my comment first), what you can do is retrieve the comma-seperated data, explode it into a php array, and then use the array_search built-in function:

$likers_attribute_data = '1,2,3,4,5,';
$likers_array = explode(',', $likers_attribute_data);
// check if user 3 is a liker:
if (array_search('3', $likers_array) {
    // he has :)
} else {
    // he hasn't :(
}

Again, this is a very sloppy and inefficient way of doing business. Please just go with the solution in my comment!


问:
GDB not returning useful backtraces
I've been writing a game engine on the side. I've been doing great progress, except anytime I need to debug anything. When I run GDB, I usually get stacktraces like this:

```<code>Thread 2 received signal SIGABRT, Aborted.
0x00007fffb73f9d42 in ?? ()
(gdb) bt
#0  0x00007fffb73f9d42 in ?? ()
#1  0x00007fffb74e75bf in ?? ()
#2  0x00007fff5fbfafd0 in ?? ()
#3  0x000003075fbfb110 in ?? ()
#4  0x00007fff5fbfafd0 in ?? ()
#5  0x00007fffb5edbc2f in ?? ()
#6  0x00007fff5fbfafe0 in ?? ()
#7  0x00007fffb735f420 in ?? ()
#8  0xffffffff5fbfb110 in ?? ()
#9  0x0000000000000030 in ?? ()
#10 0x00007fffffffffdf in ?? ()
#11 0x00007fffc01c1a20 in ?? ()
#12 0x00007fff5fbfb100 in ?? ()
#13 0x00007fffb5eb584a in ?? ()
#14 0x0000000000000000 in ?? ()
</code>```

Which makes it really hard to do any debugging. I'm on macOS Sierra, and this is my Makefile:

```<code>OUT_FILE := game

OUT_DIR := out
INC_DIR := src
SRC_DIR := src
OBJ_DIR := obj/native

C := gcc
CXX := g++
LINKER := g++
INC_DIRS := -I$(INC_DIR)
C_FLAGS = \
    -Wall \
    -D NATIVE \
    -pedantic \
    -g

CXX_FLAGS = \
    -std=c++11 \
    -std=c++14 \
    -Wall \
    -D NATIVE \
    -pedantic \
    -D DRAW_FPS \
    -D DRAW_COLLISION \
    -gdwarf \
    -g
    #-Wextra \
    #-Wshadow \

EXEC_FLAGS =
LIBS := -I /Library/Frameworks/SDL2.framework/Headers -I /Library/Frameworks/SDL2_image.framework/Headers -I /Library/Frameworks/SDL2_ttf.framework/Headers -framework SDL2 -framework SDL2_image -framework SDL2_ttf

SRC_FILES := $(shell find $(SRC_DIR) -name '*.cpp' -o -name '*.c')
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRC_FILES))
OBJ_FILES := $(patsubst $(SRC_DIR)/%.c,   $(OBJ_DIR)/%.o, $(OBJ_FILES))
DEPFILES := $(patsubst  $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.d, $(SRC_FILES))
DEPFILES := $(patsubst  $(SRC_DIR)/%.c,   $(OBJ_DIR)/%.d, $(DEPFILES))

$(OUT_FILE): $(OBJ_FILES)
    $(LINKER) $(CXX_FLAGS) $(EXEC_FLAGS) $^ $(LIBS) -o $@

clean:
    rm -rf $(OBJ_DIR) $(OUT_FILE)

list:
    @echo "$(SRC_FILES)"
    @echo "$(OBJ_FILES)"

depends:
    rm -rf $(OBJ_DIR)/*.d
    $(MAKE) $(DEPFILES)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
    @mkdir -p $(@D)
    $(C) $(C_FLAGS) $(INC_DIRS) -c $< -o $@

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXX_FLAGS) $(INC_DIRS) -c $< -o $@

$(OBJ_DIR)/%.d: $(SRC_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXX_FLAGS) $(INC_DIRS) -MM $< | tr '\n\r\\' ' ' | sed -e 's%^%$@ %' -e 's% % $(OBJ_DIR)/%' > $@

-include $(DEPFILES)
</code>```

Does anyone know what I'm missing?

答:
Try to add -ggdb for more debug

Use valgrind to find out where you corrupt the stack. It obvious, what you corrupt some memory at stack.

Title: GDB not returning useful backtraces

Body:
I've been writing a game engine on the side. I've been doing great progress, except anytime I need to debug anything. When I run GDB, I usually get stacktraces like this:

Thread 2 received signal SIGABRT, Aborted.
0x00007fffb73f9d42 in ?? ()
(gdb) bt
#0  0x00007fffb73f9d42 in ?? ()
#1  0x00007fffb74e75bf in ?? ()
#2  0x00007fff5fbfafd0 in ?? ()
#3  0x000003075fbfb110 in ?? ()
#4  0x00007fff5fbfafd0 in ?? ()
#5  0x00007fffb5edbc2f in ?? ()
#6  0x00007fff5fbfafe0 in ?? ()
#7  0x00007fffb735f420 in ?? ()
#8  0xffffffff5fbfb110 in ?? ()
#9  0x0000000000000030 in ?? ()
#10 0x00007fffffffffdf in ?? ()
#11 0x00007fffc01c1a20 in ?? ()
#12 0x00007fff5fbfb100 in ?? ()
#13 0x00007fffb5eb584a in ?? ()
#14 0x0000000000000000 in ?? ()

Which makes it really hard to do any debugging. I'm on macOS Sierra, and this is my Makefile:

OUT_FILE := game

OUT_DIR := out
INC_DIR := src
SRC_DIR := src
OBJ_DIR := obj/native

C := gcc
CXX := g++
LINKER := g++
INC_DIRS := -I$(INC_DIR)
C_FLAGS = \
    -Wall \
    -D NATIVE \
    -pedantic \
    -g

CXX_FLAGS = \
    -std=c++11 \
    -std=c++14 \
    -Wall \
    -D NATIVE \
    -pedantic \
    -D DRAW_FPS \
    -D DRAW_COLLISION \
    -gdwarf \
    -g
    #-Wextra \
    #-Wshadow \

EXEC_FLAGS =
LIBS := -I /Library/Frameworks/SDL2.framework/Headers -I /Library/Frameworks/SDL2_image.framework/Headers -I /Library/Frameworks/SDL2_ttf.framework/Headers -framework SDL2 -framework SDL2_image -framework SDL2_ttf

SRC_FILES := $(shell find $(SRC_DIR) -name '*.cpp' -o -name '*.c')
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRC_FILES))
OBJ_FILES := $(patsubst $(SRC_DIR)/%.c,   $(OBJ_DIR)/%.o, $(OBJ_FILES))
DEPFILES := $(patsubst  $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.d, $(SRC_FILES))
DEPFILES := $(patsubst  $(SRC_DIR)/%.c,   $(OBJ_DIR)/%.d, $(DEPFILES))

$(OUT_FILE): $(OBJ_FILES)
    $(LINKER) $(CXX_FLAGS) $(EXEC_FLAGS) $^ $(LIBS) -o $@

clean:
    rm -rf $(OBJ_DIR) $(OUT_FILE)

list:
    @echo "$(SRC_FILES)"
    @echo "$(OBJ_FILES)"

depends:
    rm -rf $(OBJ_DIR)/*.d
    $(MAKE) $(DEPFILES)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
    @mkdir -p $(@D)
    $(C) $(C_FLAGS) $(INC_DIRS) -c $< -o $@

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXX_FLAGS) $(INC_DIRS) -c $< -o $@

$(OBJ_DIR)/%.d: $(SRC_DIR)/%.cpp
    @mkdir -p $(@D)
    $(CXX) $(CXX_FLAGS) $(INC_DIRS) -MM $< | tr '\n\r\\' ' ' | sed -e 's%^%$@ %' -e 's% % $(OBJ_DIR)/%' > $@

-include $(DEPFILES)

Does anyone know what I'm missing?


问:
Robotic arm calibration
I'm working on an image recognition software for bacteria colony. So far I have been able to obtain the pixel coordinates of the colony recognized. Now what conversion operation should I apply so that a robot arm can pick up the colonies? any suggestions on what I should look up? A little clueless here</p>

答:
"Camera calibration" (intrinsic and extrinsic) yields the geometric relationship between pixels on the image and rays in 3D space.

"Hand-eye calibration" relates the kinematics (direct and inverse) of a robotic arm to the geometry of a camera observing the robot's workspace.

There are vast amounts of literature on both subjects, hard to be more specific without knowing more about your particular use case.

Title: Robotic arm calibration


问:
all strings of length k that can be formed from a set of n characters
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

```<code>input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')
</code>```

答:
A little more complicated than I'd like. I think outer() only works for n=2. combn doesn't include repeats.

```<code>allcomb <- function(input = c('a', 'b'), n=2) {
  args <- rep(list(input),n)
  gr <- do.call(expand.grid,args)
  return(do.call(paste0,gr))
}
</code>```

Thanks to @thelatemail for improvements ...

```<code>allcomb(n=4)
## [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba"
## [8] "bbba" "aaab" "baab" "abab" "bbab" "aabb" "babb"
## [15] "abbb" "bbbb"
</code>```

Body:
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')

Body:
A little more complicated than I'd like. I think outer() only works for n=2. combn doesn't include repeats.

allcomb <- function(input = c('a', 'b'), n=2) {
  args <- rep(list(input),n)
  gr <- do.call(expand.grid,args)
  return(do.call(paste0,gr))
}

Thanks to @thelatemail for improvements ...

allcomb(n=4)
## [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba"
## [8] "bbba" "aaab" "baab" "abab" "bbab" "aabb" "babb"
## [15] "abbb" "bbbb"


问:
CSS color sections dived diagonally
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="diagonal">
</div></code>```

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

答:
You could try using a separate div for the linear-gradient

.diagonal-top {
    background-image: linear-gradient(to left top, whitesmoke 50%, #34ADFF 50%);
    height: 20px;
}
.diagonal-bottom {
    background-image: linear-gradient(to right top, #34ADFF 50%, whitesmoke 50%);
    height: 40px;
}

.header {
  height: 30px;
  background-color: #34ADFF;
}

.footer {
  height: 50px;
  background-color: #34ADFF;
}

.clearfix  {
  height: 30px;
  background-color: whitesmoke;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header"></div>
<div class="diagonal-top"></div>
<div class="clearfix"></div>
<div class="diagonal-bottom"></div>
<div class="footer"></div></code>```

Title: CSS color sections dived diagonally

Body:
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

Body:
You could try using a separate div for the linear-gradient

.diagonal-top {
    background-image: linear-gradient(to left top, whitesmoke 50%, #34ADFF 50%);
    height: 20px;
}
.diagonal-bottom {
    background-image: linear-gradient(to right top, #34ADFF 50%, whitesmoke 50%);
    height: 40px;
}

.header {
  height: 30px;
  background-color: #34ADFF;
}

.footer {
  height: 50px;
  background-color: #34ADFF;
}

.clearfix  {
  height: 30px;
  background-color: whitesmoke;
}

<div class="header"></div>
<div class="diagonal-top"></div>
<div class="clearfix"></div>
<div class="diagonal-bottom"></div>
<div class="footer"></div>


问:
A succinct binary tree of sums, array construction and addressing
Using 'sum' as a short hand for some arbitrary computation. I have a process that computes a single sum from a list of values by recursively summing pairs of values. Un-paired values are promoted up the tree unaltered until they can be paired.

Given this computation, I'm in search of the best way to balance computation (i.e. number of operation required to access array elements/nodes), and the most succinct encoding of all nodes in a 1 dimensional array (i.e. no gaps, nil values, or repeated values), and preferably without an additional index array that cannot be easily derived from the succinct encoding so that it would have to be saved along with the array.

Although the following are simple examples, in reality the number of values in the initial list can be extraordinarily large (2^47 or more).

For example, given the list [1, 2, 3, 4], the array is trivial: [10, 3, 7, 1, 2, 3, 4], and split nicely into rows that are easy to address by node, or as a reference to the entire row.

But for a 5 item list the tree looks like this:

Tree 1

```<code>         15
        /  \
       /    \
      /      \
     /        \
    10          5
  /   \       /   \
 3     7     5     -
/ \   / \   / \   / \
1  2  3  4 5   - -   -
</code>```

The standard mapping left = i*2+1, right = i*2+2 gives us this array:

Array 1

```<code>[ 15, 10,  5,  3,   7,   5,  nil,   1,   2,   3,   4,   5,   nil,   nil, nil]
</code>```

This array has 4 nil values, and the last element in the list '5' is repeated 2 times.

To improve this we can imply the repetition of the 5, and remove the nil values:

Array 2

```<code>[15, 10, 3, 7, 1, 2, 3, 4, 5]
</code>```

Which is much more compact. This tree is the same, but conceptually looks a bit like:

Tree 2

```<code>       15
      / \
     /   \
    10    \
  /   \    \
 3     7    \
/ \   / \    \
1  2  3  4    5
</code>```

In the Array 2 encoding I have 4 rows:

```<code>1. [1, 2, 3, 4]
2. [3, 7]
3. [10, 5]
4. [15]
</code>```

Rows 1, 2 and 4 can simply be references into Array 2 allowing me to compute results 'in-place' with no allocations or copies. Very fast. Row 3 however, contains values in two non-contiguous cells. I have to break the simple logic used for the other rows, and possibly add copy, indexing or storage for a map.

I can construct complete/balanced sub trees (such as indexes 1-7, the tree for 1, 2, 3, 4), but it seems like they will not always be so nicely aligned when the odd number of items appears at different rows depending on input length.  For example consider a tree with an initial list of 6 elements.

答: It sounds like you're asking for a succinct encoding of a binary tree.  For this it's sufficient to store the node data in pre-order with one additional bit to denote leaf vs internal node. The algorithms for encoding and decoding are rather simple and given in a Wikipedia article, so I won't repeat them here. This encoding is very close to the information-theoretic best possible. It's probably not worth looking for a better one.</p>

Body:
Using 'sum' as a short hand for some arbitrary computation. I have a process that computes a single sum from a list of values by recursively summing pairs of values. Un-paired values are promoted up the tree unaltered until they can be paired.

Given this computation, I'm in search of the best way to balance computation (i.e. number of operation required to access array elements/nodes), and the most succinct encoding of all nodes in a 1 dimensional array (i.e. no gaps, nil values, or repeated values), and preferably without an additional index array that cannot be easily derived from the succinct encoding so that it would have to be saved along with the array.

Although the following are simple examples, in reality the number of values in the initial list can be extraordinarily large (2^47 or more).

For example, given the list [1, 2, 3, 4], the array is trivial: [10, 3, 7, 1, 2, 3, 4], and split nicely into rows that are easy to address by node, or as a reference to the entire row.

But for a 5 item list the tree looks like this:

Tree 1

         15
        /  \
       /    \
      /      \
     /        \
    10          5
  /   \       /   \
 3     7     5     -
/ \   / \   / \   / \
1  2  3  4 5   - -   -

The standard mapping left = i*2+1, right = i*2+2 gives us this array:

Array 1

[ 15, 10,  5,  3,   7,   5,  nil,   1,   2,   3,   4,   5,   nil,   nil, nil]

This array has 4 nil values, and the last element in the list '5' is repeated 2 times.

To improve this we can imply the repetition of the 5, and remove the nil values:

Array 2

[15, 10, 3, 7, 1, 2, 3, 4, 5]

Which is much more compact. This tree is the same, but conceptually looks a bit like:

Tree 2

       15
      / \
     /   \
    10    \
  /   \    \
 3     7    \
/ \   / \    \
1  2  3  4    5

In the Array 2 encoding I have 4 rows:

1. [1, 2, 3, 4]
2. [3, 7]
3. [10, 5]
4. [15]

Rows 1, 2 and 4 can simply be references into Array 2 allowing me to compute results 'in-place' with no allocations or copies. Very fast. Row 3 however, contains values in two non-contiguous cells. I have to break the simple logic used for the other rows, and possibly add copy, indexing or storage for a map.

I can construct complete/balanced sub trees (such as indexes 1-7, the tree for 1, 2, 3, 4), but it seems like they will not always be so nicely aligned when the odd number of items appears at different rows depending on input length.  For example consider a tree with an initial list of 6 elements.


问:
"global" keyword needed in the top-level declaration
I am keen to know whether there is any need to use the keyword global in the top-level declaration/assignment in Python (such as the one for the 1st line of code below).

Both fn_2() and fn_4() have the same effect to change the corresponding variables in the codes below.

```<code>global factor_1
factor_1 = None

factor_2 = None

def main():

    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_1()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_2()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_3()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_4()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

def fn_1():
    factor_1 = 10

def fn_2():
    global factor_1
    factor_1 = 20

def fn_3():
    factor_2 = 30

def fn_4():
    global factor_2
    factor_2 = 40

if __name__ == '__main__':
    main()
</code>```

答: No, there isn't.  You need to use global inside a function if you want to set the value of a global variable in that function.  You don't need to use global outside functions.

Body:
I am keen to know whether there is any need to use the keyword global in the top-level declaration/assignment in Python (such as the one for the 1st line of code below).

Both fn_2() and fn_4() have the same effect to change the corresponding variables in the codes below.

global factor_1
factor_1 = None

factor_2 = None

def main():

    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_1()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_2()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_3()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

    fn_4()
    print('factor_1 = {}, factor_2 = {}'.format(factor_1, factor_2))

def fn_1():
    factor_1 = 10

def fn_2():
    global factor_1
    factor_1 = 20

def fn_3():
    factor_2 = 30

def fn_4():
    global factor_2
    factor_2 = 40

if __name__ == '__main__':
    main()


问:
path works from root only
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

```<code>  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
</code>```

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

答:
Change your $base_url to

```<code>$base_url = $_SERVER['DOCUMENT_ROOT'].'/posters';
</code>```

To get root directory path of a PHP project:

For PHP >= 5.3.0

use: DIR

Note: The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE). This directory name does not have a trailing slash unless it is the root directory.

For PHP < 5.3.0

use: dirname(FILE) or realpath(dirname(FILE))

Or in most common for getting server document root directory where projects resides :

$_SERVER['DOCUMENT_ROOT'] or filter_input(INPUT_SERVER, 'DOCUMENT_ROOT')

Title: path works from root only

Body:
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '

  ';

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

Body:
Change your $base_url to

$base_url = $_SERVER['DOCUMENT_ROOT'].'/posters';

To get root directory path of a PHP project:

For PHP >= 5.3.0

use: DIR

Note: The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE). This directory name does not have a trailing slash unless it is the root directory.

For PHP < 5.3.0

use: dirname(FILE) or realpath(dirname(FILE))

Or in most common for getting server document root directory where projects resides :

$_SERVER['DOCUMENT_ROOT'] or filter_input(INPUT_SERVER, 'DOCUMENT_ROOT')


问:
how to add items in an array list while using jsp and servlet
I'am making a shopping cart using JSP and servlet and I'am adding the items to cart through an arraylist from my database. I'am doing this by setting and getting the value of attributes of session.But it is adding only 1 value and after that the output is null.Please tell me how to resolve this problem.
This is my Cart.java page where elements are added to ArrayList

```<code>ArrayList al=null;
        HttpSession session=request.getSession(false);
        try (PrintWriter out = response.getWriter()) {

            String id=request.getParameter("xyz");
            int i=Integer.parseInt(id);
            if (session.getAttribute("Il")==null)
            {

                al=new ArrayList();

            try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
            while(rs.next())
            {
                Item item=new Item();
                item.itemid=rs.getInt(1);
                String name=rs.getString(2);
                item.itemname=rs.getString(2);
                item.itemprice=rs.getString(3);
                al.add(item);

        }
            session.setAttribute("Il", al);
            con.close();
            RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
            rd.forward(request, response);
            }
            catch(Exception e)
            {
                out.println(e.getMessage());
    }
        }
            else
            {

                try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
            while(rs.next())
            {
                Item item=new Item();
                item.itemid=rs.getInt(1);
                String name=rs.getString(2);
                item.itemname=rs.getString(2);
                item.itemprice=rs.getString(3);
                al.add(item);

        }
            session.setAttribute("Il", al);
            con.close();
            RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
            rd.forward(request, response);
            }
            catch(Exception e)
            {
                out.println(e.getMessage());
    }
            }
</code>```

This is my Cart.jsp page where all values are displayed.

```<code>    <%--
    Document   : Cart
    Created on : Jul 1, 2017, 10:36:09 AM
    Author     : hp-pc
--%>

<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="p1.Item"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Cart</title>
        <style>
            h1{
                float: right;
            }
          </style>

    </head>
    <body>
        <%
          String name=(String)session.getAttribute("username");
            %>
            <h1>
                <%=name%>
            </h1>

                 <table>
                <tr>
                    <th> Select</th>
                    <th>Id</th>
                    <th> Name</th>
                    <th> Price</th>
                </tr>
                <form>
                  <%
                      System.out.println("testing.......................");
        ArrayList items=(ArrayList)session.getAttribute("Il");
        System.out.println("success........................"+items);
        Iterator it=items.iterator();

        while(it.hasNext())
        {
            Item i=(Item)it.next();
    %>
    <tr>
        <td>
                 <div class="radio">
                     <label><input type="radio" name="optradio"></label>
                 </div>
            </td>
        <td><%=i.itemid%></td>
        <td><%=i.itemname%></td>
        <td><%=i.itemprice%></td>
    </tr>
    <%
        }
      %>
                </form>
                 </table>

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

答:
You need to add al = (ArrayList) session.getAttribute("Il"); after } else { :

```<code>        } else {
            al = (ArrayList) session.getAttribute("Il"); // add this line
            try {
                Class.forName("com.mysql.jdbc.Driver");
</code>```

at least.

Body:
I'am making a shopping cart using JSP and servlet and I'am adding the items to cart through an arraylist from my database. I'am doing this by setting and getting the value of attributes of session.But it is adding only 1 value and after that the output is null.Please tell me how to resolve this problem.
This is my Cart.java page where elements are added to ArrayList

ArrayList al=null;
        HttpSession session=request.getSession(false);
        try (PrintWriter out = response.getWriter()) {

            String id=request.getParameter("xyz");
            int i=Integer.parseInt(id);
            if (session.getAttribute("Il")==null)
            {

                al=new ArrayList();

            try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
            while(rs.next())
            {
                Item item=new Item();
                item.itemid=rs.getInt(1);
                String name=rs.getString(2);
                item.itemname=rs.getString(2);
                item.itemprice=rs.getString(3);
                al.add(item);

        }
            session.setAttribute("Il", al);
            con.close();
            RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
            rd.forward(request, response);
            }
            catch(Exception e)
            {
                out.println(e.getMessage());
    }
        }
            else
            {

                try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
            while(rs.next())
            {
                Item item=new Item();
                item.itemid=rs.getInt(1);
                String name=rs.getString(2);
                item.itemname=rs.getString(2);
                item.itemprice=rs.getString(3);
                al.add(item);

        }
            session.setAttribute("Il", al);
            con.close();
            RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
            rd.forward(request, response);
            }
            catch(Exception e)
            {
                out.println(e.getMessage());
    }
            }

This is my Cart.jsp page where all values are displayed.

    <%--
    Document   : Cart
    Created on : Jul 1, 2017, 10:36:09 AM
    Author     : hp-pc
--%>

<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="p1.Item"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Cart</title>

        <%
          String name=(String)session.getAttribute("username");
            %>

                <%=name%>

                     Select
                    Id
                     Name
                     Price

                <form>
                  <%
                      System.out.println("testing.......................");
        ArrayList items=(ArrayList)session.getAttribute("Il");
        System.out.println("success........................"+items);
        Iterator it=items.iterator();

        while(it.hasNext())
        {
            Item i=(Item)it.next();
    %>

                     <input type="radio" name="optradio">

        <%=i.itemid%>
        <%=i.itemname%>
        <%=i.itemprice%>

    <%
        }
      %>
                </form>

Body:
You need to add al = (ArrayList) session.getAttribute("Il"); after } else { :

        } else {
            al = (ArrayList) session.getAttribute("Il"); // add this line
            try {
                Class.forName("com.mysql.jdbc.Driver");

at least.


问:
enable dragging of element in a ScrollView after long press
I have implemented drag n drop list with panResponder and ScrollView. I want to be able to scroll the list even when I touch the item. Problem is that the item moves when I do the gesture to scroll. Of course I also want to be able to move the item but now it has the same gesture as scroll. I want to overcome it by enabling dragging the element only after it was long pressed (1,5 sec). How to implement it? I thought to use Touchable as an element with onPressIn / onPressOut just like described here: http://browniefed.com/blog/react-native-press-and-hold-button-actions/
and somehow to enable panResponder after the time period, but I don't know how to enable it programmatically.

Right now this is my code for element in the list:

```<code>class AccountItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
      zIndex: 0,
    }

    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: (e, gestureState) => {
        this.setState({ zIndex: 100 });
        this.props.disableScroll();
      },
      onPanResponderMove: Animated.event([null, {
        dx: this.state.pan.x,
        dy: this.state.pan.y,
      }]),
      onPanResponderRelease: (e, gesture) => {
        this.props.submitNewPositions();
        Animated.spring(
          this.state.pan,
          {toValue:{ x:0, y:0 }}
        ).start();
        this.setState({ zIndex: 0 });
        this.props.enableScroll();
      }
    })
  }

  meassureMyComponent = (event) => {
    const { setElementPosition } = this.props;
    let posY = event.nativeEvent.layout.y;
    setElementPosition(posY);
  }

  render() {
    const {name, index, onChangeText, onRemoveAccount} = this.props;

    return (
        <Animated.View
          style={[this.state.pan.getLayout(), styles.container, {zIndex: this.state.zIndex}]}
          {...this.panResponder.panHandlers}
          onLayout={this.meassureMyComponent}
        >

some other components...

        </Animated.View>
    )
  }
}

export default AccountItem;
</code>```

答:
I met the same issue with you. My solution is to define 2 different panResponder handler for onLongPress and normal behaviour.

```<code>  _onLongPressPanResponder(){
    return PanResponder.create({
      onPanResponderTerminationRequest: () => false,
      onStartShouldSetPanResponderCapture: () => true,
      onPanResponderMove: Animated.event([
        null, {dx: this.state.pan.x, dy: this.state.pan.y},
      ]),
      onPanResponderRelease: (e, {vx, vy}) => {
        this.state.pan.flattenOffset()
        Animated.spring(this.state.pan, {         //This will make the draggable card back to its original position
           toValue: 0
        }).start();
        this.setState({panResponder: undefined})   //Clear panResponder when user release on long press
      }
    })
  }

  _normalPanResponder(){
    return PanResponder.create({
      onPanResponderTerminationRequest: () => false,
      onStartShouldSetPanResponderCapture: () => true,
      onPanResponderGrant: (e, gestureState) => {
        this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
        this.state.pan.setValue({x: 0, y: 0})
        this.longPressTimer=setTimeout(this._onLongPress, 400)  // this is where you trigger the onlongpress panResponder handler
      },
      onPanResponderRelease: (e, {vx, vy}) => {
        if (!this.state.panResponder) {
            clearTimeout(this.longPressTimer);   // clean the timeout handler
        }
      }
    })
  }
</code>```

Define your _onLongPress function:

```<code>  _onLongPress(){
    // you can add some animation effect here as wll
    this.setState({panResponder: this._onLongPressPanResponder()})
  }
</code>```

Define your constructor:

```<code>  constructor(props){
    super(props)
    this.state = {
      pan: new Animated.ValueXY()
    };
    this._onLongPress = this._onLongPress.bind(this)
    this._onLongPressPanResponder = this._onLongPressPanResponder.bind(this)
    this._normalPanResponder = this._normalPanResponder.bind(this)
    this.longPressTimer = null
  }
</code>```

Finally, before you render, you should switch to different panResponder handlers according to the state:

```<code>  let panHandlers = {}
    if(this.state.panResponder){
      panHandlers = this.state.panResponder.panHandlers
    }else{
      panHandlers = this._normalPanResponder().panHandlers
    }
</code>```

Then attach the panHandlers to your view  {...panHandlers}
You can even change the css for different panHandlers to show different effect.

Body:
I have implemented drag n drop list with panResponder and ScrollView. I want to be able to scroll the list even when I touch the item. Problem is that the item moves when I do the gesture to scroll. Of course I also want to be able to move the item but now it has the same gesture as scroll. I want to overcome it by enabling dragging the element only after it was long pressed (1,5 sec). How to implement it? I thought to use Touchable as an element with onPressIn / onPressOut just like described here: http://browniefed.com/blog/react-native-press-and-hold-button-actions/
and somehow to enable panResponder after the time period, but I don't know how to enable it programmatically.

Right now this is my code for element in the list:

class AccountItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
      zIndex: 0,
    }

    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: (e, gestureState) => {
        this.setState({ zIndex: 100 });
        this.props.disableScroll();
      },
      onPanResponderMove: Animated.event([null, {
        dx: this.state.pan.x,
        dy: this.state.pan.y,
      }]),
      onPanResponderRelease: (e, gesture) => {
        this.props.submitNewPositions();
        Animated.spring(
          this.state.pan,
          {toValue:{ x:0, y:0 }}
        ).start();
        this.setState({ zIndex: 0 });
        this.props.enableScroll();
      }
    })
  }

  meassureMyComponent = (event) => {
    const { setElementPosition } = this.props;
    let posY = event.nativeEvent.layout.y;
    setElementPosition(posY);
  }

  render() {
    const {name, index, onChangeText, onRemoveAccount} = this.props;

    return (
        <Animated.View
          style={[this.state.pan.getLayout(), styles.container, {zIndex: this.state.zIndex}]}
          {...this.panResponder.panHandlers}
          onLayout={this.meassureMyComponent}
        >

some other components...

        </Animated.View>
    )
  }
}

export default AccountItem;

Body:
I met the same issue with you. My solution is to define 2 different panResponder handler for onLongPress and normal behaviour.

  _onLongPressPanResponder(){
    return PanResponder.create({
      onPanResponderTerminationRequest: () => false,
      onStartShouldSetPanResponderCapture: () => true,
      onPanResponderMove: Animated.event([
        null, {dx: this.state.pan.x, dy: this.state.pan.y},
      ]),
      onPanResponderRelease: (e, {vx, vy}) => {
        this.state.pan.flattenOffset()
        Animated.spring(this.state.pan, {         //This will make the draggable card back to its original position
           toValue: 0
        }).start();
        this.setState({panResponder: undefined})   //Clear panResponder when user release on long press
      }
    })
  }

  _normalPanResponder(){
    return PanResponder.create({
      onPanResponderTerminationRequest: () => false,
      onStartShouldSetPanResponderCapture: () => true,
      onPanResponderGrant: (e, gestureState) => {
        this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
        this.state.pan.setValue({x: 0, y: 0})
        this.longPressTimer=setTimeout(this._onLongPress, 400)  // this is where you trigger the onlongpress panResponder handler
      },
      onPanResponderRelease: (e, {vx, vy}) => {
        if (!this.state.panResponder) {
            clearTimeout(this.longPressTimer);   // clean the timeout handler
        }
      }
    })
  }

Define your _onLongPress function:

  _onLongPress(){
    // you can add some animation effect here as wll
    this.setState({panResponder: this._onLongPressPanResponder()})
  }

Define your constructor:

  constructor(props){
    super(props)
    this.state = {
      pan: new Animated.ValueXY()
    };
    this._onLongPress = this._onLongPress.bind(this)
    this._onLongPressPanResponder = this._onLongPressPanResponder.bind(this)
    this._normalPanResponder = this._normalPanResponder.bind(this)
    this.longPressTimer = null
  }

Finally, before you render, you should switch to different panResponder handlers according to the state:

  let panHandlers = {}
    if(this.state.panResponder){
      panHandlers = this.state.panResponder.panHandlers
    }else{
      panHandlers = this._normalPanResponder().panHandlers
    }

Then attach the panHandlers to your view  {...panHandlers}
You can even change the css for different panHandlers to show different effect.


问:
Why I cannot render data correctly although I can receive data (angularjs with flask-restapi/jinja2)
I tried to debug around 2 hours, but no luck.

This is my error:

jinja2.exceptions.UndefinedError
  jinja2.exceptions.UndefinedError: 'item' is undefined

I can receive the data ($scope.questions) correctly.

My index.html:

```<code><html>

<head>
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

    <div ng-app="myApp" ng-controller="myCtrl">
        <div ng-repeat="item in questions">
            {{item.question}}
        </div>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http({
                method: "GET",
                url: "http://127.0.0.1:5000/questions"
            }).then(function mySuccess(response) {
                $scope.questions = response.data;
            }, function myError(response) {
                $scope.myWelcome = response.statusText;
            });
        });
    </script>
</body>

</html>
</code>```

My server side:

```<code>import os

from flask import Flask, request, render_template, Response
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

question_id_serial = 2
questions = {
    1: {
        'id': 1,
        'question': 'Is this hard?',
    },
    2: {
        'id': 2,
        'question': 'Who is going to win the SuperBowl in 2017?',
    }
}

answer_id_serial = 6
answers = {
    1: {
        'id': 1,
        'question_id': 1,
        'answer': 'Yes',
        'count': 0
    },
    2: {
        'id': 2,
        'question_id': 1,
        'answer': 'No',
        'count': 0
    },
    3: {
        'id': 3,
        'question_id': 2,
        'answer': 'Eagles',
        'count': 0
    },
    4: {
        'id': 4,
        'question_id': 2,
        'answer': 'Patriots',
        'count': 0
    },
    5: {
        'id': 5,
        'question_id': 2,
        'answer': 'Seahawks',
        'count': 0
    },
    6: {
        'id': 6,
        'question_id': 2,
        'answer': 'Broncos'
    }
}

class Answer(Resource):
    def get(self, answer_id):
        return answers[answer_id]

    def put(self, answer_id):
        answer = answers[answer_id]
        data = request.get_json()
        values = {k: data.get(k, v) for k, v in answer.items()}
        answers[answer_id].update(values)
        return values

    def delete(self, answer_id):
        values = answers[answer_id]
        del answers[answer_id]
        return values

class Answers(Resource):
    def get(self):
        return answers.values()

    def post(self):
        global answer_id_serial
        answer_id_serial += 1
        data = request.get_json()
        values = {
            'id': answer_id_serial,
            'answer': data['answer'],
            'count': data.get('count', 0),
            'question_id': data['question_id']
        }

        answers[answer_id_serial] = values
        return values

class Question(Resource):
    def get(self, question_id):
        data = questions[question_id].copy()
        data['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return data

    def put(self, question_id):
        question = questions[question_id]
        data = request.get_json()
        data.pop('answers', [])
        values = {k: data.get(k, v) for k, v in question.items()}
        questions[question_id].update(values)
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

    def delete(self, question_id):
        values = questions[question_id]
        del questions[question_id]
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

class Questions(Resource):
    def get(self):
        output = []
        for question in  questions.values():
            question = question.copy()
            question['answers'] = [ans for ans in answers.values() if ans['question_id'] == question['id']]
            output.append(question)
        return output

    def post(self):
        global question_id_serial
        question_id_serial += 1
        data = request.get_json()
        values = {
            'id': question_id_serial,
            'question': data['question']
        }
        questions[question_id_serial] = values
        return values

api.add_resource(Questions, '/questions')
api.add_resource(Question,  '/questions/<int:question_id>')
api.add_resource(Answers,   '/answers')
api.add_resource(Answer,    '/answers/<int:answer_id>')

@app.route('/')
def show_page():
    return render_template('index.html')

@app.route('/assets/<path:path>')
def get_resource(path):
    mimetypes = {
        '.css': 'text/css',
        '.html': 'text/html',
        '.js': 'application/javascript'
    }

    content = open(path).read()
    return Response(content, mimetype=mimetypes[os.path.splitext(path)[1]])

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
After add {% raw %} and {% endraw %} to the template, it works fine now. I refer to this post

I attached working template, hope this will help future developers who works with Flask Restapi and AngularJS:

```<code>{% raw %}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

    <div ng-app="myApp" ng-controller="myCtrl">

        <h1 ng-repeat="question in questions">{{question.question}}</h1>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http({
                method: "GET",
                url: "http://127.0.0.1:5000/questions"
            }).then(function mySuccess(response) {
                $scope.questions = response.data;
            }, function myError(response) {
                $scope.myWelcome = response.statusText;
            });
        });
    </script>
</body>

</html>
{% endraw %}
</code>```

Body:
I tried to debug around 2 hours, but no luck.

This is my error:

jinja2.exceptions.UndefinedError
  jinja2.exceptions.UndefinedError: 'item' is undefined

I can receive the data ($scope.questions) correctly.

My index.html:

            {{item.question}}

My server side:

import os

from flask import Flask, request, render_template, Response
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

question_id_serial = 2
questions = {
    1: {
        'id': 1,
        'question': 'Is this hard?',
    },
    2: {
        'id': 2,
        'question': 'Who is going to win the SuperBowl in 2017?',
    }
}

answer_id_serial = 6
answers = {
    1: {
        'id': 1,
        'question_id': 1,
        'answer': 'Yes',
        'count': 0
    },
    2: {
        'id': 2,
        'question_id': 1,
        'answer': 'No',
        'count': 0
    },
    3: {
        'id': 3,
        'question_id': 2,
        'answer': 'Eagles',
        'count': 0
    },
    4: {
        'id': 4,
        'question_id': 2,
        'answer': 'Patriots',
        'count': 0
    },
    5: {
        'id': 5,
        'question_id': 2,
        'answer': 'Seahawks',
        'count': 0
    },
    6: {
        'id': 6,
        'question_id': 2,
        'answer': 'Broncos'
    }
}

class Answer(Resource):
    def get(self, answer_id):
        return answers[answer_id]

    def put(self, answer_id):
        answer = answers[answer_id]
        data = request.get_json()
        values = {k: data.get(k, v) for k, v in answer.items()}
        answers[answer_id].update(values)
        return values

    def delete(self, answer_id):
        values = answers[answer_id]
        del answers[answer_id]
        return values

class Answers(Resource):
    def get(self):
        return answers.values()

    def post(self):
        global answer_id_serial
        answer_id_serial += 1
        data = request.get_json()
        values = {
            'id': answer_id_serial,
            'answer': data['answer'],
            'count': data.get('count', 0),
            'question_id': data['question_id']
        }

        answers[answer_id_serial] = values
        return values

class Question(Resource):
    def get(self, question_id):
        data = questions[question_id].copy()
        data['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return data

    def put(self, question_id):
        question = questions[question_id]
        data = request.get_json()
        data.pop('answers', [])
        values = {k: data.get(k, v) for k, v in question.items()}
        questions[question_id].update(values)
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

    def delete(self, question_id):
        values = questions[question_id]
        del questions[question_id]
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

class Questions(Resource):
    def get(self):
        output = []
        for question in  questions.values():
            question = question.copy()
            question['answers'] = [ans for ans in answers.values() if ans['question_id'] == question['id']]
            output.append(question)
        return output

    def post(self):
        global question_id_serial
        question_id_serial += 1
        data = request.get_json()
        values = {
            'id': question_id_serial,
            'question': data['question']
        }
        questions[question_id_serial] = values
        return values

api.add_resource(Questions, '/questions')
api.add_resource(Question,  '/questions/<int:question_id>')
api.add_resource(Answers,   '/answers')
api.add_resource(Answer,    '/answers/<int:answer_id>')

@app.route('/')
def show_page():
    return render_template('index.html')

@app.route('/assets/<path:path>')
def get_resource(path):
    mimetypes = {
        '.css': 'text/css',
        '.html': 'text/html',
        '.js': 'application/javascript'
    }

    content = open(path).read()
    return Response(content, mimetype=mimetypes[os.path.splitext(path)[1]])

if __name__ == '__main__':
    app.run(debug=True)

Body:
After add {% raw %} and {% endraw %} to the template, it works fine now. I refer to this post

I attached working template, hope this will help future developers who works with Flask Restapi and AngularJS:

{% raw %}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

    <div ng-app="myApp" ng-controller="myCtrl">

        <h1 ng-repeat="question in questions">{{question.question}}</h1>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http({
                method: "GET",
                url: "http://127.0.0.1:5000/questions"
            }).then(function mySuccess(response) {
                $scope.questions = response.data;
            }, function myError(response) {
                $scope.myWelcome = response.statusText;
            });
        });
    </script>
</body>

</html>
{% endraw %}


问:
vim scrolls wrong window
I am using vim 7.4 under Ubuntu Linux.
When I split window by using ":sp hello.c",
if I click the upper window, then the mouse wheel scrolls the upper window.
But if I click the lower window, then depending on which part of the lower window I click, it scrolls either the upper window or the lower window.
Specifically, if I click inside the upper half of the lower window, it scrolls the upper window; if I click inside the lower half of the lower window, it scrolls the lower window.
How can I make it work correctly?
Thanks.</p>

答:
I was able to get around this problem, by adding the following lines to my .vimrc file:

```<code>noremap <ScrollWheelUp>     4<C-Y>
noremap <ScrollWheelDown>   4<C-E>
noremap <S-ScrollWheelUp>   <C-B>
noremap <S-ScrollWheelDown> <C-F>
</code>```

from the following document:
https://superuser.com/questions/351972/how-can-i-change-the-scroll-wheel-behavior-in-vim-so-that-it-scrolls-instead-of

Title: vim scrolls wrong window

Body:
I was able to get around this problem, by adding the following lines to my .vimrc file:

noremap <ScrollWheelUp>     4<C-Y>
noremap <ScrollWheelDown>   4<C-E>
noremap <S-ScrollWheelUp>   <C-B>
noremap <S-ScrollWheelDown> <C-F>

from the following document:
https://superuser.com/questions/351972/how-can-i-change-the-scroll-wheel-behavior-in-vim-so-that-it-scrolls-instead-of


问:
Print specific part of webpage
I'm trying to print a specific part of my application.

The application has a list of users, displaying their first and last name. When I click a user I get a popup with more detailed information about them.

How would I go about printing just the popup for a user I clicked?
The popup looks like this:

```<code> <div id="user<?=$user->id;?>" class="popup">
      <div class="details">
           User details...
      </div>
      <a href="#print">Print</a>
 </div>
</code>```

The print button isn't working yet though.

答:
Here is my enhanced version that when we want to load css files or there are image references in the part to print.

In these cases, we have to wait until the css files or the images are fully loaded before calling the print() function. Therefor, we'd better to move the print() and close() function calls into the html. Following is the code example:

```<code>var prtContent = document.getElementById("order-to-print");
var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write('<html><head>');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/normalize.css">');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/receipt.css">');
WinPrint.document.write('</head><body onload="print();close();">');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write('</body></html>');
WinPrint.document.close();
WinPrint.focus();
</code>```

Title: Print specific part of webpage

Body:
I'm trying to print a specific part of my application.

The application has a list of users, displaying their first and last name. When I click a user I get a popup with more detailed information about them.

How would I go about printing just the popup for a user I clicked?
The popup looks like this:

 <div id="user<?=$user->id;?>" class="popup">

           User details...

      Print

The print button isn't working yet though.

Body:
Here is my enhanced version that when we want to load css files or there are image references in the part to print.

In these cases, we have to wait until the css files or the images are fully loaded before calling the print() function. Therefor, we'd better to move the print() and close() function calls into the html. Following is the code example:

var prtContent = document.getElementById("order-to-print");
var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write('<html><head>');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/normalize.css">');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/receipt.css">');
WinPrint.document.write('</head><body onload="print();close();">');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write('</body></html>');
WinPrint.document.close();
WinPrint.focus();


问:
How can we plot charts dynamically in iPhone SDK?
In my iPhone app, I need to plot the charts dynamically based on the data that comes from my database.

How can I make the charts and display them?

答:
If your chart should be as simple enough you can try the Google Chart API. Where the chart will be fetched via web. Or you can go for core plot

See this stackoverflow post

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
My Android layout design is not on the same placement when running it on emulator, and shows them incorrect positioned
I am using Android 2.3.3 version and making a tic tac toe game on it. I am  having a problem with a placement of objects when designing the layout, and  also there is something wrong with a game state of the game.
Any help would be great !

look below  image of my layout

Here is my xml code:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sherzod.ion.tictactoeandroid.MainActivity">

    <GridLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="46dp"
        android:layout_marginEnd="1dp"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="46dp"
        android:background="@drawable/board"
        android:columnCount="3"
        android:rowCount="3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="0" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="1"/>

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="2"/>

        <ImageView
            android:id="@+id/imageView9"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="3"/>

        <ImageView
            android:id="@+id/imageView10"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="4"
            tools:ignore="RtlHardcoded" />

        <ImageView
            android:id="@+id/imageView11"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="5" />

        <ImageView
            android:id="@+id/imageView12"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="6"/>

        <ImageView
            android:id="@+id/imageView14"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="7"/>

        <ImageView
            android:id="@+id/imageView13"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="8"/>

    </GridLayout>
</android.support.constraint.ConstraintLayout>
</code>```

Here is my Main Activity file:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    // 0 = yellow ; 1 = red;
    int activePlayer = 0;

    // ** 2 means unplayed
    int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};

    public void dropIn(View view) {

        ImageView counter = (ImageView) view;

        System.out.println(counter.getTag().toString());

        int tappedCounter = Integer.parseInt(counter.getTag().toString());

        if(gameState[tappedCounter] == 2) {
            gameState[tappedCounter] = activePlayer;
        }

        counter.setTranslationY(-1000f);

        if(activePlayer == 0) {
            counter.setImageResource(R.drawable.yellow);
            activePlayer = 1;

        }else {
            counter.setImageResource(R.drawable.red);
            activePlayer = 0;
        }

        counter.animate().translationYBy(1000f).rotation(360).setDuration(200);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

答:
I have made a few changes to your layout:

Added columnWeight and rowWeight to each grid item

Added layout_gravity fill to each grid item

Check the below xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/board"
    android:layout_marginBottom="46dp"
    android:layout_marginEnd="1dp"
    android:layout_marginLeft="1dp"
    android:layout_marginRight="1dp"
    android:layout_marginStart="1dp"
    android:layout_marginTop="46dp"
    android:columnCount="3"
    android:rowCount="3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="0" />

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="1" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="2" />

    <ImageView
        android:id="@+id/imageView9"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="3" />

    <ImageView
        android:id="@+id/imageView10"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="4"
        tools:ignore="RtlHardcoded" />

    <ImageView
        android:id="@+id/imageView11"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="5" />

    <ImageView
        android:id="@+id/imageView12"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="6" />

    <ImageView
        android:id="@+id/imageView14"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="7" />

    <ImageView
        android:id="@+id/imageView13"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="8" />

</GridLayout>
</android.support.constraint.ConstraintLayout>
</code>```

Body:
I am using Android 2.3.3 version and making a tic tac toe game on it. I am  having a problem with a placement of objects when designing the layout, and  also there is something wrong with a game state of the game.
Any help would be great !

look below  image of my layout

Here is my xml code:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sherzod.ion.tictactoeandroid.MainActivity">

    <GridLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="46dp"
        android:layout_marginEnd="1dp"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="46dp"
        android:background="@drawable/board"
        android:columnCount="3"
        android:rowCount="3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="0" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="1"/>

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_row="0"
            android:onClick="dropIn"
            android:tag="2"/>

        <ImageView
            android:id="@+id/imageView9"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="3"/>

        <ImageView
            android:id="@+id/imageView10"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="4"
            tools:ignore="RtlHardcoded" />

        <ImageView
            android:id="@+id/imageView11"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="40dp"
            android:layout_row="1"
            android:onClick="dropIn"
            android:tag="5" />

        <ImageView
            android:id="@+id/imageView12"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="0"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="6"/>

        <ImageView
            android:id="@+id/imageView14"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="2"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="7"/>

        <ImageView
            android:id="@+id/imageView13"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_column="1"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="50dp"
            android:layout_row="2"
            android:onClick="dropIn"
            android:tag="8"/>

    </GridLayout>
</android.support.constraint.ConstraintLayout>

Here is my Main Activity file:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    // 0 = yellow ; 1 = red;
    int activePlayer = 0;

    // ** 2 means unplayed
    int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};

    public void dropIn(View view) {

        ImageView counter = (ImageView) view;

        System.out.println(counter.getTag().toString());

        int tappedCounter = Integer.parseInt(counter.getTag().toString());

        if(gameState[tappedCounter] == 2) {
            gameState[tappedCounter] = activePlayer;
        }

        counter.setTranslationY(-1000f);

        if(activePlayer == 0) {
            counter.setImageResource(R.drawable.yellow);
            activePlayer = 1;

        }else {
            counter.setImageResource(R.drawable.red);
            activePlayer = 0;
        }

        counter.animate().translationYBy(1000f).rotation(360).setDuration(200);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Body:
I have made a few changes to your layout:

Added columnWeight and rowWeight to each grid item

Added layout_gravity fill to each grid item

Check the below xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/board"
    android:layout_marginBottom="46dp"
    android:layout_marginEnd="1dp"
    android:layout_marginLeft="1dp"
    android:layout_marginRight="1dp"
    android:layout_marginStart="1dp"
    android:layout_marginTop="46dp"
    android:columnCount="3"
    android:rowCount="3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="0" />

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="1" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="2" />

    <ImageView
        android:id="@+id/imageView9"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="3" />

    <ImageView
        android:id="@+id/imageView10"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="4"
        tools:ignore="RtlHardcoded" />

    <ImageView
        android:id="@+id/imageView11"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="40dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="5" />

    <ImageView
        android:id="@+id/imageView12"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="6" />

    <ImageView
        android:id="@+id/imageView14"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="7" />

    <ImageView
        android:id="@+id/imageView13"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_gravity="fill"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:onClick="dropIn"
        android:src="@mipmap/ic_launcher"
        android:tag="8" />

</GridLayout>
</android.support.constraint.ConstraintLayout>


问:
select query postgreqs fails on nodejs
i am super new to postgres and trying to do a simple select query.

my table looks like:

create table push_table
(
    seq_id int,
    device_id text,
    primary key (seq_id),
    user_id varchar(100)
);
```

<p>and my nodejs code as follows:</p>

<pre class="lang-javascript prettyprint-override"><code>pool.connect(function (err, client, done)
  {
    if (err) console.log(err)
    myClient = client

    //query if the user exists
    var ageQuery = format('SELECT * from push_table WHERE user_id = ' + userId);
    myClient.query(ageQuery, function (err, result) {
        if (err) {
            console.log(err)
        }
        console.log("number of rows:" + result.rows.length);
    });
  });
</code>```

on running nodejs server log prints:

```<code>{ [error: missing FROM-clause entry for table "catherine"]
  name: 'error',
  length: 113,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '42',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '3129',
  routine: 'errorMissingRTE' }
/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58
                            console.log("number of rows:" + result.rows.length);
                                                                  ^

TypeError: Cannot read property 'rows' of undefined
    at null.callback (/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58:46)
    at Query.handleError (/data/OSC_Push_OOW/shared/node_modules/pg/lib/query.js:161:17)
    at null.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/client.js:188:26)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Socket.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/connection.js:133:12)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
</code>```

答:
The column user_id is varchar:

```<code>user_id varchar(100)
</code>```

so a valid SQL query must use single quotes to define the varchar value, e.g.:

```<code>SELECT * from push_table WHERE user_id = 'Vik'
</code>```

Your code does not provide the quotes needed.

Title: select query postgreqs fails on nodejs

Body:
i am super new to postgres and trying to do a simple select query.

my table looks like:

create table push_table
(
    seq_id int,
    device_id text,
    primary key (seq_id),
    user_id varchar(100)
);

and my nodejs code as follows:

pool.connect(function (err, client, done)
  {
    if (err) console.log(err)
    myClient = client

    //query if the user exists
    var ageQuery = format('SELECT * from push_table WHERE user_id = ' + userId);
    myClient.query(ageQuery, function (err, result) {
        if (err) {
            console.log(err)
        }
        console.log("number of rows:" + result.rows.length);
    });
  });

on running nodejs server log prints:

{ [error: missing FROM-clause entry for table "catherine"]
  name: 'error',
  length: 113,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '42',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '3129',
  routine: 'errorMissingRTE' }
/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58
                            console.log("number of rows:" + result.rows.length);
                                                                  ^

TypeError: Cannot read property 'rows' of undefined
    at null.callback (/data/OSC_Push_OOW/releases/20170703215021/api/controllers/pushcontroller.js:58:46)
    at Query.handleError (/data/OSC_Push_OOW/shared/node_modules/pg/lib/query.js:161:17)
    at null.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/client.js:188:26)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Socket.<anonymous> (/data/OSC_Push_OOW/shared/node_modules/pg/lib/connection.js:133:12)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)

Body:
The column user_id is varchar:

user_id varchar(100)

so a valid SQL query must use single quotes to define the varchar value, e.g.:

SELECT * from push_table WHERE user_id = 'Vik'

Your code does not provide the quotes needed.


问:
Apollo Client subscriptions must provide schema
I have no idea why it is happening.
I am listening to subscription postAdded which gets published every time I create a post using mutation.

```<code>import React, { Component } from 'react'
import { graphql, gql } from 'react-apollo'

class App extends Component {
  componentDidMount() {
    this.props.subscribeToNewPosts()
  }

  render() {
    return (
      <div>
        <h1>Hello world</h1>
        {console.log(this.props)}
      </div>
    )
  }
}

const Query = gql`
  query Posts {
    posts {
      id
      title
      content
      author {
        firstName
        lastName
      }
    }
  }
`

const Subscription = gql`
  subscription postAdded {
    postAdded {
      id
      title
      content
      author {
        firstName
        lastName
      }
    }
  }
`

App = graphql(Query, {
  name: 'posts',
  props: props => {
    return {
      subscribeToNewPosts: () => {
        return props.posts.subscribeToMore({
          document: Subscription,
          updateQuery: (prev, { subscriptionData }) => {
            if(!subscriptionData.data) {
              return prev
            }

            const newPost = subscriptionData.data.postAdded

            console.log(newPost)

            return {
              ...prev,
              posts: [...prev.posts, newPost]
            }
          }
        })
      },
      posts: props.posts
    }
  }
})(App)

export default App
</code>```

The error:

答:
First, this is most likely a server implementation issue. The error is likely being throw by graphql-tools that's your graphql end point.

The exact same thing happened to me while following second part of the Full-stack + GraphQL tutorial on the official blog.

While it is not necessarily the same case, what happened to me was that the tutorial exports the schema object with: export { schema } which is equivalent to export { schema: schema } instead of the usual exports as default, e.g. export default schema

In my graphql server endpoint I import with import schema from './src/schema' which was wrong because schema was exported as a sub object and not the default export. Correct import for my case should have been import { schema } from './src/schema'

TL;DR Check your server code, check your export and import statements. The error message is really misleading but it most likely has to do with module import/ export.

It could have been avoided or giving more explicit information if we were compiling using webpack instead of using babel-node like in the tutorial.

Body:
I have no idea why it is happening.
I am listening to subscription postAdded which gets published every time I create a post using mutation.

import React, { Component } from 'react'
import { graphql, gql } from 'react-apollo'

class App extends Component {
  componentDidMount() {
    this.props.subscribeToNewPosts()
  }

  render() {
    return (

Hello world

        {console.log(this.props)}

    )
  }
}

const Query = gql`
  query Posts {
    posts {
      id
      title
      content
      author {
        firstName
        lastName
      }
    }
  }
`

const Subscription = gql`
  subscription postAdded {
    postAdded {
      id
      title
      content
      author {
        firstName
        lastName
      }
    }
  }
`

App = graphql(Query, {
  name: 'posts',
  props: props => {
    return {
      subscribeToNewPosts: () => {
        return props.posts.subscribeToMore({
          document: Subscription,
          updateQuery: (prev, { subscriptionData }) => {
            if(!subscriptionData.data) {
              return prev
            }

            const newPost = subscriptionData.data.postAdded

            console.log(newPost)

            return {
              ...prev,
              posts: [...prev.posts, newPost]
            }
          }
        })
      },
      posts: props.posts
    }
  }
})(App)

export default App

The error: