问:
Batching and shuffling padded tf.train.SequenceExample
I have some training example of a sequence-to-sequence scenario which are stored as tf.train.SequenceExample in one (or more) file(s) written TFRecordWriter. I would like to read, decode them and feed shuffled batches of them into my network. I have been struggling with the documentation and some tutorials found here and there but I could not make anything out of such stuff. I am working on a self-contained example, here below.

```<code>import random

import tensorflow as tf

from six.moves import xrange

MIN_LEN = 6
MAX_LEN = 12
NUM_EXAMPLES = 20
BATCH_SIZE = 3
PATH = 'ciaone.tfrecords'
MIN_AFTER_DEQUEUE = 10
NUM_THREADS = 2
SAFETY_MARGIN = 1
CAPACITY = MIN_AFTER_DEQUEUE + (NUM_THREADS + SAFETY_MARGIN) * BATCH_SIZE

def generate_example():
    # fake examples which are just useful to have a quick visualization.
    # The input is a sequence of random numbers.
    # The output is a sequence made of those numbers from the
    # input sequence which are greater or equal then the average.
    length = random.randint(MIN_LEN, MAX_LEN)
    input_ = [random.randint(0, 10) for _ in xrange(length)]
    avg = sum([1.0 * item for item in input_]) / len(input_)
    output = [item for item in input_ if item >= avg]
    return input_, output

def encode(input_, output):
    length = len(input_)
    example = tf.train.SequenceExample(
        context=tf.train.Features(
            feature={
                'length': tf.train.Feature(
                    int64_list=tf.train.Int64List(value=[length]))
            }),
        feature_lists=tf.train.FeatureLists(
            feature_list={
                'input': tf.train.FeatureList(
                    feature=[
                        tf.train.Feature(
                            int64_list=tf.train.Int64List(value=[item]))
                        for item in input_]),
                'output': tf.train.FeatureList(
                    feature=[
                        tf.train.Feature(
                            int64_list=tf.train.Int64List(value=[item]))
                        for item in output])
            }
        )
    )
    return example

def decode(example):
    context_features = {
        'length': tf.FixedLenFeature([], tf.int64)
    }
    sequence_features = {
        'input': tf.FixedLenSequenceFeature([], tf.int64),
        'output': tf.FixedLenSequenceFeature([], tf.int64)
    }
    ctx, seq = tf.parse_single_sequence_example(
        example, context_features, sequence_features)
    input_ = seq['input']
    output = seq['output']
    return input_, output

if __name__ == '__main__':
    # STEP 1. -- generate a dataset.
    with tf.python_io.TFRecordWriter(PATH) as writer:
        for _ in xrange(NUM_EXAMPLES):
           record = encode(*generate_example())
           writer.write(record.SerializeToString())

    with tf.Session() as sess:
        queue = tf.train.string_input_producer([PATH])
        reader = tf.TFRecordReader()
        _, value = reader.read(queue)
        input_, output = decode(value)

        # HERE I AM STUCK!

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        sess.run(tf.local_variables_initializer())
        sess.run(tf.global_variables_initializer())
        try:
            while True:
                # do something...
        except tf.errors.OutOfRangeError, e:
            coord.request_stop(e)
        finally:
            coord.request_stop()
            coord.join(threads)
        coord.request_stop()
        coord.join(threads)
</code>```

Can anyone suggest me how to proceed?
Thanks in advance!

P.S. as a side request: any pointer about resources to better understand the input pipeline APIs of TensorFlow is appreciated.

答:
If you were dealing with Examples rather than SequenceExamples, it would be as easy as adding a call to tf.train.shuffle_batch on your decoded tensors.

```<code>_, value = reader.read(queue)
input_, output = decode(value)
batch_input, batch_output = tf.train.shuffle_batch([input_, output],
    batch_size=BATCH_SIZE, capacity=CAPACITY,
    min_after_sequeue=MIN_AFTER_DEQUEUE)
</code>```

However, shuffle-batch requires that the tensors you pass in have a static shape, which is not true here. For variable shape tensors, you can instead use tf.train.batch with dynamic_pad=True. This will take care of the batching (and padding) for you, but will not shuffle your examples. Unfortunately, shuffle_batch does not take a dynamic_pad argument.

There's a workaround described here where you can add a RandomShuffleQueue before the call to tf.train.batch:

```<code>inputs = decode(value)
dtypes = list(map(lambda x: x.dtype, inputs))
shapes = list(map(lambda x: x.get_shape(), inputs))
queue = tf.RandomShuffleQueue(CAPACITY, MIN_AFTER_DEQUEUE, dtypes)
enqueue_op = queue.enqueue(inputs)
qr = tf.train.QueueRunner(queue, [enqueue_op] * NUM_THREADS)
tf.add_to_collection(tf.GraphKeys.QUEUE_RUNNERS, qr)
inputs = queue.dequeue()
for tensor, shape in zip(inputs, shapes):
    tensor.set_shape(shape)

# Now you can use tf.train.batch with dynamic_pad=True, and the order in which
# it enqueues elements will be permuted because of RandomShuffleQueue.
batch_input, batch_output = tf.train.batch(inputs, batch_size, capacity=capacity,
                              dynamic_pad=True, name=name)
</code>```

There's an example of this pattern implemented here (in Google's Magenta project).

Body:
I have some training example of a sequence-to-sequence scenario which are stored as tf.train.SequenceExample in one (or more) file(s) written TFRecordWriter. I would like to read, decode them and feed shuffled batches of them into my network. I have been struggling with the documentation and some tutorials found here and there but I could not make anything out of such stuff. I am working on a self-contained example, here below.

import random

import tensorflow as tf

from six.moves import xrange

MIN_LEN = 6
MAX_LEN = 12
NUM_EXAMPLES = 20
BATCH_SIZE = 3
PATH = 'ciaone.tfrecords'
MIN_AFTER_DEQUEUE = 10
NUM_THREADS = 2
SAFETY_MARGIN = 1
CAPACITY = MIN_AFTER_DEQUEUE + (NUM_THREADS + SAFETY_MARGIN) * BATCH_SIZE

def generate_example():
    # fake examples which are just useful to have a quick visualization.
    # The input is a sequence of random numbers.
    # The output is a sequence made of those numbers from the
    # input sequence which are greater or equal then the average.
    length = random.randint(MIN_LEN, MAX_LEN)
    input_ = [random.randint(0, 10) for _ in xrange(length)]
    avg = sum([1.0 * item for item in input_]) / len(input_)
    output = [item for item in input_ if item >= avg]
    return input_, output

def encode(input_, output):
    length = len(input_)
    example = tf.train.SequenceExample(
        context=tf.train.Features(
            feature={
                'length': tf.train.Feature(
                    int64_list=tf.train.Int64List(value=[length]))
            }),
        feature_lists=tf.train.FeatureLists(
            feature_list={
                'input': tf.train.FeatureList(
                    feature=[
                        tf.train.Feature(
                            int64_list=tf.train.Int64List(value=[item]))
                        for item in input_]),
                'output': tf.train.FeatureList(
                    feature=[
                        tf.train.Feature(
                            int64_list=tf.train.Int64List(value=[item]))
                        for item in output])
            }
        )
    )
    return example

def decode(example):
    context_features = {
        'length': tf.FixedLenFeature([], tf.int64)
    }
    sequence_features = {
        'input': tf.FixedLenSequenceFeature([], tf.int64),
        'output': tf.FixedLenSequenceFeature([], tf.int64)
    }
    ctx, seq = tf.parse_single_sequence_example(
        example, context_features, sequence_features)
    input_ = seq['input']
    output = seq['output']
    return input_, output

if __name__ == '__main__':
    # STEP 1. -- generate a dataset.
    with tf.python_io.TFRecordWriter(PATH) as writer:
        for _ in xrange(NUM_EXAMPLES):
           record = encode(*generate_example())
           writer.write(record.SerializeToString())

    with tf.Session() as sess:
        queue = tf.train.string_input_producer([PATH])
        reader = tf.TFRecordReader()
        _, value = reader.read(queue)
        input_, output = decode(value)

        # HERE I AM STUCK!

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        sess.run(tf.local_variables_initializer())
        sess.run(tf.global_variables_initializer())
        try:
            while True:
                # do something...
        except tf.errors.OutOfRangeError, e:
            coord.request_stop(e)
        finally:
            coord.request_stop()
            coord.join(threads)
        coord.request_stop()
        coord.join(threads)

Can anyone suggest me how to proceed?
Thanks in advance!

P.S. as a side request: any pointer about resources to better understand the input pipeline APIs of TensorFlow is appreciated.

Body:
If you were dealing with Examples rather than SequenceExamples, it would be as easy as adding a call to tf.train.shuffle_batch on your decoded tensors.

_, value = reader.read(queue)
input_, output = decode(value)
batch_input, batch_output = tf.train.shuffle_batch([input_, output],
    batch_size=BATCH_SIZE, capacity=CAPACITY,
    min_after_sequeue=MIN_AFTER_DEQUEUE)

However, shuffle-batch requires that the tensors you pass in have a static shape, which is not true here. For variable shape tensors, you can instead use tf.train.batch with dynamic_pad=True. This will take care of the batching (and padding) for you, but will not shuffle your examples. Unfortunately, shuffle_batch does not take a dynamic_pad argument.

There's a workaround described here where you can add a RandomShuffleQueue before the call to tf.train.batch:

inputs = decode(value)
dtypes = list(map(lambda x: x.dtype, inputs))
shapes = list(map(lambda x: x.get_shape(), inputs))
queue = tf.RandomShuffleQueue(CAPACITY, MIN_AFTER_DEQUEUE, dtypes)
enqueue_op = queue.enqueue(inputs)
qr = tf.train.QueueRunner(queue, [enqueue_op] * NUM_THREADS)
tf.add_to_collection(tf.GraphKeys.QUEUE_RUNNERS, qr)
inputs = queue.dequeue()
for tensor, shape in zip(inputs, shapes):
    tensor.set_shape(shape)

# Now you can use tf.train.batch with dynamic_pad=True, and the order in which
# it enqueues elements will be permuted because of RandomShuffleQueue.
batch_input, batch_output = tf.train.batch(inputs, batch_size, capacity=capacity,
                              dynamic_pad=True, name=name)

There's an example of this pattern implemented here (in Google's Magenta project).


来源: stackexchange

问:
Send an image to another Activity - How change a resource to integer?
How can I send image res to another Activity - How change Resources to integer?
i create class to pass Image Resources to another activity:

public class MyImageView extends ImageView implements View.OnClickListener {

```<code>Context contxt;

public MyImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setOnClickListener(this);
    this.contxt = context;
}

public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnClickListener(this);
    this.contxt = context;
}

public MyImageView(Context context) {
    super(context);
    setOnClickListener(this);
    this.contxt = context;
}

@Override
public void setOnClickListener(OnClickListener l) {

    super.setOnClickListener(l);
}

@Override
public void onClick(View v) {

    int g = getResourse......................;(this is my peroblem)
    Bundle extras = new Bundle();
    extras.putInt("imagebitmap", g);
    Intent i = new Intent(contxt, zara.knauf.Img.class);
    i.putExtras(extras);
    contxt.startActivity(i);

}
}
</code>```

答:
Simply set g to a R.drawable integer value. You don't need to call getResources.

You also don't need to create a Bundle object.

See How to pass integer from one activity to another?

ContentLicense: CC BY-SA 3.0

Body:
How can I send image res to another Activity - How change Resources to integer?
i create class to pass Image Resources to another activity:

public class MyImageView extends ImageView implements View.OnClickListener {

Context contxt;

public MyImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setOnClickListener(this);
    this.contxt = context;
}

public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnClickListener(this);
    this.contxt = context;
}

public MyImageView(Context context) {
    super(context);
    setOnClickListener(this);
    this.contxt = context;
}

@Override
public void setOnClickListener(OnClickListener l) {

    super.setOnClickListener(l);
}

@Override
public void onClick(View v) {

    int g = getResourse......................;(this is my peroblem)
    Bundle extras = new Bundle();
    extras.putInt("imagebitmap", g);
    Intent i = new Intent(contxt, zara.knauf.Img.class);
    i.putExtras(extras);
    contxt.startActivity(i);

}
}


问:
How do I perform a collision check?
I have no clue what to do here, I want to make it so that a turtle in Python will shoot a bullet and if it collides with the other turtle, the score goes up. Except if I run this code, the game will crash when I shoot the bullet. So far, I only tried it for one of the eight move commands.

```<code>#imports turtles
import turtle
import random
#Sets screen, turtle program, and colour group
turtle.setup(1000, 800)
screen = turtle.Screen()
wn = turtle.Screen()
wn.bgcolor("springgreen")

amir = turtle.Turtle()
amir.shape("arrow")
amir.shapesize(1)
amir.speed(10)
amir.pensize (2)
amir.color("blue")
amir.setheading(90)
amir.penup()
#bullet 1
jonafat = turtle.Turtle()
jonafat.shape("circle")
jonafat.shapesize(0.5)
jonafat.speed(2)
jonafat.pensize (1)
jonafat.color("black")
jonafat.penup()
jonafat.ht()

hossein = turtle.Turtle()
hossein.shape("arrow")
hossein.shapesize(1)
hossein.speed(10)
hossein.pensize (2)
hossein.color("gold")
hossein.setheading(90)
hossein.penup()
#bullet
jonafat2 = turtle.Turtle()
jonafat2.shape("circle")
jonafat2.shapesize(0.5)
jonafat2.speed(2)
jonafat2.pensize (1)
jonafat2.color("black")
jonafat2.penup()
jonafat2.ht()
#scoreboard
TT = turtle.Turtle()
TT.ht()
TT.penup()
TT.goto(-500,200)
TT.color("black")
TT.write("0", move = False, align = "center", font = ("Arial", 20, "normal"))
#second scoreboard
TT = turtle.Turtle()
TT.ht()
TT.penup()
TT.goto(-500,200)
TT.color("black")
TT.write("0", move = False, align = "center", font = ("Arial", 20, "normal"))

x = 0
y = 0
amirs = 2
hosseins = 2
auto = 15
vanguard = 15
trump = 0
time = 1
score = 0
panda = 295

def up():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(90)
    n = 1
    for i in range(0, n):
        amir.sety(amir.ycor()+10)
        n + 1

def down():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(270)
    n = 1
    for i in range(0, n):
        amir.sety(amir.ycor()-10)
        n + 1

def left():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(180)
    n = 1
    for i in range(0, n):
        amir.setx(amir.xcor()-10)
        n + 1

def right():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(0)
    n = 1
    for i in range(0, n):
        amir.setx(amir.xcor()+10)
        n + 1

def up2():
    global hossein
    global y
    global hosseins
    hossein.seth(90)
    n = 1
    for i in range(0, n):
        hossein.sety(hossein.ycor()+10)
        n + 1

def down2():
    global hossein
    global y
    global hosseins
    hossein.seth(270)
    n = 1
    for i in range(0, n):
        hossein.sety(hossein.ycor()-10)
        n + 1

def left2():
    global hossein
    global y
    global hosseins
    hossein.seth(180)
    n = 1
    for i in range(0, n):
        hossein.setx(hossein.xcor()-10)
        n + 1

def right2():
    global hossein
    global y
    global hosseins
    hossein.seth(0)
    n = 1
    for i in range(0, n):
        hossein.setx(hossein.xcor()+10)
        n + 1

def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash

def clock():
    global time
    time = time-1

def move():
    global auto
    global vanguard
    global score
    global time
    wn.ontimer(clock,1000)
    angle = amir.heading()
    jonafat.ht()
    jonafat.speed(10)
    jonafat.setpos(amir.xcor(), amir.ycor())
    if angle == 0:
        trump = 1.
        time = time-1
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()+300, amir.ycor())
            n + 1
        infLoop = 1
        while infLoop == 1:
                if collisionCheck(jonafat, hossein) == True:
                    infLoop = 0
                    break
                    score = score + 1
                    TT.clear()
                    TT.write(score, move = False, align = "center", font = ("Arial", 20, "normal"))

                if time == 0:
                    break
                    infLoop = 0

    if angle == 90:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor(),amir.ycor()+300)
            n + 1
    if angle == 180:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()-300, amir.ycor())
            n + 1
    if angle == 270:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor(), amir.ycor()-300)
            n + 1

def move2():
    angle2 = hossein.heading()
    jonafat2.ht()
    jonafat2.speed(10)
    jonafat2.setpos(hossein.xcor(), hossein.ycor())
    if angle2 == 0:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor()+300, hossein.ycor())
            n + 1
    if angle2 == 90:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor(), hossein.ycor()+300)
            n + 1
    if angle2 == 180:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor()-300, hossein.ycor())
            n + 1
    if angle2 == 270:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor(), hossein.ycor()-300)
            n + 1

wn.onkeypress(up, "w")
wn.onkeypress(down, "s")
wn.onkeypress(left, "a")
wn.onkeypress(right, "d")
wn.onkeypress(up2, "Up")
wn.onkeypress(down2, "Down")
wn.onkeypress(left2, "Left")
wn.onkeypress(right2, "Right")
wn.onkeypress(move2, "Shift_R")

wn.onkeypress(move, "space")

wn.listen()
</code>```

This is the part I have trouble with

```<code>def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash

def clock():
    global time
    time = time-1

def move():
    global auto
    global vanguard
    global score
    global time
    wn.ontimer(clock,1000)
    angle = amir.heading()
    jonafat.ht()
    jonafat.speed(10)
    jonafat.setpos(amir.xcor(), amir.ycor())
    if angle == 0:
        trump = 1.
        time = time-1
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()+300, amir.ycor())
            n + 1
        infLoop = 1
        while infLoop == 1:
                if collisionCheck(jonafat, hossein) == True:
                    infLoop = 0
                    break
                    score = score + 1
                    TT.clear()
                    TT.write(score, move = False, align = "center", font = ("Arial", 20, "normal"))

                if time == 0:
                    break
                    infLoop = 0
</code>```

答:
Instead of all this:

```<code>def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash
</code>```

Let's take advantage of @JoshuaWaring's advice as well as turtle's distance() method and come up with something more like:

```<code>PERSONAL_SPACE = 10  # assign this to be how close is too close

def collisionCheck(jonafat, hossein):
    return jonafat.distance(hossein) < PERSONAL_SPACE
</code>```

Let's rework the rest of the code to produce a minimally playable game:

```<code># imports turtles
from turtle import Turtle, Screen

PERSONAL_SPACE = 15  # assign this to be how close is too close
FIRE_DISTANCE = 300
FONT = ('Arial', 36, 'normal')

# Sets screen, turtle program, and color group
screen = Screen()
screen.setup(1000, 800)
screen.bgcolor('springgreen')

def collisionCheck(bullet, player):
    return bullet.distance(player) < PERSONAL_SPACE

def up1():
    player1.seth(90)
    player1.forward(10)

def down1():
    player1.seth(270)
    player1.forward(10)

def left1():
    player1.seth(180)
    player1.forward(10)

def right1():
    player1.seth(0)
    player1.forward(10)

def clock1():
    global time1, score1

    if collisionCheck(bullet1, player2):
        score1 += 1
        TT1.undo()
        TT1.write(score1, align='center', font=FONT)
        time1 = 1
    else:
        bullet1.forward(1)

    time1 -= 1

    if time1:
        screen.ontimer(clock1, 10)
    else:
        bullet1.hideturtle()

def fire1():
    global time1

    bullet1.setpos(player1.pos())
    bullet1.setheading(player1.heading())
    bullet1.showturtle()

    time1 = FIRE_DISTANCE
    screen.ontimer(clock1, 100)

screen.onkeypress(up1, 'w')
screen.onkeypress(down1, 's')
screen.onkeypress(left1, 'a')
screen.onkeypress(right1, 'd')
screen.onkeypress(fire1, 'space')

def up2():
    player2.seth(90)
    player2.forward(10)

def down2():
    player2.seth(270)
    player2.forward(10)

def left2():
    player2.seth(180)
    player2.forward(10)

def right2():
    player2.seth(0)
    player2.forward(10)

def clock2():
    global time2, score2

    if collisionCheck(bullet2, player1):
        score2 += 1
        TT2.undo()
        TT2.write(score2, align='center', font=FONT)
        time2 = 1
    else:
        bullet2.forward(1)

    time2 -= 1

    if time2:
        screen.ontimer(clock2, 10)
    else:
        bullet2.hideturtle()

def fire2():
    global time2

    bullet2.setpos(player2.pos())
    bullet2.setheading(player2.heading())
    bullet2.showturtle()

    time2 = FIRE_DISTANCE
    screen.ontimer(clock2, 100)

screen.onkeypress(up2, 'Up')
screen.onkeypress(down2, 'Down')
screen.onkeypress(left2, 'Left')
screen.onkeypress(right2, 'Right')
screen.onkeypress(fire2, '0')

player1 = Turtle('arrow')
player1.speed('fastest')
player1.color('blue')
player1.setheading(180)
player1.penup()
player1.forward(10)

# bullet 1
bullet1 = Turtle('circle', visible=False)
bullet1.shapesize(0.5)
bullet1.speed('fastest')
bullet1.color('black', 'blue')
bullet1.penup()

player2 = Turtle('arrow')
player2.speed('fastest')
player2.color('gold')
player2.setheading(0)
player2.penup()
player2.forward(10)

# bullet 2
bullet2 = Turtle('circle', visible=False)
bullet2.shapesize(0.5)
bullet2.speed('fastest')
bullet2.color('black', 'gold')
bullet2.penup()

# scoreboard
TT1 = Turtle(visible=False)
TT1.penup()
TT1.goto(-450, 300)
TT1.color('blue')
TT1.write('0', align='center', font=FONT)

# second scoreboard
TT2 = Turtle(visible=False)
TT2.penup()
TT2.goto(450, 300)
TT2.color('gold')
TT2.write('0', align='center', font=FONT)

time1 = 0
score1 = 0

time2 = 0
score2 = 0

screen.listen()

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

Still needs additional work, i.e. doesn't handle (or disable) multiple shots correctly, etc.

Title: How do I perform a collision check?

Body:
I have no clue what to do here, I want to make it so that a turtle in Python will shoot a bullet and if it collides with the other turtle, the score goes up. Except if I run this code, the game will crash when I shoot the bullet. So far, I only tried it for one of the eight move commands.

#imports turtles
import turtle
import random
#Sets screen, turtle program, and colour group
turtle.setup(1000, 800)
screen = turtle.Screen()
wn = turtle.Screen()
wn.bgcolor("springgreen")

amir = turtle.Turtle()
amir.shape("arrow")
amir.shapesize(1)
amir.speed(10)
amir.pensize (2)
amir.color("blue")
amir.setheading(90)
amir.penup()
#bullet 1
jonafat = turtle.Turtle()
jonafat.shape("circle")
jonafat.shapesize(0.5)
jonafat.speed(2)
jonafat.pensize (1)
jonafat.color("black")
jonafat.penup()
jonafat.ht()

hossein = turtle.Turtle()
hossein.shape("arrow")
hossein.shapesize(1)
hossein.speed(10)
hossein.pensize (2)
hossein.color("gold")
hossein.setheading(90)
hossein.penup()
#bullet
jonafat2 = turtle.Turtle()
jonafat2.shape("circle")
jonafat2.shapesize(0.5)
jonafat2.speed(2)
jonafat2.pensize (1)
jonafat2.color("black")
jonafat2.penup()
jonafat2.ht()
#scoreboard
TT = turtle.Turtle()
TT.ht()
TT.penup()
TT.goto(-500,200)
TT.color("black")
TT.write("0", move = False, align = "center", font = ("Arial", 20, "normal"))
#second scoreboard
TT = turtle.Turtle()
TT.ht()
TT.penup()
TT.goto(-500,200)
TT.color("black")
TT.write("0", move = False, align = "center", font = ("Arial", 20, "normal"))

x = 0
y = 0
amirs = 2
hosseins = 2
auto = 15
vanguard = 15
trump = 0
time = 1
score = 0
panda = 295

def up():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(90)
    n = 1
    for i in range(0, n):
        amir.sety(amir.ycor()+10)
        n + 1

def down():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(270)
    n = 1
    for i in range(0, n):
        amir.sety(amir.ycor()-10)
        n + 1

def left():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(180)
    n = 1
    for i in range(0, n):
        amir.setx(amir.xcor()-10)
        n + 1

def right():
    global amir
    global x
    global amirs
    global hosseins
    amir.seth(0)
    n = 1
    for i in range(0, n):
        amir.setx(amir.xcor()+10)
        n + 1

def up2():
    global hossein
    global y
    global hosseins
    hossein.seth(90)
    n = 1
    for i in range(0, n):
        hossein.sety(hossein.ycor()+10)
        n + 1

def down2():
    global hossein
    global y
    global hosseins
    hossein.seth(270)
    n = 1
    for i in range(0, n):
        hossein.sety(hossein.ycor()-10)
        n + 1

def left2():
    global hossein
    global y
    global hosseins
    hossein.seth(180)
    n = 1
    for i in range(0, n):
        hossein.setx(hossein.xcor()-10)
        n + 1

def right2():
    global hossein
    global y
    global hosseins
    hossein.seth(0)
    n = 1
    for i in range(0, n):
        hossein.setx(hossein.xcor()+10)
        n + 1

def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash

def clock():
    global time
    time = time-1

def move():
    global auto
    global vanguard
    global score
    global time
    wn.ontimer(clock,1000)
    angle = amir.heading()
    jonafat.ht()
    jonafat.speed(10)
    jonafat.setpos(amir.xcor(), amir.ycor())
    if angle == 0:
        trump = 1.
        time = time-1
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()+300, amir.ycor())
            n + 1
        infLoop = 1
        while infLoop == 1:
                if collisionCheck(jonafat, hossein) == True:
                    infLoop = 0
                    break
                    score = score + 1
                    TT.clear()
                    TT.write(score, move = False, align = "center", font = ("Arial", 20, "normal"))

                if time == 0:
                    break
                    infLoop = 0

    if angle == 90:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor(),amir.ycor()+300)
            n + 1
    if angle == 180:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()-300, amir.ycor())
            n + 1
    if angle == 270:
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor(), amir.ycor()-300)
            n + 1

def move2():
    angle2 = hossein.heading()
    jonafat2.ht()
    jonafat2.speed(10)
    jonafat2.setpos(hossein.xcor(), hossein.ycor())
    if angle2 == 0:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor()+300, hossein.ycor())
            n + 1
    if angle2 == 90:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor(), hossein.ycor()+300)
            n + 1
    if angle2 == 180:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor()-300, hossein.ycor())
            n + 1
    if angle2 == 270:
        jonafat2.showturtle()
        jonafat2.speed(2)
        n = 1
        for i in range(0, n):
            jonafat2.goto(hossein.xcor(), hossein.ycor()-300)
            n + 1

wn.onkeypress(up, "w")
wn.onkeypress(down, "s")
wn.onkeypress(left, "a")
wn.onkeypress(right, "d")
wn.onkeypress(up2, "Up")
wn.onkeypress(down2, "Down")
wn.onkeypress(left2, "Left")
wn.onkeypress(right2, "Right")
wn.onkeypress(move2, "Shift_R")

wn.onkeypress(move, "space")

wn.listen()

This is the part I have trouble with

def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash

def clock():
    global time
    time = time-1

def move():
    global auto
    global vanguard
    global score
    global time
    wn.ontimer(clock,1000)
    angle = amir.heading()
    jonafat.ht()
    jonafat.speed(10)
    jonafat.setpos(amir.xcor(), amir.ycor())
    if angle == 0:
        trump = 1.
        time = time-1
        jonafat.showturtle()
        jonafat.speed(2)
        n = 1
        for i in range(0, n):
            jonafat.goto(amir.xcor()+300, amir.ycor())
            n + 1
        infLoop = 1
        while infLoop == 1:
                if collisionCheck(jonafat, hossein) == True:
                    infLoop = 0
                    break
                    score = score + 1
                    TT.clear()
                    TT.write(score, move = False, align = "center", font = ("Arial", 20, "normal"))

                if time == 0:
                    break
                    infLoop = 0

Body:
Instead of all this:

def collisionCheck(jonafat, hossein):
    crash = True
    jonafat1X = jonafat.xcor()
    jonafat1Y = jonafat.ycor()
    hossein2X = hossein.xcor()
    hossein2Y = hossein.ycor()
    jonafatPos = (int(jonafat1X), int(jonafat1Y))
    hosseinPos = (int(hossein2X), int(hossein2Y))
    if jonafatPos != hosseinPos:
        crash = False
    if jonafatPos == hosseinPos:
        crash = True
    return crash

Let's take advantage of @JoshuaWaring's advice as well as turtle's distance() method and come up with something more like:

PERSONAL_SPACE = 10  # assign this to be how close is too close

def collisionCheck(jonafat, hossein):
    return jonafat.distance(hossein) < PERSONAL_SPACE

Let's rework the rest of the code to produce a minimally playable game:

# imports turtles
from turtle import Turtle, Screen

PERSONAL_SPACE = 15  # assign this to be how close is too close
FIRE_DISTANCE = 300
FONT = ('Arial', 36, 'normal')

# Sets screen, turtle program, and color group
screen = Screen()
screen.setup(1000, 800)
screen.bgcolor('springgreen')

def collisionCheck(bullet, player):
    return bullet.distance(player) < PERSONAL_SPACE

def up1():
    player1.seth(90)
    player1.forward(10)

def down1():
    player1.seth(270)
    player1.forward(10)

def left1():
    player1.seth(180)
    player1.forward(10)

def right1():
    player1.seth(0)
    player1.forward(10)

def clock1():
    global time1, score1

    if collisionCheck(bullet1, player2):
        score1 += 1
        TT1.undo()
        TT1.write(score1, align='center', font=FONT)
        time1 = 1
    else:
        bullet1.forward(1)

    time1 -= 1

    if time1:
        screen.ontimer(clock1, 10)
    else:
        bullet1.hideturtle()

def fire1():
    global time1

    bullet1.setpos(player1.pos())
    bullet1.setheading(player1.heading())
    bullet1.showturtle()

    time1 = FIRE_DISTANCE
    screen.ontimer(clock1, 100)

screen.onkeypress(up1, 'w')
screen.onkeypress(down1, 's')
screen.onkeypress(left1, 'a')
screen.onkeypress(right1, 'd')
screen.onkeypress(fire1, 'space')

def up2():
    player2.seth(90)
    player2.forward(10)

def down2():
    player2.seth(270)
    player2.forward(10)

def left2():
    player2.seth(180)
    player2.forward(10)

def right2():
    player2.seth(0)
    player2.forward(10)

def clock2():
    global time2, score2

    if collisionCheck(bullet2, player1):
        score2 += 1
        TT2.undo()
        TT2.write(score2, align='center', font=FONT)
        time2 = 1
    else:
        bullet2.forward(1)

    time2 -= 1

    if time2:
        screen.ontimer(clock2, 10)
    else:
        bullet2.hideturtle()

def fire2():
    global time2

    bullet2.setpos(player2.pos())
    bullet2.setheading(player2.heading())
    bullet2.showturtle()

    time2 = FIRE_DISTANCE
    screen.ontimer(clock2, 100)

screen.onkeypress(up2, 'Up')
screen.onkeypress(down2, 'Down')
screen.onkeypress(left2, 'Left')
screen.onkeypress(right2, 'Right')
screen.onkeypress(fire2, '0')

player1 = Turtle('arrow')
player1.speed('fastest')
player1.color('blue')
player1.setheading(180)
player1.penup()
player1.forward(10)

# bullet 1
bullet1 = Turtle('circle', visible=False)
bullet1.shapesize(0.5)
bullet1.speed('fastest')
bullet1.color('black', 'blue')
bullet1.penup()

player2 = Turtle('arrow')
player2.speed('fastest')
player2.color('gold')
player2.setheading(0)
player2.penup()
player2.forward(10)

# bullet 2
bullet2 = Turtle('circle', visible=False)
bullet2.shapesize(0.5)
bullet2.speed('fastest')
bullet2.color('black', 'gold')
bullet2.penup()

# scoreboard
TT1 = Turtle(visible=False)
TT1.penup()
TT1.goto(-450, 300)
TT1.color('blue')
TT1.write('0', align='center', font=FONT)

# second scoreboard
TT2 = Turtle(visible=False)
TT2.penup()
TT2.goto(450, 300)
TT2.color('gold')
TT2.write('0', align='center', font=FONT)

time1 = 0
score1 = 0

time2 = 0
score2 = 0

screen.listen()

screen.mainloop()

Still needs additional work, i.e. doesn't handle (or disable) multiple shots correctly, etc.


问:
Form with radio buttons + logic
I'm trying to create a form (kind of like a quiz) that uses radio buttons and logic to generate and display different diagnostic results. Here is what I have for some of the form structure (there are many more options and the logic is more weighty in the real version):

```<code>  <form action='index.php' method='post'>
  Q1: Does Patient experience Symptom X?
  <br/>
  <label><input type="radio" name="Q1" value="Q1Y"/> Yes</label>
  <label><input type="radio" name="Q1" value="Q1N"/> No</label>
  <br/>
  <br/>

  Q2: Does Patient experience Symptom Y?
  <br/>
  <label><input type="radio" name="Q2" value="Q2Y"/> Yes</label>
  <label><input type="radio" name="Q2" value="Q2N"/> No</label>
  <br/>
  <br/>

  Q3: Does Patient experience Symptom Z?
  <br/>
  <label><input type="radio" name="Q3" value="Q3Y"/> Yes</label>
  <label><input type="radio" name="Q3" value="Q3N"/> No</label>
  <br/>
  <br/>

  <input type="submit" name="formSubmit" value="See Result"/>
  <br/>
