问:
Laravel how to get the AVG value of first 3 records from each group
I have a database table, which includes points against the player. A Single player have multiple records in the table. I need to group the records by the player_id. And I am trying to get the average of first 3 records of the each group. I tried to reach this over the last evening. But I had not any luck to solve this.

This is my initial code, And I need to modify this to get the AVG of first 3 records of each group(grouped by player_id)

```<code>$oSelect = DB::table('statistics')
          ->where('statistics.league_id', $league_id)
          ->select('id, AVG('statistics.points as points'),player_id, scheduled')
          ->orderBy('statistics.scheduled','DESC')
          ->groupBy('statistics.player_id');
</code>```

Thank you in advanced

答:
Try this:

```<code>$oSelect = DB::table('statistics')
      ->select(DB::raw('id, AVG(statistics.points) as points,player_id,scheduled'))
      ->where('statistics.league_id', $league_id)
      ->orderBy('statistics.scheduled','DESC')
      ->groupBy('statistics.player_id')->limit(3)->get();
</code>```

Notice: if you get nonaggregated column error that case you must add id column to grouped by columns list or disable the only_full_group_by option in mySql

Disable ONLY_FULL_GROUP_BY

Body:
I have a database table, which includes points against the player. A Single player have multiple records in the table. I need to group the records by the player_id. And I am trying to get the average of first 3 records of the each group. I tried to reach this over the last evening. But I had not any luck to solve this.

This is my initial code, And I need to modify this to get the AVG of first 3 records of each group(grouped by player_id)

$oSelect = DB::table('statistics')
          ->where('statistics.league_id', $league_id)
          ->select('id, AVG('statistics.points as points'),player_id, scheduled')
          ->orderBy('statistics.scheduled','DESC')
          ->groupBy('statistics.player_id');

Thank you in advanced

Body:
Try this:

$oSelect = DB::table('statistics')
      ->select(DB::raw('id, AVG(statistics.points) as points,player_id,scheduled'))
      ->where('statistics.league_id', $league_id)
      ->orderBy('statistics.scheduled','DESC')
      ->groupBy('statistics.player_id')->limit(3)->get();

Notice: if you get nonaggregated column error that case you must add id column to grouped by columns list or disable the only_full_group_by option in mySql

Disable ONLY_FULL_GROUP_BY


来源: stackexchange

问:
Why is my LSTM in tensorflow learning so slowly and badly?
This program reads a text file RNNtext.txt, creates one-hot vector representation for all the data, trains the LSTM with the data and displays a bunch of sampled characters every now and then. However, even looking at the cost vs iterations graph shows that it's learning very very inefficiently. Honestly, the raw code (numpy) for the LSTM I have does a MUCH better job. It's not only faster but it produces mostly meaningful words. This produces gibberish only. Where is my mistake? I really am out of ideas and I can't seem to find where it is logically wrong.

```<code>import numpy as np
import random
import tensorflow as tf
import os
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

# Reading RNNtext.txt file
direc = os.path.dirname(os.path.realpath(__file__))
data = open(direc + "/RNNtext.txt", "r").read()

# Array of unique characters
chars = list(set(data))

num_hidden = 80
iterations = 1000
display_iteration = 100 # Sample when iteration % display_iteration == 0
sample_size = 250
batch_size = 120 # batch size or the number of time steps to unroll RNN
alpha = 0.01 # Learning rate

#Vocabulary and text file sizes
vocab_size = len(chars)
data_size = len(data)

# Bijection from a unique character to an index
char_to_ix = {}
# Bijection from an index to a unique character
ix_to_char = {}

for j in range(vocab_size):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

# Transforming all characters to indices
data_ix = [char_to_ix[ch] for ch in data]

train_data = [] # This will contain one-hot vectors
for k in range(data_size):
    # Representing each index/character by a one-hot vector
    hot1 = np.zeros((vocab_size, 1))
    hot1[data_ix[k]] = 1
    train_data.append(hot1)

X = tf.placeholder(tf.float32, [None, vocab_size, 1]) #Number of examples, number of input, dimension of each input
target = tf.placeholder(tf.float32, [None, vocab_size])

cell = tf.contrib.rnn.LSTMCell(num_hidden,state_is_tuple=True)
output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)
output = tf.transpose(output, [1, 0, 2])

weight = tf.Variable(tf.random_normal([num_hidden, vocab_size]))
bias = tf.Variable(tf.constant(0.0, shape=[vocab_size]))

prediction = tf.matmul(output[-1], weight) + bias
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=target))

optimizer = tf.train.ProximalGradientDescentOptimizer(alpha)
minimize = optimizer.minimize(cost)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

ARR = [i for i in range(vocab_size)] # for extracting index by probabilities in np.random.choice()

ITER = []
COST = []

p = 0 # p will be iterated by batch_size steps
for i in range(iterations):
    if p + batch_size >= data_size:
        p = 0

    # sweeping through data one-hot vectors
    inp, out = train_data[p:p+batch_size], train_data[p+1:p+batch_size+1]
    out = np.reshape(out, [-1, vocab_size])

    c = sess.run(cost, {X: inp, target: out}) # calculating cost for plotting later
    COST.append(c)
    ITER.append(i)

    sess.run(minimize, {X: inp, target: out})

    # displaying sample_size number of characters with random seed
    # doesn't affect training
    if i % display_iteration == 0:
        seed = np.random.randint(0, vocab_size)
        CHARS = []
        for j in range(sample_size):
            x = np.zeros((vocab_size, 1))
            x[seed] = 1
            x = [x]
            pred = sess.run(prediction, {X: x})[0]
            pred = np.exp(pred) / np.sum(np.exp(pred))
            pred = pred.ravel()

            seed = np.random.choice(ARR, 1, p = pred)[0]
            ch = ix_to_char[seed]
            CHARS.append(ch)
        TXT = ''.join(CHARS)

        print("-------------------------------------------------")
        print(TXT)
        print("Iteration: ", str(i))

    p += batch_size
sess.close()
plt.plot(ITER, COST)
plt.show()
</code>```

EDIT: Added numpy code for comparison

```<code>import numpy as np
import matplotlib.pyplot as plt
import os
plt.style.use('fivethirtyeight')
direc = os.path.dirname(os.path.realpath(__file__))

readFile = open(direc + "\RNNtext.txt", 'r')

data = readFile.read()
readFile.close()

chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print(chars)
print("Vocabulary size: " + str(vocab_size))
char_to_ix = {}
ix_to_char = {}

for j in range(len(chars)):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

hidden_size = 80
batch_size = 120
alpha = 0.1
sample_size = 250
iterations = 1000
display_iteration = 100

Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
bh = np.zeros((hidden_size, 1)) # hidden bias
by = np.zeros((vocab_size, 1)) # output bias

def sample(hid, seed, weights, sample_size):
    X = np.zeros((vocab_size, 1))
    X[seed] = 1
    CHARS = []
    ARR = [i for i in range(vocab_size)]

    for t in range(sample_size):
        hid = np.tanh(np.dot(Wxh, X)  + np.dot(Whh, hid) + bh)
        y = np.dot(Why, hid) + by
        prob = np.exp(y) / np.sum(np.exp(y))
        prob = prob.ravel()
        ix = np.random.choice(ARR, 1, p=prob)[0]
        CHARS.append(ix_to_char[ix])
        X = np.zeros((vocab_size, 1))
        X[ix] = 1
        TXT = ''.join(CHARS)
    return TXT

LOSS = []
ITER = []
p = 0

mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad

smooth_loss = -np.log(1.0/vocab_size)*batch_size # loss at iteration 0
hprev = np.zeros((hidden_size,1))

for i in range(iterations): ## just time passing by

    dWxh = np.zeros_like(Wxh)
    dWhh = np.zeros_like(Whh)
    dWhy = np.zeros_like(Why)
    dbh = np.zeros_like(bh)
    dby = np.zeros_like(by)

    if p+batch_size >= len(data) or i == 0:
        hprev = np.zeros((hidden_size,1))
        p = 0

    inputs = [char_to_ix[ch] for ch in data[p:p+batch_size]]
    targets = [char_to_ix[ch] for ch in data[p+1:p+batch_size+1]]

    HID = {}
    X = {}
    Y = {}
    P = {}
    HID[-1] = np.copy(hprev)

    loss = 0

    ##======FORWARD======##
    for t in range(len(inputs)):
        X[t] = np.zeros((vocab_size,1))
        X[t][inputs[t]] = 1

        HID[t] = np.tanh(np.dot(Wxh, X[t])  + np.dot(Whh, HID[t-1]) + bh) # inp -> X
        Y[t] = np.dot(Why, HID[t]) + by # tanh
        P[t] = np.exp(Y[t]) / np.sum(np.exp(Y[t]))
        loss += -np.log(P[t][targets[t]][0])
    dhnext = np.zeros_like(HID[0])
    ##======BACKPROP======##
    for t in reversed(range(len(inputs))):

        dy = np.copy(P[t])
        dy[targets[t]] -= 1
        dh = (np.dot(Why.T, dy) + dhnext)*(1-HID[t]*HID[t])
        dx = np.dot(Why.T, dy)*(1 - HID[t]**2)

        dWhy += np.dot(dy, HID[t].T)
        dWhh += np.dot(dh, HID[t-1].T)
        dWxh += np.dot(dh, X[t].T)
        dby += dy
        dbh += dh

        dhnext = np.dot(Whh.T, dh)

    ##=====================##
    hprev = HID[-1]
    smooth_loss = smooth_loss * 0.999 + loss * 0.001
    for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -1, 1, out=dparam) # clip to mitigate exploding gradients

    for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
                                [dWxh, dWhh, dWhy, dbh, dby],
                                [mWxh, mWhh, mWhy, mbh, mby]):

        mem += dparam * dparam

        param += -alpha * dparam / np.sqrt(mem + 1e-8) # Adagrad
    if i % display_iteration == 0:
        print(str(i))
        weights = [Wxh,Whh,Why,bh,by]
        seed = inputs[np.random.randint(0,len(inputs))]
        TXT = sample(HID[-1], seed, weights, sample_size)
        print("-----------------------------------------------")
        print(TXT)
        print("-----------------------------------------------")
        with open(direc + "\RNNout.txt", 'w') as writeFile:
            writeFile.write(TXT)
    ITER.append(i)
    LOSS.append(loss)

    p += batch_size
best_text = sample(HID[-1], inputs[0], weights, sample_size)

plt.plot(ITER, LOSS, linewidth = 1)
plt.show()

writeFile.close()
</code>```

