问:
Filter a MultiMap<Predicate, value>
Block are some long-lived instances representing types, e.g. A Minecraft BlockType grass, green_wool etc.

I'm trying to find a DataStructure that can efficiently store and test for a given BlockPattern (think like, an obsidian portal, Wither etc if you are familiar with Minecraft) but if you are not familiar, being able to create a class that can test for a given structure being built out of blocks at given Vector3i's relative to the block being placed.

The Vector3i represents an integer vector of where in a 'block pattern' that a given predicate can match to.

e.g. you could have a predicate that tests for an arbitrary block property 'hotness' that tests true for fire and lava.

So rather then scan the whole pattern each time to make sure that the block positions in the world, match the predicates, I was thinking about reversing the problem.

Cache the potential positions that a Block can be in a pattern in a multimap, and get all the potential positions, in order to limit the amount of checks that happen afterwards.

So I have a Multimap<Predicate<Block>,Vector3i> patternLookup cache.

Which is representing the potential positions that a block is allowed to be found in the BlockPattern.

So the player places a Block, I need to filter the Multimap, collecting all possible locations the block is 'allowed' (predicate true) to be in.

However, as an optimization step, I thought it may be faster to only test the predicates that have a potential match (in terms of identity). (3 years on I'm not sure if this assumption is true)

How can I filter the contents of the multimap to get a collection of values, using guava's functional features? (or am I better just iterating over the EntrySet?)

e.g.

答:
You could use Multimaps.filterEntries(), something like:

```<code>public static <V> Multimap<Predicate<V>, V> filterByPredicateKey(
    Multimap<Predicate<V>, V> multimap) {
  return Multimaps.filterEntries(multimap, e -> e.getKey().apply(e.getValue()));
}
</code>```

That doesn't quite match the multimap type signature you mention in your question, but I assume block and Vector3i are related in some way, otherwise you couldn't apply the predicate to the values anyways.

This returns a view of the backing multimap, which is free (O(1)) to construct but applies the filtering at access time, so .get() on the returned multimap is O(n). Depending on the expected use cases you may prefer to copy this multimap into a separate immutable multimap so the filtering only happens once.

Title: Filter a MultiMap<Predicate, value>

Body:
You could use Multimaps.filterEntries(), something like:

public static <V> Multimap<Predicate<V>, V> filterByPredicateKey(
    Multimap<Predicate<V>, V> multimap) {
  return Multimaps.filterEntries(multimap, e -> e.getKey().apply(e.getValue()));
}

That doesn't quite match the multimap type signature you mention in your question, but I assume block and Vector3i are related in some way, otherwise you couldn't apply the predicate to the values anyways.

This returns a view of the backing multimap, which is free (O(1)) to construct but applies the filtering at access time, so .get() on the returned multimap is O(n). Depending on the expected use cases you may prefer to copy this multimap into a separate immutable multimap so the filtering only happens once.


来源: stackexchange

问:
What's the proper REST API url for updating sub-resources?
It seems to be a good practice to follow this rule:

If a resource is related to another resource use subresources.

Example:

GET /users/711/posts ====> Returns a list of posts for user 711

  GET /users/711/posts/4 ====> Returns post #4 for user 711

Now what if I want to update a sub-resource? Should I still use this relation? Which of the following two approaches is more preferred/standard?

PUT /users/711/posts/4 =====> Update post #4

  PUT /posts/4

答:
Keep it consistent.

/users/711/posts/4 is a URI that identifies/locates a resource in your server. The same identifier/locator should be used to get a representation, delete and replace the state of the resource.

ContentLicense: CC BY-SA 3.0


问:
Taking different Inputs in single line of Python
I am trying to take input from a single line in Python but it's not working.

Error:

```<code>Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'
</code>```

Code:

```<code>q = int(input())
lis = []
for i in range(q) :
  a = int(input())
  print(a)
  if(a==1) :
    b = int(input())
    lis.append(b)
  else :
    print("Do Nothing")
</code>```

In this code for a given integer i.e.,q.

I have to take two inputs and if the first integer is 1 then we have to add the second input to the array.

Form input:

```<code>5
1 4
1 9
</code>```

If input of first line is 1, we have to add 4 to list. I am unable to take input in line 1 as only 1 it is taking both 1 4.

答:
This is the most basic way of doing it

```<code>string = input()  # Read Input as string
print(string)

str_array = string.split(" ")  # Split the string
print(str_array)

int_arr = [int(i) for i in str_array]  # Parse the individual strings to int
print(int_arr)
</code>```

Output

```<code>1 56 9 87 7
['1', '56', '9', '87', '7']
[1, 56, 9, 87, 7]
</code>```

If you really want the most pythonic way of doing it

```<code>int_arr = [int(i) for i in input().split(" ")]
</code>```

Body:
I am trying to take input from a single line in Python but it's not working.

Error:

Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'

Code:

q = int(input())
lis = []
for i in range(q) :
  a = int(input())
  print(a)
  if(a==1) :
    b = int(input())
    lis.append(b)
  else :
    print("Do Nothing")

In this code for a given integer i.e.,q.

I have to take two inputs and if the first integer is 1 then we have to add the second input to the array.

Form input:

5
1 4
1 9

If input of first line is 1, we have to add 4 to list. I am unable to take input in line 1 as only 1 it is taking both 1 4.

Body:
This is the most basic way of doing it

string = input()  # Read Input as string
print(string)

str_array = string.split(" ")  # Split the string
print(str_array)

int_arr = [int(i) for i in str_array]  # Parse the individual strings to int
print(int_arr)

Output

1 56 9 87 7
['1', '56', '9', '87', '7']
[1, 56, 9, 87, 7]

If you really want the most pythonic way of doing it

int_arr = [int(i) for i in input().split(" ")]


问:
Arduino | Everything on the X-axis works but not on the Y-axis
I want to make a simple memory game for the Arduino. But instead of buttons I want to use a joystick to select the blinking LEDs.

I am in the early stage of the project but my Y-axis won't read and I can't figure the problem out.

```<code>//Joystick
const int X_pin = A4;
const int Y_pin = A5;
int Joy_Waarde;
//leds
const int led_Rood = 13;
const int led_Groen = 12;
const int led_Blauw = 11;
const int led_Geel = 10;
//componenten
const int buzzer = 4;

int X_Value = 0;
int Y_Value = 0;

void setup() {
  pinMode (led_Rood, OUTPUT);
  pinMode (led_Groen, OUTPUT);
  pinMode (led_Blauw, OUTPUT);
  pinMode (led_Geel, OUTPUT);
  pinMode(buzzer, OUTPUT);

  Serial.begin(9600);
  randomSeed(analogRead(A0));
  Serial.println("Het spel is begonnen!");
}

void loop() {
  X_Value = analogRead(X_pin);
  Y_Value = analogRead(Y_pin);
  if (X_Value == 1023) {
    digitalWrite(led_Groen, HIGH);
  } else {
    digitalWrite(led_Groen, LOW);
  }
  if (X_Value == 0) {
    digitalWrite(led_Blauw, HIGH);
  } else {
    digitalWrite(led_Blauw, LOW);
  }
  if (Y_Value == 1023) {
    digitalWrite(led_Geel, HIGH);
  } else {
    digitalWrite(led_Geel, LOW);
  }
  if (Y_Value == 0) {
    digitalWrite(led_Rood, HIGH);
  } else {
    digitalWrite(led_Rood, LOW);
  }
}
</code>```

Hopefully you guys now something about it! Thanks in advance!

答:
It worked, It was something with the wiring!

Thank you!

Body:
I want to make a simple memory game for the Arduino. But instead of buttons I want to use a joystick to select the blinking LEDs.

I am in the early stage of the project but my Y-axis won't read and I can't figure the problem out.

//Joystick
const int X_pin = A4;
const int Y_pin = A5;
int Joy_Waarde;
//leds
const int led_Rood = 13;
const int led_Groen = 12;
const int led_Blauw = 11;
const int led_Geel = 10;
//componenten
const int buzzer = 4;

int X_Value = 0;
int Y_Value = 0;

void setup() {
  pinMode (led_Rood, OUTPUT);
  pinMode (led_Groen, OUTPUT);
  pinMode (led_Blauw, OUTPUT);
  pinMode (led_Geel, OUTPUT);
  pinMode(buzzer, OUTPUT);

  Serial.begin(9600);
  randomSeed(analogRead(A0));
  Serial.println("Het spel is begonnen!");
}

void loop() {
  X_Value = analogRead(X_pin);
  Y_Value = analogRead(Y_pin);
  if (X_Value == 1023) {
    digitalWrite(led_Groen, HIGH);
  } else {
    digitalWrite(led_Groen, LOW);
  }
  if (X_Value == 0) {
    digitalWrite(led_Blauw, HIGH);
  } else {
    digitalWrite(led_Blauw, LOW);
  }
  if (Y_Value == 1023) {
    digitalWrite(led_Geel, HIGH);
  } else {
    digitalWrite(led_Geel, LOW);
  }
  if (Y_Value == 0) {
    digitalWrite(led_Rood, HIGH);
  } else {
    digitalWrite(led_Rood, LOW);
  }
}

Hopefully you guys now something about it! Thanks in advance!


问:
r: Fill two dataframe columns with the t-statistic and p-value from t.test
Given the American Community Survey dataset from Lock5Data, I want to calculate the t-stat (and its Bonferroni-corrected p-value) of incomes for each combination of races.  I'd like to store the results in a dataframe with columns 'race1', 'race2, 'tstat', and 'pval'.  This way I can sort the dataframe to show the biggest (or most significant) differences in income.

```<code>library(Lock5Data)
data("ACS")
ACS$Sex <- factor(ACS$Sex, labels = c("Female","Male"))
sub_acs <- subset(ACS, select = c("Income","Sex","Race"))
sub_acs <- na.omit(sub_acs)

# form results df (t_df)
race_unique <- unique(sub_acs$Race)
t_df <- expand.grid(race1 = race_unique, race2 = race_unique)
t_df <- t_df[t_df$race1 != t_df$race2,]
rownames(t_df) <- NULL

# fill df col with t-stat
t_df$tstat <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$statistic

# fill df col with p_val
t_df$pval <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$p.value
</code>```

Unfortunately, the results df t_df appears to only show the first result for each test repeated down all the rows.  How do I correctly map the t-statistic and p-value results?  Answers that make my current solution more elegant and portable are welcome!

答:
Consider Map (the simplified wrapper to mapply) and use t_df as only a helper dataframe to pass unique values into the multiple apply method.

```<code>t_df <- subset(expand.grid(race1 = race_unique, race2 = race_unique), race1 < race2)

ttest_proc <- function(r1, r2) {
   output <- t.test(sub_acs[sub_acs$Race == r1,]$Income,
                    sub_acs[sub_acs$Race == r2,]$Income,
                    p.adjust.methods='bonferroni')

   df <- data.frame(race1 = r1,
                    race2 = r2,
                    t_stat = output$statistic,
                    p_val = output$p.value)
   return(df)
}

df_list <- Map(ttest_proc, t_df$race1, t_df$race2)

final_df <- do.call(rbind, df_list)
</code>```

Body:
Given the American Community Survey dataset from Lock5Data, I want to calculate the t-stat (and its Bonferroni-corrected p-value) of incomes for each combination of races.  I'd like to store the results in a dataframe with columns 'race1', 'race2, 'tstat', and 'pval'.  This way I can sort the dataframe to show the biggest (or most significant) differences in income.

library(Lock5Data)
data("ACS")
ACS$Sex <- factor(ACS$Sex, labels = c("Female","Male"))
sub_acs <- subset(ACS, select = c("Income","Sex","Race"))
sub_acs <- na.omit(sub_acs)

# form results df (t_df)
race_unique <- unique(sub_acs$Race)
t_df <- expand.grid(race1 = race_unique, race2 = race_unique)
t_df <- t_df[t_df$race1 != t_df$race2,]
rownames(t_df) <- NULL

# fill df col with t-stat
t_df$tstat <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$statistic

# fill df col with p_val
t_df$pval <- t.test(sub_acs[sub_acs$Race == t_df$race1,]$Income,
           sub_acs[sub_acs$Race == t_df$race2,]$Income,
           p.adjust.methods='bonferroni')$p.value

Unfortunately, the results df t_df appears to only show the first result for each test repeated down all the rows.  How do I correctly map the t-statistic and p-value results?  Answers that make my current solution more elegant and portable are welcome!

Body:
Consider Map (the simplified wrapper to mapply) and use t_df as only a helper dataframe to pass unique values into the multiple apply method.

t_df <- subset(expand.grid(race1 = race_unique, race2 = race_unique), race1 < race2)

ttest_proc <- function(r1, r2) {
   output <- t.test(sub_acs[sub_acs$Race == r1,]$Income,
                    sub_acs[sub_acs$Race == r2,]$Income,
                    p.adjust.methods='bonferroni')

   df <- data.frame(race1 = r1,
                    race2 = r2,
                    t_stat = output$statistic,
                    p_val = output$p.value)
   return(df)
}

df_list <- Map(ttest_proc, t_df$race1, t_df$race2)

final_df <- do.call(rbind, df_list)


问:
PHP echo total number of rows from SQL query
I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!</p>

```<code>$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);

echo $count;
</code>```

答:
You should use php prepare statement like this

```<code>$count  = 0;
$mysqli = new mysqli(host, dbUser, dbPassword, dbName);
mysqli_set_charset($mysqli, "utf8");
$sql    = "select count(*)  from advisors";
if ($stmt   = mysqli_prepare($mysqli, $sql))
{
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $c);
    if (mysqli_stmt_fetch($stmt))
    {
        $count = $c;
    }
    mysqli_stmt_close($stmt);
}
return $count;
</code>```

For more information, here is the link for php prepare statement
Documentation of php prepare statement

Body:
I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!

$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);