</code>```

How do I set up the rest of the logic such that:

```<code>If (Q1Y && Q2Y){
Diagnosis = A;
}

If (Q2Y && Q3Y){
Diagnosis = B;
}
</code>```

Ideally, the diagnosis would store in a variable then show on the current page when the user clicks submit on the form.

Title: Form with radio buttons + logic

Body:
I'm trying to create a form (kind of like a quiz) that uses radio buttons and logic to generate and display different diagnostic results. Here is what I have for some of the form structure (there are many more options and the logic is more weighty in the real version):

  <form action='index.php' method='post'>
  Q1: Does Patient experience Symptom X?

  <input type="radio" name="Q1" value="Q1Y"/> Yes
  <input type="radio" name="Q1" value="Q1N"/> No

  Q2: Does Patient experience Symptom Y?

  <input type="radio" name="Q2" value="Q2Y"/> Yes
  <input type="radio" name="Q2" value="Q2N"/> No

  Q3: Does Patient experience Symptom Z?

  <input type="radio" name="Q3" value="Q3Y"/> Yes
  <input type="radio" name="Q3" value="Q3N"/> No

  <input type="submit" name="formSubmit" value="See Result"/>

How do I set up the rest of the logic such that:

If (Q1Y && Q2Y){
Diagnosis = A;
}

If (Q2Y && Q3Y){
Diagnosis = B;
}

Ideally, the diagnosis would store in a variable then show on the current page when the user clicks submit on the form.

Body:
if(($_POST['Q1']=='Q1Y') && ($_POST['Q2']=='Q2Y'))
{
// Your Logic
}
if(($_POST['Q2']=='Q2Y') && ($_POST['Q3']=='Q3Y'))
{
// Your Logic
}


问:
How to get Year and Month of a DATE using Oracle
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

```<code>SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017
</code>```

however it gives ORA-30076 Error

答:
```<code>SELECT *
FROM myschema.mytablename
WHERE   TO_CHAR(myDATE, 'YYYY') = '2017';
</code>```

Explicitly convert year part of DATE into CHAR and compare it with literal.
For year and month comparison:

```<code>SELECT *
    FROM myschema.mytablename
    WHERE   TO_CHAR(myDATE, 'YYYY') = '2017' AND TO_CHAR(myDate, 'MM') = '07';
</code>```

Body:
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017

however it gives ORA-30076 Error

Body:
SELECT *
FROM myschema.mytablename
WHERE   TO_CHAR(myDATE, 'YYYY') = '2017';

Explicitly convert year part of DATE into CHAR and compare it with literal.
For year and month comparison:

SELECT *
    FROM myschema.mytablename
    WHERE   TO_CHAR(myDATE, 'YYYY') = '2017' AND TO_CHAR(myDate, 'MM') = '07';


问:
LINQ in IronPython
I have a question about usage method in IronPython. Let's say I have some collection and then I create IronPython anonymous type from that collection and I want to iterate all over that collection. My code looks like this:

```<code>listInt = List[int]([0, 1, 2, 3, 4])
firstCollection = listInt.Select(lambda(v): type('SomeType', (object,),{"TypeValue": v*v, "TypeIndex": v})())
enumeratorFirst = IEnumerable[object].GetEnumerator(firstCollection)
while enumeratorFirst.MoveNext():
    item = enumeratorFirst.Current
</code>```

This code works fine. But when I use Select method with index incorporating, then I get error: 'int' object is not iterable.

My code looks like this:

```<code>listInt = List[int]([0, 1, 2, 3, 4])
secondCollection = listInt.Select(lambda(v, i): type('SomeType', (object,), {"TypeValue": v*v, "TypeIndex": i})())
enumeratorSecond = IEnumerable[object].GetEnumerator(secondCollection)
while enumeratorSecond.MoveNext():
    item = enumeratorSecond.Current
</code>```

Can anyone provide me with some help? Why there is error in second case?

P.S.: For interface usage I looked here: Interface In IronPython.  For anonymous type usage I looked here: Anonymous objects in Python.

答:
I cannot reproduce your direct example, i'm curious about the module you're using to create the lists and the IEnumerable (i'm facing a MakeGenericType on non generic type issue), HOWEVER, i managed to reproduce your issue in Python:

```<code>listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
                  {"TypeValue": v*v, "TypeIndex": i})(), listInt)
for item in secondCollection:
    print(item)
</code>```

This throws the same error

'int' object is not iterable.

because the lambda is taking 2 parameters, so we only have to enumerate the listInt to give an appropriate tuple to the lambda :

```<code>listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
                  {"TypeValue": v*v, "TypeIndex": i})(), enumerate(listInt))
for item in secondCollection:
    print(item.TypeIndex, item.TypeValue)

>>> (0, 0)
>>> (1, 1)
>>> (2, 4)
>>> (3, 9)
>>> (4, 16)
</code>```

I hope it can help you with the System types, i do prefer Python :-p

Title: LINQ in IronPython

Body:
I have a question about usage method in IronPython. Let's say I have some collection and then I create IronPython anonymous type from that collection and I want to iterate all over that collection. My code looks like this:

listInt = List[int]([0, 1, 2, 3, 4])
firstCollection = listInt.Select(lambda(v): type('SomeType', (object,),{"TypeValue": v*v, "TypeIndex": v})())
enumeratorFirst = IEnumerable[object].GetEnumerator(firstCollection)
while enumeratorFirst.MoveNext():
    item = enumeratorFirst.Current

This code works fine. But when I use Select method with index incorporating, then I get error: 'int' object is not iterable.

My code looks like this:

listInt = List[int]([0, 1, 2, 3, 4])
secondCollection = listInt.Select(lambda(v, i): type('SomeType', (object,), {"TypeValue": v*v, "TypeIndex": i})())
enumeratorSecond = IEnumerable[object].GetEnumerator(secondCollection)
while enumeratorSecond.MoveNext():
    item = enumeratorSecond.Current

Can anyone provide me with some help? Why there is error in second case?

P.S.: For interface usage I looked here: Interface In IronPython.  For anonymous type usage I looked here: Anonymous objects in Python.

Body:
I cannot reproduce your direct example, i'm curious about the module you're using to create the lists and the IEnumerable (i'm facing a MakeGenericType on non generic type issue), HOWEVER, i managed to reproduce your issue in Python:

listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
                  {"TypeValue": v*v, "TypeIndex": i})(), listInt)
for item in secondCollection:
    print(item)

This throws the same error

'int' object is not iterable.

because the lambda is taking 2 parameters, so we only have to enumerate the listInt to give an appropriate tuple to the lambda :

listInt = [0,1,2,3,4]
secondCollection = map(lambda(v, i): type('SomeType', (object,),
                  {"TypeValue": v*v, "TypeIndex": i})(), enumerate(listInt))
for item in secondCollection:
    print(item.TypeIndex, item.TypeValue)

>>> (0, 0)
>>> (1, 1)
>>> (2, 4)
>>> (3, 9)
>>> (4, 16)

I hope it can help you with the System types, i do prefer Python :-p


问:
Communicate OPC Server
Is there any dashboard solutions available to communicate OPC Server directly (OLE for Process Control + Used in Industrial Standards)?
If so please suggest the dashboard vendor name.</p>

答:
I am using https://thingsboard.io/, an open-source IOT platform. The IOT Gateway service gathers the time-stamped data (telemetry) from OPC UA servers on my network. Thingsboard stores all the telemetry in a open-source, fault tolerant database, and provides web-based, customizable dashboards for visualization.

Check out the live demo.

Title: Communicate OPC Server


问:
JQuery/javascript: How to run a 'complete' eventlistener on a custom function?
I have the following call

```<code>$('.fblikes span').fblikecount();

