问:
R data.table reshape data
I reshape data using data.table.

```<code>library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
#     stkcd type roa2013 roa2014 lev2013 lev2016
# 1:     1    1       2       4       6       8
# 2:     2    0       3       5       7       9
melt(market,
     measure.vars = patterns("^roa", "^lev"),
     variable.name = "year",
     value.name = c("roa","lev"))
#     stkcd type year roa lev
# 1:     1    1    1   2   6
# 2:     2    0    1   3   7
# 3:     1    1    2   4   8
# 4:     2    0    2   5   9
</code>```

This is how the final data should look like.

```<code>#     stkcd type year roa lev
# 1     1    1 2013   2   6
# 2     1    1 2014   4  NA
# 3     1    1 2016  NA   8
# 4     2    0 2013   3   7
# 5     2    0 2014   5  NA
# 6     2    0 2016  NA   9
</code>```

Does anybody have any good ways for it?
Thanks.

答:
1.use reshape {stats},

```<code>library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))

market[,`:=`(roa2016=NA,lev2014=NA)]
long <- reshape(market,
        idvar = "stkcd",
        varying = c("roa2013","lev2013",
                    "roa2014","lev2014",
                    "roa2016","lev2016"),
        sep = "",
        timevar = "year",
        direction = "long")
setorder(long,stkcd,year)
long
#     stkcd type year roa lev
# 1:     1    1 2013   2   6
# 2:     1    1 2014   4  NA
# 3:     1    1 2016  NA   8
# 4:     2    0 2013   3   7
# 5:     2    0 2014   5  NA
# 6:     2    0 2016  NA   9
</code>```

2.str_extract str

```<code>library(data.table)
library(stringr)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
long <- melt(market,
             id.vars = c("stkcd","type"))
long[,`:=`(year=str_extract(variable,pattern = "[0-9]{4}"),
           vars=str_extract(variable,pattern = "[a-zA-Z]{1,}"))][,variable:=NULL]
long <- dcast(long, stkcd + type + year ~ vars, value.var = "value")
long
#     stkcd type year lev roa
# 1:     1    1 2013   6   2
# 2:     1    1 2014  NA   4
# 3:     1    1 2016   8  NA
# 4:     2    0 2013   7   3
# 5:     2    0 2014  NA   5
# 6:     2    0 2016   9  NA
</code>```

...

Title: R data.table reshape data

Body:
I reshape data using data.table.

library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
#     stkcd type roa2013 roa2014 lev2013 lev2016
# 1:     1    1       2       4       6       8
# 2:     2    0       3       5       7       9
melt(market,
     measure.vars = patterns("^roa", "^lev"),
     variable.name = "year",
     value.name = c("roa","lev"))
#     stkcd type year roa lev
# 1:     1    1    1   2   6
# 2:     2    0    1   3   7
# 3:     1    1    2   4   8
# 4:     2    0    2   5   9

This is how the final data should look like.

#     stkcd type year roa lev
# 1     1    1 2013   2   6
# 2     1    1 2014   4  NA
# 3     1    1 2016  NA   8
# 4     2    0 2013   3   7
# 5     2    0 2014   5  NA
# 6     2    0 2016  NA   9

Does anybody have any good ways for it?
Thanks.

Body:
1.use reshape {stats},

library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))

market[,`:=`(roa2016=NA,lev2014=NA)]
long <- reshape(market,
        idvar = "stkcd",
        varying = c("roa2013","lev2013",
                    "roa2014","lev2014",
                    "roa2016","lev2016"),
        sep = "",
        timevar = "year",
        direction = "long")
setorder(long,stkcd,year)
long
#     stkcd type year roa lev
# 1:     1    1 2013   2   6
# 2:     1    1 2014   4  NA
# 3:     1    1 2016  NA   8
# 4:     2    0 2013   3   7
# 5:     2    0 2014   5  NA
# 6:     2    0 2016  NA   9

2.str_extract str

library(data.table)
library(stringr)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
long <- melt(market,
             id.vars = c("stkcd","type"))
long[,`:=`(year=str_extract(variable,pattern = "[0-9]{4}"),
           vars=str_extract(variable,pattern = "[a-zA-Z]{1,}"))][,variable:=NULL]
long <- dcast(long, stkcd + type + year ~ vars, value.var = "value")
long
#     stkcd type year lev roa
# 1:     1    1 2013   6   2
# 2:     1    1 2014  NA   4
# 3:     1    1 2016   8  NA
# 4:     2    0 2013   7   3
# 5:     2    0 2014  NA   5
# 6:     2    0 2016   9  NA

...


来源: stackexchange

问:
Create all combinations from regex
I have sentences that define a template for random combinations:

```<code>I like dogs/cats
I want to eat today/(the next day)
</code>```

I tried using a regex:

```<code>m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]
</code>```

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?

答:
r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))''

([a-zA-Z]+|\(.+?\)) matches strings like "word" or "(some word)". And it also matches "()", we need to remove heading "(" and trailing ")" using strip.

```<code>m = re.search(r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w.strip('()')) for w in words]]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create all combinations from regex

Body:
I have sentences that define a template for random combinations:

I like dogs/cats
I want to eat today/(the next day)

I tried using a regex:

m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?

Body:
r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))''

([a-zA-Z]+|\(.+?\)) matches strings like "word" or "(some word)". And it also matches "()", we need to remove heading "(" and trailing ")" using strip.

m = re.search(r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w.strip('()')) for w in words]]


问:
C++ - Segmentation fault when returning a string
I have this class

```<code>#include "Room.h"
#include "Book.h"
#include <cstdlib>
#include <iostream>

static int book_counter = 100;

//Constructors
Book::Book() {
    for(int i = 0; i < 13; i++) {
        this->customer_name += 97 + rand() % 26;
    }
    this->arrival = rand() % 30;
    this->duration = 1 + (rand() % 10);
    this->ppl = 1 + rand() % 5;
    this->room = nullptr;
    this->book_code = book_counter++;
}
Book::Book(std::string nm, int arr, int dur, int ppl) {
    this->customer_name = nm;
    this->arrival = arr;
    this->duration = dur;
    this->ppl = ppl;
    this->room = nullptr;
    this->book_code = book_counter++;
}

//Methods
int Book::getArr() {
    return arrival;
}
int Book::getDur() {
    return duration;
}
int Book::getPpl() {
    return ppl;
}
void Book::anathesi(Room* x) {
    this->room = x;
}
int Book::getBookCode() {
    return book_code;
}
Room* Book::getRoom() {
    return room;
}
std::string Book::getCustomerName() {
    return customer_name;
}
</code>```

which includes a string getter method getCustomerName().
When I call this method on main, via an instance created via the first constructor, everything works fine. On the other hand, if the instance is created via the second constructor, the method will cause a segmentation fault.

It seems like customer_name has an infinite length, thus causing a segmentation fault when I try to return it.

The method is called in main with this line of code:

```<code>cout << hotel.getBooks(i)->getBookCode() << " " << hotel.getBooks(i)->getCustomerName()
                             << " " << hotel.getBooks(i)->getRoom()->getRoomCode() << "\n";
</code>```

I am new into C++, so please elaborate my fault as much as needed.

The header file for class Book:

```<code>#ifndef PROJECT_BOOK_H
#define PROJECT_BOOK_H
#include <string>

class Room;

class Book {
    protected:
        std::string customer_name;
        int book_code;
        int arrival;
        int duration;
        int ppl;
        Room* room;
    public:
        Book();
        Book(std::string nm, int arr, int dur, int ppl);
        void anathesi(Room* x);
        int getArr();
        int getDur();
        int getPpl();
        int getBookCode();
        std::string getCustomerName();
        Room* getRoom();
};