答:
With the information provided, I would suggest these two initial steps to try to improve the model.

Increase the number of iterations, Recurrent Neural Networks work differently than other deep arhitectures and could need maybe an additional order of magnitude in iteration number, to settle.

Play with the seeds: from my experience in order to get meaningful sequences can depend on the quality of the used seeds.

ContentLicense: CC BY-SA 3.0

Body:
This program reads a text file RNNtext.txt, creates one-hot vector representation for all the data, trains the LSTM with the data and displays a bunch of sampled characters every now and then. However, even looking at the cost vs iterations graph shows that it's learning very very inefficiently. Honestly, the raw code (numpy) for the LSTM I have does a MUCH better job. It's not only faster but it produces mostly meaningful words. This produces gibberish only. Where is my mistake? I really am out of ideas and I can't seem to find where it is logically wrong.

import numpy as np
import random
import tensorflow as tf
import os
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

# Reading RNNtext.txt file
direc = os.path.dirname(os.path.realpath(__file__))
data = open(direc + "/RNNtext.txt", "r").read()

# Array of unique characters
chars = list(set(data))

num_hidden = 80
iterations = 1000
display_iteration = 100 # Sample when iteration % display_iteration == 0
sample_size = 250
batch_size = 120 # batch size or the number of time steps to unroll RNN
alpha = 0.01 # Learning rate

#Vocabulary and text file sizes
vocab_size = len(chars)
data_size = len(data)

# Bijection from a unique character to an index
char_to_ix = {}
# Bijection from an index to a unique character
ix_to_char = {}

for j in range(vocab_size):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

# Transforming all characters to indices
data_ix = [char_to_ix[ch] for ch in data]

train_data = [] # This will contain one-hot vectors
for k in range(data_size):
    # Representing each index/character by a one-hot vector
    hot1 = np.zeros((vocab_size, 1))
    hot1[data_ix[k]] = 1
    train_data.append(hot1)

X = tf.placeholder(tf.float32, [None, vocab_size, 1]) #Number of examples, number of input, dimension of each input
target = tf.placeholder(tf.float32, [None, vocab_size])

cell = tf.contrib.rnn.LSTMCell(num_hidden,state_is_tuple=True)
output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)
output = tf.transpose(output, [1, 0, 2])

weight = tf.Variable(tf.random_normal([num_hidden, vocab_size]))
bias = tf.Variable(tf.constant(0.0, shape=[vocab_size]))

prediction = tf.matmul(output[-1], weight) + bias
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=target))

optimizer = tf.train.ProximalGradientDescentOptimizer(alpha)
minimize = optimizer.minimize(cost)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

ARR = [i for i in range(vocab_size)] # for extracting index by probabilities in np.random.choice()

ITER = []
COST = []

p = 0 # p will be iterated by batch_size steps
for i in range(iterations):
    if p + batch_size >= data_size:
        p = 0

    # sweeping through data one-hot vectors
    inp, out = train_data[p:p+batch_size], train_data[p+1:p+batch_size+1]
    out = np.reshape(out, [-1, vocab_size])

    c = sess.run(cost, {X: inp, target: out}) # calculating cost for plotting later
    COST.append(c)
    ITER.append(i)

    sess.run(minimize, {X: inp, target: out})

    # displaying sample_size number of characters with random seed
    # doesn't affect training
    if i % display_iteration == 0:
        seed = np.random.randint(0, vocab_size)
        CHARS = []
        for j in range(sample_size):
            x = np.zeros((vocab_size, 1))
            x[seed] = 1
            x = [x]
            pred = sess.run(prediction, {X: x})[0]
            pred = np.exp(pred) / np.sum(np.exp(pred))
            pred = pred.ravel()

            seed = np.random.choice(ARR, 1, p = pred)[0]
            ch = ix_to_char[seed]
            CHARS.append(ch)
        TXT = ''.join(CHARS)

        print("-------------------------------------------------")
        print(TXT)
        print("Iteration: ", str(i))

    p += batch_size
sess.close()
plt.plot(ITER, COST)
plt.show()

EDIT: Added numpy code for comparison

import numpy as np
import matplotlib.pyplot as plt
import os
plt.style.use('fivethirtyeight')
direc = os.path.dirname(os.path.realpath(__file__))

readFile = open(direc + "\RNNtext.txt", 'r')

data = readFile.read()
readFile.close()

chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print(chars)
print("Vocabulary size: " + str(vocab_size))
char_to_ix = {}
ix_to_char = {}

for j in range(len(chars)):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

hidden_size = 80
batch_size = 120
alpha = 0.1
sample_size = 250
iterations = 1000
display_iteration = 100

Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
bh = np.zeros((hidden_size, 1)) # hidden bias
by = np.zeros((vocab_size, 1)) # output bias

def sample(hid, seed, weights, sample_size):
    X = np.zeros((vocab_size, 1))
    X[seed] = 1
    CHARS = []
    ARR = [i for i in range(vocab_size)]

    for t in range(sample_size):
        hid = np.tanh(np.dot(Wxh, X)  + np.dot(Whh, hid) + bh)
        y = np.dot(Why, hid) + by
        prob = np.exp(y) / np.sum(np.exp(y))
        prob = prob.ravel()
        ix = np.random.choice(ARR, 1, p=prob)[0]
        CHARS.append(ix_to_char[ix])
        X = np.zeros((vocab_size, 1))
        X[ix] = 1
        TXT = ''.join(CHARS)
    return TXT

LOSS = []
ITER = []
p = 0

mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad

smooth_loss = -np.log(1.0/vocab_size)*batch_size # loss at iteration 0
hprev = np.zeros((hidden_size,1))