$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...
}
</code>```

which will run through all my fblikes classes (about 30) and run my 'socialscore' function on them, which basically updates the facebook like count for each one.

After ALL of them are completed, I wanted to run another function, I was thinking a callback is the way to go and have it run as an eventlistener for when the facebooklikecount() function is completed for all iterations of the .fblikes class.  I can succussfully run a callback for each individual call of fblikecount but I just want to run the callback ONCE when ALL of the fblikecount functions have completed.

My ideal solution would be something like this

```<code>$('.fblikes span').fblikecount().on( "complete", function() {
  //do something
});
</code>```

Possible?

答:
Here is simpliest way I can think off:

```<code>$('.fblikes span').fblikecount();

function myAjaxThing() {

}

$.fn.fblikecount = function(options){
   var settings = $.extend({
        callback: function() {},
    }, options );

   var buttons = this.find('.....')

   $.when(buttons.map(myAjaxThing)).then(options.callback)

    return this;
}
</code>```

If you want to handle named events, consider using namespaced events:

```<code>$.fn.fblikecount = function(options){
   var self = this;
   var settings = $.extend({
        callback: function() {},
    }, options );

   var buttons = this.find('.....')

   $.when(buttons.map(myAjaxThing)).then(function(ret) {
      self.trigger('complete.fblike', [ret])
   })

   return this;
}

$('.fblikes span').fblikecount().on( "complete.fblike", function() {
   //this will trigger now
});
</code>```

Body:
I have the following call

$('.fblikes span').fblikecount();

$.fn.fblikecount = function(){

    //DO SOME JSON XHR stuff to get FB like counts and update the # on page ...
}

which will run through all my fblikes classes (about 30) and run my 'socialscore' function on them, which basically updates the facebook like count for each one.

After ALL of them are completed, I wanted to run another function, I was thinking a callback is the way to go and have it run as an eventlistener for when the facebooklikecount() function is completed for all iterations of the .fblikes class.  I can succussfully run a callback for each individual call of fblikecount but I just want to run the callback ONCE when ALL of the fblikecount functions have completed.

My ideal solution would be something like this

$('.fblikes span').fblikecount().on( "complete", function() {
  //do something
});

Possible?

Body:
Here is simpliest way I can think off:

$('.fblikes span').fblikecount();

function myAjaxThing() {

}

$.fn.fblikecount = function(options){
   var settings = $.extend({
        callback: function() {},
    }, options );

   var buttons = this.find('.....')

   $.when(buttons.map(myAjaxThing)).then(options.callback)

    return this;
}

If you want to handle named events, consider using namespaced events:

$.fn.fblikecount = function(options){
   var self = this;
   var settings = $.extend({
        callback: function() {},
    }, options );

   var buttons = this.find('.....')

   $.when(buttons.map(myAjaxThing)).then(function(ret) {
      self.trigger('complete.fblike', [ret])
   })

   return this;
}

$('.fblikes span').fblikecount().on( "complete.fblike", function() {
   //this will trigger now
});


问:
XML attribute required with empty value
I've set the attribut "number" to #REQUIRED, but is an empty value valid?

DTD:

```<code><!ATTLIST person number CDATA #REQUIRED>
</code>```

XML:

```<code><person number="" />
</code>```

答:
Yes, an empty value suffices to meet the #REQUIRED constraint on an XML attribute.  The value of the attribute is irrelevant; the presence of the attribute is all that's required:

Validity constraint: Required Attribute

If the default declaration is the keyword #REQUIRED, then the
  attribute must be specified for all elements of the type in the
  attribute-list declaration.

Title: XML attribute required with empty value

Body:
I've set the attribut "number" to #REQUIRED, but is an empty value valid?

DTD:

<!ATTLIST person number CDATA #REQUIRED>

XML:

<person number="" />


问:
Android Studio: Project location contains whitespace in user folder. How do I change my user folder name
I recently installed Android Studio 2.2.3 but when I try to create a project it gives me a message saying that my project location contains whitespace.

Here is my project location: C:\Users\Ziyaad B\AndroidStudioProjects\MyApplication.

I tried moving all Android Studio files to C:\Android but it won't delete or be removed from C:\Users\Ziyaad B\AndroidStudioProjects\MyApplication.

Is there any way that I can possibly change that user folder to not have a space?

答: You can simply remove the space like C:\Users\Ziyaad B... to C:\Users\ZiyaadB... . Then in Android Studio and go to File>Open. Now select the location where your project is stored. Also, next time it automatically pick that location.</p>


问:
ASP.NET: Can GridView be used to create a hierarchy?
We are using the GridView controls in some pages of our project which we dont want to change drastically, would it be possible to create a hierarchy in a gridview? Can this be achieved by using a GridView inside a Gridview to get the parent - child relation? </p>

答:
Check out Telerik, their RadGrid has this kind of stuff out of the box (NestedHierarchy and detailtables)

http://demos.telerik.com/aspnet-ajax/Grid/Examples/Overview/DefaultCS.aspx

OwnerDisplayName: Anthraxer

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Henk


问:
PowerShell unable to find type [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]
Currently I'm having a strange problem using the PowerCLI Api from VMware.
I wrote a function that needs an VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl Object as parameter, but every time I provide such an object it errors out.
While debugging, I found that not even assigning this Object to another Variable with the same type.

```<code>PS vi:\IX-eShelter> [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$t = Get-VDPortgroup -Name "dv-test-vlan" | Get-Member
Unable to find type [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl].
At line:1 char:1
+ [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$t = Get-VDPo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (VMware.VimAutom...VDPortgroupImpl:TypeName) [], RuntimeExc
   eption
    + FullyQualifiedErrorId : TypeNotFound
</code>```

I already tried the following:

```<code>[System.Reflection.Assembly]::LoadWithPartialName("VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl")
Add-Type -AssemblyName "VMware.VimAutomation.Vds.Impl"
</code>```

Edit:
My Function:

```<code>function New-VMDeployment {Param([Parameter(Mandatory=$true,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)][VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$port)
Write-Host $port;
};
</code>```

I'm calling it like that:

```<code>$deployment = [PSCustomObject]@{ "port" = Get-VDPortgroup -Name "dv-test-vlan";};
$deployment | New-VMDeployment;
</code>```

答:
Looks like the implementation (Impl) type has broken for distributed port groups. You should be able to switch over to the Types type and find it operational.

I would suggest modifying the function to read like:

```<code>function New-VMDeployment {
    param(
        [Parameter(
            Position=0,
            Mandatory=$true,
            ValueFromPipeline=$false,
            ValueFromPipelineByPropertyName=$true)
        ]
        [VMware.VimAutomation.Vds.Types.V1.VmwareVDPortgroup]$port
    )

    Write-Host $port
}
</code>```

Additional information: https://blogs.vmware.com/PowerCLI/2016/04/powercli-best-practice-correct-use-strong-typing.html

Body:
Currently I'm having a strange problem using the PowerCLI Api from VMware.
I wrote a function that needs an VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl Object as parameter, but every time I provide such an object it errors out.
While debugging, I found that not even assigning this Object to another Variable with the same type.

PS vi:\IX-eShelter> [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$t = Get-VDPortgroup -Name "dv-test-vlan" | Get-Member
Unable to find type [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl].
At line:1 char:1
+ [VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$t = Get-VDPo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (VMware.VimAutom...VDPortgroupImpl:TypeName) [], RuntimeExc
   eption
    + FullyQualifiedErrorId : TypeNotFound

I already tried the following:

[System.Reflection.Assembly]::LoadWithPartialName("VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl")
Add-Type -AssemblyName "VMware.VimAutomation.Vds.Impl"

Edit:
My Function:

function New-VMDeployment {Param([Parameter(Mandatory=$true,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)][VMware.VimAutomation.Vds.Impl.V1.VmwareVDPortgroupImpl]$port)
Write-Host $port;
};

I'm calling it like that:

$deployment = [PSCustomObject]@{ "port" = Get-VDPortgroup -Name "dv-test-vlan";};
$deployment | New-VMDeployment;

Body:
Looks like the implementation (Impl) type has broken for distributed port groups. You should be able to switch over to the Types type and find it operational.

I would suggest modifying the function to read like:

function New-VMDeployment {
    param(
        [Parameter(
            Position=0,
            Mandatory=$true,
            ValueFromPipeline=$false,
            ValueFromPipelineByPropertyName=$true)
        ]
        [VMware.VimAutomation.Vds.Types.V1.VmwareVDPortgroup]$port
    )

    Write-Host $port
}

Additional information: https://blogs.vmware.com/PowerCLI/2016/04/powercli-best-practice-correct-use-strong-typing.html


问:
Trouble centering background image
I'm having problems centering the background image within a certain div. I'm using the following code for CSS:

```<code>.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background: linear-gradient( rgba(86, 71, 71, 0.56), rgba(86, 71, 71, 0.56)), url(img/kitpage.jpg) no-repeat 50% 50%;
}
</code>```

I've tinkered and tried, but to no avail. I'm pretty sure it's an easy answer, and thank you all in advance for your help and advice.

A screenshot of the problem is attached below

答:
Use the following in your CSS:</p>

```<code>display: block;
</code>```

Title: Trouble centering background image

Body:
I'm having problems centering the background image within a certain div. I'm using the following code for CSS:

.background3 {
  max-width: 90%;
  height: 400px;
  margin: 0 auto;
  background: linear-gradient( rgba(86, 71, 71, 0.56), rgba(86, 71, 71, 0.56)), url(img/kitpage.jpg) no-repeat 50% 50%;
}

I've tinkered and tried, but to no avail. I'm pretty sure it's an easy answer, and thank you all in advance for your help and advice.

A screenshot of the problem is attached below

Body:
Use the following in your CSS:

display: block;


问:
C++ 11 save memory by using pointer in class declaration
most of the time I could find answers on stack overflow.

I am working on a project and I need some suggestions.

Class A will have millions of object/instance.
Class A have several members including Class B, C, and D, etc,.
Class B, C and D, etc. have many member Class H, I, J, and K, etc.

Class A will always only have one "effective" class member, which means only B or C  (or others) is used.
However, class B usually have more than one "effective" class members.

So what will be the differences in using "class B" or "class * B" in Class A declaration? Similarly, how about Class B declaration?

some illustration code:
Solution 1

```<code>Class A
{
  B b;//i assume once A has an object, both b and c will take memory
  C c;
}

Class B
{
  H h;
  I i;
}
</code>```

or Solution 2

```<code>Class A
{
  B * b;  //only one of B or C may be used buy we don't know so far
  C * c;
}
Class B
{
  H * h;//a combination of h, i, j, k, etc may be used, we still don't know so far.
  I * i;
}
</code>```

I am assuming by use empty pointer in class declaration (Solution 2), I can save a lot of memory during definition and program run. Because I know only one or a few of the pointers will be actually used.

What do you think?

答:
This sounds like a job for polymorphism.

Judging from the fact that A may contain B or C, and having either does not change the interface of A, it seems B and C should inherit from a common base BC and A should have a pointer to that

```<code>struct BC
{
    virtual int foo() = 0;
};
struct B : BC
{
    virtual int foo() override { return 42; }
};
struct C : BC
{
    virtual int foo() override { return 420; }
};
struct A
{
    BC* bc;  // which should likely be...
    std::unique_ptr<BC> ubc;

    int foo() { return ubc->foo(); }
};
</code>```

The same goes for H onwards, keep a collection of their common base pointers in B

If you find that the containing class has its interface changed significantly based on its contents, it is likely you are building a monolith that have a leaky abstraction. Consider restructuring.

Body:
most of the time I could find answers on stack overflow.

I am working on a project and I need some suggestions.

Class A will have millions of object/instance.
Class A have several members including Class B, C, and D, etc,.
Class B, C and D, etc. have many member Class H, I, J, and K, etc.

Class A will always only have one "effective" class member, which means only B or C  (or others) is used.
However, class B usually have more than one "effective" class members.

So what will be the differences in using "class B" or "class * B" in Class A declaration? Similarly, how about Class B declaration?

some illustration code:
Solution 1

Class A
{
  B b;//i assume once A has an object, both b and c will take memory
  C c;
}

Class B
{
  H h;
  I i;
}

or Solution 2

Class A
{
  B * b;  //only one of B or C may be used buy we don't know so far
  C * c;
}
Class B
{
  H * h;//a combination of h, i, j, k, etc may be used, we still don't know so far.
  I * i;
}

I am assuming by use empty pointer in class declaration (Solution 2), I can save a lot of memory during definition and program run. Because I know only one or a few of the pointers will be actually used.

What do you think?

Body:
This sounds like a job for polymorphism.

Judging from the fact that A may contain B or C, and having either does not change the interface of A, it seems B and C should inherit from a common base BC and A should have a pointer to that

struct BC
{
    virtual int foo() = 0;
};
struct B : BC
{
    virtual int foo() override { return 42; }
};
struct C : BC
{
    virtual int foo() override { return 420; }
};
struct A
{
    BC* bc;  // which should likely be...
    std::unique_ptr<BC> ubc;

    int foo() { return ubc->foo(); }
};

The same goes for H onwards, keep a collection of their common base pointers in B

If you find that the containing class has its interface changed significantly based on its contents, it is likely you are building a monolith that have a leaky abstraction. Consider restructuring.


问:
For some reason, when submitting my `users` table won't update at all and my `user_infos` table adds new column instead of updating
Here's my store function. I've tried playing with it a few different ways. For some reason I thought maybe putting the $post->save(); inside the if would at least change the profile image, but no. Not even that works. I initially tried return redirect()->route('profile')->withUser($user); and that didn't work either. This is my latest attempt. And still no luck so I thought to post it here. Thanks in advance! Using: Laravel 5.4

```<code>    public function store(Request $request)
  {
    $this->validate($request, array(
      'description' => 'required|string',
      'projects'    => 'required|string',
      'experience'  => 'required|string',
      'links'       => 'required|string',
      'status'      => 'required|string',
    ));

    $userInfo = new User_Info;
    $user_id = Auth()->user()->id;
    $user = User::find($user_id);

    $userInfo->user_id = $user_id;
    $userInfo->description = $request->input('description');
    $userInfo->projects = $request->input('projects');
    $userInfo->experience = $request->input('experience');
    $userInfo->links = $request->input('links');
    $userInfo->status = $request->input('status');

    $userInfo->save();

    return redirect()->route('profile')->withUser($user);
  }

  public function settings($id)
  {
    $user = User::find($id);
    return view("profile.settings")->withUser($user);
  }

  public function update(Request $request, $id)
  {
      $user_id = Auth()->user()->id;

      $this->validate($request, array(
        'first_name'  => 'required|string|max:255',
        'last_name'   => 'required|string|max:255',
        'email'       => 'required|string|email|max:255|unique:users',
        'type'        => 'required|string',
        'description' => 'required|string',
        'projects'    => 'required|string',
        'experience'  => 'required|string',
        'links'       => 'required|string',
        'status'      => 'required|string'
      ));

      if($request->hasFile('avatar')){
          $avatar = $request->file('avatar');
          $filename = time() . '.' . $avatar->getClientOriginalExtension();
          Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );

          $user = Auth::user();
          $user->avatar = $filename;
      }

      $user = User::find($id);
      $user->first_name = $request->input('first_name');
      $user->last_name  = $request->input('last_name');
      $user->email      = $request->input('email');
      $user->type       = $request->input('type');

      $user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
      $user_info->description = $request->input('description');
      $user_info->projects    = $request->input('projects');
      $user_info->expereince  = $request->input('experience');
      $user_info->status      = $request->input('status');

      $user->save();
      $user_info->save();

      return view('profile.profile')->withUser($user);
  }
</code>```

答:
You don't get existing object, so change this:

```<code>$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
</code>```

To something like this:

```<code>$user_info = UserInfo::where('user_id', $user->id)->first();
</code>```

Body:
Here's my store function. I've tried playing with it a few different ways. For some reason I thought maybe putting the $post->save(); inside the if would at least change the profile image, but no. Not even that works. I initially tried return redirect()->route('profile')->withUser($user); and that didn't work either. This is my latest attempt. And still no luck so I thought to post it here. Thanks in advance! Using: Laravel 5.4

    public function store(Request $request)
  {
    $this->validate($request, array(
      'description' => 'required|string',
      'projects'    => 'required|string',
      'experience'  => 'required|string',
      'links'       => 'required|string',
      'status'      => 'required|string',
    ));

    $userInfo = new User_Info;
    $user_id = Auth()->user()->id;
    $user = User::find($user_id);

    $userInfo->user_id = $user_id;
    $userInfo->description = $request->input('description');
    $userInfo->projects = $request->input('projects');
    $userInfo->experience = $request->input('experience');
    $userInfo->links = $request->input('links');
    $userInfo->status = $request->input('status');

    $userInfo->save();

    return redirect()->route('profile')->withUser($user);
  }

  public function settings($id)
  {
    $user = User::find($id);
    return view("profile.settings")->withUser($user);
  }

  public function update(Request $request, $id)
  {
      $user_id = Auth()->user()->id;

      $this->validate($request, array(
        'first_name'  => 'required|string|max:255',
        'last_name'   => 'required|string|max:255',
        'email'       => 'required|string|email|max:255|unique:users',
        'type'        => 'required|string',
        'description' => 'required|string',
        'projects'    => 'required|string',
        'experience'  => 'required|string',
        'links'       => 'required|string',
        'status'      => 'required|string'
      ));

      if($request->hasFile('avatar')){
          $avatar = $request->file('avatar');
          $filename = time() . '.' . $avatar->getClientOriginalExtension();
          Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );

          $user = Auth::user();
          $user->avatar = $filename;
      }

      $user = User::find($id);
      $user->first_name = $request->input('first_name');
      $user->last_name  = $request->input('last_name');
      $user->email      = $request->input('email');
      $user->type       = $request->input('type');

      $user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
      $user_info->description = $request->input('description');
      $user_info->projects    = $request->input('projects');
      $user_info->expereince  = $request->input('experience');
      $user_info->status      = $request->input('status');

      $user->save();
      $user_info->save();

      return view('profile.profile')->withUser($user);
  }

Body:
You don't get existing object, so change this:

$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");

To something like this:

$user_info = UserInfo::where('user_id', $user->id)->first();


问:
Refresh the method after item add or delete from SQL database
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

```<code>private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }
</code>```

答: What I wanted to do is to avoid calling the method on refresh because as #oldcoder said, the network traffic will be unnecessarily big. Just was thinking of something like INSERT from pc1 -> DB -> send information about the insert to pc2,pc3. If this is not possible or too complicating, I will just refresh the function every 10sec or so.</p>

Body:
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }


问:
gulpfile only running once with watch
I have this as my gulpfile.js:

```<code>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task( 'default', ['sass'] );