#endif //PROJECT_BOOK_H
</code>```

In Hotel.h:

```<code>private: std::vector<Book*> books;
public: Book* getBooks(int i);
</code>```

In Hotel.cpp:

```<code>Book* Hotel::getBooks(int i) {
    return books[i];
}
</code>```

答:
Found the problem and fixed it.
I was creating instances with this piece of code:

```<code>Book obj(onoma, afiksh - 1, meres, arithmos);
</code>```

which caused the segmentation I said.
I changed this to:

```<code>Book *obj = new Book(onoma, afiksh - 1, meres, arithmos);
</code>```

and fixed the problem. Thanks for your time and help.
Unfortunately, I don't really know why this works, but it does, everything functions properly. Therefore I guess I'll have to look at new documentation.

Body:
I have this class

#include "Room.h"
#include "Book.h"
#include <cstdlib>
#include <iostream>

static int book_counter = 100;

//Constructors
Book::Book() {
    for(int i = 0; i < 13; i++) {
        this->customer_name += 97 + rand() % 26;
    }
    this->arrival = rand() % 30;
    this->duration = 1 + (rand() % 10);
    this->ppl = 1 + rand() % 5;
    this->room = nullptr;
    this->book_code = book_counter++;
}
Book::Book(std::string nm, int arr, int dur, int ppl) {
    this->customer_name = nm;
    this->arrival = arr;
    this->duration = dur;
    this->ppl = ppl;
    this->room = nullptr;
    this->book_code = book_counter++;
}

//Methods
int Book::getArr() {
    return arrival;
}
int Book::getDur() {
    return duration;
}
int Book::getPpl() {
    return ppl;
}
void Book::anathesi(Room* x) {
    this->room = x;
}
int Book::getBookCode() {
    return book_code;
}
Room* Book::getRoom() {
    return room;
}
std::string Book::getCustomerName() {
    return customer_name;
}

which includes a string getter method getCustomerName().
When I call this method on main, via an instance created via the first constructor, everything works fine. On the other hand, if the instance is created via the second constructor, the method will cause a segmentation fault.

It seems like customer_name has an infinite length, thus causing a segmentation fault when I try to return it.

The method is called in main with this line of code:

cout << hotel.getBooks(i)->getBookCode() << " " << hotel.getBooks(i)->getCustomerName()
                             << " " << hotel.getBooks(i)->getRoom()->getRoomCode() << "\n";

I am new into C++, so please elaborate my fault as much as needed.

The header file for class Book:

#ifndef PROJECT_BOOK_H
#define PROJECT_BOOK_H
#include <string>

class Room;

class Book {
    protected:
        std::string customer_name;
        int book_code;
        int arrival;
        int duration;
        int ppl;
        Room* room;
    public:
        Book();
        Book(std::string nm, int arr, int dur, int ppl);
        void anathesi(Room* x);
        int getArr();
        int getDur();
        int getPpl();
        int getBookCode();
        std::string getCustomerName();
        Room* getRoom();
};

#endif //PROJECT_BOOK_H

In Hotel.h:

private: std::vector<Book*> books;
public: Book* getBooks(int i);

In Hotel.cpp:

Book* Hotel::getBooks(int i) {
    return books[i];
}

Body:
Found the problem and fixed it.
I was creating instances with this piece of code:

Book obj(onoma, afiksh - 1, meres, arithmos);

which caused the segmentation I said.
I changed this to:

Book *obj = new Book(onoma, afiksh - 1, meres, arithmos);

and fixed the problem. Thanks for your time and help.
Unfortunately, I don't really know why this works, but it does, everything functions properly. Therefore I guess I'll have to look at new documentation.


问:
Parsing Opus TOC Byte
For working with the Opus audio codec, I need to parse a TOC byte from a char buffer and extract the config, s and c segments, each representing a number.

I would need to store these numbers into separate variables for further use and am wondering what the best way to achieve this (in C++) is.

A well-formed Opus packet MUST contain at least one byte [R1].

This byte forms a table-of-contents (TOC) header:

0 1 2 3 4 5 6 7

+-+-+-+-+-+-+-+-+

| config  |s| c |

+-+-+-+-+-+-+-+-+

The top five bits of the TOC byte, labeled "config", encode one of 32
possible configurations of operating mode, audio bandwidth, and frame
size.

One additional bit, labeled "s", signals mono vs. stereo, with 0
indicating mono and 1 indicating stereo.

The remaining two bits of the TOC byte, labeled "c", code the number
of frames per packet (codes 0 to 3).

This format is according to the RFC found here: https://www.rfc-editor.org/rfc/rfc6716#section-3.1

Thanks!

答:
Just use a right shift (>>) to shift the bits to the low bits if needed, and a bitwise and (&) to mask out the other bits.

```<code>int config = (toc >> 3) & 31;
int s = (toc >> 2) & 1;
int c = toc & 3;
</code>```

Title: Parsing Opus TOC Byte

Body:
Just use a right shift (>>) to shift the bits to the low bits if needed, and a bitwise and (&) to mask out the other bits.

int config = (toc >> 3) & 31;
int s = (toc >> 2) & 1;
int c = toc & 3;


问:
Pyplot truth value of an array with more than one element is ambiguous
I am trying to implement a knn 1D estimate:

```<code># nearest neighbors estimate
def nearest_n(x, k, data):
    # Order dataset
    #data = np.sort(data, kind='mergesort')
    nnb = []
    # iterate over all data and get k nearest neighbours around x
    for n in data:
        if nnb.__len__()<k:
            nnb.append(n)
        else:
            for nb in np.arange(0,k):
                if np.abs(x-n) < np.abs(x-nnb[nb]):
                    nnb[nb] = n
                    break

    nnb = np.array(nnb)
    # get volume(distance) v of k nearest neighbours around x
    v = nnb.max() - nnb.min()
    v = k/(data.__len__()*v)

    return v

interval = np.arange(-4.0, 8.0, 0.1)
plt.figure()
for k in (2,8,35):
    plt.plot(interval, nearest_n(interval, k,train_data), label=str(o))
plt.legend()
plt.show()
</code>```

Which throws:

```<code>  File "x", line 55, in nearest_n
    if np.abs(x-n) < np.abs(x-nnb[nb]):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I know the error comes from the array input in plot(), but I am not sure how to avoid this in a function with operators >/==/<

'data' comes from a 1D txt file containing floats.

I tried using vectorize:

```<code>nearest_n = np.vectorize(nearest_n)
</code>```

which results in:

```<code>line 50, in nearest_n
    for n in data:
TypeError: 'numpy.float64' object is not iterable
</code>```

Here is an example, let's say:

```<code>data = [0.5,1.7,2.3,1.2,0.2,2.2]
k = 2
</code>```

nearest_n(1.5) should then lead to

```<code>nbb=[1.2,1.7]
v = 0.5
</code>```

and return 2/(6*0.5) = 2/3

The function runs for example neares_n(2.0,4,data) and gives 0.0741586011463

答: You're passing in np.arange(-4, 8, .01) as your x, which is an array of values. So x - n is an array of the same length as x, in this case 120 elements, since subtraction of an array and a scalar does element-wise subtraction. Same with nnb[nb]. So the result of your comparison there is a 120-length array with boolean values depending on whether each element of np.abs(x-n) is less than the corresponding element of np.abs(x-nnb[nb]). This can't be directly used as a conditional, you would need to coalesce these values to a single boolean (using all(), any(), or simply rethinking your code).

Body:
I am trying to implement a knn 1D estimate:

# nearest neighbors estimate
def nearest_n(x, k, data):
    # Order dataset
    #data = np.sort(data, kind='mergesort')
    nnb = []
    # iterate over all data and get k nearest neighbours around x
    for n in data:
        if nnb.__len__()<k:
            nnb.append(n)
        else:
            for nb in np.arange(0,k):
                if np.abs(x-n) < np.abs(x-nnb[nb]):
                    nnb[nb] = n
                    break

    nnb = np.array(nnb)
    # get volume(distance) v of k nearest neighbours around x
    v = nnb.max() - nnb.min()
    v = k/(data.__len__()*v)

    return v

interval = np.arange(-4.0, 8.0, 0.1)
plt.figure()
for k in (2,8,35):
    plt.plot(interval, nearest_n(interval, k,train_data), label=str(o))
plt.legend()
plt.show()

Which throws:

  File "x", line 55, in nearest_n
    if np.abs(x-n) < np.abs(x-nnb[nb]):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know the error comes from the array input in plot(), but I am not sure how to avoid this in a function with operators >/==/<

'data' comes from a 1D txt file containing floats.

I tried using vectorize:

nearest_n = np.vectorize(nearest_n)

which results in:

line 50, in nearest_n
    for n in data:
TypeError: 'numpy.float64' object is not iterable

Here is an example, let's say:

data = [0.5,1.7,2.3,1.2,0.2,2.2]
k = 2

nearest_n(1.5) should then lead to

nbb=[1.2,1.7]
v = 0.5

and return 2/(6*0.5) = 2/3

The function runs for example neares_n(2.0,4,data) and gives 0.0741586011463


问:
how to create a string from char array by adding char by char in java
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.</p>

```<code>String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}
</code>```

答:
Take a look at this:</p>

```<code>//Word to be delimited by commas
    String t = "ThisIsATest";

    //get length of word.
    int l = t.length(); //4

    char[] a;
    a = new char[l];
    // we will set this to a comma below inside the loop
    String rel = "";
    //set ret to empty string instead of null otherwise the word "null" gets put at the front of your return string
    String ret = "";

    for (int i = 0; i<l; i++){
        //you had 0 instead of 'i' as the parameter of t.charAt. You need to iterate through the elements of the string as well
        a[i] = new Character(t.charAt(i));
    }

    for (int v = 0; v<l; v++){
    /*set rel to empty string so that you can add it BEFORE the first element of the array and then afterwards change it to a comma
     this prevents you from having an extra comma at the end of your list.         */

        ret += rel;
        ret += a[v];
        rel = ",";
    }
    System.out.println(ret);
</code>```

Body:
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}

Body:
Take a look at this:

//Word to be delimited by commas
    String t = "ThisIsATest";

    //get length of word.
    int l = t.length(); //4

    char[] a;
    a = new char[l];
    // we will set this to a comma below inside the loop
    String rel = "";
    //set ret to empty string instead of null otherwise the word "null" gets put at the front of your return string
    String ret = "";

    for (int i = 0; i<l; i++){
        //you had 0 instead of 'i' as the parameter of t.charAt. You need to iterate through the elements of the string as well
        a[i] = new Character(t.charAt(i));
    }

    for (int v = 0; v<l; v++){
    /*set rel to empty string so that you can add it BEFORE the first element of the array and then afterwards change it to a comma
     this prevents you from having an extra comma at the end of your list.         */

        ret += rel;
        ret += a[v];
        rel = ",";
    }
    System.out.println(ret);


问:
I am losing a number when subtracting cpp integers
I am going through a C++ course and am asked to make a simple cashier program with change in dollars and cents, separately.

In doing so, I came across an instance where if I cout my calculation of cout<<change*100 - dollars*100<<endl; I get 40 cents correctly.