for i in range(iterations): ## just time passing by

    dWxh = np.zeros_like(Wxh)
    dWhh = np.zeros_like(Whh)
    dWhy = np.zeros_like(Why)
    dbh = np.zeros_like(bh)
    dby = np.zeros_like(by)

    if p+batch_size >= len(data) or i == 0:
        hprev = np.zeros((hidden_size,1))
        p = 0

    inputs = [char_to_ix[ch] for ch in data[p:p+batch_size]]
    targets = [char_to_ix[ch] for ch in data[p+1:p+batch_size+1]]

    HID = {}
    X = {}
    Y = {}
    P = {}
    HID[-1] = np.copy(hprev)

    loss = 0

    ##======FORWARD======##
    for t in range(len(inputs)):
        X[t] = np.zeros((vocab_size,1))
        X[t][inputs[t]] = 1

        HID[t] = np.tanh(np.dot(Wxh, X[t])  + np.dot(Whh, HID[t-1]) + bh) # inp -> X
        Y[t] = np.dot(Why, HID[t]) + by # tanh
        P[t] = np.exp(Y[t]) / np.sum(np.exp(Y[t]))
        loss += -np.log(P[t][targets[t]][0])
    dhnext = np.zeros_like(HID[0])
    ##======BACKPROP======##
    for t in reversed(range(len(inputs))):

        dy = np.copy(P[t])
        dy[targets[t]] -= 1
        dh = (np.dot(Why.T, dy) + dhnext)*(1-HID[t]*HID[t])
        dx = np.dot(Why.T, dy)*(1 - HID[t]**2)

        dWhy += np.dot(dy, HID[t].T)
        dWhh += np.dot(dh, HID[t-1].T)
        dWxh += np.dot(dh, X[t].T)
        dby += dy
        dbh += dh

        dhnext = np.dot(Whh.T, dh)

    ##=====================##
    hprev = HID[-1]
    smooth_loss = smooth_loss * 0.999 + loss * 0.001
    for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -1, 1, out=dparam) # clip to mitigate exploding gradients

    for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
                                [dWxh, dWhh, dWhy, dbh, dby],
                                [mWxh, mWhh, mWhy, mbh, mby]):

        mem += dparam * dparam

        param += -alpha * dparam / np.sqrt(mem + 1e-8) # Adagrad
    if i % display_iteration == 0:
        print(str(i))
        weights = [Wxh,Whh,Why,bh,by]
        seed = inputs[np.random.randint(0,len(inputs))]
        TXT = sample(HID[-1], seed, weights, sample_size)
        print("-----------------------------------------------")
        print(TXT)
        print("-----------------------------------------------")
        with open(direc + "\RNNout.txt", 'w') as writeFile:
            writeFile.write(TXT)
    ITER.append(i)
    LOSS.append(loss)

    p += batch_size
best_text = sample(HID[-1], inputs[0], weights, sample_size)

plt.plot(ITER, LOSS, linewidth = 1)
plt.show()

writeFile.close()


问:
Global legend for subplots with different content
I read through previous solutions but couldn´t make any of them work. I want to have a global legend for individual subplots.
The ax objects for this subplot are generated by a predefined function "get_plot" out of a predefined class
"The_predefined_plotting_class" roughly like this:

the function returns an ax object and each ax objects has multiple "plots"/ from multiple columns of the original "datafiles".

In one of the solutions i found on this site i read that i could use:

to make a global legend. Unfortunately i have no idea how to append the individual ax objects ( or the data therein) to handles to make this work.
Each plots contains some identical column names and some that differ. If an entry/name exists in many subplots it should only be printed once.

Solution1

Solution2

Solution3

EDIT

I am really sorry that i had to use pictures, but whatever i did the webside did not let me post my code even tho it was shown properly in the preview window ( the screenshots are from this window)

EDIT2

If i do it like this:

```<code>lines=[]
labels=[]
for idata, datafile in enumerate(datafiles):

    MYData = The_predefined_plotting_class.from_file(datafile)

    axis[idata] = The_predefined_plotting_class.get_plot( *kwargs)
    h, l = axis[idata].get_legend_handles_labels()

    lines.append(h)
    labels.append(l)

LINES=[]
LABELS=[]
for i in range(0, nrows):
    LINES+=lines[i]
    LABELS+=labels[i]
plt.legend( LINES, LABELS, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True)
plt.show()
</code>```

Then it shows all Data . Some of the Data has the same lines and labels handler. I am now left with the problem to iterate through both lists and delete only one entry if in both lists the tuple (LINES[j];LABELS[j]) = (LINES[i];LABELS[i]) exist twice (and only then). Preferably the first entry:

EDIT3

```<code>labels =[]
lines = []
h=["Cat","Mouse","Dog","Cat","Cat","Kangaroo","Dog"]
l=["black","white","brown","white","black","yellow","brown"]

for handle, label in zip(h, l):
    if label not in labels :

            lines.append(handle)
            labels.append(label)

print "The disired Output is :"
print '["Cat","Mouse","Dog","Cat","Kangaroo"]'
print '["black","white","brown","white","yellow"]'

print "currently you get:"

print lines
print labels
</code>```

EDIT4

I add a "minimum" working example which should contain all possible situations that occur in my real data.

```<code>lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

a = np.cos(2 * np.pi * x1) * np.exp(-x1)
b = np.cos(2 * np.pi * x2)
c = np.cos(5 * np.pi * x1) * np.exp(-x1)
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1)
d = np.cos(2 * np.pi * x2 )
d2 = np.cos(2 * np.pi * x2-1 )
e = x1*5
e2 = -x1*5
f = np.exp(x1)-e
f2 = (np.exp(x1)-e)/2

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].plot(x1, e, 'k--', label='Label1',color="green")
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue")
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow")
axis[1].plot(x1, c, 'k--', label='Label1',color="green")
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue")
axis[1].plot(x1, a, 'k--', label='Label3',color="grey")
axis[2].plot(x2, d, '*', label='Label1',color="green")
axis[2].plot(x2, d2, 'D', label='Label2',color="green")
axis[3].plot(x1, f, 'H', label='Label1',color="green")
axis[3].plot(x1, f2, 'D', label='Label2',color="green")

for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for handle, label in zip(h, l):
        if label not in labels:
            lines.append(handle)
            labels.append(label)

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()
</code>```

EDIT5

this is the part form the script in question where the actual plots are generated. "columns" contains just the names of the actual data to be ploted.

```<code>    # add plots
    ic = 0
    for col in columns:
        if col == "envelope":
            ax.plot(self.data.index, self.data.envelope,
                    linewidth=LINEWIDTH_envelope, c=last_color, label="")
        elif col == "Exp":
            ax.plot(self.data.index, self.data.Exp, c=first_color, linestyle="",
                    label="Exp", marker="o", markersize=MARKERSIZE )
        else:
            color = used_colors[ic % len(used_colors)]
            if fill and "BG" in self.data.columns:
                ax.fill_between(self.data.index, self.data.BG,
                                self.data[col], label=col, alpha=ALPHA,
                                color=color)
            else:
                ax.plot(self.data.index, self.data[col], linewidth=LINEWIDTH,
                        c=color, label=col)
            ic += 1
</code>```

EDIT6

I tried to find a solution based on the idea i presented here:

Iteration though lists

Unfortunately what works for two Lists containing strings does not work for the artist handels it seems.

```<code>import matplotlib.pyplot as plt
import numpy as np
LI=[]
lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

a = np.cos(2 * np.pi * x1) * np.exp(-x1)
b = np.cos(2 * np.pi * x2)
c = np.cos(5 * np.pi * x1) * np.exp(-x1)
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1)
d = np.cos(2 * np.pi * x2 )
d2 = np.cos(2 * np.pi * x2-1 )
e = x1*5
e2 = -x1*5
f = np.exp(x1)-e
f2 = (np.exp(x1)-e)/2

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].plot(x1, e, 'k--', label='Label1',color="green")
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue")
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow")
axis[1].plot(x1, c, 'k--', label='Label1',color="green")
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue")
axis[1].plot(x1, a, 'k--', label='Label3',color="grey")
axis[2].plot(x2, d, '*', label='Label1',color="green")
axis[2].plot(x2, d2, 'D', label='Label2',color="green")
axis[3].plot(x1, f, 'H', label='Label1',color="green")
axis[3].plot(x1, f2, 'D', label='Label2',color="green")

for i in range(nrows):
    print i
    h, l = axis[i].get_legend_handles_labels()
    for hl in zip(h,l):

        if hl not in LI:
            LI.append(hl)
            lines.append(LI[-1][0])
            labels.append(LI[-1][1])

print LI

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()
</code>```

I think the problem is that only the string for the Memory adress is compared in

```<code>if hl not in LI:
</code>```

not the actual content of "h"?

solution  based on the explanation of ImportanceOfBeingErnest gave in a related post Link7:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import matplotlib.collections

def is_inlist(handle, handles):
    for h in handles:
        if isinstance(handle, matplotlib.collections.PolyCollection) and isinstance(h, matplotlib.collections.PolyCollection):
            if np.all(h.get_facecolor() == handle.get_facecolor()) and \
                np.all(h.get_linestyle() == handle.get_linestyle()) and \
                np.all(h.get_alpha() == handle.get_alpha()):
                return True
        if isinstance(handle, matplotlib.lines.Line2D) and isinstance(h, matplotlib.lines.Line2D):
            if h.get_color() == handle.get_color() and \
                h.get_linestyle() == handle.get_linestyle() and \
                h.get_marker() == handle.get_marker():
                return True

    return False

lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data

mu = 0
mu2 = 5
variance = 1
variance2 = 2
sigma = math.sqrt(variance)
sigma2 = math.sqrt(variance2)
x = np.linspace(mu-3*variance,mu+3*variance, 100)
x2 = np.linspace(mu2-3*variance2,mu2+3*variance2, 100)

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[0].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True)
axis[0].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[0].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[0].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[1].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[1].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True)
axis[1].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[1].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[1].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='yellow',alpha=0.5,label="PEAK5", interpolate=True)
axis[1].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[2].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[2].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True)
axis[2].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK3", interpolate=True)
axis[2].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[2].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[3].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[3].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True)
axis[3].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[3].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[3].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK5", interpolate=True)
axis[3].fill_between(x+5.5,0,mlab.normpdf(x, mu, sigma), color='violet',alpha=0.5,label="PEAK6", interpolate=True)
axis[3].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for hi, li in zip(h,l):
        if not is_inlist(hi, lines):
            lines.append(hi)
            labels.append(li)

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows-1+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()
</code>```

Here my real data is reflected better as i have both matplotlib.collections.PolyCollection) and matplotlib.lines.Line2D objects wich need to be compared.

答:
The Edit2 looks promising. You can then check if the label is already in the labels list and if not, append it. Of course I cannot test the following, but it should at least show the concept.

```<code>lines=[]
labels=[]
for idata, datafile in enumerate(datafiles):

    MYData = The_predefined_plotting_class.from_file(datafile)

    axis[idata] = The_predefined_plotting_class.get_plot( *kwargs)
    h, l = axis[idata].get_legend_handles_labels()

    for handle, label in zip(h, l):
        if label not in labels:
            lines.append(handle)
            labels.append(label)

plt.legend(handles=lines, labels=labels, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True)
plt.show()
</code>```

If you want to aviod diplicate handles, you may use the properties which make them appear equal and see if a similar artist is already present in the handles list.

```<code>def is_inlist(handle, handles):
    for h in handles:
        if h.get_color() == handle.get_color() and \
            h.get_linestyle() == handle.get_linestyle() and \
            h.get_marker() == handle.get_marker():
            return True
    return False

lines=[]
labels=[]
for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for hi, li in zip(h,l):
        if not is_inlist(hi, lines):
            lines.append(hi)
            labels.append(li)