echo $count;

Body:
You should use php prepare statement like this

$count  = 0;
$mysqli = new mysqli(host, dbUser, dbPassword, dbName);
mysqli_set_charset($mysqli, "utf8");
$sql    = "select count(*)  from advisors";
if ($stmt   = mysqli_prepare($mysqli, $sql))
{
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $c);
    if (mysqli_stmt_fetch($stmt))
    {
        $count = $c;
    }
    mysqli_stmt_close($stmt);
}
return $count;

For more information, here is the link for php prepare statement
Documentation of php prepare statement


问:
Creating barchart ggplot2 single dim dataframe
I'm trying to create a barchart in ggplot2, I have a dataframe that has column names and associated numeric values, but I keep running into unexpected errors creating the dataframe:

```<code>ggplot(audit_count,aes(x=colnames(audit_count),y=audit_count[1,])) +geom_bar()
</code>```

gives me error message

```<code>Error: Aesthetics must be either length 1 or the same as the data (1): x, y
</code>```

But this error message doesnt make sense to me, as colnames(audit_count) and audit_count[1,] are the same length.

Is there some kind of transform I need to do to my data to get it to plot as barchart with the column names as bar names, and the numeric values as y values?

Data below:

```<code>structure(list(page_title_missing = 56L, page_title_length = 164L,
    page_title_duplicates = 630L, meta_desc_missing = 703L, meta_desc_length = 0L,
    meta_desc_duplicate = 28L, url_dynamic = 397L, url_underscore = 26L,
    url_uppercase = 701L, pagination = 0L, image_alt_missing = 223L,
    h1_missing = 56L, h1_multiple = 427L, meta_keyword_present = 0L,
    https_missing = 0L, non_canonical = 293L, meta_no_index = 0L,
    meta_no_follow = 0L, content_duplication = 617L, content_depth = 461L,
    non_301_redirects = 55L, redirec_chains = 56L, errors_404 = 0L,
    mobile_url_inconsisten = 0L, hreflang_missing = 731L), .Names = c("page_title_missing",
"page_title_length", "page_title_duplicates", "meta_desc_missing",
"meta_desc_length", "meta_desc_duplicate", "url_dynamic", "url_underscore",
"url_uppercase", "pagination", "image_alt_missing", "h1_missing",
"h1_multiple", "meta_keyword_present", "https_missing", "non_canonical",
"meta_no_index", "meta_no_follow", "content_duplication", "content_depth",
"non_301_redirects", "redirec_chains", "errors_404", "mobile_url_inconsisten",
"hreflang_missing"), row.names = c(NA, -1L), class = "data.frame")
</code>```

答:
I would transpose the data with t() and then feed in the rownames() as the x and V1 as the y into the ggplot. in the geom_bar(), stat = 'identity' signifies to use the values as the bar length

```<code>library(ggplot2)
library(dplyr)

audit_count <- t(audit_count) %>% as.data.frame
ggplot(audit_count, aes(x = rownames(audit_count), y = V1)) + geom_bar(stat = 'identity') + coord_flip()
</code>```

Body:
I'm trying to create a barchart in ggplot2, I have a dataframe that has column names and associated numeric values, but I keep running into unexpected errors creating the dataframe:

ggplot(audit_count,aes(x=colnames(audit_count),y=audit_count[1,])) +geom_bar()

gives me error message

Error: Aesthetics must be either length 1 or the same as the data (1): x, y

But this error message doesnt make sense to me, as colnames(audit_count) and audit_count[1,] are the same length.

Is there some kind of transform I need to do to my data to get it to plot as barchart with the column names as bar names, and the numeric values as y values?

Data below:

structure(list(page_title_missing = 56L, page_title_length = 164L,
    page_title_duplicates = 630L, meta_desc_missing = 703L, meta_desc_length = 0L,
    meta_desc_duplicate = 28L, url_dynamic = 397L, url_underscore = 26L,
    url_uppercase = 701L, pagination = 0L, image_alt_missing = 223L,
    h1_missing = 56L, h1_multiple = 427L, meta_keyword_present = 0L,
    https_missing = 0L, non_canonical = 293L, meta_no_index = 0L,
    meta_no_follow = 0L, content_duplication = 617L, content_depth = 461L,
    non_301_redirects = 55L, redirec_chains = 56L, errors_404 = 0L,
    mobile_url_inconsisten = 0L, hreflang_missing = 731L), .Names = c("page_title_missing",
"page_title_length", "page_title_duplicates", "meta_desc_missing",
"meta_desc_length", "meta_desc_duplicate", "url_dynamic", "url_underscore",
"url_uppercase", "pagination", "image_alt_missing", "h1_missing",
"h1_multiple", "meta_keyword_present", "https_missing", "non_canonical",
"meta_no_index", "meta_no_follow", "content_duplication", "content_depth",
"non_301_redirects", "redirec_chains", "errors_404", "mobile_url_inconsisten",
"hreflang_missing"), row.names = c(NA, -1L), class = "data.frame")

Body:
I would transpose the data with t() and then feed in the rownames() as the x and V1 as the y into the ggplot. in the geom_bar(), stat = 'identity' signifies to use the values as the bar length

library(ggplot2)
library(dplyr)

audit_count <- t(audit_count) %>% as.data.frame
ggplot(audit_count, aes(x = rownames(audit_count), y = V1)) + geom_bar(stat = 'identity') + coord_flip()