But when I set the int cents = change * 100 - dollars * 100; Then cout<<cents<<endl; I get 39.

Is this because of the data types I am using have some unintended consequences that I'm not aware of? Here is the whole program:

```<code>#include <iostream>
using namespace std;

int main()
{
    double price, paymentAmount, change;
    int dollars, cents;

    price = 23.00;
    paymentAmount = 24.40;

    cout<<"total: "<<price<<endl;
    cout<<"paid: "<<paymentAmount<<endl;

    change = paymentAmount-price;

    dollars = change; // implicit conversion from double -> int
    cents = change * 100 - dollars * 100;

    cout<<"dollars: "<<dollars<<endl;
    cout<<"cents: "<<change*100 - dollars*100<<endl; // outputs 40
    cout<<"cents: "<<cents<<endl; // outputs 39

    return 0;
}
</code>```

Thanks for the help

Edit:

Turns out this is from converting the double to int, which truncates the decimals. My number was something like 39.99999 but was truncated to 39 when converting to int. I think that conversion aspect makes this a non duplicate question

答:
The problem is that change*100 - dollars*100 is a floating point expression of type double. This will be rounded when you output it.

But when you assign it to an integer variable, the floating point value is truncated, where the decimals are simply cut away. So if you have something like 39.9 that will be rounded to 40 and truncated to 39.

Body:
I am going through a C++ course and am asked to make a simple cashier program with change in dollars and cents, separately.

In doing so, I came across an instance where if I cout my calculation of cout<<change*100 - dollars*100<<endl; I get 40 cents correctly.

But when I set the int cents = change * 100 - dollars * 100; Then cout<<cents<<endl; I get 39.

Is this because of the data types I am using have some unintended consequences that I'm not aware of? Here is the whole program:

#include <iostream>
using namespace std;

int main()
{
    double price, paymentAmount, change;
    int dollars, cents;

    price = 23.00;
    paymentAmount = 24.40;

    cout<<"total: "<<price<<endl;
    cout<<"paid: "<<paymentAmount<<endl;

    change = paymentAmount-price;

    dollars = change; // implicit conversion from double -> int
    cents = change * 100 - dollars * 100;

    cout<<"dollars: "<<dollars<<endl;
    cout<<"cents: "<<change*100 - dollars*100<<endl; // outputs 40
    cout<<"cents: "<<cents<<endl; // outputs 39

    return 0;
}

Thanks for the help

Edit:

Turns out this is from converting the double to int, which truncates the decimals. My number was something like 39.99999 but was truncated to 39 when converting to int. I think that conversion aspect makes this a non duplicate question


问:
Turtle gives error: AttributeError: 'Turtle' object has no attribute 'onkeyrelease'
I am trying to add 1 every time I release a key:

```<code>from turtle import *
import turtle
turtle1 = Turtle()
screen = turtle1.getscreen()
goPressed = False
</code>```

imported Turtle...

```<code>currentWatts=0

def onaclicked():
     global currentWatts
     currentWatts+=1
     print (currentWatts)
</code>```

defined my function to be run when the key: 1, is released

```<code>turtle.onkeyrelease(onaclicked, "1")
</code>```

for some reason onkeyrelease isn't there even though I imported Turtle and checked in Python documentation. It SHOULD work, shouldn't it? Did I improperly import? Can you please help me?

The reason I want it to be onkeyrelease instead of onkey, is because it is for a game. With onkey, when you hold your finger on the key, it adds 1 to currentWatts every around 0.25 seconds. You could cheat by placing something on the key so I want it only to add 1 when you release the key.

答:
You've several problems with your code: you import turtle two different ways which confuses things; onkeyrelease() is really a method of the screen/window, not a turtle; you didn't call listen() which allows keystrokes to be processed.  The following should work in Python 3:

```<code>from turtle import Turtle, Screen, mainloop

def onaclicked():
    global currentWatts
    currentWatts += 1
    print(currentWatts)

currentWatts = 0

screen = Screen()

screen.onkeyrelease(onaclicked, "1")

screen.listen()

mainloop()
</code>```

Make sure to click on the window once before you start typing to make it active.

If you're using Python 2, which I suspect from the error message you got, then replace the Python 3 alias onkeyrelease with onkey:

The method Screen.onkeypress() has been added as a complement to
  Screen.onkey() which in fact binds actions to the keyrelease event.
  Accordingly the latter has got an alias: Screen.onkeyrelease().

This change should work the same in both versions.  Using onkeyrelease instead of onkey wasn't going fix your holding a finger on the key issue.

when you hold your finger on the key, it adds 1 to
  currentWatts every around 0.25 seconds. You could cheat by placing
  something on the key so I want it only to add 1 when you release

It appears that automatic key repeats are handled by the operating system and may need to be disabled external to Python, depending on the OS.  Some example links:

Apple OSX: Set how quickly a key
repeats

Ubuntu: Turn off repeated key
presses

X-Windows from Python: key repeat in
tkinter

Body:
I am trying to add 1 every time I release a key:

from turtle import *
import turtle
turtle1 = Turtle()
screen = turtle1.getscreen()
goPressed = False

imported Turtle...

currentWatts=0

def onaclicked():
     global currentWatts
     currentWatts+=1
     print (currentWatts)

defined my function to be run when the key: 1, is released

turtle.onkeyrelease(onaclicked, "1")

for some reason onkeyrelease isn't there even though I imported Turtle and checked in Python documentation. It SHOULD work, shouldn't it? Did I improperly import? Can you please help me?

The reason I want it to be onkeyrelease instead of onkey, is because it is for a game. With onkey, when you hold your finger on the key, it adds 1 to currentWatts every around 0.25 seconds. You could cheat by placing something on the key so I want it only to add 1 when you release the key.

Body:
You've several problems with your code: you import turtle two different ways which confuses things; onkeyrelease() is really a method of the screen/window, not a turtle; you didn't call listen() which allows keystrokes to be processed.  The following should work in Python 3:

from turtle import Turtle, Screen, mainloop

def onaclicked():
    global currentWatts
    currentWatts += 1
    print(currentWatts)

currentWatts = 0

screen = Screen()

screen.onkeyrelease(onaclicked, "1")

screen.listen()

mainloop()

Make sure to click on the window once before you start typing to make it active.

If you're using Python 2, which I suspect from the error message you got, then replace the Python 3 alias onkeyrelease with onkey:

The method Screen.onkeypress() has been added as a complement to
  Screen.onkey() which in fact binds actions to the keyrelease event.
  Accordingly the latter has got an alias: Screen.onkeyrelease().

This change should work the same in both versions.  Using onkeyrelease instead of onkey wasn't going fix your holding a finger on the key issue.

when you hold your finger on the key, it adds 1 to
  currentWatts every around 0.25 seconds. You could cheat by placing
  something on the key so I want it only to add 1 when you release

It appears that automatic key repeats are handled by the operating system and may need to be disabled external to Python, depending on the OS.  Some example links:

Apple OSX: Set how quickly a key
repeats

Ubuntu: Turn off repeated key
presses

X-Windows from Python: key repeat in
tkinter


问:
jQuery Ajax function does not work?
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

```<code><script>
 function submitForLogin()
 {
    $.ajax({
            type: "POST",
            url: "php/login.php",
            data: { email: "example@abc.com",password:"123" }}).done(function(data){alert(data);});

 }

</script>
</code>```

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

```<code><?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>
</code>```

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

答:
You need to include a function for when the request is successful, which includes the response.</p>

```<code>$.ajax({
    type: "POST",
    url: "php/login.php",
    data: { email: "example@abc.com",password:"123" },
    success:function(data){
        alert(data)
    };
});
</code>```

Title: jQuery Ajax function does not work?

Body:
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

Body:
You need to include a function for when the request is successful, which includes the response.

$.ajax({
    type: "POST",
    url: "php/login.php",
    data: { email: "example@abc.com",password:"123" },
    success:function(data){
        alert(data)
    };
});


问:
Overriding functions from dynamic libraries
Hello I have a program with a global function that I'd like to customize at run time. Say, there are many versions of function foo() scattered over shared libraries. Now, based on system configuration detected at run time I'd like to use function from appropriate library.

File loader.cpp:

```<code>#include <dlfcn.h>
#include <iostream>

void __attribute__((weak)) foo();

    int main(int argc, char *argv[])
    {
        void* dl = dlopen("./other.so", RTLD_NOW | RTLD_GLOBAL);
        if (!dl)
        {
            std::cerr << dlerror() << std::endl;
            return 1;
        }
        if (foo)
        {
            foo();
        }
        else
        {
            std::cerr << "No foo?" << std::endl;
        }
        dlclose(dl);
        return 0;
    }
</code>```

File other.cpp:

```<code>#include <iostream>

void foo()
{
    std::cout << "FOO!" << std::endl;
}
</code>```

I compile the program with

```<code>g++ -Wall -fPIC -o loaded loader.cpp -ldl
g++ -Wall -fPIC -shared -o other.so  other.cpp
</code>```

However the weak symbol is not overriden. Any hints?

答:
Symbols are resolved during load time of the image in which they are referenced. So when your executable is loaded, the reference to foo is already resolved. A later dlopen won't go and rebind all symbols - it only may affect later loads.

You'll have to use dlsym instead, or set LD_PRELOAD:

```<code>martin@mira:/tmp$ LD_PRELOAD=/tmp/other.so ./loaded
FOO!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hello I have a program with a global function that I'd like to customize at run time. Say, there are many versions of function foo() scattered over shared libraries. Now, based on system configuration detected at run time I'd like to use function from appropriate library.

File loader.cpp:

#include <dlfcn.h>
#include <iostream>

void __attribute__((weak)) foo();

    int main(int argc, char *argv[])
    {
        void* dl = dlopen("./other.so", RTLD_NOW | RTLD_GLOBAL);
        if (!dl)
        {
            std::cerr << dlerror() << std::endl;
            return 1;
        }
        if (foo)
        {
            foo();
        }
        else
        {
            std::cerr << "No foo?" << std::endl;
        }
        dlclose(dl);
        return 0;
    }

File other.cpp:

#include <iostream>

void foo()
{
    std::cout << "FOO!" << std::endl;
}

I compile the program with

g++ -Wall -fPIC -o loaded loader.cpp -ldl
g++ -Wall -fPIC -shared -o other.so  other.cpp

However the weak symbol is not overriden. Any hints?

Body:
Symbols are resolved during load time of the image in which they are referenced. So when your executable is loaded, the reference to foo is already resolved. A later dlopen won't go and rebind all symbols - it only may affect later loads.

You'll have to use dlsym instead, or set LD_PRELOAD:

martin@mira:/tmp$ LD_PRELOAD=/tmp/other.so ./loaded
FOO!


问:
Iterate 2 lists of same length; create a list of n consecutive numbers without using generators
I have seen questions asking about creating a list of N numbers in python. Say an input N = 6 should create [0,1,2,3,4,5]. All answers I saw had the range function. Now I am using Python 3. On executing the range function to create a list, I have seen that code executes slowly, popping 1 digit at a time because range is a generator function.

Is there an alternative to create a list of consecutive numbers(assuming a very large one) that doesn't use a generator function like range so that there is no slow down? I can use a C type approach of checking if n < N but is there a more Pythonic way of doing it?

Please run this code in IDLE to understand my question more clearly:

```<code>x = list(range(14))
for n in x:
    print(n)
</code>```

答:
In general, using generators is the Pythonic way to do it. Generators tend to be very fast in Python. Let's start by just looking at different ways of creating a precomputed list of N integers:

```<code>import timeit

print(
    "Generating list from range:",
    timeit.timeit("list(range(100))")
)
print(
    "Generating list with comprehension:",
    timeit.timeit("[i for i in range(100)]")
)
print(
    "Generating list with while:",
    timeit.timeit(
        """\
i = 0
res = []
while i < 100:
    res.append(i)
    i += 1"""
    )
)
</code>```

On my system (with Python 3.5.2), this gives:

```<code>Generating list from range: 1.0031339479999133
Generating list with comprehension: 3.2253709860001436
Generating list with while: 12.400529407000022
</code>```

So, just directly converting the range object to a list gives the best performance if you're just trying to create a precomputed list of N integers. Now, let's see what happens when iterating on a precomputed list vs. iterating on a range object:

```<code>print(
    "Precomputed range:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = range(100)'
    )
)

print(
    "Precomputed list:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = list(range(100))'
    )
)
</code>```

On my system, this yields

```<code>Precomputed range: 3.063208956000153
Precomputed list: 3.0270772009998836
</code>```

The performance difference from iterating on a range object vs. a precomputed list is negligible. So, in general, I would give preference to just using a range object if you need an iterable with N integers, regardless of performance considerations.

Body:
I have seen questions asking about creating a list of N numbers in python. Say an input N = 6 should create [0,1,2,3,4,5]. All answers I saw had the range function. Now I am using Python 3. On executing the range function to create a list, I have seen that code executes slowly, popping 1 digit at a time because range is a generator function.

Is there an alternative to create a list of consecutive numbers(assuming a very large one) that doesn't use a generator function like range so that there is no slow down? I can use a C type approach of checking if n < N but is there a more Pythonic way of doing it?

Please run this code in IDLE to understand my question more clearly:

x = list(range(14))
for n in x:
    print(n)

Body:
In general, using generators is the Pythonic way to do it. Generators tend to be very fast in Python. Let's start by just looking at different ways of creating a precomputed list of N integers:

import timeit

print(
    "Generating list from range:",
    timeit.timeit("list(range(100))")
)
print(
    "Generating list with comprehension:",
    timeit.timeit("[i for i in range(100)]")
)
print(
    "Generating list with while:",
    timeit.timeit(
        """\
i = 0
res = []
while i < 100:
    res.append(i)
    i += 1"""
    )
)

On my system (with Python 3.5.2), this gives:

Generating list from range: 1.0031339479999133
Generating list with comprehension: 3.2253709860001436
Generating list with while: 12.400529407000022

So, just directly converting the range object to a list gives the best performance if you're just trying to create a precomputed list of N integers. Now, let's see what happens when iterating on a precomputed list vs. iterating on a range object:

print(
    "Precomputed range:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = range(100)'
    )
)

print(
    "Precomputed list:",
    timeit.timeit(
        '[x for x in seq]',
        setup='seq = list(range(100))'
    )
)

On my system, this yields

Precomputed range: 3.063208956000153
Precomputed list: 3.0270772009998836

The performance difference from iterating on a range object vs. a precomputed list is negligible. So, in general, I would give preference to just using a range object if you need an iterable with N integers, regardless of performance considerations.


问:
RegEx to split camelCase or TitleCase (advanced)
I found a brilliant RegEx to extract the part of a camelCase or TitleCase expression.

```<code> (?<!^)(?=[A-Z])
</code>```

It works as expected:

value -> value

camelValue -> camel / Value

TitleValue -> Title / Value

For example with Java:

```<code>String s = "loremIpsum";
words = s.split("(?<!^)(?=[A-Z])");
//words equals words = new String[]{"lorem","Ipsum"}
</code>```

My problem is that it does not work in some cases:

Case 1: VALUE -> V / A / L / U / E

Case 2: eclipseRCPExt -> eclipse / R / C / P / Ext

To my mind, the result shoud be:

Case 1: VALUE

Case 2: eclipse / RCP / Ext

In other words, given n uppercase chars:

if the n chars are followed by lower case chars, the groups should be: (n-1 chars) / (n-th char + lower chars)

if the n chars are at the end, the group should be: (n chars).

Any idea on how to improve this regex?

答:
Instead of looking for separators that aren't there you might also considering finding the name components (those are certainly there):

```<code>String test = "_eclipse福福RCPExt";

Pattern componentPattern = Pattern.compile("_? (\\p{Upper}?\\p{Lower}+ | (?:\\p{Upper}(?!\\p{Lower}))+ \\p{Digit}*)", Pattern.COMMENTS);

Matcher componentMatcher = componentPattern.matcher(test);
List<String> components = new LinkedList<>();
int endOfLastMatch = 0;
while (componentMatcher.find()) {
    // matches should be consecutive
    if (componentMatcher.start() != endOfLastMatch) {
        // do something horrible if you don't want garbage in between

        // we're lenient though, any Chinese characters are lucky and get through as group
        String startOrInBetween = test.substring(endOfLastMatch, componentMatcher.start());
        components.add(startOrInBetween);
    }
    components.add(componentMatcher.group(1));
    endOfLastMatch = componentMatcher.end();
}

if (endOfLastMatch != test.length()) {
    String end = test.substring(endOfLastMatch, componentMatcher.start());
    components.add(end);
}

System.out.println(components);
</code>```

This outputs [eclipse, 福福, RCP, Ext]. Conversion to an array is of course simple.

Body:
I found a brilliant RegEx to extract the part of a camelCase or TitleCase expression.

 (?<!^)(?=[A-Z])

It works as expected:

value -> value

camelValue -> camel / Value

TitleValue -> Title / Value

For example with Java:

String s = "loremIpsum";
words = s.split("(?<!^)(?=[A-Z])");
//words equals words = new String[]{"lorem","Ipsum"}

My problem is that it does not work in some cases:

Case 1: VALUE -> V / A / L / U / E

Case 2: eclipseRCPExt -> eclipse / R / C / P / Ext

To my mind, the result shoud be:

Case 1: VALUE

Case 2: eclipse / RCP / Ext

In other words, given n uppercase chars:

if the n chars are followed by lower case chars, the groups should be: (n-1 chars) / (n-th char + lower chars)

if the n chars are at the end, the group should be: (n chars).

Any idea on how to improve this regex?

Body:
Instead of looking for separators that aren't there you might also considering finding the name components (those are certainly there):

String test = "_eclipse福福RCPExt";

Pattern componentPattern = Pattern.compile("_? (\\p{Upper}?\\p{Lower}+ | (?:\\p{Upper}(?!\\p{Lower}))+ \\p{Digit}*)", Pattern.COMMENTS);

Matcher componentMatcher = componentPattern.matcher(test);
List<String> components = new LinkedList<>();
int endOfLastMatch = 0;
while (componentMatcher.find()) {
    // matches should be consecutive
    if (componentMatcher.start() != endOfLastMatch) {
        // do something horrible if you don't want garbage in between

        // we're lenient though, any Chinese characters are lucky and get through as group
        String startOrInBetween = test.substring(endOfLastMatch, componentMatcher.start());
        components.add(startOrInBetween);
    }
    components.add(componentMatcher.group(1));
    endOfLastMatch = componentMatcher.end();
}

if (endOfLastMatch != test.length()) {
    String end = test.substring(endOfLastMatch, componentMatcher.start());
    components.add(end);
}

System.out.println(components);

This outputs [eclipse, 福福, RCP, Ext]. Conversion to an array is of course simple.


问:
How to tell mod_rewrite to only rewrite when specific urls are being entered?
I am having an issue with my .htaccess / .php files
I set up my web project in a way that it's split into 3 levels:

base level (mywebsite.com)

pages (mywebsite.com/news)

subpages/articles (mywebsite.com/news/123)

And all three are working as expected, here's my .htaccess:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?page=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&sub=$2 [L]
</code>```