plt.legend(handles=lines, labels=labels)
</code>```

Body:
I read through previous solutions but couldn´t make any of them work. I want to have a global legend for individual subplots.
The ax objects for this subplot are generated by a predefined function "get_plot" out of a predefined class
"The_predefined_plotting_class" roughly like this:

the function returns an ax object and each ax objects has multiple "plots"/ from multiple columns of the original "datafiles".

In one of the solutions i found on this site i read that i could use:

to make a global legend. Unfortunately i have no idea how to append the individual ax objects ( or the data therein) to handles to make this work.
Each plots contains some identical column names and some that differ. If an entry/name exists in many subplots it should only be printed once.

Solution1

Solution2

Solution3

EDIT

I am really sorry that i had to use pictures, but whatever i did the webside did not let me post my code even tho it was shown properly in the preview window ( the screenshots are from this window)

EDIT2

If i do it like this:

lines=[]
labels=[]
for idata, datafile in enumerate(datafiles):

    MYData = The_predefined_plotting_class.from_file(datafile)

    axis[idata] = The_predefined_plotting_class.get_plot( *kwargs)
    h, l = axis[idata].get_legend_handles_labels()

    lines.append(h)
    labels.append(l)

LINES=[]
LABELS=[]
for i in range(0, nrows):
    LINES+=lines[i]
    LABELS+=labels[i]
plt.legend( LINES, LABELS, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True)
plt.show()

Then it shows all Data . Some of the Data has the same lines and labels handler. I am now left with the problem to iterate through both lists and delete only one entry if in both lists the tuple (LINES[j];LABELS[j]) = (LINES[i];LABELS[i]) exist twice (and only then). Preferably the first entry:

EDIT3

labels =[]
lines = []
h=["Cat","Mouse","Dog","Cat","Cat","Kangaroo","Dog"]
l=["black","white","brown","white","black","yellow","brown"]

for handle, label in zip(h, l):
    if label not in labels :

            lines.append(handle)
            labels.append(label)

print "The disired Output is :"
print '["Cat","Mouse","Dog","Cat","Kangaroo"]'
print '["black","white","brown","white","yellow"]'

print "currently you get:"

print lines
print labels

EDIT4

I add a "minimum" working example which should contain all possible situations that occur in my real data.

lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

a = np.cos(2 * np.pi * x1) * np.exp(-x1)
b = np.cos(2 * np.pi * x2)
c = np.cos(5 * np.pi * x1) * np.exp(-x1)
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1)
d = np.cos(2 * np.pi * x2 )
d2 = np.cos(2 * np.pi * x2-1 )
e = x1*5
e2 = -x1*5
f = np.exp(x1)-e
f2 = (np.exp(x1)-e)/2

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].plot(x1, e, 'k--', label='Label1',color="green")
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue")
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow")
axis[1].plot(x1, c, 'k--', label='Label1',color="green")
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue")
axis[1].plot(x1, a, 'k--', label='Label3',color="grey")
axis[2].plot(x2, d, '*', label='Label1',color="green")
axis[2].plot(x2, d2, 'D', label='Label2',color="green")
axis[3].plot(x1, f, 'H', label='Label1',color="green")
axis[3].plot(x1, f2, 'D', label='Label2',color="green")

for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for handle, label in zip(h, l):
        if label not in labels:
            lines.append(handle)
            labels.append(label)

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()

EDIT5

this is the part form the script in question where the actual plots are generated. "columns" contains just the names of the actual data to be ploted.

    # add plots
    ic = 0
    for col in columns:
        if col == "envelope":
            ax.plot(self.data.index, self.data.envelope,
                    linewidth=LINEWIDTH_envelope, c=last_color, label="")
        elif col == "Exp":
            ax.plot(self.data.index, self.data.Exp, c=first_color, linestyle="",
                    label="Exp", marker="o", markersize=MARKERSIZE )
        else:
            color = used_colors[ic % len(used_colors)]
            if fill and "BG" in self.data.columns:
                ax.fill_between(self.data.index, self.data.BG,
                                self.data[col], label=col, alpha=ALPHA,
                                color=color)
            else:
                ax.plot(self.data.index, self.data[col], linewidth=LINEWIDTH,
                        c=color, label=col)
            ic += 1

EDIT6

I tried to find a solution based on the idea i presented here:

Iteration though lists

Unfortunately what works for two Lists containing strings does not work for the artist handels it seems.

import matplotlib.pyplot as plt
import numpy as np
LI=[]
lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

a = np.cos(2 * np.pi * x1) * np.exp(-x1)
b = np.cos(2 * np.pi * x2)
c = np.cos(5 * np.pi * x1) * np.exp(-x1)
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1)
d = np.cos(2 * np.pi * x2 )
d2 = np.cos(2 * np.pi * x2-1 )
e = x1*5
e2 = -x1*5
f = np.exp(x1)-e
f2 = (np.exp(x1)-e)/2

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].plot(x1, e, 'k--', label='Label1',color="green")
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue")
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow")
axis[1].plot(x1, c, 'k--', label='Label1',color="green")
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue")
axis[1].plot(x1, a, 'k--', label='Label3',color="grey")
axis[2].plot(x2, d, '*', label='Label1',color="green")
axis[2].plot(x2, d2, 'D', label='Label2',color="green")
axis[3].plot(x1, f, 'H', label='Label1',color="green")
axis[3].plot(x1, f2, 'D', label='Label2',color="green")

for i in range(nrows):
    print i
    h, l = axis[i].get_legend_handles_labels()
    for hl in zip(h,l):

        if hl not in LI:
            LI.append(hl)
            lines.append(LI[-1][0])
            labels.append(LI[-1][1])

print LI

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()

I think the problem is that only the string for the Memory adress is compared in

if hl not in LI:

not the actual content of "h"?

solution  based on the explanation of ImportanceOfBeingErnest gave in a related post Link7:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
import matplotlib.collections

def is_inlist(handle, handles):
    for h in handles:
        if isinstance(handle, matplotlib.collections.PolyCollection) and isinstance(h, matplotlib.collections.PolyCollection):
            if np.all(h.get_facecolor() == handle.get_facecolor()) and \
                np.all(h.get_linestyle() == handle.get_linestyle()) and \
                np.all(h.get_alpha() == handle.get_alpha()):
                return True
        if isinstance(handle, matplotlib.lines.Line2D) and isinstance(h, matplotlib.lines.Line2D):
            if h.get_color() == handle.get_color() and \
                h.get_linestyle() == handle.get_linestyle() and \
                h.get_marker() == handle.get_marker():
                return True

    return False

lines=[]
labels=[]
legend_properties = {'weight':'bold','size':10}
# Example data

mu = 0
mu2 = 5
variance = 1
variance2 = 2
sigma = math.sqrt(variance)
sigma2 = math.sqrt(variance2)
x = np.linspace(mu-3*variance,mu+3*variance, 100)
x2 = np.linspace(mu2-3*variance2,mu2+3*variance2, 100)

nrows = 4
# Plot

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8))
fig.subplots_adjust(hspace=0.0001)
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold')

axis[0].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[0].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True)
axis[0].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[0].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[0].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[1].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[1].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True)
axis[1].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[1].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[1].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='yellow',alpha=0.5,label="PEAK5", interpolate=True)
axis[1].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[2].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[2].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True)
axis[2].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK3", interpolate=True)
axis[2].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[2].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

axis[3].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True)
axis[3].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True)
axis[3].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True)
axis[3].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True)
axis[3].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK5", interpolate=True)
axis[3].fill_between(x+5.5,0,mlab.normpdf(x, mu, sigma), color='violet',alpha=0.5,label="PEAK6", interpolate=True)
axis[3].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4)

for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for hi, li in zip(h,l):
        if not is_inlist(hi, lines):
            lines.append(hi)
            labels.append(li)

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows-1+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0)

plt.show()

Here my real data is reflected better as i have both matplotlib.collections.PolyCollection) and matplotlib.lines.Line2D objects wich need to be compared.

Body:
The Edit2 looks promising. You can then check if the label is already in the labels list and if not, append it. Of course I cannot test the following, but it should at least show the concept.

lines=[]
labels=[]
for idata, datafile in enumerate(datafiles):

    MYData = The_predefined_plotting_class.from_file(datafile)

    axis[idata] = The_predefined_plotting_class.get_plot( *kwargs)
    h, l = axis[idata].get_legend_handles_labels()

    for handle, label in zip(h, l):
        if label not in labels:
            lines.append(handle)
            labels.append(label)

plt.legend(handles=lines, labels=labels, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True)
plt.show()

If you want to aviod diplicate handles, you may use the properties which make them appear equal and see if a similar artist is already present in the handles list.

def is_inlist(handle, handles):
    for h in handles:
        if h.get_color() == handle.get_color() and \
            h.get_linestyle() == handle.get_linestyle() and \
            h.get_marker() == handle.get_marker():
            return True
    return False

lines=[]
labels=[]
for i in range(nrows):
    h, l = axis[i].get_legend_handles_labels()
    for hi, li in zip(h,l):
        if not is_inlist(hi, lines):
            lines.append(hi)
            labels.append(li)

plt.legend(handles=lines, labels=labels)


问:
Change every single element in Numpy object
I have a Numpy object with random N*M elements, and I also have two numbers A and B.

Now I want to access every element in this N*M array and make a change, i.e., if the element > 0, replace this element to A (i.e., element <- A), and if this element < 0, replace this element to B (i.e., element <- B).

I know there is a naive way to implement this method, that is accessing every single element using for loop, but it is very slow.

Can we use more fancy code to implement this ?

Body:
Boolean masked assignment will change values in place:

In [493]: arr = np.random.randint(-10,10,(5,7))
In [494]: arr
Out[494]:
array([[ -5,  -6,  -7,  -1,  -8,  -8, -10],
       [ -9,   1,  -3,  -9,   3,   8,  -1],
       [  6,  -7,   4,   0,  -4,   4,  -2],
       [ -3, -10,  -2,   7,  -4,   2,   2],
       [ -5,   5,  -1,  -7,   7,   5,  -7]])
In [495]: arr[arr>0] = 100
In [496]: arr[arr<0] = -50
In [497]: arr
Out[497]:
array([[-50, -50, -50, -50, -50, -50, -50],
       [-50, 100, -50, -50, 100, 100, -50],
       [100, -50, 100,   0, -50, 100, -50],
       [-50, -50, -50, 100, -50, 100, 100],
       [-50, 100, -50, -50, 100, 100, -50]])

I just gave a similar answer in

python numpy: iterate for different conditions without using a loop


问:
elasticsearch : Avoid repetitive scoring when using ngram analyzer
Suppose I search for "hello" when the document contains "hello" and "hello hello" I want "hello" to have higher scoring.

I am using ngram index and search analyzer. (Because I really need this for other scenarios) So "hello hello" gets matched twice and hence shows as the top result. Is there any way I can avoid this? I have already tried term query, match phrase query, multi match queries all of them scores "hello hello" higher.

答:
I solved this by adding a duplicate unanalyzed (keyword) column for the document and used bool clause to boost the term query.</p>

```<code>var res = client.Search<MyClass>(s => s
  .Query(q => q
    .Bool(
        b1 => b1.Should(
            s1 =>s1
            .Term(m=>m
                .Field(f => f._DUPLICATE_COLUMN)
                .Value("hello")
                .Boost(1)
            ),

            s1=>s1.Match(m => m
            .Field(f => f.MY_COLUMN)
            .Query("hello")
            .Analyzer("myNgramSearchAnalyzer")
            )
        )
        .MinimumShouldMatch(1)
    )
  )
);
</code>```

Body:
I solved this by adding a duplicate unanalyzed (keyword) column for the document and used bool clause to boost the term query.

var res = client.Search<MyClass>(s => s
  .Query(q => q
    .Bool(
        b1 => b1.Should(
            s1 =>s1
            .Term(m=>m
                .Field(f => f._DUPLICATE_COLUMN)
                .Value("hello")
                .Boost(1)
            ),

            s1=>s1.Match(m => m
            .Field(f => f.MY_COLUMN)
            .Query("hello")
            .Analyzer("myNgramSearchAnalyzer")
            )
        )
        .MinimumShouldMatch(1)
    )
  )
);


问:
how to return a json response of validation in laravel
Validation code

```<code> $this->validate($request, [
            'email'=> 'required|email|unique:users',
            'email'=> 'required|max:120',
            'password' => 'required|min:4'
            ]);
</code>```

how can i return the errors of validation if they exist as a json response?

答:
Using $this->validate on the controller action automates the whole process significantly. If the validation fails, it automatically redirects to the previous page, while a list of errors should be available in $errors variable in your view.

If you want to have a control over the process you can do it that way:

```<code>$validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
]);

if ($validator->fails()) {
  return $validator->errors();
}

// Validation successful
</code>```

Please see https://laravel.com/docs/5.4/validation for more information.

Body:
Validation code

 $this->validate($request, [
            'email'=> 'required|email|unique:users',
            'email'=> 'required|max:120',
            'password' => 'required|min:4'
            ]);

how can i return the errors of validation if they exist as a json response?

Body:
Using $this->validate on the controller action automates the whole process significantly. If the validation fails, it automatically redirects to the previous page, while a list of errors should be available in $errors variable in your view.

If you want to have a control over the process you can do it that way:

$validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
]);

if ($validator->fails()) {
  return $validator->errors();
}

// Validation successful

Please see https://laravel.com/docs/5.4/validation for more information.


问:
Shorten if statement with same condition
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

```<code>bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}
</code>```

答:
Actually if you use C++11 or higher you can do some shortening:

```<code>#include <iostream>
#include <string>
#include <tuple>

int main() {
    int x = 1;
    std::string y = "Hello";
    double z = 3.14;

    if(std::make_tuple(x, y, z) == std::make_tuple(1, "Hello", 3.14))
        std::cout << "Everything is okay." << std::endl;
    else
        std::cout << "Something went wrong." << std::endl;

    return 0;
}
</code>```

Or for your case (if the type of your variables is int):

```<code>if(std::vector<int> { x, y, z } == std::vector<int> { 1, 1, 1 })
    std::cout << "Everything is okay." << std::endl;
else
    std::cout << "Something went wrong." << std::endl;