问:
2 groupby in the same dataframe, it is possible?
I want to the following df, to make a df = df.groupby(['id','quarter'])['jobs].mean() but at the same time that dataframe must have the mean of jobs by id and year in another column.

```<code> id    year   quarter    month    jobs
  1    2007      1         1        10
  1    2007      1         2        12
  1    2007      1         3        12
  1    2007      2         4        12
  1    2007      2         5        12
  1    2007      2         6        13
  1    2007      3         7        14
  1    2007      3         8         9
  1    2007      3         9        12
  1    2007      4         10       15
  1    2007      4         12       18
  2    2007      1         1        15
  2    2007      1         2        15
  2    2007      1         3        16
  2    2007      2         4        17
  2    2007      2         5        18
  2    2007      2         6        10
  2    2007      3         7        12
  2    2007      3         8        12
  2    2007      3         9        12
  2    2007      4         10       12
  2    2007      4         11       13
  2    2007      4         12       14
</code>```

result should look like this

```<code> id    year   quarter         jobs         jobs_year
  1    2007      1       (mean quarter)   (mean year)
  1    2007      2       (mean quarter)   (mean year)
  1    2007      3       (mean quarter)   (mean year)
  1    2007      4       (mean quarter)   (mean year)
  2    2007      1       (mean quarter)   (mean year)
  2    2007      2       (mean quarter)   (mean year)
  2    2007      3       (mean quarter)   (mean year)
  2    2007      4       (mean quarter)   (mean year)
</code>```

Body:
I want to the following df, to make a df = df.groupby(['id','quarter'])['jobs].mean() but at the same time that dataframe must have the mean of jobs by id and year in another column.

 id    year   quarter    month    jobs
  1    2007      1         1        10
  1    2007      1         2        12
  1    2007      1         3        12
  1    2007      2         4        12
  1    2007      2         5        12
  1    2007      2         6        13
  1    2007      3         7        14
  1    2007      3         8         9
  1    2007      3         9        12
  1    2007      4         10       15
  1    2007      4         12       18
  2    2007      1         1        15
  2    2007      1         2        15
  2    2007      1         3        16
  2    2007      2         4        17
  2    2007      2         5        18
  2    2007      2         6        10
  2    2007      3         7        12
  2    2007      3         8        12
  2    2007      3         9        12
  2    2007      4         10       12
  2    2007      4         11       13
  2    2007      4         12       14

result should look like this

 id    year   quarter         jobs         jobs_year
  1    2007      1       (mean quarter)   (mean year)
  1    2007      2       (mean quarter)   (mean year)
  1    2007      3       (mean quarter)   (mean year)
  1    2007      4       (mean quarter)   (mean year)
  2    2007      1       (mean quarter)   (mean year)
  2    2007      2       (mean quarter)   (mean year)
  2    2007      3       (mean quarter)   (mean year)
  2    2007      4       (mean quarter)   (mean year)

Body:
Using transform then drop_duplicates

df['jobs1']=df.groupby(['id','quarter'])['jobs'].transform('mean')
df['jobs_year']=df.groupby(['id','year'])['jobs'].transform('mean')
df=df.drop_duplicates(['id','year','quarter'])
df
Out[305]:
    id  year  quarter  month  jobs      jobs1  jobs_year
0    1  2007        1      1    10  11.333333  12.636364
3    1  2007        2      4    12  12.333333  12.636364
6    1  2007        3      7    14  11.666667  12.636364
9    1  2007        4     10    15  16.500000  12.636364
11   2  2007        1      1    15  15.333333  13.833333
14   2  2007        2      4    17  15.000000  13.833333
17   2  2007        3      7    12  12.000000  13.833333
20   2  2007        4     10    12  13.000000  13.833333


问:
jQuery – "Read More" span not reappearing after clicking "Read Less"
I'm setting up a portfolio website with project descriptions that are previewed with an excerpt and reveal the full details upon clicking "Read More." I'm pretty new to jQuery but I got it working so that you click "Read More," the paragraph shows up with a "Close" span at the end, and then you click "Close" and it disappears. The problem is "Read More" doesn't reappear after the paragraph is hidden.

https://codepen.io/anon/pen/OOegJx

```<code><div class="project-description">
    <p class="excerpt">Excerpt goes here.</p>
    <span class="read-more open">Read More</span>
    <p class="full hidden">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   <span class="read-more close">Close</span></p>
</div>

.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: block;
}

$(document).ready(function(){
  $('.open').click(function() {
     $(this).siblings('.full').removeClass('hidden');
     $(this).css('display', 'none');
  })

  $('.close').click(function() {
     $(this).parent('.full').addClass('hidden');
     $(this).parent('.open').css('display', 'block');
  })
});
</code>```

(My site is one-page, so I tried to write the JS in a way that won't open up all of my other project's descriptions, just the one I clicked "Read More" on. Not sure if that affects finding a solution)

答:
.open is not a parent of .close - so you need to select it as follows: </p>

```<code>$(this).parent().siblings('.open').css('display', 'block');
</code>```

Body:
I'm setting up a portfolio website with project descriptions that are previewed with an excerpt and reveal the full details upon clicking "Read More." I'm pretty new to jQuery but I got it working so that you click "Read More," the paragraph shows up with a "Close" span at the end, and then you click "Close" and it disappears. The problem is "Read More" doesn't reappear after the paragraph is hidden.

https://codepen.io/anon/pen/OOegJx

Excerpt goes here.

    Read More

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   Close

.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: block;
}

$(document).ready(function(){
  $('.open').click(function() {
     $(this).siblings('.full').removeClass('hidden');
     $(this).css('display', 'none');
  })

  $('.close').click(function() {
     $(this).parent('.full').addClass('hidden');
     $(this).parent('.open').css('display', 'block');
  })
});

(My site is one-page, so I tried to write the JS in a way that won't open up all of my other project's descriptions, just the one I clicked "Read More" on. Not sure if that affects finding a solution)

Body:
.open is not a parent of .close - so you need to select it as follows:

$(this).parent().siblings('.open').css('display', 'block');


问:
How to count individual user selections in a while loop
I would like to know how to count the number of times a user selects a specific option within a while loop. The user is selecting location, and I need to keep track of how many times this location is selected. What's the best way to do this without using an array? For example, I want to keep track of each time the while loop processes, how many London, Rome, or Key West options are selected. </p>

```<code>locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
    }
    if (locationSelection == 'Q') {
        break;
    }
</code>```

答:
```<code>System.out.printf("Total London Vacations: %d", counterLondon);
System.out.printf("Total Rome Vacations: %d", counterRome );
System.out.printf("Total Key West Vacations: %d", counterKeyWest );
</code>```

Body:
I would like to know how to count the number of times a user selects a specific option within a while loop. The user is selecting location, and I need to keep track of how many times this location is selected. What's the best way to do this without using an array? For example, I want to keep track of each time the while loop processes, how many London, Rome, or Key West options are selected.

locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
    }
    if (locationSelection == 'Q') {
        break;
    }


问:
Form Fields outside dropzone box
I am using dropzone.js for drag and drop file upload. I also have two fields and a submit button, but they only appear in the preview pane despite it being in it's own
 tag. I would like it to appear below the

CSS:

```<code>    #attachmentdropzone {
        cursor: pointer;
        border: 3px dashed #0000FF;
        padding: 30px 0;
    }
</code>```

HTML:

```<code><div class="container">
<form action="{{ url_for('upload') }}" method="POST" class="dropzone" enctype="multipart/form-data"
      id="attachmentdropzone">

    <div class="dropzone-previews"></div>
    <div class="container">

        <input type="email" name="username"/>
        <input type="password" name="password"/>

        <button type="submit">Submit data and files!</button>
    </div>
</form>
</code>```

Current layout that I'd like to fix. I would like the form fields and button outside the blue dotted line.

EDIT: in a fiddle: https://jsfiddle.net/boavzunL/

答:
I have added a following CSS Class(Your Example):</p>

```<code>.container {
     position: absolute;
    margin-top: 75px;
    width:100%;
}
</code>```

Title: Form Fields outside dropzone box

Body:
I am using dropzone.js for drag and drop file upload. I also have two fields and a submit button, but they only appear in the preview pane despite it being in it's own
 tag. I would like it to appear below the

CSS:

    #attachmentdropzone {
        cursor: pointer;
        border: 3px dashed #0000FF;
        padding: 30px 0;
    }

HTML:

<form action="{{ url_for('upload') }}" method="POST" class="dropzone" enctype="multipart/form-data"
      id="attachmentdropzone">

        <input type="email" name="username"/>
        <input type="password" name="password"/>

        <button type="submit">Submit data and files!</button>

</form>

Current layout that I'd like to fix. I would like the form fields and button outside the blue dotted line.

EDIT: in a fiddle: https://jsfiddle.net/boavzunL/

Body:
I have added a following CSS Class(Your Example):

.container {
     position: absolute;
    margin-top: 75px;
    width:100%;
}


问:
Select values that meet different conditions on different rows?
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

```<code>userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1
</code>```

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

答:
```<code>SELECT userid
FROM UserRole
WHERE roleid IN (1, 2, 3)
GROUP BY userid
HAVING COUNT(DISTINCT roleid) = 3;
</code>```

To anyone reading this:  my answer is simple and straightforward, and got the 'accepted' status, but please do go read the answer given by @cletus.  It has much better performance.

Justing thinking out loud, another way to write the self-join described by @cletus is:

```<code>SELECT t1.userid
FROM userrole t1
JOIN userrole t2 ON t1.userid = t2.userid
JOIN userrole t3 ON t2.userid = t3.userid
WHERE (t1.roleid, t2.roleid, t3.roleid) = (1, 2, 3);
</code>```

This might be easier to read for you, and MySQL supports comparisons of tuples like that.  MySQL also knows how to utilize covering indexes intelligently for this query.  Just run it through EXPLAIN and see "Using index" in the notes for all three tables, which means it's reading the index and doesn't even have to touch the data rows.

I ran this query over 2.1 million rows (the Stack Overflow July data dump for PostTags) using MySQL 5.1.48 on my Macbook, and it returned the result in 1.08 sec.  On a decent server with enough memory allocated to innodb_buffer_pool_size, it should be even faster.

OwnerDisplayName: John

Body:
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