I have to admit, I am not very good with the Regular Expressions for .htaccess/mod_rewrite as it is something I have done very rarely up to this point.

However my issue now is, that people dont get sent to a 404 error page if the page id (see $1) is not valid, like people can technically enter mywebsite.com/asdasdasd/ and it'll bring them (obviously) to the index.php, now my question is, can this be done some way in the .htaccess or should I just use php to check if the id they entered is valid or not? I did see that there's a thing called rewriteMap but I dont want to change the httpd.conf

Can anyone help?

答:
Try this code. Hope this will help you,

.htaccess

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</code>```

index.php

```<code>if (isset($_GET['url'])) {
    $url = explode('/',filter_var(rtrim($_GET['url'],'/')), FILTER_SANITIZE_URL);
    print_r($url);die();
  }
</code>```

Now, in the url you will get all the url segment in the arry format.

```<code>If your url is: mywebsite.com/news/123 then output will be:

Array ( [0] => news [1] => 123 )
</code>```

you can access and add your own logic or condition as per your need. hope this will help you.

Greetings!

Body:
I am having an issue with my .htaccess / .php files
I set up my web project in a way that it's split into 3 levels:

base level (mywebsite.com)

pages (mywebsite.com/news)

subpages/articles (mywebsite.com/news/123)

And all three are working as expected, here's my .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?page=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&sub=$2 [L]

I have to admit, I am not very good with the Regular Expressions for .htaccess/mod_rewrite as it is something I have done very rarely up to this point.

However my issue now is, that people dont get sent to a 404 error page if the page id (see $1) is not valid, like people can technically enter mywebsite.com/asdasdasd/ and it'll bring them (obviously) to the index.php, now my question is, can this be done some way in the .htaccess or should I just use php to check if the id they entered is valid or not? I did see that there's a thing called rewriteMap but I dont want to change the httpd.conf

Can anyone help?

Body:
Try this code. Hope this will help you,

.htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

index.php

if (isset($_GET['url'])) {
    $url = explode('/',filter_var(rtrim($_GET['url'],'/')), FILTER_SANITIZE_URL);
    print_r($url);die();
  }

Now, in the url you will get all the url segment in the arry format.

If your url is: mywebsite.com/news/123 then output will be:

Array ( [0] => news [1] => 123 )

you can access and add your own logic or condition as per your need. hope this will help you.

Greetings!


问:
If click button StopPropagation button parent row click
My problem is when I click my button it does not appear my button click it appears my row click (collapse event).

I have two button here one is for open modal and another have onclick event but it doesn't work.It's open row collapse event.

My modal open button is Cevapla.Sil button is deleting the message but it is only collapsing the panel under row

Here is my html :

```<code><tr class='accordion-toggle'  onclick='UpdateIsRead(this);' style='cursor:pointer;background-color:{6}' data-toggle='collapse' data-target='#gelenRow{0}' data-isread='{5}'>
   <td class='email-title'>{1}
   </td>
   <td class='email-body'>{2}
   </td>
   <td>{3}
   </td>
   <td>
      <a class='modalButton btn btn-info btn-xs' data-height='550' title='Cevap Yaz' data-src='{7}apps/pages/PrivateMessage.aspx?topic={8}&toWho={9}' data-title='Cevap Yaz' data-headericoncolor='#000000' data-headercolor='#000000' data-icon='fa fa-envelope' data-toggle='modal' style='cursor: pointer' data-target='#popup' style='height:28px'><span class='fa fa-edit'></span> Cevapla</a>
      <a style='height:28px' onclick='DeleteMessage();'  title='Sil'  class='btn btn-danger btn-xs'><span class='fa fa-remove'></span> Sil</a>
   </td>
</tr>
<tr id='gelenRow{0}' class='collapse' style='background-color:#F5F5F5'>
   <td colspan='6'>
      <div class='panel-footer' style='padding: 10px 35px;'>
         <div class='row'>
            <div id='filter-panel' class='filter-panel'>
               <div class='panel panel-default'>
                  <div class='panel-body'>
                     {4}
                  </div>
               </div>
            </div>
            <button type='button' class='btn btn-sm btn-primary' >Cevap Yaz</button>
         </div>
      </div>
   </td>
</tr>
</code>```

And I try this code :

```<code>$(document).on("click","tr", function(e){
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.parent().stopPropagation();
    }
});

$(document).on("click","tr", function(e){
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.stopPropagation();
    }
});
</code>```

答:
Because your DeleteMessage & UpdateIsRead functions are inline in the HTML you can consider to pass the current element and event:

```<code><tr class='accordion-toggle'  onclick='UpdateIsRead(this, event);'
</code>```

In this way you can add a test in your functions to stop propagation or action.

The event handlers order, clicking on DeleteMessage button is:

DeleteMessage

UpdateIsRead

$(document).on("click", "tr",...

function UpdateIsRead(ele, e) {
    console.log('UpdateIsRead');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        //e.stopPropagation();
    }
}
function DeleteMessage(ele, e) {
    console.log('DeleteMessage');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        //e.stopPropagation();
    }
}
$(document).on("click", "tr", function(e){
    console.log('$(document).on("click", "tr"...');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.stopPropagation();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table class="table table-striped">
    <tbody>
    <tr class='accordion-toggle'  onclick='UpdateIsRead(this, event);' style='cursor:pointer;background-color:{6}' data-toggle='collapse' data-target='#gelenRow0' data-isread='{5}'>
        <td class='email-title'>{1}
        </td>
        <td class='email-body'>{2}
        </td>
        <td>{3}
        </td>
        <td>
            <span class='fa fa-edit'></span> Cevapla
            <span class='fa fa-remove'></span> Sil
        </td>
    </tr>
    <tr id='gelenRow0' class='collapse' style='background-color:#F5F5F5'>
        <td colspan='6'>
            <div class='panel-footer' style='padding: 10px 35px;'>
                <div class='row'>
                    <div id='filter-panel' class='filter-panel'>
                        <div class='panel panel-default'>
                            <div class='panel-body'>
                                {4}
                            </div>
                        </div>
                    </div>
                    <button type='button' class='btn btn-sm btn-primary' >Cevap Yaz</button>
                </div>
            </div>
        </td>
    </tr>
    </tbody>
</table></code>```

Body:
My problem is when I click my button it does not appear my button click it appears my row click (collapse event).

I have two button here one is for open modal and another have onclick event but it doesn't work.It's open row collapse event.

My modal open button is Cevapla.Sil button is deleting the message but it is only collapsing the panel under row

Here is my html :

   {1}

   {2}

   {3}

       Cevapla
       Sil

                     {4}

            <button type='button' class='btn btn-sm btn-primary' >Cevap Yaz</button>

And I try this code :

$(document).on("click","tr", function(e){
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.parent().stopPropagation();
    }
});

$(document).on("click","tr", function(e){
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.stopPropagation();
    }
});

Body:
Because your DeleteMessage & UpdateIsRead functions are inline in the HTML you can consider to pass the current element and event:

<tr class='accordion-toggle'  onclick='UpdateIsRead(this, event);'

In this way you can add a test in your functions to stop propagation or action.

The event handlers order, clicking on DeleteMessage button is:

DeleteMessage

UpdateIsRead