</code>```

But remember, these techniques come handy when you have to test many inputs at once, or you have to overload the comparison operators for your type. In your example (as the comments point out too) this is unnecessary, the x == 1 && y == 1 && z == 1 is trivial enough.

After you edited your question it became clear that you intend to use objects (std::string) in comparison. In that case copying them into an std::tuple or into an array each time a comparison is made will occur a serious performance hit.

To don't make a significant overhead compared to expressions inside your if statements, you can use variadic templates like follows:

```<code>template<typename T, typename... Args>
bool equalToAll(T&& test, Args&&... args) {
    bool result = true;
    bool dummy[] { false, (result &= (test == args))... };
    return (static_cast<void>(dummy), result);
}

// Usage:
// equalToAll(player, grid[i][j], grid[i + 1][j], grid[i + 2][j], grid[i + 3][j])
</code>```

This example performs a parameter pack expansion with list initializer which about you can read more here and here.

Body:
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}

Body:
Actually if you use C++11 or higher you can do some shortening:

#include <iostream>
#include <string>
#include <tuple>

int main() {
    int x = 1;
    std::string y = "Hello";
    double z = 3.14;

    if(std::make_tuple(x, y, z) == std::make_tuple(1, "Hello", 3.14))
        std::cout << "Everything is okay." << std::endl;
    else
        std::cout << "Something went wrong." << std::endl;

    return 0;
}

Or for your case (if the type of your variables is int):

if(std::vector<int> { x, y, z } == std::vector<int> { 1, 1, 1 })
    std::cout << "Everything is okay." << std::endl;
else
    std::cout << "Something went wrong." << std::endl;

But remember, these techniques come handy when you have to test many inputs at once, or you have to overload the comparison operators for your type. In your example (as the comments point out too) this is unnecessary, the x == 1 && y == 1 && z == 1 is trivial enough.

After you edited your question it became clear that you intend to use objects (std::string) in comparison. In that case copying them into an std::tuple or into an array each time a comparison is made will occur a serious performance hit.

To don't make a significant overhead compared to expressions inside your if statements, you can use variadic templates like follows:

template<typename T, typename... Args>
bool equalToAll(T&& test, Args&&... args) {
    bool result = true;
    bool dummy[] { false, (result &= (test == args))... };
    return (static_cast<void>(dummy), result);
}

// Usage:
// equalToAll(player, grid[i][j], grid[i + 1][j], grid[i + 2][j], grid[i + 3][j])

This example performs a parameter pack expansion with list initializer which about you can read more here and here.


问:
pytest: environment variable to specify pytest.ini location
How can I set an environment variable with the location of the pytest.ini, tox.ini or setup.cfg for running pytest by default?

I created a docker container with a volume pointing to my project directory, so every change I make is also visible inside the docker container. The problem is that I have a pytest.ini file on my project root which won't apply to the docker container.

So I want to set an environment variable inside the docker container to specify where to look for the pytest configuration. Does anyone have any idea how could I do that?

答: There is no way to do that. You can use a different pytest configuration using pytest -c but tox.ini and setup.cfg must reside in the top-level directory of your package, next to setup.py.


问:
On focus, how to place the caret after the last character in an already populated field in IE?
On focus, how to place the caret after the last character  in an already populated field in IE?</p>

答:
IE9 makes it easy, with .selectionStart and .selectionEnd.

It looks like in prior versions you'll need to call .createTextRange, and then manipulate the returned object with .move, .moveStart, .moveEnd, and .movePoint.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
ImportError in Python
I tried to execute a program using geonames_rdf, but I cant execute it by this error:

```<code>Traceback (most recent call last):
File "geo1.py", line 13, in <module>
 import geonames.config.log