gulp.task('sass', function () {
  return gulp.src('./sass/theme.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});
</code>```

I works and compiles the sass however it stops running instead of watching? I am not too familiar with how gulp works so help would really be appreciated!

the output in console looks like this:

```<code>[13:14:29] Using gulpfile ~/public_html/mysite/gulpfile.js
[13:14:29] Starting 'sass'...
[13:14:31] Finished 'sass' after 1.2 s
[13:14:31] Starting 'default'...
[13:14:31] Finished 'default' after 15 μs
</code>```

答:
You haven't started sass:watch task.

```<code>gulp.task( 'default', ['sass', 'sass:watch'] );
</code>```

Title: gulpfile only running once with watch

Body:
I have this as my gulpfile.js:

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task( 'default', ['sass'] );

gulp.task('sass', function () {
  return gulp.src('./sass/theme.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

I works and compiles the sass however it stops running instead of watching? I am not too familiar with how gulp works so help would really be appreciated!

the output in console looks like this:

[13:14:29] Using gulpfile ~/public_html/mysite/gulpfile.js
[13:14:29] Starting 'sass'...
[13:14:31] Finished 'sass' after 1.2 s
[13:14:31] Starting 'default'...
[13:14:31] Finished 'default' after 15 μs

Body:
You haven't started sass:watch task.

gulp.task( 'default', ['sass', 'sass:watch'] );


问:
STL Namespace Errors in fstream.h with qmake/make
I'm trying to compile my QT5 project the old school way, with qmake && make.  However, I'm getting unexpected errors.  There are ~20, but here's a sampling (they're all similar):

```<code>In file included from src/main.cc:18:
In file included from include/Ctx.h:7:
In file included from include/SrcFile.h:5:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/fstream:268:9: error:
      no template named 'has_facet'; did you mean
      '::std::has_facet'?
    if (has_facet<codecvt<char_type, char, state_...
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:177:1: note:
      '::std::has_facet' declared here
has_facet(const locale& __l)  _NOEXCEPT
^
In file included from src/main.cc:18:
In file included from include/Ctx.h:7:
In file included from include/SrcFile.h:5:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/fstream:268:19: error:
      no template named 'codecvt'; did you mean
      '::std::codecvt'?
    if (has_facet<codecvt<char_type, char, state_...
                  ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:817:86: note:
      '::std::codecvt' declared here
  ...class _StateT> class _LIBCPP_TYPE_VIS_ONLY codecvt;
                                                ^
fatal error: too many errors emitted, stopping now
      [-ferror-limit=]
20 errors generated.
make: *** [tmp/main.o] Error 1
</code>```

Below is SrcFile.h

```<code>#ifndef SRCFILE_H
#define SRCFILE_H

#include <string>
#include <fstream>
#include "SrcObj.h"

namespace oonalysis {

class SrcFile : public SrcObj
{
public:
    SrcFile(const std::string& filename);
    std::string get_text() const;
    std::string present_name() const;
private:
    std::filebuf* get_file();
    std::string filename;
}; // class SrcFile

} // namespace oonalysis

#endif // SRCFILE_H
</code>```

And below are the likely segments of the generated Makefile

```<code>INCPATH       = -I. -Iinclude -I/usr/local/Cellar/qt/5.9.1/lib/QtWidgets.fram
ework/Headers -I/usr/local/Cellar/qt/5.9.1/lib/QtGui.framework/Headers -I/usr
/local/Cellar/qt/5.9.1/lib/QtCore.framework/Headers -I. -I/Applications/Xcode
.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.
sdk/System/Library/Frameworks/OpenGL.framework/Headers -I/Applications/Xcode.
app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.s
dk/System/Library/Frameworks/AGL.framework/Headers -I/usr/local/Cellar/qt/5.9
.1/mkspecs/macx-clang -F/usr/local/Cellar/qt/5.9.1/lib
CC            = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
CXX           = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
CXXFLAGS      = -pipe -stdlib=libc++ -g -std=gnu++1y $(EXPORT_ARCH_ARGS) -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -mmacosx-version-min=10.10 -Wall -W -fPIC $(DEFINES)
tmp/srcfile.o: src/srcfile.cc include/SrcFile.h \
                include/SrcObj.h \
                include/oonalysis.h
        $(CXX) -c $(CXXFLAGS) $(INCPATH) -o tmp/srcfile.o src/srcfile.cc
</code>```

Have I misconfigured something?  Is there any way I could have two stl versions floating around?

答: The issue was not intuitive.  In an unrelated header, gui.h, I hadn't closed off my namespace gui with an end brace.  I figured this out by commenting out #include <fstream> and compiling.  Now it works fine.

Body:
I'm trying to compile my QT5 project the old school way, with qmake && make.  However, I'm getting unexpected errors.  There are ~20, but here's a sampling (they're all similar):

In file included from src/main.cc:18:
In file included from include/Ctx.h:7:
In file included from include/SrcFile.h:5:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/fstream:268:9: error:
      no template named 'has_facet'; did you mean
      '::std::has_facet'?
    if (has_facet<codecvt<char_type, char, state_...
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:177:1: note:
      '::std::has_facet' declared here
has_facet(const locale& __l)  _NOEXCEPT
^
In file included from src/main.cc:18:
In file included from include/Ctx.h:7:
In file included from include/SrcFile.h:5:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/fstream:268:19: error:
      no template named 'codecvt'; did you mean
      '::std::codecvt'?
    if (has_facet<codecvt<char_type, char, state_...
                  ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:817:86: note:
      '::std::codecvt' declared here
  ...class _StateT> class _LIBCPP_TYPE_VIS_ONLY codecvt;
                                                ^
fatal error: too many errors emitted, stopping now
      [-ferror-limit=]
20 errors generated.
make: *** [tmp/main.o] Error 1

Below is SrcFile.h

#ifndef SRCFILE_H
#define SRCFILE_H

#include <string>
#include <fstream>
#include "SrcObj.h"

namespace oonalysis {

class SrcFile : public SrcObj
{
public:
    SrcFile(const std::string& filename);
    std::string get_text() const;
    std::string present_name() const;
private:
    std::filebuf* get_file();
    std::string filename;
}; // class SrcFile

} // namespace oonalysis

#endif // SRCFILE_H

And below are the likely segments of the generated Makefile

INCPATH       = -I. -Iinclude -I/usr/local/Cellar/qt/5.9.1/lib/QtWidgets.fram
ework/Headers -I/usr/local/Cellar/qt/5.9.1/lib/QtGui.framework/Headers -I/usr
/local/Cellar/qt/5.9.1/lib/QtCore.framework/Headers -I. -I/Applications/Xcode
.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.
sdk/System/Library/Frameworks/OpenGL.framework/Headers -I/Applications/Xcode.
app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.s
dk/System/Library/Frameworks/AGL.framework/Headers -I/usr/local/Cellar/qt/5.9
.1/mkspecs/macx-clang -F/usr/local/Cellar/qt/5.9.1/lib
CC            = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
CXX           = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
CXXFLAGS      = -pipe -stdlib=libc++ -g -std=gnu++1y $(EXPORT_ARCH_ARGS) -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -mmacosx-version-min=10.10 -Wall -W -fPIC $(DEFINES)
tmp/srcfile.o: src/srcfile.cc include/SrcFile.h \
                include/SrcObj.h \
                include/oonalysis.h
        $(CXX) -c $(CXXFLAGS) $(INCPATH) -o tmp/srcfile.o src/srcfile.cc

Have I misconfigured something?  Is there any way I could have two stl versions floating around?


问:
Implementing a button in ag-grid
I'm trying to learn from this example of ag-grid in order to create a delete button in every row in a grid. The aforementioned example is working, but my code isn't and I can't figure out why.

I'm attaching my code and hope someone can help me.

home.component.ts:

```<code>@Component({
  selector: 'home',
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  private items: Item[] = [];
  private gridOptions:GridOptions;
  private columnDefs = [];

  constructor(
    private itemsService: ItemsService
  ) {
    this.gridOptions = {};
    this.columnDefs = this.createColumnDefs();
  }

  remove() {
    alert("yey!")
  }

  ngOnInit(){
    this.itemsService
      .getAll()
      .subscribe(result => {
        this.items = result;
      });
  }

  private createColumnDefs() {
    return [
      {
        headerName: "Foo",
        field: "foo",
        width: 100,
      },
      {
        headerName: "Bar",
        field: "bar",
        width: 100,
      },
      {
        headerName: "",
        field: "_id",
        cellRendererFramework: RemoveButton,
        colId: "params",
        width: 100
      },
    ];
  }
}
</code>```

home.component.html:

```<code><div>
      <ag-grid-angular #agGrid style="width: 602px; height: 350px;" class="ag-fresh"
                       [gridOptions]="gridOptions"
                       [columnDefs]="columnDefs"
                       [rowData]="items">
      </ag-grid-angular>
  </div>
</code>```

RemoveButton.ts:

```<code>@Component({
  selector: 'remove-button',
  template: `<span><button style="height: 20px" (click)="remove()">X</button></span>`
})
export class RemoveButton implements ICellRendererAngularComp {
  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  public remove() {
    this.params.context.componentParent.remove();
  }
}
</code>```

The grid is displayed with all the data, but clicking the button produces this error:

```<code>ERROR TypeError: Cannot read property 'componentParent' of undefined
    at RemoveButton.webpackJsonpac__name_.453.RemoveButton.remove
</code>```

meaning context of params is undefined.

If any further code or information is needed, please let me know.

答:
I've solved my problem. Obviously context was undefined because I hadn't defined it. Defining the context inside gridOptions has solved that:

```<code>this.gridOptions ={
      context: {
        componentParent: this
      }
    };
</code>```

Title: Implementing a button in ag-grid

Body:
I'm trying to learn from this example of ag-grid in order to create a delete button in every row in a grid. The aforementioned example is working, but my code isn't and I can't figure out why.

I'm attaching my code and hope someone can help me.

home.component.ts:

@Component({
  selector: 'home',
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  private items: Item[] = [];
  private gridOptions:GridOptions;
  private columnDefs = [];

  constructor(
    private itemsService: ItemsService
  ) {
    this.gridOptions = {};
    this.columnDefs = this.createColumnDefs();
  }

  remove() {
    alert("yey!")
  }

  ngOnInit(){
    this.itemsService
      .getAll()
      .subscribe(result => {
        this.items = result;
      });
  }

  private createColumnDefs() {
    return [
      {
        headerName: "Foo",
        field: "foo",
        width: 100,
      },
      {
        headerName: "Bar",
        field: "bar",
        width: 100,
      },
      {
        headerName: "",
        field: "_id",
        cellRendererFramework: RemoveButton,
        colId: "params",
        width: 100
      },
    ];
  }
}

home.component.html:

      <ag-grid-angular #agGrid style="width: 602px; height: 350px;" class="ag-fresh"
                       [gridOptions]="gridOptions"
                       [columnDefs]="columnDefs"
                       [rowData]="items">
      </ag-grid-angular>

RemoveButton.ts:

@Component({
  selector: 'remove-button',
  template: `<span><button style="height: 20px" (click)="remove()">X</button></span>`
})
export class RemoveButton implements ICellRendererAngularComp {
  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  public remove() {
    this.params.context.componentParent.remove();
  }
}

The grid is displayed with all the data, but clicking the button produces this error:

ERROR TypeError: Cannot read property 'componentParent' of undefined
    at RemoveButton.webpackJsonpac__name_.453.RemoveButton.remove

meaning context of params is undefined.

If any further code or information is needed, please let me know.

Body:
I've solved my problem. Obviously context was undefined because I hadn't defined it. Defining the context inside gridOptions has solved that:

this.gridOptions ={
      context: {
        componentParent: this
      }
    };


问:
Passing in a value to a usercontrol through a foreach loop
in my asp.net mark up I have a foreach loop that iterates through a simple list. In this foreach loop I am adding a new user control and attempting to pass in the value from the loop. However, this value just wont budge and get inside that damn  control! Anyone have any suggestions?

```<code><%foreach (userInfo i in this.items)
    { %>
        <uc1:ItemControl ID="ItemControl" runat="server" UserID='<%#Eval("userID") %>'/>
<%} %>
</code>```

userID is a public property in the control, when it goes to set, the value is just literally : <%#Eval("userID") %>. I've tried #Bind and =Value but nothing seems to work.

Any help would be appreciated!

答: Try use a Repeater control for your purpose</p>

Body:
in my asp.net mark up I have a foreach loop that iterates through a simple list. In this foreach loop I am adding a new user control and attempting to pass in the value from the loop. However, this value just wont budge and get inside that damn  control! Anyone have any suggestions?

<%foreach (userInfo i in this.items)
    { %>
        <uc1:ItemControl ID="ItemControl" runat="server" UserID='<%#Eval("userID") %>'/>
<%} %>

userID is a public property in the control, when it goes to set, the value is just literally : <%#Eval("userID") %>. I've tried #Bind and =Value but nothing seems to work.

Any help would be appreciated!


问:
C recursive program to find the maximum element from array
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

```<code>#include <stdio.h>

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}
</code>```

Thank you all for your time!

答:
Problems that are well-suited to recursion can be broken down into smaller, simpler subproblems. This is one of the things that gives recursion its power. When trying to use recursion to solve a problem, it usually seems best to try to break the problem down into simpler subproblems in finding your way to a solution.

You might notice that in finding the maximum value stored in an array, it is either the value of the first element, or the maximum value of the remaining elements. This breaks the problem into two parts: if the first element is larger than any remaining elements, you are done; otherwise, you must continue and see if the next element is larger than the remaining elements. In code, this might look like:

```<code>int max_in(size_t rest_sz, int *rest)
{
    int curr_val = rest[0];
    if (rest_sz == 1) {
        return curr_val;
    }

    int max_in_rest = max_in(rest_sz-1, rest+1);

    return curr_val > max_in_rest ? curr_val : max_in_rest;
}
</code>```

Here, there is a base case: if rest_sz is 1, there is no need to look further; the value of first element (curr_val = rest[0]) is the maximum, and that value is returned. If the base case is not satisfied, execution of the function continues. max_in_rest is the result from the recursive function call max_in(rest_sz-1, rest+1). Here rest_sz-1 indicates the number of elements remaining in the portion of the array indicated by rest+1. In the new function call, the base case is met again, and eventually this case will be true since rest_sz is decremented with each recursive call. When that happens, the value of curr_val in the current stack frame will be returned; note that this value is the value of the last element in the array. Then, when the function returns to its caller, max_in_rest in that frame will get the returned value, after which the larger of curr_val or max_in_rest is returned to the previous caller, and so on, until finally control is returned to main().

Using pencil and paper to diagram each function call, the values of its variables, and what is returned would help to understand exactly how this recursion works.

You can apply the same method to solving the problem of finding the index of the maximum value of an array. In this case, if the value of the first element is greater than the value of any remaining elements, then the index of the maximum element is the index of the first element; otherwise the index of the maximum element is the index of the maximum value of the remaining elements. In code, this might look like:

```<code>size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx)
{
    if (rest_sz == 1) {
        return curr_ndx;
    }

    int curr_val = arr[curr_ndx];
    size_t max_in_rest_ndx = find_max_r(arr, rest+1, rest_sz-1, curr_ndx+1);
    int max_in_rest = arr[max_in_rest_ndx];

    return curr_val >= max_in_rest ? curr_ndx : max_in_rest_ndx;
}
</code>```

There is just a little more information to keep track of this time. Here, if the base case is satisfied, and rest_sz is 1, then there is no reason to look further, the current index curr_ndx is the index of the maximum value. Otherwise, find_max_r() is recursively called, with rest incremented to point to the remaining elements of the array, and rest_sz suitably decremented. This time, curr_ndx is keeping track of the current index with respect to the original array, and this value is passed into each function call; also, a pointer to the first element of the original array, arr, is passed into each function call so the index value curr_ndx can access the values from the original array.

Again, when the base case is reached, the current position in the array will be the end of the array, so the first elements to be compared in the return statement will be towards the end of the array, moving towards the front of the array. Note that >= is used here, instead of > so that the index of the first maximum value is returned; if you instead want the index of the last maximum value, simply change this to >.

Here is a complete program. Note the use of the helper function find_max() to call the recursive function find_max_r(), which allows the caller to use a function with the same signature that the posted code uses (except for the use of size_t types, which is really the correct type for array indices):

```<code>#include <stdio.h>

int max_in(size_t sz, int *rest);
size_t find_max(size_t sz, int arr[]);
size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx);

int main(void)
{
    int array[] = { 2, 7, 1, 8, 2, 5, 1, 8 };
    size_t array_sz = sizeof array / sizeof array[0];

    int max_val = max_in(array_sz, array);
    printf("Maximum value is: %d\n", max_val);

    size_t max_ndx = find_max(array_sz, array);
    printf("Maximum value index: %zu\n", max_ndx);

    return 0;
}

int max_in(size_t rest_sz, int *rest)
{
    int curr_val = rest[0];
    if (rest_sz == 1) {
        return curr_val;
    }

    int max_in_rest = max_in(rest_sz-1, rest+1);

    return curr_val > max_in_rest ? curr_val : max_in_rest;
}

size_t find_max(size_t sz, int arr[])
{
    int *rest = arr;
    return find_max_r(arr, rest, sz, 0);
}

size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx)
{
    if (rest_sz == 1) {
        return curr_ndx;
    }

    int curr_val = arr[curr_ndx];
    size_t max_in_rest_ndx = find_max_r(arr, rest+1, rest_sz-1, curr_ndx+1);
    int max_in_rest = arr[max_in_rest_ndx];

    return curr_val >= max_in_rest ? curr_ndx : max_in_rest_ndx;
}
</code>```

Program output:

Maximum value is: 8
Maximum value index: 3
```

Body:
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

#include <stdio.h>

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}

Thank you all for your time!

Body:
Problems that are well-suited to recursion can be broken down into smaller, simpler subproblems. This is one of the things that gives recursion its power. When trying to use recursion to solve a problem, it usually seems best to try to break the problem down into simpler subproblems in finding your way to a solution.

You might notice that in finding the maximum value stored in an array, it is either the value of the first element, or the maximum value of the remaining elements. This breaks the problem into two parts: if the first element is larger than any remaining elements, you are done; otherwise, you must continue and see if the next element is larger than the remaining elements. In code, this might look like:

int max_in(size_t rest_sz, int *rest)
{
    int curr_val = rest[0];
    if (rest_sz == 1) {
        return curr_val;
    }

    int max_in_rest = max_in(rest_sz-1, rest+1);

    return curr_val > max_in_rest ? curr_val : max_in_rest;
}

Here, there is a base case: if rest_sz is 1, there is no need to look further; the value of first element (curr_val = rest[0]) is the maximum, and that value is returned. If the base case is not satisfied, execution of the function continues. max_in_rest is the result from the recursive function call max_in(rest_sz-1, rest+1). Here rest_sz-1 indicates the number of elements remaining in the portion of the array indicated by rest+1. In the new function call, the base case is met again, and eventually this case will be true since rest_sz is decremented with each recursive call. When that happens, the value of curr_val in the current stack frame will be returned; note that this value is the value of the last element in the array. Then, when the function returns to its caller, max_in_rest in that frame will get the returned value, after which the larger of curr_val or max_in_rest is returned to the previous caller, and so on, until finally control is returned to main().

Using pencil and paper to diagram each function call, the values of its variables, and what is returned would help to understand exactly how this recursion works.

You can apply the same method to solving the problem of finding the index of the maximum value of an array. In this case, if the value of the first element is greater than the value of any remaining elements, then the index of the maximum element is the index of the first element; otherwise the index of the maximum element is the index of the maximum value of the remaining elements. In code, this might look like:

size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx)
{
    if (rest_sz == 1) {
        return curr_ndx;
    }

    int curr_val = arr[curr_ndx];
    size_t max_in_rest_ndx = find_max_r(arr, rest+1, rest_sz-1, curr_ndx+1);
    int max_in_rest = arr[max_in_rest_ndx];

    return curr_val >= max_in_rest ? curr_ndx : max_in_rest_ndx;
}