$(document).on("click", "tr",...

function UpdateIsRead(ele, e) {
    console.log('UpdateIsRead');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        //e.stopPropagation();
    }
}
function DeleteMessage(ele, e) {
    console.log('DeleteMessage');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        //e.stopPropagation();
    }
}
$(document).on("click", "tr", function(e){
    console.log('$(document).on("click", "tr"...');
    if (e.target.nodeName == "A" || e.target.nodeName == "SPAN") {
        e.stopPropagation();
    }
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table class="table table-striped">
    <tbody>
    <tr class='accordion-toggle'  onclick='UpdateIsRead(this, event);' style='cursor:pointer;background-color:{6}' data-toggle='collapse' data-target='#gelenRow0' data-isread='{5}'>
        <td class='email-title'>{1}
        </td>
        <td class='email-body'>{2}
        </td>
        <td>{3}
        </td>
        <td>
            <a class='modalButton btn btn-info btn-xs' data-height='550' title='Cevap Yaz' data-src='{7}apps/pages/PrivateMessage.aspx?topic={8}&toWho={9}' data-title='Cevap Yaz' data-headericoncolor='#000000' data-headercolor='#000000' data-icon='fa fa-envelope' data-toggle='modal' style='cursor: pointer' data-target='#popup' style='height:28px'><span class='fa fa-edit'></span> Cevapla</a>
            <a style='height:28px' onclick='DeleteMessage(this, event);'  title='Sil'  class='btn btn-danger btn-xs'><span class='fa fa-remove'></span> Sil</a>
        </td>
    </tr>
    <tr id='gelenRow0' class='collapse' style='background-color:#F5F5F5'>
        <td colspan='6'>
            <div class='panel-footer' style='padding: 10px 35px;'>
                <div class='row'>
                    <div id='filter-panel' class='filter-panel'>
                        <div class='panel panel-default'>
                            <div class='panel-body'>
                                {4}
                            </div>
                        </div>
                    </div>
                    <button type='button' class='btn btn-sm btn-primary' >Cevap Yaz</button>
                </div>
            </div>
        </td>
    </tr>
    </tbody>
</table>


问:
optimizing modular arithmetic computations in C++
I am developing some linear algebra code that that is templated on the
matrix coefficient type.  One of the possible types is a class to do
modular arithmetic, naively implemented as follows:

```<code>template<typename val_t> // `val_t` is an integer type
class Modular
{
  val_t val_;
  static val_t modulus_;
public:
  Modular(const val_t& value) : val_(value) { };
  static void global_set_modulus(const val_t& modulus) { modulus_ = modulus; };

  Modular<val_t>& operator=(const Modular<val_t>& other) { val_ = other.val_; return *this; }

  Modular<val_t>& operator+=(const Modular<val_t>& other) { val_ += other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator-=(const Modular<val_t>& other) { val_ -= other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator*=(const Modular<val_t>& other) { val_ *= other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator/=(const Modular<val_t>& other) { val_ *= other.inverse().val_; val_ %= modulus_; return *this; }

  friend Modular<val_t> operator+(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ + b.val_) % Modular<val_t>::modulus_); };
  friend Modular<val_t> operator-(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ - b.val_) % Modular<val_t>::modulus_); };
  // ...etc.
};
</code>```

However, when the program runs with the Modular<int> coefficients, it is several
times slower than when it runs with int coefficients.

What are the things that I should change in the "Modular" class in
order to gain maximum performance?

For instance, is it possible to optimize expressions like a*b + c*d
to (a.val_*b.val_ + c.val_*d.val_) % modulus, and instead of the obvious:

```<code>(((a.val_*b.val_) % modulus) + ((c.val_*d.val_ % modulus) % modulus) % modulus)
</code>```

答:
Yes.  It is possible.  What you want to look up is "expression templates" and start from there.  From that point you're going to have to build some metaprogram logic to optimize/simplify the expression.  Far from a trivial task, but that's not what you asked.

NVM - it's way trivial:

```<code>int count = 0;
int modulus() { count++; return 10; }

template < typename T >
struct modular
{
  modular(T v) : value_(v) {}

  T value() const { return value_; }
  void value(T v) { value_ = v; }

  typedef modular<T> modular_type;
  typedef T raw_type;
private:
  T value_;
};

template < typename LH, typename RH >
struct multiply
{
  multiply(LH l, RH r) : lh(l), rh(r) {}

  typedef typename LH::modular_type modular_type;
  typedef typename LH::raw_type raw_type;

  raw_type value() const { return lh.value() * rh.value(); }

  operator modular_type () const { return modular_type(value() % modulus()); }

private:
  LH lh; RH rh;
};

template < typename LH, typename RH >
struct add
{
  add(LH l, RH r) : lh(l), rh(r) {}

  typedef typename LH::modular_type modular_type;
  typedef typename LH::raw_type raw_type;

  raw_type value() const { return lh.value() + rh.value(); }
  operator modular_type () const { return modular_type(value() % modulus()); }

private:
  LH lh; RH rh;
};

template < typename LH, typename RH >
add<LH,RH> operator+(LH const& lh, RH const& rh)
{
  return add<LH,RH>(lh,rh);
}

template < typename LH, typename RH >
multiply<LH,RH> operator*(LH const& lh, RH const& rh)
{
  return multiply<LH,RH>(lh,rh);
}

#include <iostream>

int main()
{
  modular<int> a = 5;
  modular<int> b = 7;
  modular<int> c = 3;
  modular<int> d = 8;

  std::cout << (5*7+3*8) % 10 << std::endl;

  modular<int> result = a * b + c * d;
  std::cout << result.value() << std::endl;

  std::cout << count << std::endl;

  std::cin.get();
}
</code>```

If you were smart though, you'd put the use of % in the constructor for modular so it's always modular; you'd also put checks in to make sure LH and RH are compatible along with SFINAE crap to keep the operators from killing it for any time at all.  You might also make modulus a template parameter and provide metafunctions to access it.  At any rate...there you go.

Edit: BTW, you can use this same technique to make your matrices calculate faster.  Instead of creating a new matrix for each operation in a string of operations, you make these things and then finally do the math, element by element, when you assign the result.  There's papers on it on the internet and everything, comparing it to FORTRAN and such.  Was one of the first uses of metaprogramming like template use in C++.  Also in the book http://www.amazon.com/Scientific-Engineering-Introduction-Advanced-Techniques/dp/0201533936 <- keep in mind though that "advanced techniques" was in 94 :p.  It's not as relevant today.

Body:
I am developing some linear algebra code that that is templated on the
matrix coefficient type.  One of the possible types is a class to do
modular arithmetic, naively implemented as follows:

template<typename val_t> // `val_t` is an integer type
class Modular
{
  val_t val_;
  static val_t modulus_;
public:
  Modular(const val_t& value) : val_(value) { };
  static void global_set_modulus(const val_t& modulus) { modulus_ = modulus; };

  Modular<val_t>& operator=(const Modular<val_t>& other) { val_ = other.val_; return *this; }

  Modular<val_t>& operator+=(const Modular<val_t>& other) { val_ += other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator-=(const Modular<val_t>& other) { val_ -= other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator*=(const Modular<val_t>& other) { val_ *= other.val_; val_ %= modulus_; return *this; }
  Modular<val_t>& operator/=(const Modular<val_t>& other) { val_ *= other.inverse().val_; val_ %= modulus_; return *this; }

  friend Modular<val_t> operator+(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ + b.val_) % Modular<val_t>::modulus_); };
  friend Modular<val_t> operator-(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ - b.val_) % Modular<val_t>::modulus_); };
  // ...etc.
};

However, when the program runs with the Modular<int> coefficients, it is several
times slower than when it runs with int coefficients.

What are the things that I should change in the "Modular" class in
order to gain maximum performance?

For instance, is it possible to optimize expressions like a*b + c*d
to (a.val_*b.val_ + c.val_*d.val_) % modulus, and instead of the obvious:

(((a.val_*b.val_) % modulus) + ((c.val_*d.val_ % modulus) % modulus) % modulus)

Body:
Yes.  It is possible.  What you want to look up is "expression templates" and start from there.  From that point you're going to have to build some metaprogram logic to optimize/simplify the expression.  Far from a trivial task, but that's not what you asked.

NVM - it's way trivial:

int count = 0;
int modulus() { count++; return 10; }

template < typename T >
struct modular
{
  modular(T v) : value_(v) {}

  T value() const { return value_; }
  void value(T v) { value_ = v; }

  typedef modular<T> modular_type;
  typedef T raw_type;
private:
  T value_;
};

template < typename LH, typename RH >
struct multiply
{
  multiply(LH l, RH r) : lh(l), rh(r) {}

  typedef typename LH::modular_type modular_type;
  typedef typename LH::raw_type raw_type;

  raw_type value() const { return lh.value() * rh.value(); }

  operator modular_type () const { return modular_type(value() % modulus()); }

private:
  LH lh; RH rh;
};

template < typename LH, typename RH >
struct add
{
  add(LH l, RH r) : lh(l), rh(r) {}

  typedef typename LH::modular_type modular_type;
  typedef typename LH::raw_type raw_type;

  raw_type value() const { return lh.value() + rh.value(); }
  operator modular_type () const { return modular_type(value() % modulus()); }

private:
  LH lh; RH rh;
};

template < typename LH, typename RH >
add<LH,RH> operator+(LH const& lh, RH const& rh)
{
  return add<LH,RH>(lh,rh);
}

template < typename LH, typename RH >
multiply<LH,RH> operator*(LH const& lh, RH const& rh)
{
  return multiply<LH,RH>(lh,rh);
}

#include <iostream>

int main()
{
  modular<int> a = 5;
  modular<int> b = 7;
  modular<int> c = 3;
  modular<int> d = 8;

  std::cout << (5*7+3*8) % 10 << std::endl;

  modular<int> result = a * b + c * d;
  std::cout << result.value() << std::endl;

  std::cout << count << std::endl;

  std::cin.get();
}

If you were smart though, you'd put the use of % in the constructor for modular so it's always modular; you'd also put checks in to make sure LH and RH are compatible along with SFINAE crap to keep the operators from killing it for any time at all.  You might also make modulus a template parameter and provide metafunctions to access it.  At any rate...there you go.

Edit: BTW, you can use this same technique to make your matrices calculate faster.  Instead of creating a new matrix for each operation in a string of operations, you make these things and then finally do the math, element by element, when you assign the result.  There's papers on it on the internet and everything, comparing it to FORTRAN and such.  Was one of the first uses of metaprogramming like template use in C++.  Also in the book http://www.amazon.com/Scientific-Engineering-Introduction-Advanced-Techniques/dp/0201533936 <- keep in mind though that "advanced techniques" was in 94 :p.  It's not as relevant today.


问:
I am working on this code to update google contacts with google forms and spreadsheet linked to it
I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful

Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?