ImportError: No module named config.log
</code>```

I read several posts abot ImportError and I check the path of the system and it is correct. I'm working in a VirtualBox with a fresh Ubuntu 16.04.

The imports of my program are:

```<code>import sys
import os
import os.path
import logging
import geonames.config.log
import geonames.compat
import geonames.adapters.search
</code>```

I've also tried add this line:

```<code>sys.path.append('/usr/local/lib/python2.7/dist-packages/geonames/')
</code>```

The command that I used to instal this package was

```<code>sudo pip install geonames_rdf
</code>```

答:
I just tried to use geonames_rdf, but I didn't know I needed it to do a geonames search so I installed geonames first, then discovered I had to install fiona and gdal (I'm on Windows, had to install these two using prebuilt whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/). Don't know why these dependencies aren't baked into geonames.

Anyway once I then installed geonames_rdf it seemed to install into the geonames folder in c:\Python27\lib\site-packages, added at least the adapters package. In c:\Python27\lib\site-packages\geonames there is a config folder with log.py in it.

Title: ImportError in Python

Body:
I tried to execute a program using geonames_rdf, but I cant execute it by this error:

Traceback (most recent call last):
File "geo1.py", line 13, in <module>
 import geonames.config.log
ImportError: No module named config.log

I read several posts abot ImportError and I check the path of the system and it is correct. I'm working in a VirtualBox with a fresh Ubuntu 16.04.

The imports of my program are:

import sys
import os
import os.path
import logging
import geonames.config.log
import geonames.compat
import geonames.adapters.search

I've also tried add this line:

sys.path.append('/usr/local/lib/python2.7/dist-packages/geonames/')

The command that I used to instal this package was

sudo pip install geonames_rdf


问:
Equivalent of `git add -p` for cvs
I am stuck with cvs (don't ask!) and I was thinking that out of all the goodness of git, there is one that could be approximated reasonably enough: incremental addition of changes, à la git add -p followed by git commit. Before I try to hack together a solution, does anyone know of an implementation of such a feature?

答: Thanks to you guys, @Tom Lord and @emory, I got motivated to search again for some tool that could incrementally import cvs to git, and I have found one that seem to work fast enough and reliably enough, at least on the repo I have to deal with. I haven't seen it mentioned much, hence that answer. It's called crap-clone (sense of humour!?) and the git repo is https://github.com/rcls/crap.</p>

Title: Equivalent of `git add -p` for cvs


问:
How can I merge duplicate objects with Linq while concatenating a property?
I have an object:

```<code>private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }
</code>```

I also have a list of that object:

```<code>List<User> users = new List<User>();
</code>```

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

```<code>users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();
</code>```

答:
Using D Stanley answer, I ran the code on online compiler, with some mods. Needs to add the others properties in merge function, like Stanley said.

http://rextester.com/YJV50083

The user list (the 'A,B,C,D,E' are securityroles):

Users:

Test1 A

Test1 B

Test2 C

Test2 D

Test3 E

After linq:

New users:

Test1 A, B

Test2 C, D

Test3 E

Body:
I have an object:

private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }

I also have a list of that object:

List<User> users = new List<User>();

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();


问:
The "FindConfigFiles" task failed unexpectedly. Visual studio and Typescript issue with VS2015 Angular 2
This is the issue, cannot even understand why this issue is occuring.

Severity    Code    Description Project File    Line
Error       The "FindConfigFiles" task failed unexpectedly.
System.InvalidOperationException: The item metadata "%(FullPath)" cannot be applied to the path "content\scripts\angular\typings\node_modules\typings-core\node_modules\popsicle\node_modules\form-data\node_modules\combined-stream\node_modules\delayed-stream\test\integration\test-delayed-stream.js". content\scripts\angular\typings\node_modules\typings-core\node_modules\popsicle\node_modules\form-data\node_modules\combined-stream\node_modules\delayed-stream\test\integration\test-delayed-stream.js
   at Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)
   at Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInvalidOperation(Boolean condition, String resourceName, Object arg0, Object arg1, Object arg2)
   at Microsoft.Build.Shared.FileUtilities.ItemSpecModifiers.GetItemSpecModifier(String currentDirectory, String itemSpec, String definingProjectEscaped, String modifier, String& fullPath)
   at Microsoft.Build.Evaluation.BuiltInMetadata.GetMetadataValueEscaped(String currentDirectory, String evaluatedIncludeBeforeWildcardExpansionEscaped, String evaluatedIncludeEscaped, String definingProjectEscaped, String name, String& fullPath)
   at Microsoft.Build.Execution.ProjectItemInstance.TaskItem.GetBuiltInMetadataEscaped(String name)
   at Microsoft.Build.Execution.ProjectItemInstance.TaskItem.GetMetadataEscaped(String metadataName)
   at Microsoft.Build.Execution.ProjectItemInstance.TaskItem.GetMetadata(String metadataName)
   at TypeScript.Tasks.FindConfigFiles.<>c.b__12_0(ITaskItem f)
   at System.Linq.Enumerable.WhereArrayIterator1.MoveNext()
   at System.Linq.Buffer1..ctor(IEnumerable1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
   at TypeScript.Tasks.FindConfigFiles.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext()

答:
Had similar issues during migration from VS 2015 to 2017.

```<code>Error       The "FindConfigFiles" task could not be initialized with its input parameters.
Error       The "IsFileSystemCaseSensitive" parameter is not supported by the "FindConfigFiles" task. Verify the parameter exists on the task, and it is a settable public instance property.
</code>```

Fixed by
- closing VS 2017,
- uninstalling old VS TypeScript plugin,
- removing nuget plugin packages (also cleaning physical folder just in case),
- installing TypeScript SDK for Visual Studio 2017.

Maybe it would save someone's time.

Body:
Had similar issues during migration from VS 2015 to 2017.

Error       The "FindConfigFiles" task could not be initialized with its input parameters.
Error       The "IsFileSystemCaseSensitive" parameter is not supported by the "FindConfigFiles" task. Verify the parameter exists on the task, and it is a settable public instance property.

Fixed by
- closing VS 2017,
- uninstalling old VS TypeScript plugin,
- removing nuget plugin packages (also cleaning physical folder just in case),
- installing TypeScript SDK for Visual Studio 2017.

Maybe it would save someone's time.


问:
How to figure out who owns a worker thread that is still running when my app exits?
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

```<code>ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]
</code>```

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

```<code>    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes
</code>```

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.

答:
The worker thread Id you are seeing is 0. This is a framework thread and is expected - it is not a thread that the program has "spawned". If you attach to any .Net process you will see this. I'm not sure which framework thread it is - definitely not the finalizer thread as this is never thread 0. Perhaps a JIT thread?

What is more interesting then is your main thread, as this appears to be hanging. I would concentrate on debugging your main thread to bottom this out. Has it deadlocked itself from a window closed event handler waiting for something that will never happen for example?

Update

After reading the stack trace for the main thread added to the question, it would be interesting to run a test to bottom out whether the main thread is stalled or whether it is simply idle waiting for a message (and that it is waiting for a WM_CLOSE that it never received or was never sent).

The code below can be used to manually send a WM_CLOSE message to your application. Simply wait for your program to hang when you have shut it down, and then run the code. Replace the process name with your own.

Update 2

Ok, it looks like the main thread is well and truly hung as it is not processing WM_CLOSE or WM_QUIT messages.

Please try and make the smallest application that can reproduce the issue and post the code.

Example WM_CLOSE\WM_QUIT App

```<code>internal class Program
{
    private const int WM_QUIT = 0x0012;
    private const int WM_CLOSE = 0x0010;

    [DllImport("user32.dll")]
    private static extern bool PostMessage(int hhwnd, uint msg, IntPtr wParam, IntPtr lParam);

    private static void Main()
    {
        Process p = GetProcess("Your process name - no '.exe' required");

        CloseMainWindow(p);
    }

    private static Process GetProcess(string name)
    {
        List<Process> processes = Process.GetProcessesByName(name).ToList();

        if (processes.Count != 1)
        {
            throw new Exception(
              "Expected 1 process with name '" + name +
              "' but found " + processes.Count + ".");
        }

        return processes[0];
    }

    private static void CloseMainWindow(Process p)
    {
        PostMessage(p, WM_CLOSE, "close");
    }

    private static void QuitApplication(Process p)
    {
        PostMessage(p, WM_QUIT, "quit");
    }

    private static void PostMessage(Process p, uint message, string name)
    {
        Console.WriteLine("Posting {0} message to '{1}'...", name, p.ProcessName);

        bool succeeded = PostMessage(p.MainWindowHandle.ToInt32(), message, IntPtr.Zero, IntPtr.Zero);

        Console.WriteLine("Posted {0} message to '{1}' (succeeded:{2}).", name, p.ProcessName, succeeded);
    }
}
</code>```

Body:
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.

Body:
The worker thread Id you are seeing is 0. This is a framework thread and is expected - it is not a thread that the program has "spawned". If you attach to any .Net process you will see this. I'm not sure which framework thread it is - definitely not the finalizer thread as this is never thread 0. Perhaps a JIT thread?

What is more interesting then is your main thread, as this appears to be hanging. I would concentrate on debugging your main thread to bottom this out. Has it deadlocked itself from a window closed event handler waiting for something that will never happen for example?

Update

After reading the stack trace for the main thread added to the question, it would be interesting to run a test to bottom out whether the main thread is stalled or whether it is simply idle waiting for a message (and that it is waiting for a WM_CLOSE that it never received or was never sent).

The code below can be used to manually send a WM_CLOSE message to your application. Simply wait for your program to hang when you have shut it down, and then run the code. Replace the process name with your own.

Update 2

Ok, it looks like the main thread is well and truly hung as it is not processing WM_CLOSE or WM_QUIT messages.

Please try and make the smallest application that can reproduce the issue and post the code.

Example WM_CLOSE\WM_QUIT App

internal class Program
{
    private const int WM_QUIT = 0x0012;
    private const int WM_CLOSE = 0x0010;

    [DllImport("user32.dll")]
    private static extern bool PostMessage(int hhwnd, uint msg, IntPtr wParam, IntPtr lParam);

    private static void Main()
    {
        Process p = GetProcess("Your process name - no '.exe' required");

        CloseMainWindow(p);
    }

    private static Process GetProcess(string name)
    {
        List<Process> processes = Process.GetProcessesByName(name).ToList();

        if (processes.Count != 1)
        {
            throw new Exception(
              "Expected 1 process with name '" + name +
              "' but found " + processes.Count + ".");
        }

        return processes[0];
    }

    private static void CloseMainWindow(Process p)
    {
        PostMessage(p, WM_CLOSE, "close");
    }

    private static void QuitApplication(Process p)
    {
        PostMessage(p, WM_QUIT, "quit");
    }

    private static void PostMessage(Process p, uint message, string name)
    {
        Console.WriteLine("Posting {0} message to '{1}'...", name, p.ProcessName);

        bool succeeded = PostMessage(p.MainWindowHandle.ToInt32(), message, IntPtr.Zero, IntPtr.Zero);

        Console.WriteLine("Posted {0} message to '{1}' (succeeded:{2}).", name, p.ProcessName, succeeded);
    }
}


问:
JQuery on/click functions not working in Chrome Extension
I'm trying to write a simple Chrome extension to grab info on flats from a website but I can't even get the on/click functions from JQuery to work.

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "Flat",
  "description": "Adds flats to app",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
  ],
  "content_scripts": [
    {
      "matches": [
        "https://www.spareroom.co.uk/flatshare/flatshare_detail.pl*",
      ],
      "js": ["lib/jquery.min.js", "lib/bootstrap.min.js", "content.js"]
    }
  ]
}
</code>```

content.js

```<code>$(document).ready(function () {
    console.log('Viewing flat');
    $("#hello").on("click", function () {
        console.log("Hello");
    });
    $("#hello").click(function () {
        console.log("hello");
    });
});
</code>```

popup.html

```<code><html>
<head>
    <title>Popup</title>
    <link rel="stylesheet" href="lib/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="lib/jquery.min.js"></script>
    <script src="lib/bootstrap.min.js"></script>
    <script src="content.js"></script>
</head>
<body>
    <div class="container">
        <button id="hello" class="btn btn-default">Add Flat</button>
    </div>
</body>
</html>
</code>```

I'm not sure what the issue here is. JQuery is 3.2.1 and Bootstrap is 3.3.7. There is not a lot of JQuery related Chrome Extensions questions on here. I found this one Chrome extensions with jQuery but I already have the document ready function encapsulating the other code. Also looked at this one $(document).click() not working in chrome extension but that solution doesn't take advantage of JQuery click/on functions.

答:
Alright so the issue here was my misunderstanding of the context each of the JS files are ran and the messaging system in Chrome. So I'll outline the changes to my code below. There might be a better way of doing this but this is the first time I've developed a Chrome extension.

I modified manifest.json as shown below

manifest.json

```<code>...
"background": {
    "scripts": ["background.js"]
},
"content_scripts": {
  {
    ...
    "js": ["lib/jquery.min.js"]
  }
}
</code>```

I added the background script as well as changed the script used in popup.html to be popup.js instead of content.js

popup.js is shown below. This is ran in the context of the extension on popup.html and sends a message to Chrome that kicks off a handler in background.js

popup.js