LastEditorDisplayName: John

Body:
SELECT userid
FROM UserRole
WHERE roleid IN (1, 2, 3)
GROUP BY userid
HAVING COUNT(DISTINCT roleid) = 3;

To anyone reading this:  my answer is simple and straightforward, and got the 'accepted' status, but please do go read the answer given by @cletus.  It has much better performance.

Justing thinking out loud, another way to write the self-join described by @cletus is:

SELECT t1.userid
FROM userrole t1
JOIN userrole t2 ON t1.userid = t2.userid
JOIN userrole t3 ON t2.userid = t3.userid
WHERE (t1.roleid, t2.roleid, t3.roleid) = (1, 2, 3);

This might be easier to read for you, and MySQL supports comparisons of tuples like that.  MySQL also knows how to utilize covering indexes intelligently for this query.  Just run it through EXPLAIN and see "Using index" in the notes for all three tables, which means it's reading the index and doesn't even have to touch the data rows.

I ran this query over 2.1 million rows (the Stack Overflow July data dump for PostTags) using MySQL 5.1.48 on my Macbook, and it returned the result in 1.08 sec.  On a decent server with enough memory allocated to innodb_buffer_pool_size, it should be even faster.

OwnerDisplayName: Bill Karwin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Bill Karwin


问:
base64 encoded powershell "Cannot index into a null array." but runs from ISE
We're working on protecting files with RMS in our environment. We have to use PowerShell.

I can't even use WDS server with MDT joined to the domain as the psxml files it uses aren't signed.

I have to run PS scripts as single line commands or as encoded commands using the
    [convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
   line with my script wrapped in $code = {}.

This script works when run from PowerShell ISE.

```<code>$lines = Get-Content E:\folder\list.txt | Select-String -Pattern "Success Message" -AllMatches -Context 1,0 | % $_.Context.PreContext[0]
    foreach ( $line in $lines ) {
        $file = $line.ToString().TrimStart("chars. ")
        Protect-RMSFile -File $file -InPlace -DoNotPersistEncryptionKey All -TemplateID "template-ID" -OwnerEmail "admin@domain.com" | Out-File -FilePath E:\folder\logs\results.log -Append
        }
</code>```

Batch script:

```<code>"e:\folder\command.exe -switches" > "E:\folder\list.txt"

powershell.exe -EncodedCommand encodedBlob
</code>```

Output:

```<code>Cannot index into a null array.
At line:3 char:1
+ $lines = Get-Content E:\folder\list.txt | Select-String      -Pattern "S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
</code>```

I saw on another question an exception log of some sort may be of assistance...

```<code>$Error.Exception | Where-Object -Property Message -Like "Cannot index into a null array." | Format-List -Force | Out-File -FilePath E:\folder\err.log
</code>```

Output:

```<code>ErrorRecord                 : Cannot index into a null array.
StackTrace                  :    at CallSite.Target(Closure , CallSite , Object , Int32 )
                             at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
                             at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
                             at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                             at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
WasThrownFromThrowStatement : False
Message                     : Cannot index into a null array.
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              :
TargetSite                  : System.Object CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object,
                              Int32)
HelpLink                    :
Source                      : Anonymously Hosted DynamicMethods Assembly
HResult                     : -2146233087
</code>```

Thinking it was something as simple as NTFS permissions, I took owner and replaced all permissions on this folder structure with admin and me full control. No change in the error.

Any tips? Am I overlooking something simple?

答:
Your ForEach-Object call (% $_) doesn't make any sense and was causing the issue.

```<code>$Lines = Select-String -LiteralPath 'E:\folder\list.txt' -Pattern 'success\smessage' -AllMatches -Context 1,0

ForEach ($Line in $Lines.Context.PreContext)
{
    $File = $Line.TrimStart('chars. ')
    Protect-RMSFile -File $File -InPlace -DoNotPersistEncryptionKey 'All' -TemplateID 'template-ID' -OwnerEmail 'admin@domain.com' |
        Out-File -FilePath 'E:\folder\logs\results.log' -Append
}
</code>```

One-liner-esque (suitable for encoding):

```<code>SLS 'success\smessage' 'E:\folder\list.txt' -AllMatches -Context 1,0 |
  % { Protect-RMSFile -File $_.Context.PreContext.TrimStart('chars. ') -InPlace -DoNotPersistEncryptionKey 'All' -TemplateID 'template-ID' -OwnerEmail 'admin@domain.com' |
  Out-File 'E:\folder\logs\results.log' -Append
</code>```

In this example, I've utilized aliases and positionally-bound parameters to make the code shorter.

Body:
We're working on protecting files with RMS in our environment. We have to use PowerShell.

I can't even use WDS server with MDT joined to the domain as the psxml files it uses aren't signed.

I have to run PS scripts as single line commands or as encoded commands using the
    [convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
   line with my script wrapped in $code = {}.

This script works when run from PowerShell ISE.

$lines = Get-Content E:\folder\list.txt | Select-String -Pattern "Success Message" -AllMatches -Context 1,0 | % $_.Context.PreContext[0]
    foreach ( $line in $lines ) {
        $file = $line.ToString().TrimStart("chars. ")
        Protect-RMSFile -File $file -InPlace -DoNotPersistEncryptionKey All -TemplateID "template-ID" -OwnerEmail "admin@domain.com" | Out-File -FilePath E:\folder\logs\results.log -Append
        }

Batch script:

"e:\folder\command.exe -switches" > "E:\folder\list.txt"

powershell.exe -EncodedCommand encodedBlob

Output:

Cannot index into a null array.
At line:3 char:1
+ $lines = Get-Content E:\folder\list.txt | Select-String      -Pattern "S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

I saw on another question an exception log of some sort may be of assistance...

$Error.Exception | Where-Object -Property Message -Like "Cannot index into a null array." | Format-List -Force | Out-File -FilePath E:\folder\err.log

Output:

ErrorRecord                 : Cannot index into a null array.
StackTrace                  :    at CallSite.Target(Closure , CallSite , Object , Int32 )
                             at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
                             at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
                             at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                             at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
WasThrownFromThrowStatement : False
Message                     : Cannot index into a null array.
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              :
TargetSite                  : System.Object CallSite.Target(System.Runtime.CompilerServices.Closure, System.Runtime.CompilerServices.CallSite, System.Object,
                              Int32)
HelpLink                    :
Source                      : Anonymously Hosted DynamicMethods Assembly
HResult                     : -2146233087

Thinking it was something as simple as NTFS permissions, I took owner and replaced all permissions on this folder structure with admin and me full control. No change in the error.

Any tips? Am I overlooking something simple?

Body:
Your ForEach-Object call (% $_) doesn't make any sense and was causing the issue.

$Lines = Select-String -LiteralPath 'E:\folder\list.txt' -Pattern 'success\smessage' -AllMatches -Context 1,0

ForEach ($Line in $Lines.Context.PreContext)
{
    $File = $Line.TrimStart('chars. ')
    Protect-RMSFile -File $File -InPlace -DoNotPersistEncryptionKey 'All' -TemplateID 'template-ID' -OwnerEmail 'admin@domain.com' |
        Out-File -FilePath 'E:\folder\logs\results.log' -Append
}

One-liner-esque (suitable for encoding):

SLS 'success\smessage' 'E:\folder\list.txt' -AllMatches -Context 1,0 |
  % { Protect-RMSFile -File $_.Context.PreContext.TrimStart('chars. ') -InPlace -DoNotPersistEncryptionKey 'All' -TemplateID 'template-ID' -OwnerEmail 'admin@domain.com' |
  Out-File 'E:\folder\logs\results.log' -Append

In this example, I've utilized aliases and positionally-bound parameters to make the code shorter.


问:
Display FCM notification message in Listview onClicking Notification
I have successfully sent Firebase notifications using my own server to Android app and I want to listing the messages in a ListView in a new activity by clicking the notification. what i shoud do to notification messages are getting displayed in ListView , I want to help complete this work.

FirebaseMessageservice.java:

```<code>    public class FcmMessagingService extends FirebaseMessagingService {
    private Map<String, String> data;
    private static final String TAG="MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        data=remoteMessage.getData();
        String message=data.get("message");
        String titledata=data.get("title");
        ManualNotification(titledata , message);

        Set<String> noti_set = PreferenceManager.getDefaultSharedPreferences(context).getStringSet("noti_set", new HashSet<String>());
        Set<String> set = new HashSet<String>();
        set.add(titledata+"---"+message);
        set.addAll(noti_set);
        PreferenceManager.getDefaultSharedPreferences(context).edit().putStringSet("noti_set", set).apply();

    }
private void ManualNotification(String title , String messageBody){
        Intent intent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("message", messageBody);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        long[] vv = {500,1000};
        Bitmap bmp = BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher);
        Notification.BigPictureStyle bigpicture = new Notification.BigPictureStyle();
        bigpicture.bigPicture(bmp);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setLargeIcon(bmp)
                .setSound(defaultSoundUri)
                .setVibrate(vv)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}
</code>```

FcmInstanceIdService.java:

```<code>  public class FcmInstanceIdService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
@Override
public void onTokenRefresh() {
    String recent_token= FirebaseInstanceId.getInstance().getToken();
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("FCM_TOKEN",recent_token);
    editor.apply();
    Log.d(REG_TOKEN,recent_token);
}
</code>```

lst.java:

```<code>   public class lst {
private String title;
private String message;

public lst() {
}

public lst(String title, String message) {
    this.title = title;
    this.message = message;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getmessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
</code>```

}
Messages.java:

```<code>  public class Messages extends AppCompatActivity {

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

    Set<String> noti_set = PreferenceManager.getDefaultSharedPreferences(context).getStringSet("noti_set", new HashSet<String>());
    for (String noti : noti_set){
            String title = noti.splite("---")[0];
            String message = noti.splite("---")[1];
            list.add(new lst(title,message));
            adapter.notifyDataSetChanged();
    }

}
</code>```

}

答:
Firstly,

I will recommend you to use RecyclerView instead of ListView to show the list of Notifications.
More info on how to get started here

Secondly,

onMessageRecieved(...) is only triggered/fired when your app is in Foreground so if your app is in background the notification will be received but it won't get appended to the shared preferences.

Lastly

Instead on listing/storing the notification on client side, do it in server side. If you are using Firebase I recommend you to put all the notification in a Real time database and retrieve it from there when you want it.

Body:
I have successfully sent Firebase notifications using my own server to Android app and I want to listing the messages in a ListView in a new activity by clicking the notification. what i shoud do to notification messages are getting displayed in ListView , I want to help complete this work.

FirebaseMessageservice.java:

    public class FcmMessagingService extends FirebaseMessagingService {
    private Map<String, String> data;
    private static final String TAG="MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        data=remoteMessage.getData();
        String message=data.get("message");
        String titledata=data.get("title");
        ManualNotification(titledata , message);

        Set<String> noti_set = PreferenceManager.getDefaultSharedPreferences(context).getStringSet("noti_set", new HashSet<String>());
        Set<String> set = new HashSet<String>();
        set.add(titledata+"---"+message);
        set.addAll(noti_set);
        PreferenceManager.getDefaultSharedPreferences(context).edit().putStringSet("noti_set", set).apply();

    }
private void ManualNotification(String title , String messageBody){
        Intent intent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("message", messageBody);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        long[] vv = {500,1000};
        Bitmap bmp = BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher);
        Notification.BigPictureStyle bigpicture = new Notification.BigPictureStyle();
        bigpicture.bigPicture(bmp);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setLargeIcon(bmp)
                .setSound(defaultSoundUri)
                .setVibrate(vv)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

FcmInstanceIdService.java:

  public class FcmInstanceIdService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
@Override
public void onTokenRefresh() {
    String recent_token= FirebaseInstanceId.getInstance().getToken();
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("FCM_TOKEN",recent_token);
    editor.apply();
    Log.d(REG_TOKEN,recent_token);
}

lst.java:

   public class lst {
private String title;
private String message;

public lst() {
}

public lst(String title, String message) {
    this.title = title;
    this.message = message;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getmessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

}
Messages.java:

  public class Messages extends AppCompatActivity {

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

    Set<String> noti_set = PreferenceManager.getDefaultSharedPreferences(context).getStringSet("noti_set", new HashSet<String>());
    for (String noti : noti_set){
            String title = noti.splite("---")[0];
            String message = noti.splite("---")[1];
            list.add(new lst(title,message));
            adapter.notifyDataSetChanged();
    }

}

}


问:
Interval for output messages node.js
So many messages. How i can do periodical output?</p>

```<code>ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    console.log( objj.ui_price);
);
</code>```

答:
Implement a buffer and periodically print and dump the buffer. For example:</p>

```<code>var buffer = [];
ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    buffer.push(objj.ui_price);
    if(buffer.length >= 20) {
        console.log(buffer);
        buffer = [];
    }
});
</code>```

Title: Interval for output messages node.js

Body:
So many messages. How i can do periodical output?

ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    console.log( objj.ui_price);
);