There is just a little more information to keep track of this time. Here, if the base case is satisfied, and rest_sz is 1, then there is no reason to look further, the current index curr_ndx is the index of the maximum value. Otherwise, find_max_r() is recursively called, with rest incremented to point to the remaining elements of the array, and rest_sz suitably decremented. This time, curr_ndx is keeping track of the current index with respect to the original array, and this value is passed into each function call; also, a pointer to the first element of the original array, arr, is passed into each function call so the index value curr_ndx can access the values from the original array.

Again, when the base case is reached, the current position in the array will be the end of the array, so the first elements to be compared in the return statement will be towards the end of the array, moving towards the front of the array. Note that >= is used here, instead of > so that the index of the first maximum value is returned; if you instead want the index of the last maximum value, simply change this to >.

Here is a complete program. Note the use of the helper function find_max() to call the recursive function find_max_r(), which allows the caller to use a function with the same signature that the posted code uses (except for the use of size_t types, which is really the correct type for array indices):

#include <stdio.h>

int max_in(size_t sz, int *rest);
size_t find_max(size_t sz, int arr[]);
size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx);

int main(void)
{
    int array[] = { 2, 7, 1, 8, 2, 5, 1, 8 };
    size_t array_sz = sizeof array / sizeof array[0];

    int max_val = max_in(array_sz, array);
    printf("Maximum value is: %d\n", max_val);

    size_t max_ndx = find_max(array_sz, array);
    printf("Maximum value index: %zu\n", max_ndx);

    return 0;
}

int max_in(size_t rest_sz, int *rest)
{
    int curr_val = rest[0];
    if (rest_sz == 1) {
        return curr_val;
    }

    int max_in_rest = max_in(rest_sz-1, rest+1);

    return curr_val > max_in_rest ? curr_val : max_in_rest;
}

size_t find_max(size_t sz, int arr[])
{
    int *rest = arr;
    return find_max_r(arr, rest, sz, 0);
}

size_t find_max_r(int arr[], int *rest, size_t rest_sz, size_t curr_ndx)
{
    if (rest_sz == 1) {
        return curr_ndx;
    }

    int curr_val = arr[curr_ndx];
    size_t max_in_rest_ndx = find_max_r(arr, rest+1, rest_sz-1, curr_ndx+1);
    int max_in_rest = arr[max_in_rest_ndx];

    return curr_val >= max_in_rest ? curr_ndx : max_in_rest_ndx;
}

Program output:

Maximum value is: 8
Maximum value index: 3