```<code>function createHeaders() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // Freezes the first row
  sheet.setFrozenRows(1);

  // Set the values we want for headers
  var values = [
    ["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
  ];

  // Set the range of cells
  var range = sheet.getRange("A1:F1");

  // Call the setValues method on range and pass in our values
  range.setValues(values);
}

function createContact() {
  var alreadyAdded = "Already added";
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process

  // Fetch the range of cells A2:G3
  var dataRange = sheet.getRange(startRow, 1, numRows, 8)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
    for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var firstName = row[0]
    var lastName = row[1]
    var emailAddress = row[2]
    var phone = row[3]
    var company = row[4]
    var notes = row[5]
    var addedAlready = row[6];

      if (addedAlready != alreadyAdded) {
      // Create contact in Google Contacts
      var contact = ContactsApp.createContact(firstName, lastName, emailAddress);

      // Add values to new contact
      contact.addCompany(company, "");
      contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
      contact.setNotes(notes);
      sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
      };
    };
};
</code>```

答:
I was able to reproduce the error by passing one or more empty strings as arguments to the createContact() method:

```<code>var contact = ContactsApp.createContact("", "", "");
</code>```

Check the values in your data array by logging them to see if you've got any empty strings there. You can wrap the code in a try block the prevent errors from stopping program execution. Any errors will be logged in a catch block

```<code>try {
var contact = ContactsApp.createContact(a, b, c);

}

catch(error) {

Logger.log(error);

}
</code>```

Body:
I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful

Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?

function createHeaders() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // Freezes the first row
  sheet.setFrozenRows(1);

  // Set the values we want for headers
  var values = [
    ["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
  ];

  // Set the range of cells
  var range = sheet.getRange("A1:F1");

  // Call the setValues method on range and pass in our values
  range.setValues(values);
}

function createContact() {
  var alreadyAdded = "Already added";
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process

  // Fetch the range of cells A2:G3
  var dataRange = sheet.getRange(startRow, 1, numRows, 8)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
    for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var firstName = row[0]
    var lastName = row[1]
    var emailAddress = row[2]
    var phone = row[3]
    var company = row[4]
    var notes = row[5]
    var addedAlready = row[6];

      if (addedAlready != alreadyAdded) {
      // Create contact in Google Contacts
      var contact = ContactsApp.createContact(firstName, lastName, emailAddress);

      // Add values to new contact
      contact.addCompany(company, "");
      contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
      contact.setNotes(notes);
      sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
      };
    };
};

Body:
I was able to reproduce the error by passing one or more empty strings as arguments to the createContact() method:

var contact = ContactsApp.createContact("", "", "");

Check the values in your data array by logging them to see if you've got any empty strings there. You can wrap the code in a try block the prevent errors from stopping program execution. Any errors will be logged in a catch block

try {
var contact = ContactsApp.createContact(a, b, c);

}

catch(error) {

Logger.log(error);

}


问:
disable all page elements with modal feature using jquery
I wish to disable all page elements upon an action. Like the modal feature that is in the JQuery UI.

Like on an ajax action.. I wish to show a notification and at the same time to enable the modal feature. And after the request, need to re-enable the page elements back.

Is there any option available in core jquery for that or any plugins?

答:
Try adding a style of "pointer-events: none;" to the body.
To remove it use pointer-events: auto;

More info here
https://css-tricks.com/almanac/properties/p/pointer-events/
Though there may be issues with earlier browsers not supporting it


问:
Ruby: group_by operation on an array of hashes
I have an array of hashes that represent compounds stored in boxes.

```<code>database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]
</code>```

I would like to select a subset of the array, minimum by the number of boxes, that covers the full inventory of compounds (i.e., 1 to 7). Thus the result would be:

```<code>database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound7", "Box"=>4}]
</code>```

I can use the following to group compounds per box:

```<code>database.group_by{|x| x['Box']}
</code>```

I have trouble reducing the result so that duplicate compound names are removed from the grouped operation.

答:
I don't like that original data structure.  Why not just start with a hash of {CompoundX => BoxY} since "Name" and "Box" are not really useful.  But if you're married to that structure, here's how I would do it:

```<code>database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]

new_db_arr = database.collect{|h| h.flatten}.flatten.collect{|i| i if i != "Name" && i != "Box"}.compact!
new_db_hash = {}
new_db_arr.each_slice(2) do |a,b|
  if new_db_hash[a].nil?
    new_db_hash[a] = []
  end
  new_db_hash[a] << b
end

new_db_hash
boxes = new_db_hash.values
combos = boxes[0].product(*boxes[1..-1])
combos = combos.sort_by{|a| a.uniq.length }
winning_combo = combos[0].uniq
</code>```

The bulk of the work is just transforming the data structure into the hash of :Compound => boxNumber format.  Then you generate every combination of boxes, sort by the combination's number of uniq items and take the one with the smallest number of uniq items as the answer.  Not sure how great this would scale for very large datasets.

Body:
I have an array of hashes that represent compounds stored in boxes.

database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]

I would like to select a subset of the array, minimum by the number of boxes, that covers the full inventory of compounds (i.e., 1 to 7). Thus the result would be:

database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound7", "Box"=>4}]

I can use the following to group compounds per box:

database.group_by{|x| x['Box']}

I have trouble reducing the result so that duplicate compound names are removed from the grouped operation.

Body:
I don't like that original data structure.  Why not just start with a hash of {CompoundX => BoxY} since "Name" and "Box" are not really useful.  But if you're married to that structure, here's how I would do it:

database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]

new_db_arr = database.collect{|h| h.flatten}.flatten.collect{|i| i if i != "Name" && i != "Box"}.compact!
new_db_hash = {}
new_db_arr.each_slice(2) do |a,b|
  if new_db_hash[a].nil?
    new_db_hash[a] = []
  end
  new_db_hash[a] << b
end

new_db_hash
boxes = new_db_hash.values
combos = boxes[0].product(*boxes[1..-1])
combos = combos.sort_by{|a| a.uniq.length }
winning_combo = combos[0].uniq

The bulk of the work is just transforming the data structure into the hash of :Compound => boxNumber format.  Then you generate every combination of boxes, sort by the combination's number of uniq items and take the one with the smallest number of uniq items as the answer.  Not sure how great this would scale for very large datasets.


问:
Javascript foreach loop on list items
I have a basic HTML list like below...

```<code><ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>
</code>```

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

```<code>var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}
</code>```

This isn't working for me, is it because it is not really an array?

答:
You could borrow Array#map for an array like object and return just the id property of the objects.

var result = [].map.call(document.getElementsByClassName("item"), function(o) {
        return o.id;
    });

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="test_ul">
    <li class="item" id="item1">Item 1</li>
    <li class="item" id="item2">Item 2</li>
    <li class="item" id="item3">Item 3</li>
    <li class="item" id="item4">Item 4</li>
</ul></code>```

Title: Javascript foreach loop on list items

Body:
I have a basic HTML list like below...

        Item 1

        Item 2

        Item 3

        Item 4

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}

This isn't working for me, is it because it is not really an array?

Body:
You could borrow Array#map for an array like object and return just the id property of the objects.

var result = [].map.call(document.getElementsByClassName("item"), function(o) {
        return o.id;
    });

console.log(result);

<ul class="test_ul">
    <li class="item" id="item1">Item 1</li>
    <li class="item" id="item2">Item 2</li>
    <li class="item" id="item3">Item 3</li>
    <li class="item" id="item4">Item 4</li>
</ul>


问:
Divs on an ASP.NET Gridview
The GridView in ASP.NET when rendered isn't the prettiest or most semantic control ever, is there a way to use
 using constructing it? Or should there be another approach, I ideally would like to remain using the gridview because I select the DataKeyNames in my code, unless there is a similar way to select the DataKeyNames using another control like a listview?

答: Instead of using the semantics of a div, I would look to format the class using some tailored CSS. Let me know if this is something you're interested in and I can offer you some links.</p>

Title: Divs on an ASP.NET Gridview


问:
Create all combinations from regex
I have sentences that define a template for random combinations:

```<code>I like dogs/cats
I want to eat today/(the next day)
</code>```

I tried using a regex:

```<code>m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]
</code>```

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?

答:
With below code you will get something like

```<code>> sentence = 'I want to eat today/(the next day)' m =
> re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+|(\(.*?\))))', sentence)
> print m.group('list') words = m.group('list').split('/') combs = [comb
> for comb in [sentence.replace(m.group('list'), w) for w in words]]
> print combs

['I want to eat today', 'I want to eat (the next day)'
</code>```

you could dome extra processing to get rid of the extra parenthesis which should be easy

Title: Create all combinations from regex

Body:
I have sentences that define a template for random combinations:

I like dogs/cats
I want to eat today/(the next day)

I tried using a regex:

m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?

Body:
With below code you will get something like

> sentence = 'I want to eat today/(the next day)' m =
> re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+|(\(.*?\))))', sentence)
> print m.group('list') words = m.group('list').split('/') combs = [comb
> for comb in [sentence.replace(m.group('list'), w) for w in words]]
> print combs

['I want to eat today', 'I want to eat (the next day)'

you could dome extra processing to get rid of the extra parenthesis which should be easy


问:
how can refresh list when click button in item listview
i have recyclerview and button on the all item of list. when i click the button in my adapter item deleted and i want refresh recycler and show new data.</p>

```<code>@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());

      }
    });
  }
</code>```

答:
For re-initializing the recycler view and get callback on onBindViewHolder

simple call notifyDataSetChanged();

```<code>       @Override
    public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
        lietner = lietners.get(position);

        holder.next_level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // delete the item, or change the data.
                notifyDataSetChanged();
            }
        });
    }