Body:
Implement a buffer and periodically print and dump the buffer. For example:

var buffer = [];
ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    buffer.push(objj.ui_price);
    if(buffer.length >= 20) {
        console.log(buffer);
        buffer = [];
    }
});


问:
regexp_substr Finding two letter words
I have a address field in Oracle from where I need o extract the State Code.

```<code>select  '111 BROADWAY ~ ST LOUIS, WA 58585' from dual
union
select  '111 BROADWAY ~ ST LOUIS, WA' from dual
union
select  '111 BROADWAY ~ ST LOUIS,58585 WA' from dual
</code>```

Sometimes the state code WA is before Postal Code and some times after.
Also in some cases the Postal code is not present.

Need help to extract WA in all these cases.

答:
Place United States State Abbreviation Code (2 Letters) in Pattern Parameter

This is just a permutation of mathguy's answer.  Since we have defined and relatively short list of states codes, we could place the state codes (from usps website) in the pattern parameter and separate them using the alternation operator.

```<code>SCOTT@db>WITH tst AS (
  2      SELECT
  3          '111 BROADWAY ~ ST LOUIS, WA 58585' us_addrss
  4      FROM
  5          dual
  6      UNION ALL
  7      SELECT
  8          '111 BROADWAY ~ ST LOUIS, WA' us_addrss
  9      FROM
 10          dual
 11      UNION ALL
 12      SELECT
 13          '111 BROADWAY ~ ST LOUIS,58585 WA' us_addrss
 14      FROM
 15          dual
 16  ) SELECT
 17      regexp_substr(t.us_addrss,'( |,)(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)( |$)' state_code
 18  ,1,1,'c',2)
 19    FROM
 20      tst t;
state_code
------
WA
WA
WA
</code>```

Other 2 letter matches will not be included.  Also, my match parameter used, 'c', calls for the case to match.

This case requirement was not identified, but looks like it is consistent based on samples provided.

More explanation:

-My match pattern uses three character groupings and I reference the 2nd one in the sub-expression parameter.

-I check for a space or a comma preceding the two letter code.  From your example, you always had a space preceding the state code.

-I check for a space or the column ending after the state code.

Title: regexp_substr Finding two letter words

Body:
I have a address field in Oracle from where I need o extract the State Code.

select  '111 BROADWAY ~ ST LOUIS, WA 58585' from dual
union
select  '111 BROADWAY ~ ST LOUIS, WA' from dual
union
select  '111 BROADWAY ~ ST LOUIS,58585 WA' from dual

Sometimes the state code WA is before Postal Code and some times after.
Also in some cases the Postal code is not present.

Need help to extract WA in all these cases.

Body:
Place United States State Abbreviation Code (2 Letters) in Pattern Parameter

This is just a permutation of mathguy's answer.  Since we have defined and relatively short list of states codes, we could place the state codes (from usps website) in the pattern parameter and separate them using the alternation operator.

SCOTT@db>WITH tst AS (
  2      SELECT
  3          '111 BROADWAY ~ ST LOUIS, WA 58585' us_addrss
  4      FROM
  5          dual
  6      UNION ALL
  7      SELECT
  8          '111 BROADWAY ~ ST LOUIS, WA' us_addrss
  9      FROM
 10          dual
 11      UNION ALL
 12      SELECT
 13          '111 BROADWAY ~ ST LOUIS,58585 WA' us_addrss
 14      FROM
 15          dual
 16  ) SELECT
 17      regexp_substr(t.us_addrss,'( |,)(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)( |$)' state_code
 18  ,1,1,'c',2)
 19    FROM
 20      tst t;
state_code
------
WA
WA
WA

Other 2 letter matches will not be included.  Also, my match parameter used, 'c', calls for the case to match.

This case requirement was not identified, but looks like it is consistent based on samples provided.

More explanation:

-My match pattern uses three character groupings and I reference the 2nd one in the sub-expression parameter.

-I check for a space or a comma preceding the two letter code.  From your example, you always had a space preceding the state code.

-I check for a space or the column ending after the state code.


答:
You can use union all:

```<code>select s, a, m, q
from mycount
union all
select s, a, m, 0
from catalog as c
where not exists (select 1
                  from mycount as mc
                  where mc.s = c.s and mc.a = c.a and mc.m = c.m
                 );
</code>```

Title: union access query

Body:
i have union question on access.

i have table MyCount

S | A | M | Q
=============
1 |10 |111| 4
1 |10 |222| 5
1 |10 |333| 9
1 |20 |444|10

I have table Catalog

S | A | M |
=============
1 |10 |111|
1 |10 |222|
1 |10 |333|
1 |10 |444|
1 |10 |555|
1 |20 |999|
1 |20 |888|
1 |20 |777|

i need all the data from MyCount with the Catalog - but if data on MyCount

not in Catalog, it will came with Qty=0

i need union query that the resault will looks like this:

S | A | M | Q
=============
1 |10 |111| 4
1 |10 |222| 5
1 |10 |333| 9
1 |10 |444| 0
1 |10 |555| 0
1 |20 |999|10
1 |20 |888| 0
1 |20 |777| 0

Body:
You can use union all:

select s, a, m, q
from mycount
union all
select s, a, m, 0
from catalog as c
where not exists (select 1
                  from mycount as mc
                  where mc.s = c.s and mc.a = c.a and mc.m = c.m
                 );


问:
CMake generates project twice
I'm grouping sources in folders by some rules and I want to be able to individually test each group in isolation for faster iteration. To do so I want to CMake to generate one executable for each group. I simplified the project structure to:

```<code>root
    build
    group_1
        CMakeLists.txt
        group_1_file_1.cpp
        group_1_tests
            CMakeLists.txt
            group_1_file_1_tests.cpp
</code>```

where group_1/CMakeLists.txt is:

```<code>SET(group_1_srcs
    ${CMAKE_CURRENT_SOURCE_DIR}/group_1_file_1.cpp
)

#Generate standalone application for unit tests when cmake is started with this CMakeLists as root
IF(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    ADD_SUBDIRECTORY("group_1_tests/")
ENDIF()
</code>```

and group_1/group_1_tests/CMakeLists.txt is

```<code>PROJECT(group_1_tests)
SET(group_1_tests_srcs
    ${CMAKE_CURRENT_SOURCE_DIR}/group_1_file_1_tests.cpp
)
ADD_EXECUTABLE(${PROJECT_NAME} "${group_1_tests_srcs}" "${group_1_srcs}")
</code>```

Running cmake ../group_1 from root/build/ generates me the project I want, root/build/group_1_tests/group_1_tests.sln, but also root/build/Project.sln with the same files & settings as the previous one.

Can you please explain why this projects gets generate and how may I avoid it?