```<code>$(document).ready(function () {
    console.log('Viewing flat');
    $("#hello").click(clickHandler);
});

function clickHandler(e) {
     console.log('Adding flat');
     chrome.runtime.sendMessage({directive: "get-flat"}, function (response) {
        //
        console.log("handler", response);
    });
}
</code>```

In background.js I created a listener using the onMessage event API of chrome.runtime. This then will call chrome.tabs.executeScript that executes a script (content.js) in the context of the actual webpage. The messenger listener is a similar patter to Redux w/ React so that was pretty interesting. I found this pattern on this question Detect a button click in the browser_action form of a Google Chrome Extension

background.js

```<code>chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
       switch (request.directive) {
           case "get-flat":
               chrome.tabs.executeScript(null, { file: "content.js" });
               sendResponse("in get-flat directive");
               break;
           case "process":
               console.log("process", request.data);
               break;
            default:
               break;
        }
    }
);
</code>```

The next part is content.js which runs in the context of the webpage and grabs the data I care about. It then passes that message back to background.js for further actions. I simplified the code for brevity's sake.

content.js

```<code>function getFlat() {
    console.log("in getFlat");
    // Do stuff
    var val = $("#something").text();
    return val;
}
chrome.runtime.sendMessage({directive: "process", data: getFlat()});
</code>```

I should mention that I think the only reason JQuery worked in content.js was because the site I am grabbing info from also uses JQuery. I would of had to do something along the lines of tabs.executeScript - passing parameters and using libraries? in background.js to inject JQuery into the context so content.js could use it if that wasn't the case.

Edit

^^ This was incorrect in that I am injecting JQuery via the content_scripts part of manifest.json

end edit

Either way I was able to resolve the issue. I also used this for reference Pass a parameter to a content script injected using chrome.tabs.executeScript()

If there is a better way of doing this feel free to comment. Like I said this was my first attempt at a Chrome extension.

Body:
I'm trying to write a simple Chrome extension to grab info on flats from a website but I can't even get the on/click functions from JQuery to work.

manifest.json

{
  "manifest_version": 2,

  "name": "Flat",
  "description": "Adds flats to app",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
  ],
  "content_scripts": [
    {
      "matches": [
        "https://www.spareroom.co.uk/flatshare/flatshare_detail.pl*",
      ],
      "js": ["lib/jquery.min.js", "lib/bootstrap.min.js", "content.js"]
    }
  ]
}

content.js

$(document).ready(function () {
    console.log('Viewing flat');
    $("#hello").on("click", function () {
        console.log("Hello");
    });
    $("#hello").click(function () {
        console.log("hello");
    });
});

popup.html

    <title>Popup</title>
    <link rel="stylesheet" href="lib/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

        <button id="hello" class="btn btn-default">Add Flat</button>

I'm not sure what the issue here is. JQuery is 3.2.1 and Bootstrap is 3.3.7. There is not a lot of JQuery related Chrome Extensions questions on here. I found this one Chrome extensions with jQuery but I already have the document ready function encapsulating the other code. Also looked at this one $(document).click() not working in chrome extension but that solution doesn't take advantage of JQuery click/on functions.

Body:
Alright so the issue here was my misunderstanding of the context each of the JS files are ran and the messaging system in Chrome. So I'll outline the changes to my code below. There might be a better way of doing this but this is the first time I've developed a Chrome extension.

I modified manifest.json as shown below

manifest.json

...
"background": {
    "scripts": ["background.js"]
},
"content_scripts": {
  {
    ...
    "js": ["lib/jquery.min.js"]
  }
}

I added the background script as well as changed the script used in popup.html to be popup.js instead of content.js

popup.js is shown below. This is ran in the context of the extension on popup.html and sends a message to Chrome that kicks off a handler in background.js

popup.js

$(document).ready(function () {
    console.log('Viewing flat');
    $("#hello").click(clickHandler);
});

function clickHandler(e) {
     console.log('Adding flat');
     chrome.runtime.sendMessage({directive: "get-flat"}, function (response) {
        //
        console.log("handler", response);
    });
}

In background.js I created a listener using the onMessage event API of chrome.runtime. This then will call chrome.tabs.executeScript that executes a script (content.js) in the context of the actual webpage. The messenger listener is a similar patter to Redux w/ React so that was pretty interesting. I found this pattern on this question Detect a button click in the browser_action form of a Google Chrome Extension

background.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
       switch (request.directive) {
           case "get-flat":
               chrome.tabs.executeScript(null, { file: "content.js" });
               sendResponse("in get-flat directive");
               break;
           case "process":
               console.log("process", request.data);
               break;
            default:
               break;
        }
    }
);

The next part is content.js which runs in the context of the webpage and grabs the data I care about. It then passes that message back to background.js for further actions. I simplified the code for brevity's sake.

content.js

function getFlat() {
    console.log("in getFlat");
    // Do stuff
    var val = $("#something").text();
    return val;
}
chrome.runtime.sendMessage({directive: "process", data: getFlat()});

I should mention that I think the only reason JQuery worked in content.js was because the site I am grabbing info from also uses JQuery. I would of had to do something along the lines of tabs.executeScript - passing parameters and using libraries? in background.js to inject JQuery into the context so content.js could use it if that wasn't the case.

Edit

^^ This was incorrect in that I am injecting JQuery via the content_scripts part of manifest.json

end edit

Either way I was able to resolve the issue. I also used this for reference Pass a parameter to a content script injected using chrome.tabs.executeScript()

If there is a better way of doing this feel free to comment. Like I said this was my first attempt at a Chrome extension.


问:
Silverstripe Userforms custom templates ( + bootstrap )
I have a website using Silverstripe CMS ( 3.6.1 ), Framework(3.6.1). I have a page with a big form with lots of fields. I am using the UserForms module (4.0).

My questions is:
Can i format how those fields are displayed on template? Because I would like to use bootstrap grid so I can have a custom format: some rows to have 3 inputs ( col-md-4 ) and other rows to have ( col-md-6 ). Depending on the PSD format I have to convert.

EDIT1:

I have noticed that I can add Field inside Groups. So what I did was:
for a row that has 3 inputs, I added a Group with 3 fields and so on.

Maybe this could help somehow ?

答:
One option (nuclear) is you can copy the templates from the userforms/templates folder into your theme, or mysite/templates and modify them as required.

Be aware when doing this that you'll be responsible for backporting any changes as the userforms module gets updated underneath though.

You could also add extra CSS classes, if that is all you need, by using $editableFormField->ExtraClass .= 'col-md-6 col-sm-12'; etc. See here for where it gets used. I believe that the 4.0.x versions might not apply this on every field however, so I'd firstly advise upgrading to the latest version (currently 4.4.0).

For reference, the CWP "starter" theme uses Bootstrap and works with userforms - this involves some template duplication. Note that you may not be able to view this repository publicly.


问:
Uncaught TypeError: Object function ()
I wrote the following functions. At run time the browser complains about uncaught TypeError ...has no method 'init'. What's wrong of my code? </p>

```<code>function build_results_grid (response) {

        // build grid
        grid_ui.init();

    } // build the results grid

    var grid_ui = function () {

        return {
            init: function () {
               //build_grid();
            }
      }; // return
    }
</code>```

答:
since a call to grid_ui is necessary to return the function with init inside, you need

```<code>    grid_ui().init();
</code>```

Since grid_ui must be called.  Or you can make grid_ui be the return of the call, as SLaks did

EDIT - I misread your braces, if you noticed the question I had here before you can disregard it.

Title: Uncaught TypeError: Object function ()

Body:
I wrote the following functions. At run time the browser complains about uncaught TypeError ...has no method 'init'. What's wrong of my code?

function build_results_grid (response) {

        // build grid
        grid_ui.init();

    } // build the results grid

    var grid_ui = function () {

        return {
            init: function () {
               //build_grid();
            }
      }; // return
    }

Body:
since a call to grid_ui is necessary to return the function with init inside, you need

    grid_ui().init();

Since grid_ui must be called.  Or you can make grid_ui be the return of the call, as SLaks did

EDIT - I misread your braces, if you noticed the question I had here before you can disregard it.


问:
Using threads with Observer Pattern
I have this code:

```<code>public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}
</code>```

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?

答: You could implement message passing via blocking concurrent queues. The classExample thread could then wait blocking for new messages to be sent via the queue. This thread could then execute the stuff you originally wanted to execute in the update method, when a new message comes.

Title: Using threads with Observer Pattern

Body:
I have this code:

public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?