</code>```

Body:
i have recyclerview and button on the all item of list. when i click the button in my adapter item deleted and i want refresh recycler and show new data.

@Override
  public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
    lietner = lietners.get(position);
    holder.txt_en.setText(lietner.getText_en());
    holder.txt_pe.setText(lietner.getText_pe());
    holder.time.setText(lietner.getTime());
    holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
    holder.next_level.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());

      }
    });
  }

Body:
For re-initializing the recycler view and get callback on onBindViewHolder

simple call notifyDataSetChanged();

       @Override
    public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
        lietner = lietners.get(position);

        holder.next_level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // delete the item, or change the data.
                notifyDataSetChanged();
            }
        });
    }


问:
Pyplot truth value of an array with more than one element is ambiguous
I am trying to implement a knn 1D estimate:

```<code># nearest neighbors estimate
def nearest_n(x, k, data):
    # Order dataset
    #data = np.sort(data, kind='mergesort')
    nnb = []
    # iterate over all data and get k nearest neighbours around x
    for n in data:
        if nnb.__len__()<k:
            nnb.append(n)
        else:
            for nb in np.arange(0,k):
                if np.abs(x-n) < np.abs(x-nnb[nb]):
                    nnb[nb] = n
                    break

    nnb = np.array(nnb)
    # get volume(distance) v of k nearest neighbours around x
    v = nnb.max() - nnb.min()
    v = k/(data.__len__()*v)

    return v

interval = np.arange(-4.0, 8.0, 0.1)
plt.figure()
for k in (2,8,35):
    plt.plot(interval, nearest_n(interval, k,train_data), label=str(o))
plt.legend()
plt.show()
</code>```

Which throws:

```<code>  File "x", line 55, in nearest_n
    if np.abs(x-n) < np.abs(x-nnb[nb]):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I know the error comes from the array input in plot(), but I am not sure how to avoid this in a function with operators >/==/<

'data' comes from a 1D txt file containing floats.

I tried using vectorize:

```<code>nearest_n = np.vectorize(nearest_n)
</code>```

which results in:

```<code>line 50, in nearest_n
    for n in data:
TypeError: 'numpy.float64' object is not iterable
</code>```

Here is an example, let's say:

```<code>data = [0.5,1.7,2.3,1.2,0.2,2.2]
k = 2
</code>```

nearest_n(1.5) should then lead to

```<code>nbb=[1.2,1.7]
v = 0.5
</code>```

and return 2/(6*0.5) = 2/3

The function runs for example neares_n(2.0,4,data) and gives 0.0741586011463

答:
```<code>plt.figure()
X = np.arange(-4.0,8.0,0.1)
for k in [2,8,35]:
    Y = []
    for n in X:
        Y.append(nearest_n(n,k,train_data))
    plt.plot(X,Y,label=str(k))
plt.show()
</code>```

is working fine. I thought pyplot.plot would do this exact thing for me already, but I guess it does not...

Body:
I am trying to implement a knn 1D estimate:

# nearest neighbors estimate
def nearest_n(x, k, data):
    # Order dataset
    #data = np.sort(data, kind='mergesort')
    nnb = []
    # iterate over all data and get k nearest neighbours around x
    for n in data:
        if nnb.__len__()<k:
            nnb.append(n)
        else:
            for nb in np.arange(0,k):
                if np.abs(x-n) < np.abs(x-nnb[nb]):
                    nnb[nb] = n
                    break

    nnb = np.array(nnb)
    # get volume(distance) v of k nearest neighbours around x
    v = nnb.max() - nnb.min()
    v = k/(data.__len__()*v)

    return v

interval = np.arange(-4.0, 8.0, 0.1)
plt.figure()
for k in (2,8,35):
    plt.plot(interval, nearest_n(interval, k,train_data), label=str(o))
plt.legend()
plt.show()

Which throws:

  File "x", line 55, in nearest_n
    if np.abs(x-n) < np.abs(x-nnb[nb]):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know the error comes from the array input in plot(), but I am not sure how to avoid this in a function with operators >/==/<

'data' comes from a 1D txt file containing floats.

I tried using vectorize:

nearest_n = np.vectorize(nearest_n)

which results in:

line 50, in nearest_n
    for n in data:
TypeError: 'numpy.float64' object is not iterable

Here is an example, let's say:

data = [0.5,1.7,2.3,1.2,0.2,2.2]
k = 2

nearest_n(1.5) should then lead to

nbb=[1.2,1.7]
v = 0.5

and return 2/(6*0.5) = 2/3

The function runs for example neares_n(2.0,4,data) and gives 0.0741586011463

Body:
plt.figure()
X = np.arange(-4.0,8.0,0.1)
for k in [2,8,35]:
    Y = []
    for n in X:
        Y.append(nearest_n(n,k,train_data))
    plt.plot(X,Y,label=str(k))
plt.show()

is working fine. I thought pyplot.plot would do this exact thing for me already, but I guess it does not...


问:
Security considerations when using Google Play App Signing
I just enrolled to App Signing in Play console and everything works great.

But how should I treat my new upload keystore and its passwords now?
Can I just put this keystore under version control and put passwords into build script in plain text?

As I understand this keystore is only used to temporary sign my apk prior to upload. So I consider it to be pretty safe, since nobody except myself can actually upload new apk to Play, and there is no option to access my original release keystore by knowing upload keys.

Another thing that bothers me now is that I can't see any option to change upload keystore. Is it possible now, or at least planned to be added to Play console soon? If I'll publish my upload keystore and passwords to version control it would be nice to have an option to switch to a new private keystore, if something will go wrong.

答:
As @jonathanrz said, it's best to keep your keystore files private.
It's super easy to use a gradle.properties file to store you keystore passwords, and then just reference property values in your build.gradle file.

Just remember to guard the keystore files with your life, keep backups of them in multiple places, if you lose them, you'll have to re-upload your app.


问:
Django http sometimes responds with long string consisted of unicode characters
I am building an arduino project that requests status from raspberry pi server running django web application. The web app is simple, it stores status of one switch in database (True or False meaning On or Off). I have a view that returns simple string with the status in form "Status:1" or "Status:0".

The problem is that sometimes the response from the server is in a form of long string consisted of unicode characters. The characters are unknown to me when I copy-paste them from Arduino IDE Serial Monitor they look like this: '⸮'. The arduino code repeatly loads this page and checks for status to update the HW in my project. The length of this string is completely random and sometimes even infinite. The occurence is also random so I cannot predict when it happens therefore why it happens.

The problem it is causing me is that I am parsing the response from the server on my arduino and when this infinite string occurs the program on the board freezes because it is parsing it practicaly forever. That is simply unacceptable.

The code that reads the response from server on arduino is:

```<code>while(client.connected() || client.available()){
  char c = client.read();
  Serial.print(c);
}
</code>```

It is not the code I use to parse the response, it is just code I used to find out what is the problem by outputing the response. I am attaching the screen of serial monitor window so you can see the problem (at the end of question). To parse response I use TextFinder.

The view code that creates the response in django:

```<code>def state(request, room_name):
  room = Light.objects.get(light_name=room_name)
  out = ""
  if room.light_status:
    out = "Status:1\t"
  else:
    out = "Status:0\t"
  return HttpResponse(out)
</code>```

Do any of you have any idea what could be causing this problem?

I also have one more problem that might be connected to this one but I am not sure. Sometimes the response value is wrong which causes the LED to blink (just for one iteration at random time, this might be caused by delay from server who knows).

EDIT: I thought the ASCII value of the character could be of some use. It is 255 (the last ASCII character).

The screen of the response in Arduino Serial Monitor

答:
First of all your out should be a dict i.e. out = {"Status":"1"} etc. Secondly, for your question you can remove all the non-ascii characters as
Remove Non Ascii characters

Just Replace white-space with empty i.e ''.

Body:
I am building an arduino project that requests status from raspberry pi server running django web application. The web app is simple, it stores status of one switch in database (True or False meaning On or Off). I have a view that returns simple string with the status in form "Status:1" or "Status:0".

The problem is that sometimes the response from the server is in a form of long string consisted of unicode characters. The characters are unknown to me when I copy-paste them from Arduino IDE Serial Monitor they look like this: '⸮'. The arduino code repeatly loads this page and checks for status to update the HW in my project. The length of this string is completely random and sometimes even infinite. The occurence is also random so I cannot predict when it happens therefore why it happens.

The problem it is causing me is that I am parsing the response from the server on my arduino and when this infinite string occurs the program on the board freezes because it is parsing it practicaly forever. That is simply unacceptable.

The code that reads the response from server on arduino is:

while(client.connected() || client.available()){
  char c = client.read();
  Serial.print(c);
}

It is not the code I use to parse the response, it is just code I used to find out what is the problem by outputing the response. I am attaching the screen of serial monitor window so you can see the problem (at the end of question). To parse response I use TextFinder.

The view code that creates the response in django:

def state(request, room_name):
  room = Light.objects.get(light_name=room_name)
  out = ""
  if room.light_status:
    out = "Status:1\t"
  else:
    out = "Status:0\t"
  return HttpResponse(out)

Do any of you have any idea what could be causing this problem?

I also have one more problem that might be connected to this one but I am not sure. Sometimes the response value is wrong which causes the LED to blink (just for one iteration at random time, this might be caused by delay from server who knows).

EDIT: I thought the ASCII value of the character could be of some use. It is 255 (the last ASCII character).

The screen of the response in Arduino Serial Monitor