答:
The answer is in the project() command documentation:

The top-level CMakeLists.txt file for a project must contain a literal, direct call to the project() command ... If no such call exists CMake will implicitly add one to the top that enables the default languages (C and CXX).

So Project is the default project's name. And from that point onward CMake generates a .sln solution for all CMakeLists.txt containing another project() command.

I would recommend you ignore the root solution file (if you don't want it) or restructure your project to have a single project() command call in the root CMakeList.txt (since your sub-level project won't run standalone without the top-level project anyway).

References

CMake Commit: ENH: generate a sln and dsw file for each sub project in a project

Title: CMake generates project twice

Body:
I'm grouping sources in folders by some rules and I want to be able to individually test each group in isolation for faster iteration. To do so I want to CMake to generate one executable for each group. I simplified the project structure to:

root
    build
    group_1
        CMakeLists.txt
        group_1_file_1.cpp
        group_1_tests
            CMakeLists.txt
            group_1_file_1_tests.cpp

where group_1/CMakeLists.txt is:

SET(group_1_srcs
    ${CMAKE_CURRENT_SOURCE_DIR}/group_1_file_1.cpp
)

#Generate standalone application for unit tests when cmake is started with this CMakeLists as root
IF(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    ADD_SUBDIRECTORY("group_1_tests/")
ENDIF()

and group_1/group_1_tests/CMakeLists.txt is

PROJECT(group_1_tests)
SET(group_1_tests_srcs
    ${CMAKE_CURRENT_SOURCE_DIR}/group_1_file_1_tests.cpp
)
ADD_EXECUTABLE(${PROJECT_NAME} "${group_1_tests_srcs}" "${group_1_srcs}")

Running cmake ../group_1 from root/build/ generates me the project I want, root/build/group_1_tests/group_1_tests.sln, but also root/build/Project.sln with the same files & settings as the previous one.

Can you please explain why this projects gets generate and how may I avoid it?


问:
mysql: SOURCE error 2?
When I tried to source for a particular .sql file, namely 'metropolises.sql' that I created and saved previously from a database, the following error is displayed:

Failed to open file 'metropolises.sql', error: 2

Any idea what went wrong?

答:
For me it was because the file was located on a shared drive and it could not access, for some reason, to that path.
I cut the file and put it on my local drive in a path without spaces and it got resolved.</p>

Title: mysql: SOURCE error 2?


问:
Adjust table widths for pdf output to perfectly fit the line width
My company uses Sphinx to create our user manuals and we are making extensive usage of tables in different varieties. In many cases it is necessary to adjust the column widths of the tables manually in order to generate a high quality pdf output.

For this I tried to use:

```<code>.. tabularcolumns:: |p{0.2\linewidth}|p{0.8\linewidth}|

+------+--------+
| A    | B      |
+------+--------+
</code>```

My intention was, that the table should perfectly fit the surrounding text,
but there is a little overlap. Seemingly the percentages do not account for the space occupied by the inner boxes.

How can I correctly compute the necessary amount, so that the box fits neatly to the space?

答:
With Sphinx 1.6 or later, you can use

```<code>.. tabularcolumns:: |\Y{0.2}|\Y{0.8}|
</code>```

(it is \Y, not Y.) See http://www.sphinx-doc.org/en/stable/markup/misc.html?highlight=tabularcolumns#directive-tabularcolumns.

With Sphinx 1.5 or later you can use |\X{2}{10}|\X{8}{10}|.

With Sphinx < 1.5 you need some special LaTeX, which you can extract from this code

```<code>\newcolumntype{\X}[2]{p{\dimexpr
      (\linewidth-\arrayrulewidth)*#1/#2-2\tabcolsep-\arrayrulewidth\relax}}
\newcolumntype{\Y}[1]{p{\dimexpr
      #1\dimexpr\linewidth-\arrayrulewidth\relax-2\tabcolsep-\arrayrulewidth\relax}}
</code>```

from current sphinx.sty, which explains how the \X and \Y are defined.

Body:
My company uses Sphinx to create our user manuals and we are making extensive usage of tables in different varieties. In many cases it is necessary to adjust the column widths of the tables manually in order to generate a high quality pdf output.

For this I tried to use:

.. tabularcolumns:: |p{0.2\linewidth}|p{0.8\linewidth}|

+------+--------+
| A    | B      |
+------+--------+

My intention was, that the table should perfectly fit the surrounding text,
but there is a little overlap. Seemingly the percentages do not account for the space occupied by the inner boxes.

How can I correctly compute the necessary amount, so that the box fits neatly to the space?

Body:
With Sphinx 1.6 or later, you can use

.. tabularcolumns:: |\Y{0.2}|\Y{0.8}|

(it is \Y, not Y.) See http://www.sphinx-doc.org/en/stable/markup/misc.html?highlight=tabularcolumns#directive-tabularcolumns.

With Sphinx 1.5 or later you can use |\X{2}{10}|\X{8}{10}|.

With Sphinx < 1.5 you need some special LaTeX, which you can extract from this code

\newcolumntype{\X}[2]{p{\dimexpr
      (\linewidth-\arrayrulewidth)*#1/#2-2\tabcolsep-\arrayrulewidth\relax}}
\newcolumntype{\Y}[1]{p{\dimexpr
      #1\dimexpr\linewidth-\arrayrulewidth\relax-2\tabcolsep-\arrayrulewidth\relax}}

from current sphinx.sty, which explains how the \X and \Y are defined.


问:
AWS uploading image results in uploading empty file
I am trying to upload image after processing it with PHP to AWS. When I try to upload image that is already in the folder on my server the image uploads with no issue. However adding the same script into script that process uploaded image (which works saving images locally, creating cropped version and uploading link to them to local db), resize it and after reading exif data rotates correctly I only upload empty file (correctly named) that does not look like na image (downloading it from AWS I get error message that the image is broken) and after inspecting it it usually has only around 76b. What gives? Does that mean that the script needs some time to process the resizing / rotating information and therefore it uploads image that is half ready? I do not get any error messages or warnings back.

My script for the local file upload:

```<code>try{
    $result = $s3->putObject([
        'Bucket'     => $config['s3']['bucket'],
        'Key'        => 'uploads/test.jpg',
        'Body' => WWW_ROOT.'/penguin/xcropped/test.jpg',
        'ACL' => 'public-read',
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

$image_path =  $result['ObjectURL'];
</code>```

My script in the resizing and cropping script:

```<code>      require_once('inc/aws_connect.inc.php');

    try{
        $result = $s3->putObject([
            'Bucket'     => $config['s3']['bucket'],
            'Key'        => 'uploads/test2.jpg',
            'Body' => WWW_ROOT.$thumb_path,
            'ACL' => 'public-read',
        ]);
    } catch (S3Exception $e) {
        echo $e->getMessage() . "\n";
    }

    $aws_result = $result['ObjectURL'];

echo $aws_result;
</code>```

Does anyone knows why is this happening and what might be the issue. The images are around 1.7MB size. Is this maybe a problem?

答:
In order for it to correctly work you need to have Guzzle and stream the file over to AWS. This worked for me:</p>

```<code>  use GuzzleHttp\Psr7\Stream;
  use GuzzleHttp\Psr7\CachingStream;

  try{
    $aws_result = $s3->putObject([

  'Bucket'        => $config['s3']['bucket'],
  'Key'           => 'thumbs/thumb_' . $random_string,
  'Body'          => new CachingStream(
      new Stream(fopen(WWW_ROOT.$thumb_path, 'r'))
  ),
  'ACL'           => 'public-read',
  'ContentType'   => 'image/jpg',

  ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

    $aws_result = $aws_result['ObjectURL'];
</code>```

Body:
I am trying to upload image after processing it with PHP to AWS. When I try to upload image that is already in the folder on my server the image uploads with no issue. However adding the same script into script that process uploaded image (which works saving images locally, creating cropped version and uploading link to them to local db), resize it and after reading exif data rotates correctly I only upload empty file (correctly named) that does not look like na image (downloading it from AWS I get error message that the image is broken) and after inspecting it it usually has only around 76b. What gives? Does that mean that the script needs some time to process the resizing / rotating information and therefore it uploads image that is half ready? I do not get any error messages or warnings back.

My script for the local file upload:

try{
    $result = $s3->putObject([
        'Bucket'     => $config['s3']['bucket'],
        'Key'        => 'uploads/test.jpg',
        'Body' => WWW_ROOT.'/penguin/xcropped/test.jpg',
        'ACL' => 'public-read',
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

$image_path =  $result['ObjectURL'];

My script in the resizing and cropping script:

      require_once('inc/aws_connect.inc.php');

    try{
        $result = $s3->putObject([
            'Bucket'     => $config['s3']['bucket'],
            'Key'        => 'uploads/test2.jpg',
            'Body' => WWW_ROOT.$thumb_path,
            'ACL' => 'public-read',
        ]);
    } catch (S3Exception $e) {
        echo $e->getMessage() . "\n";
    }

    $aws_result = $result['ObjectURL'];

echo $aws_result;

Does anyone knows why is this happening and what might be the issue. The images are around 1.7MB size. Is this maybe a problem?

Body:
In order for it to correctly work you need to have Guzzle and stream the file over to AWS. This worked for me:

  use GuzzleHttp\Psr7\Stream;
  use GuzzleHttp\Psr7\CachingStream;

  try{
    $aws_result = $s3->putObject([

  'Bucket'        => $config['s3']['bucket'],
  'Key'           => 'thumbs/thumb_' . $random_string,
  'Body'          => new CachingStream(
      new Stream(fopen(WWW_ROOT.$thumb_path, 'r'))
  ),
  'ACL'           => 'public-read',
  'ContentType'   => 'image/jpg',

  ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

    $aws_result = $aws_result['ObjectURL'];


问:
How to prevent multiple entries for PromptDialog.Number
I am using PromptDialog.Number method in a bot framework dialog class like this:

```<code>PromptDialog.Number(context, ResumeAfterClarification, prompt, min:1, max:3, retry:retryText);
</code>```

This works fine for most part. If a user enters a number that is not between 1 and 3, retryText is displayed and the user has to retry. However, if a user enters numbers separated by commas this is accepted (e.g. 1, 2, 3). The first number is passed to resume method, everything else is ignored.

How can I prevent this? It would make sense that any invalid entry (i.e. any entry that is not a single number between min and max) should be rejected.

Am I missing something here? Can this method accept multiple entries? How are they passed to resume method in a single int64 parameter? I really want to disable this.

答:
As mentioned by Dylan Nicholson in comments, you can inherit PromptInt64 and use a custom TryParse method:

```<code>[Serializable]
public class CustomPromptInt64 : PromptInt64
{
    public CustomPromptInt64(string prompt, string retry, int attempts, long? min = null, long? max = null)
            : base(prompt, retry, attempts, null, min, max)
    {
    }

    protected override bool TryParse(IMessageActivity message, out long result)
    {
        if(Int64.TryParse(message.Text, out result))
        {
            return (result >= this.Min && result <= this.Max);
        }
        return false;
    }
}
</code>```

And use the CustomPromptInt64 in a dialog:

```<code>    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
        return Task.CompletedTask;
    }

   private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {

        var child = new CustomPromptInt64("Number between 1 and 3", "Please try again", 3, min: 1, max: 3);
        context.Call<long>(child, ResumeAfterClarification);
    }

    private async Task ResumeAfterClarification(IDialogContext context, IAwaitable<long> result)
    {
        var number = await result;
        context.Done(true);
    }
</code>```

Body:
I am using PromptDialog.Number method in a bot framework dialog class like this:

PromptDialog.Number(context, ResumeAfterClarification, prompt, min:1, max:3, retry:retryText);

This works fine for most part. If a user enters a number that is not between 1 and 3, retryText is displayed and the user has to retry. However, if a user enters numbers separated by commas this is accepted (e.g. 1, 2, 3). The first number is passed to resume method, everything else is ignored.

How can I prevent this? It would make sense that any invalid entry (i.e. any entry that is not a single number between min and max) should be rejected.

Am I missing something here? Can this method accept multiple entries? How are they passed to resume method in a single int64 parameter? I really want to disable this.

Body:
As mentioned by Dylan Nicholson in comments, you can inherit PromptInt64 and use a custom TryParse method:

[Serializable]
public class CustomPromptInt64 : PromptInt64
{
    public CustomPromptInt64(string prompt, string retry, int attempts, long? min = null, long? max = null)
            : base(prompt, retry, attempts, null, min, max)
    {
    }

    protected override bool TryParse(IMessageActivity message, out long result)
    {
        if(Int64.TryParse(message.Text, out result))
        {
            return (result >= this.Min && result <= this.Max);
        }
        return false;
    }
}

And use the CustomPromptInt64 in a dialog:

    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
        return Task.CompletedTask;
    }

   private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {

        var child = new CustomPromptInt64("Number between 1 and 3", "Please try again", 3, min: 1, max: 3);
        context.Call<long>(child, ResumeAfterClarification);
    }

    private async Task ResumeAfterClarification(IDialogContext context, IAwaitable<long> result)
    {
        var number = await result;
        context.Done(true);
    }


问:
Prevent extra whitespace when piping data in a Windows batch script
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

```<code>@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)
</code>```

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

答:
To get rid of the last character (the whitespace) you can do:

```<code>@echo off
setlocal EnableDelayedExpansion

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
    set "result=%%x"
    (echo 1 & echo !result:~0,-1!)|Z:\Models\LossCalc.exe
)
</code>```

Hope it helps.

Body:
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

Body:
To get rid of the last character (the whitespace) you can do:

@echo off
setlocal EnableDelayedExpansion

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
    set "result=%%x"
    (echo 1 & echo !result:~0,-1!)|Z:\Models\LossCalc.exe
)

Hope it helps.


问:
c++ 2D char array sometimes duplicates data in random position
I am using a 2D char array to display a board on screen. Empty board is fulled with '.' (dots), the program write in a certain position an other char ('G'). The problem is that sometimes (more o less once every four times) a duplicate character appears in an other position.

```<code> 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |G  .  .  .  .  .  |
 1 |.  .  .  .  G  .  |
------------------------
    a  b  c  d  e  f
</code>```

Relevant code fragments are:

```<code>class Field
{
 public:
static const int FIELDWIDTH=6;
static const int FIELDHEIGHT=4;

char field[FIELDWIDTH][FIELDHEIGHT];
..
};

void Field::empty(void){
  for(int r=0; r<FIELDHEIGHT; r++)
    for(int c=0; c<FIELDWIDTH; c++)
      field[r][c] = '.';
};

Field::plot(){                   //Plots the board
for(int r=FIELDHEIGHT;r>0;r--){
    cout << std::setw(2) << std::setfill(' ') << r << " |";
    for(int c=0;c<FIELDWIDTH;c++)
      cout << field[r-1][c] << "  ";
    cout << "|" << endl;
  };
...
};

void Field::putChar(void){
...
(random definition of pr2 and pc2 and validation within limits)
...
 field[pr2][pc2]='G';
 printCors(pr2,pc2); //cout coordinate for debug
...
};
</code>```

The only two assignations to field[][] are ONE in empty() and ONE in putChar(). empty() works as expected always resulting in a plot() so:

```<code> 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f
</code>```

And the assignation in putChar is watched with the cout, which only output just one coordinate, nevertheless SOMETIMES one additional character appears with some relation with the expected one, here some runs:

```<code>b1=
 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  G  .  .  .  .  |
------------------------
    a  b  c  d  e  f

e2=
 4 |.  .  .  .  .  .  |
 3 |G  .  .  .  .  .  |
 2 |.  .  .  .  G  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

e4=
 4 |.  .  .  .  G  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

a1=
 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |G  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

a4=
 4 |G  .  .  .  .  .  |
 3 |.  .  .  .  G  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f
</code>```

If I comment the assignation to field[][]= in putChar() function the board is always empty as expected, if I add other assignation, sometimes both chars are repeats, sometimes one and sometimes anyone.

Testing with a fixed assignation in putChar():

```<code>void Field::putChar(void){
...
(random definition of pr2 and pc2 and validation within limits)
...
 field[2][5]='H';
...
};
</code>```

results are always:

```<code> 4 |.  H  .  .  .  .  |
 3 |.  .  .  .  .  H  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f
</code>```

it appears that duplicate data follows a pattern, duplication appears always -4,1 when possible... but why?
If array limits change, this pattern change with pattern position -FIELDHEIGHT,1 relative to the good one.

Any idea to solve this issue?

答: In field[r-1][c] r goes from 1 to FIELDHEIGHT, but the first dimension of field has FIELDWIDTH elements. I think you meant field[c][r-1] here.

Body:
I am using a 2D char array to display a board on screen. Empty board is fulled with '.' (dots), the program write in a certain position an other char ('G'). The problem is that sometimes (more o less once every four times) a duplicate character appears in an other position.

 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |G  .  .  .  .  .  |
 1 |.  .  .  .  G  .  |
------------------------
    a  b  c  d  e  f

Relevant code fragments are:

class Field
{
 public:
static const int FIELDWIDTH=6;
static const int FIELDHEIGHT=4;

char field[FIELDWIDTH][FIELDHEIGHT];
..
};

void Field::empty(void){
  for(int r=0; r<FIELDHEIGHT; r++)
    for(int c=0; c<FIELDWIDTH; c++)
      field[r][c] = '.';
};

Field::plot(){                   //Plots the board
for(int r=FIELDHEIGHT;r>0;r--){
    cout << std::setw(2) << std::setfill(' ') << r << " |";
    for(int c=0;c<FIELDWIDTH;c++)
      cout << field[r-1][c] << "  ";
    cout << "|" << endl;
  };
...
};

void Field::putChar(void){
...
(random definition of pr2 and pc2 and validation within limits)
...
 field[pr2][pc2]='G';
 printCors(pr2,pc2); //cout coordinate for debug
...
};

The only two assignations to field[][] are ONE in empty() and ONE in putChar(). empty() works as expected always resulting in a plot() so:

 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

And the assignation in putChar is watched with the cout, which only output just one coordinate, nevertheless SOMETIMES one additional character appears with some relation with the expected one, here some runs:

b1=
 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  G  .  .  .  .  |
------------------------
    a  b  c  d  e  f

e2=
 4 |.  .  .  .  .  .  |
 3 |G  .  .  .  .  .  |
 2 |.  .  .  .  G  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

e4=
 4 |.  .  .  .  G  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

a1=
 4 |.  .  .  .  .  .  |
 3 |.  .  .  .  .  .  |
 2 |.  .  .  .  .  .  |
 1 |G  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

a4=
 4 |G  .  .  .  .  .  |
 3 |.  .  .  .  G  .  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

If I comment the assignation to field[][]= in putChar() function the board is always empty as expected, if I add other assignation, sometimes both chars are repeats, sometimes one and sometimes anyone.

Testing with a fixed assignation in putChar():

void Field::putChar(void){
...
(random definition of pr2 and pc2 and validation within limits)
...
 field[2][5]='H';
...
};

results are always:

 4 |.  H  .  .  .  .  |
 3 |.  .  .  .  .  H  |
 2 |.  .  .  .  .  .  |
 1 |.  .  .  .  .  .  |
------------------------
    a  b  c  d  e  f

it appears that duplicate data follows a pattern, duplication appears always -4,1 when possible... but why?
If array limits change, this pattern change with pattern position -FIELDHEIGHT,1 relative to the good one.

Any idea to solve this issue?


问:
How to open .dot using Open XML

I am trying to use Office Open XML to open a .dot file using WordprocessingDocument.Open() in C#

The code below works for .docx files but I have to be able to support .dot files

Since Open XML doesn't support dot files, how can I get the contents of a dot file into a docx file?

```<code>// Open Template
byte[] sourceBytes = File.ReadAllBytes(Template.FullName);

using (MemoryStream workingMemoryStream = new MemoryStream())
{
    // Load into memory
    workingMemoryStream.Write(sourceBytes, 0, sourceBytes.Length);

    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(workingMemoryStream, true))
    {
        ...
    }
}
</code>```

I'm getting the error "File contains corrupted data"

答: Older .DOT files are in a binary format, not XML.  You'll need to use Word automation libraries or some other mechanism to open them; OpenXML does not support them.

Title: How to open .dot using Open XML

Body:
I am trying to use Office Open XML to open a .dot file using WordprocessingDocument.Open() in C#

The code below works for .docx files but I have to be able to support .dot files

Since Open XML doesn't support dot files, how can I get the contents of a dot file into a docx file?

// Open Template
byte[] sourceBytes = File.ReadAllBytes(Template.FullName);

using (MemoryStream workingMemoryStream = new MemoryStream())
{
    // Load into memory
    workingMemoryStream.Write(sourceBytes, 0, sourceBytes.Length);

    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(workingMemoryStream, true))
    {
        ...
    }
}

I'm getting the error "File contains corrupted data"


问:
Changing button's size based on its content's length, so the button keeps its shape
I have a UIButton which is created programmatically (it can be customised from Interface Builder, though). It is a circular and it looks like this:

Now I'm working on Internationalization and I need to check it for Double-Length Pseudolanguage. The image above is taken when the app language is set to double-length pseudo, but as you can see, the button only shows one word. Here are the constraints of the button:

The title style of the button is plain, its text is centre-aligned, and the line break is set to "Word Wrap".
How to make the button keep its shape but to increase its size when needed (basically, to increase its width and height for the same amount, so it keeps being a circle), so for example, in this case to show two "Menu" words? If you know how to achieve this I would appreciate your help.

答: Try setting the content compression resistance on the button to required (1000) for horizontal and vertical. It will also depend on the stackViews above and below allowing for the size change. </p>


问:
Delete line containing pattern found anywhere in another file
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

file2

```<code>these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words
</code>```

Expected output:

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

答:
If I understand correctly,
you want to exclude from the first file lines that would match any IP address in the second file.

This simple and admittedly a bit lazy solution might be good enough for your purpose:

```<code>grep -v file1 -Fwf <(awk '{ print $3 }' file2)
</code>```

The Awk extracts the 3rd column with IP addresses,
and grep will use those as fixed patterns (-F) and only match complete words (-w).

If the IP address is not always the 3rd column,
then you could extract them by using pattern matching with grep,
as @tripleee suggested:

```<code>grep -v file1 -Fwf <(grep -owE '[1-9][0-9](\.[0-9]{1,3}){3}' file2)
</code>```

Body:
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

file2

these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words

Expected output:

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

Body:
If I understand correctly,
you want to exclude from the first file lines that would match any IP address in the second file.

This simple and admittedly a bit lazy solution might be good enough for your purpose:

grep -v file1 -Fwf <(awk '{ print $3 }' file2)

The Awk extracts the 3rd column with IP addresses,
and grep will use those as fixed patterns (-F) and only match complete words (-w).

If the IP address is not always the 3rd column,
then you could extract them by using pattern matching with grep,
as @tripleee suggested:

grep -v file1 -Fwf <(grep -owE '[1-9][0-9](\.[0-9]{1,3}){3}' file2)


问:
several MYSQL statements in one
I have a place ('place') where I can have some boxes ('box'). In  each box, I can have items ('item'). I can also have items in the place outside of a box.
I want to delete a place, and by so, to delete each boxes in the place, including items in each boxes as well as the items in the place but outside any box.
I got it working with the following separated statements:

1: select the place

```<code>SELECT placeid, placename
FROM place
WHERE userid = (SELECT id
                FROM user
                WHERE username = 'username' AND password ='password')
  AND placename = 'placename'
</code>```

2: select the boxes in that place

```<code>SELECT boxid, boxname
FROM box
WHERE placeid = 'id'
</code>```

3a: for each box, delete the items in it

```<code>DELETE FROM item
WHERE boxid = 'boxid'
</code>```

3b: then delete the box

```<code>DELETE FROM box
WHERE id = 'boxid'
</code>```

4: delete the items in the place not in a box

```<code>DELETE FROM item
WHERE placeid = 'placeid' AND boxid = 0
</code>```

5: delete the place

```<code>DELETE FROM place
WHERE id = placeid
</code>```

This is working but of course this is slow. The error management is also not that nice to work with.

Is there a way of doing all this with fewer SQL statements or even only one?

I got of course the same question for deleting a box in one statement!

edit: mysql with php

Thanks a lot.

答:
You should try ON DELETE CASCADE, it would look like this:

```<code>ALTER TABLE box ADD CONSTRAINT fk_box_place_id
                FOREIGN KEY (placeid)
                REFERENCES place(id)
                ON DELETE CASCADE;

ALTER TABLE item ADD CONSTRAINT fk_item_place_id
                 FOREIGN KEY (placeid)
                 REFERENCES place(id)
                 ON DELETE CASCADE;
</code>```

I don't think you need any other cascades, since placeid is available in all tables and will cover items both in and out of boxes, but maybe I'm overlooking something.

Once set up, all you do is delete the place you want to delete and the rest is handled for you:

```<code>DELETE
FROM place
WHERE placeID = 'deletedPlaceID';
</code>```

Title: several MYSQL statements in one

Body:
I have a place ('place') where I can have some boxes ('box'). In  each box, I can have items ('item'). I can also have items in the place outside of a box.
I want to delete a place, and by so, to delete each boxes in the place, including items in each boxes as well as the items in the place but outside any box.
I got it working with the following separated statements:

1: select the place

SELECT placeid, placename
FROM place
WHERE userid = (SELECT id
                FROM user
                WHERE username = 'username' AND password ='password')
  AND placename = 'placename'

2: select the boxes in that place

SELECT boxid, boxname
FROM box
WHERE placeid = 'id'

3a: for each box, delete the items in it

DELETE FROM item
WHERE boxid = 'boxid'

3b: then delete the box

DELETE FROM box
WHERE id = 'boxid'

4: delete the items in the place not in a box

DELETE FROM item
WHERE placeid = 'placeid' AND boxid = 0

5: delete the place

DELETE FROM place
WHERE id = placeid

This is working but of course this is slow. The error management is also not that nice to work with.

Is there a way of doing all this with fewer SQL statements or even only one?

I got of course the same question for deleting a box in one statement!

edit: mysql with php

Thanks a lot.

Body:
You should try ON DELETE CASCADE, it would look like this:

ALTER TABLE box ADD CONSTRAINT fk_box_place_id
                FOREIGN KEY (placeid)
                REFERENCES place(id)
                ON DELETE CASCADE;

ALTER TABLE item ADD CONSTRAINT fk_item_place_id
                 FOREIGN KEY (placeid)
                 REFERENCES place(id)
                 ON DELETE CASCADE;

I don't think you need any other cascades, since placeid is available in all tables and will cover items both in and out of boxes, but maybe I'm overlooking something.

Once set up, all you do is delete the place you want to delete and the rest is handled for you:

DELETE
FROM place
WHERE placeID = 'deletedPlaceID';


问:
How to change markup cell font color in Jupyter notebook
I am using a customized theme for jupyter notebook and the font color for markup cells while it is active and I am typing is black and has barely enough contrast.  I was not able to locate the section in custom.css that dictate the font color. When I inspect the font color, Iit points to codemirror.css, a file that I am not able to locate on my machine. The black fonr is the case for nbextension page. I left some pictures below.

link to the custom.css file

markup cell:

nbextension page:

答:
You've made a bunch of errors/typos in your css file. I suggest running it through a css checker (e.g. jigsaw.w3.org/css-validator) before considering your work complete for custom stylesheets.

To expand:

in line 12, on the nbextensions page (and indeed the file browser), the text colour is inherited from the body, for which it looks like you've attempted to set text colour to (I assume) #333 (quite dark! maybe something like #888 would be better?), but in fact you've made a typo, and since #33 isn't a valid colour code, the rule gets ignored, and text colour remains as the default #000. This is the cause of your problem with the nbextensions page, and the file browser.

in line 27, you've mistakenly added _area to the end of a line, resulting in a parse error. This only breaks that line, which is just antialiasing, so not so noticeable.

in line 766, padding can't be none, it should be 0. This (setting it none/0) is perhaps a mistake anyway, as non-disabled menu items still have padding, so it looks weird to remove it completely only for disabled elements.

in line 2495, you've added a second closing bracket. This is a parse error, and as far as I can see, breaks everything in the file following it. This is why your CodeMirror rules are getting ignored.

in lines 2820-2833, you've actually included some javascript, which is another parse error. If you need this javascript, consider adding it to a custom.js file instead.

Finally, if you're interested in the contents of CodeMirror.css, it gets included in the notebook's main.min.css, or you can get the source on GitHub.


问:
Open-source Java-based framework that has many of the common features built in out-of-the-box?
I am looking for something like Drupal in Java -- not Drupal as a CMS but rather as an application programming framework.

For example I would like to get out the the box:

A Login screen

The ability to define new roles

The ability to tie permissions (capabilities) to roles

The ability to assign roles to specific users (and revoke roles)

The ability to self-service passwords (reset ones own password)

An ability to generate a CRUD app

A menu system (that allows you to define menus)

My understanding is that Ruby-on-Rails provides this type of stuff.

Thanks.

答:
try openxava too

"OpenXava is a tool for Rapid Java Web Development, well-suited for business and database oriented applications"