问:
Taking a 3 year average across in a panel data set with NAs
I have the following dataframe, called DF,

```<code>Country Year Var1 Var2
USA 2010 5 3
USA 2011 6 5
USA 2012 NA 8
USA 2013 4 NA
USA 2014 NA 6
USA 2015 6 9
CHN 2010 NA 5
CHN 2011 7 NA
CHN 2012 6 NA
CHN 2013 4 4
CHN 2014 NA 6
CHN 2015 NA 8
EGY 2010 3 NA
EGY 2011 3 5
EGY 2012 3 6
EGY 2013 NA 8
EGY 2014 NA NA
EGY 2015 NA 2
</code>```

I want to take a 3 year average of the data. However, if there are only two years of available data within a particular three year interval, I want to ignore the NA and take a two year average. Similarly, if data is only available for one year within a particular three year interval, I want to keep that data point as the "average" for that three year interval. Basically, within each three year interval, I want to take the mean, and ignoring the NAs.

I have tried the following solution recommended in : R: Calculating 5 year averages in panel data

```<code>int<-cut(DF$Year,seq(2010,2016,by=3),right=F)
id<-c("Var1", "Var2")
ag<-aggregate(DF[id],list(DF$Country,int), mean)
</code>```

It yielded the following:

```<code>Group.1 Group.2 Var1 Var2
CHN [2010,2013) NA NA
EGY [2010,2013) 3 NA
USA [2010,2013) NA 5.333333
CHN [2013,2016) NA 6.000000
EGY [2013,2016) NA NA
USA [2013,2016) NA NA
</code>```

But the output I am interested in is:

```<code>Group.1 Group.2 Var1 Var2
CHN [2010,2013) 6.5 5
EGY [2010,2013) 3 5.5
USA [2010,2013) 5.5 5.3
CHN [2013,2016) 4 6
EGY [2013,2016) NA 5
USA [2013,2016) 5 7.5
</code>```

答:
Here's how you can do that with package dplyr. Basically, you first create a "year group" using mutate. I used ifelse but it you have more groups, you should consider looking at case_when although nested ifelse will work. Then, we summarise by country and Year_group.

```<code>df1 <- read.table(text="Country Year Var1 Var2
                  USA 2010 5 3
                  USA 2011 6 5
                  USA 2012 NA 8
                  USA 2013 4 NA
                  USA 2014 NA 6
                  USA 2015 6 9
                  CHN 2010 NA 5
                  CHN 2011 7 NA
                  CHN 2012 6 NA
                  CHN 2013 4 4
                  CHN 2014 NA 6
                  CHN 2015 NA 8
                  EGY 2010 3 NA
                  EGY 2011 3 5
                  EGY 2012 3 6
                  EGY 2013 NA 8
                  EGY 2014 NA NA
                  EGY 2015 NA 2",header=TRUE, stringsAsFactors=FALSE)
library(dplyr)
df1%>%
  group_by(Country)%>%
  mutate(Year_group=ifelse(Year<2013,"2010-2012","2013-2016"))%>%
  group_by(Country,Year_group)%>%
  summarise(Mean_var1=mean(Var1,na.rm=TRUE),Mean_var2=mean(Var2,na.rm=TRUE)

  Country Year_group Mean_var1 Mean_var2
    <chr>      <chr>     <dbl>     <dbl>
1     CHN  2010-2012       6.5  5.000000
2     CHN  2013-2016       4.0  6.000000
3     EGY  2010-2012       3.0  5.500000
4     EGY  2013-2016       NaN  5.000000
5     USA  2010-2012       5.5  5.333333
6     USA  2013-2016       5.0  7.500000
</code>```

Body:
I have the following dataframe, called DF,

Country Year Var1 Var2
USA 2010 5 3
USA 2011 6 5
USA 2012 NA 8
USA 2013 4 NA
USA 2014 NA 6
USA 2015 6 9
CHN 2010 NA 5
CHN 2011 7 NA
CHN 2012 6 NA
CHN 2013 4 4
CHN 2014 NA 6
CHN 2015 NA 8
EGY 2010 3 NA
EGY 2011 3 5
EGY 2012 3 6
EGY 2013 NA 8
EGY 2014 NA NA
EGY 2015 NA 2

I want to take a 3 year average of the data. However, if there are only two years of available data within a particular three year interval, I want to ignore the NA and take a two year average. Similarly, if data is only available for one year within a particular three year interval, I want to keep that data point as the "average" for that three year interval. Basically, within each three year interval, I want to take the mean, and ignoring the NAs.

I have tried the following solution recommended in : R: Calculating 5 year averages in panel data

int<-cut(DF$Year,seq(2010,2016,by=3),right=F)
id<-c("Var1", "Var2")
ag<-aggregate(DF[id],list(DF$Country,int), mean)

It yielded the following:

Group.1 Group.2 Var1 Var2
CHN [2010,2013) NA NA
EGY [2010,2013) 3 NA
USA [2010,2013) NA 5.333333
CHN [2013,2016) NA 6.000000
EGY [2013,2016) NA NA
USA [2013,2016) NA NA

But the output I am interested in is:

Group.1 Group.2 Var1 Var2
CHN [2010,2013) 6.5 5
EGY [2010,2013) 3 5.5
USA [2010,2013) 5.5 5.3
CHN [2013,2016) 4 6
EGY [2013,2016) NA 5
USA [2013,2016) 5 7.5

Body:
Here's how you can do that with package dplyr. Basically, you first create a "year group" using mutate. I used ifelse but it you have more groups, you should consider looking at case_when although nested ifelse will work. Then, we summarise by country and Year_group.

df1 <- read.table(text="Country Year Var1 Var2
                  USA 2010 5 3
                  USA 2011 6 5
                  USA 2012 NA 8
                  USA 2013 4 NA
                  USA 2014 NA 6
                  USA 2015 6 9
                  CHN 2010 NA 5
                  CHN 2011 7 NA
                  CHN 2012 6 NA
                  CHN 2013 4 4
                  CHN 2014 NA 6
                  CHN 2015 NA 8
                  EGY 2010 3 NA
                  EGY 2011 3 5
                  EGY 2012 3 6
                  EGY 2013 NA 8
                  EGY 2014 NA NA
                  EGY 2015 NA 2",header=TRUE, stringsAsFactors=FALSE)
library(dplyr)
df1%>%
  group_by(Country)%>%
  mutate(Year_group=ifelse(Year<2013,"2010-2012","2013-2016"))%>%
  group_by(Country,Year_group)%>%
  summarise(Mean_var1=mean(Var1,na.rm=TRUE),Mean_var2=mean(Var2,na.rm=TRUE)

  Country Year_group Mean_var1 Mean_var2
    <chr>      <chr>     <dbl>     <dbl>
1     CHN  2010-2012       6.5  5.000000
2     CHN  2013-2016       4.0  6.000000
3     EGY  2010-2012       3.0  5.500000
4     EGY  2013-2016       NaN  5.000000
5     USA  2010-2012       5.5  5.333333
6     USA  2013-2016       5.0  7.500000


来源: stackexchange

问:
Devexpress Gridcontrol Sum of row cell values in specific Column cell
i am using devexpress gridcontrol and i have table from database and i added 1 column manualy from codebehind :

gridView1.Columns.AddVisible("Total");

i have question how i can give this column valus from summery of rows values like this for example:

```<code>Name Value value2 value3 Total
g    13     1       6     20
h     2     2       2      6
</code>```

答:
I would suggest making an unbound column and setting its UnboundExpression property to a formula that sums your other columns.

See also: Expressions

ContentLicense: CC BY-SA 3.0

Body:
i am using devexpress gridcontrol and i have table from database and i added 1 column manualy from codebehind :

gridView1.Columns.AddVisible("Total");

i have question how i can give this column valus from summery of rows values like this for example:

Name Value value2 value3 Total
g    13     1       6     20
h     2     2       2      6


问:
Make a overlay appear on text hover
I'm looking for a way to make my background image darken by hovering over an anchor within the div container that the background image is attached to.

There has been an instance where it did work but there was a enormous amount of flickering when the mouse was moved within the anchor.

答:
well, when you hover your anchor inside hover attributes you have to change linear gradient of your background according to what you want! check out linear gradient css 3 attribute for backgrounds!

thank you

Title: Make a overlay appear on text hover


问:
Auto-suggestion in Eclipse XML files refuses to die
Auto-suggestion is just an annoyance to me. I unchecked "Automatically make suggestions" in Preferences -> XML -> XML Files -> Editor, but it's still doing it when I type < or :

Using 3.5.2 if it matters.

答:
Bug 144313 introduced this preference for various types of xml files:

This patch contains Typing preference pages for XML, HTML, and JSP.

  These preferences are referenced in the XML, HTML, and JSP auto edit strategies.

Are you sure your file is a .xml one or is it some other extension with xml content?

(Like a javascript one, which has its own setting:

ditto for HTML files:

)

ContentLicense: CC BY-SA 2.5


问:
How to Iterate through arithmetic operators across a static, excecutable formula in Python?
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

```<code>1
1,2
1,3
2,3
1,2,3
</code>```

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

```<code>1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...
</code>```

arises and gives results of the equation.

How might I go about doing this?

答:
Use the corresponding functions in the operator module and iterate over pairs of them.

```<code>import itertools
import operator

ops = [operator.add, operator.sub, operator.mul, operator.div]

for f1, f2 in itertools.product(*ops, repeat=2):
    print f1(array[0], f2(array[1], array[2]))
</code>```

Now, if array can have an arbitrary length, it gets a bit tricker.

```<code>for operations in itertools.product(*ops, repeat=len(array)-1):
  result = operations[0](array[0], array[1])
  for op, operand in zip(operations[1:], array[2:]):
      result = op(result, operand)
  print(result)
</code>```

The structure above avoids having to know the appropriate identity element for each operation.

If you want to obey precedence (as seems likely), you'll want to create an expression and evaluate it with eval (standard warnings apply).

```<code>for ops in itertool.product("+", "-", "*", "/", repeat=len(array)-1):
  expr = "%s%s%s" % (array[0], ops[0], array[1])
  for op, operand in zip(ops[1:], array[2:]):
    expr = "%s%s%s" % (expr, op, operand)
  result = eval(expr)
</code>```

I leave it as an exercise to expand this to produce parenthesized expressions like (1+2)*3 in addition to 1+2*3.

Body:
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

1
1,2
1,3
2,3
1,2,3

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...

arises and gives results of the equation.

How might I go about doing this?

Body:
Use the corresponding functions in the operator module and iterate over pairs of them.

import itertools
import operator

ops = [operator.add, operator.sub, operator.mul, operator.div]

for f1, f2 in itertools.product(*ops, repeat=2):
    print f1(array[0], f2(array[1], array[2]))

Now, if array can have an arbitrary length, it gets a bit tricker.

for operations in itertools.product(*ops, repeat=len(array)-1):
  result = operations[0](array[0], array[1])
  for op, operand in zip(operations[1:], array[2:]):
      result = op(result, operand)
  print(result)

The structure above avoids having to know the appropriate identity element for each operation.

If you want to obey precedence (as seems likely), you'll want to create an expression and evaluate it with eval (standard warnings apply).

for ops in itertool.product("+", "-", "*", "/", repeat=len(array)-1):
  expr = "%s%s%s" % (array[0], ops[0], array[1])
  for op, operand in zip(ops[1:], array[2:]):
    expr = "%s%s%s" % (expr, op, operand)
  result = eval(expr)

I leave it as an exercise to expand this to produce parenthesized expressions like (1+2)*3 in addition to 1+2*3.


问:
Merge two DataFrames on ranges intersections
I am trying to merge two DataFrames based on the intersection of min-max values. Does anyone have a nice way to do it with Pandas?

```<code>##  min  max  x1       ##  min  max   x2
##0  1    20   0.5     ##0  1    12   1.2
##1  20   30   1.5     ##1  12   30   2.2
</code>```

Desired output:

```<code>##   min  max  x1   x2
##0  1    12   0.5  1.2
##1  12   20   0.5  2.2
##2  20   30   1.5  2.2
</code>```

Thx!

答:
This gives you what you're looking for based on your data set above, but I have the feeling it may not work in more complex situations.

Code:

```<code># Simple data frame append - since it looks like you want it ordered, you can order it here, and then reset index.
df = df1.append(df2).sort_values(by = 'max')[['min','max','x1','x2']].reset_index(drop = True)

# Here, set 'min' for all but the first row to the 'max' of the previous row
df.loc[1:, 'min'] = df['max'].shift()

# Fill NaNs
df.fillna(method = 'bfill', inplace = True)

# Filter out rows where min == max
df = df.loc[df['min'] != df['max']]
</code>```

Output:

```<code>    min  max   x1   x2
0   1.0   12  0.5  1.2
1  12.0   20  0.5  2.2
2  20.0   30  1.5  2.2
</code>```

Body:
I am trying to merge two DataFrames based on the intersection of min-max values. Does anyone have a nice way to do it with Pandas?

##  min  max  x1       ##  min  max   x2
##0  1    20   0.5     ##0  1    12   1.2
##1  20   30   1.5     ##1  12   30   2.2

Desired output:

##   min  max  x1   x2
##0  1    12   0.5  1.2
##1  12   20   0.5  2.2
##2  20   30   1.5  2.2

Thx!

Body:
This gives you what you're looking for based on your data set above, but I have the feeling it may not work in more complex situations.

Code:

# Simple data frame append - since it looks like you want it ordered, you can order it here, and then reset index.
df = df1.append(df2).sort_values(by = 'max')[['min','max','x1','x2']].reset_index(drop = True)

# Here, set 'min' for all but the first row to the 'max' of the previous row
df.loc[1:, 'min'] = df['max'].shift()

# Fill NaNs
df.fillna(method = 'bfill', inplace = True)

# Filter out rows where min == max
df = df.loc[df['min'] != df['max']]

Output:

    min  max   x1   x2
0   1.0   12  0.5  1.2
1  12.0   20  0.5  2.2
2  20.0   30  1.5  2.2


问:
Can Bonitasoft (BPM) be used to build an ERP system?
I have gone through the documentations of Bonita and read a book about it. I have also watched almost all the tutorials offered by bonita on YouTube. However, the software limitations are not clear to me yet.

The company that I work for, a consultancy company, wants to use bonitasoft to manage its enterprise resources.

Examples of tasks that we want to implement :

Vacation planning for our employees (This a task so it is easy to
implement with Bonita)

Finance management and generating bills. (This is not a task. I need
to link a consultant to a contract and a client. Finally, generate a
bill at the end of each month)

Manage how bonuses are attributed to different consultants. This
depends on their performance. (Not a task)

Consultants should be able to see their history and how long they
worked for a given client and how much money they have brought in.
(Not a task)

Managing job applications. (Applications and uploaded files like C.Vs
and cover letters).

I was not able to find any demo website made by bonita to see if people tried to build an ERP system based on bonitasoft. Is this possible?

I think that it should be possible to create a form and modify it using JavaScript to implement a non-task functionality.

Is this considered as hack?

Are other people using bonita this way or not?

Also is implementing non-taskfunctionality possible using widgets (HTML, JAVASCRIPT and maybe an external webservice)?

答:
Bonita BPM is a process-based application platform. I'm highlighting the process part of it here as this is a key concept in the platform.

Basically, the business logic part of any Bonita application is designed using a BPM (Business Process Management) approach. You design a process that represent your business logic and implement its behavior by coding business rules, data processing, integration with third-party systems and so on.

Then once, the business logic is implemented, you can build reports that will display to the end-user the data resulting from the execution of the different processes.

If we take the examples you gave:

Vacation planning for our employees (This a task so it is easy to implement with Bonita)

Typically handle by a process.

Finance management and generating bills. (This is not a task. I need to link a consultant to a contract and a client. Finally, generate a bill at the end of each month)

Can be handle by a process. The finance manager will have initiate the generation of a new bill from the application. But really, in the backend, it will trigger a new case (process instance), then follow all the steps down to the generation of the bill.

Manage how bonuses are attributed to different consultants. This depends on their performance. (Not a task)

You're right, not typically process based. Maybe just entering the bonuses value in a DB. If there are business rules associated to the calculation of the bonuses, it could be handled by a process.

Consultants should be able to see their history and how long they worked for a given client and how much money they have brought in. (Not a task)

Should be a report pulling data from an external DB or the Bonita DB.

Managing job applications. (Applications and uploaded files like C.Vs and cover letters).

Typically process-based.

So the short answer is yes, Bonita can be used to build this kind of application.


问:
How to use 'id' when using DocumentDB via MongDB API in Spring DATA?
I have used both the ways of mapping _id as described in the Spring Docs here.

using @Id annotation

having a field with name id without any annotation

in my previous project where we used MongoDB as database and Spring Data for DAO operations. It worked without any problem for both String a well as for BigInteger.

Now we are using DocumentDB with MongoDB API(as Spring Data does not support DocumentDB).
I am able to use all the Spring Data methods, but I am not able to use custom id.

Below is my entity:

```<code>public class S{

    private String id;

    /* other fields here */

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /* getters and setters for other fields */
}
</code>```

This is the DAO:

```<code>public interface SDao extends MongoRepository<S, String> {

}
</code>```

Now if anywhere in my code I do:

```<code>s = new S();
s.setId("some-id-here");
</code>```

The record gets successfully persisted in the DB with custom id some-id-here as String (not ObjectId), but after that it throws ClassCastException saying Long cannot be converted to Integer.

Same is the case when using BigInteger for id.

If I am not setting the custom id, i.e. I comment the setting of id as below:

```<code>s = new S();
// s.setId("some-id-here");
</code>```

no exception is being thrown, but the record is being persisted with a random id provided by database itself as ObjectcId.

I want to save the record with custom id, so that I can easily update it when needed.
Currently if I have to update a record, I need to retrieve it using a key which is not mapped to _id and then update it and then delete the old record from the DB and then persist the updated one, which I feel is absolutely inefficient as I am not able to make use of _id.

My question is why am I getting ClassCastException, that too mentioning Conversion of Long to Integer

Is DocumentDB internally doing some conversion which is throwing this exception. If yes, how to tackle it? Is this a bug?

答:
One alternative could be to let DocumentDB/ MongoDB create those IDs for you by default. In your class you can have another field which can serve as natural ID and create a unique index on that field for fetch optimization.
Refer https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ for indexes.

Body:
I have used both the ways of mapping _id as described in the Spring Docs here.

using @Id annotation

having a field with name id without any annotation

in my previous project where we used MongoDB as database and Spring Data for DAO operations. It worked without any problem for both String a well as for BigInteger.

Now we are using DocumentDB with MongoDB API(as Spring Data does not support DocumentDB).
I am able to use all the Spring Data methods, but I am not able to use custom id.

Below is my entity:

public class S{

    private String id;

    /* other fields here */

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /* getters and setters for other fields */
}

This is the DAO:

public interface SDao extends MongoRepository<S, String> {

}

Now if anywhere in my code I do:

s = new S();
s.setId("some-id-here");

The record gets successfully persisted in the DB with custom id some-id-here as String (not ObjectId), but after that it throws ClassCastException saying Long cannot be converted to Integer.

Same is the case when using BigInteger for id.

If I am not setting the custom id, i.e. I comment the setting of id as below:

s = new S();
// s.setId("some-id-here");

no exception is being thrown, but the record is being persisted with a random id provided by database itself as ObjectcId.

I want to save the record with custom id, so that I can easily update it when needed.
Currently if I have to update a record, I need to retrieve it using a key which is not mapped to _id and then update it and then delete the old record from the DB and then persist the updated one, which I feel is absolutely inefficient as I am not able to make use of _id.

My question is why am I getting ClassCastException, that too mentioning Conversion of Long to Integer

Is DocumentDB internally doing some conversion which is throwing this exception. If yes, how to tackle it? Is this a bug?


问:
Move (Copy) value of a cell based on dropdown value in Google Sheets
I'm trying to create a basic CRM using Google Sheets that holds all the client's data in one sheet and shows which part of the deal stage they're in on another sheet. Below is an example of what I mean.

Sheet 1:

```<code>Name |  Email  |  Deal Stage |
Ian     ian@..  >>Pre-launch << dropdown list
Ken     ken@..  >>Pre-launch << dropdown list
Dan     dan@..  >>Out-Reach  << dropdown list
Ben     ben@..  >>Call Booked<< dropdown list
</code>```

Sheet 2:

```<code>Pre-Launch | Out-Reach | Brochure Sent | Call Booked |
Ian          Dan                         Ben
Ken
</code>```

I'm looking to create a script that fires onEdit of any item in the dropdown cells. Is this possible, and what's the cleanest way?

I have created this Example Sheet which only includes the feature in question.

答:
One more try.

```<code>function dealStage(e)
{
  //var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ss = e.source;
  var sht = ss.getSheetByName('ClientData');
  var rng = sht.getDataRange();
  var rngA = rng.getValues();
  var clientheaders = rngA[0];
  var dsSht = ss.getSheetByName('DealStage');
  var dsShtRng = dsSht.getRange(2, 1, dsSht.getLastRow(), dsSht.getLastColumn());
  dsShtRng.clearContent();
  var dsShtHdrsRng = dsSht.getRange(1, 1, 1, dsSht.getLastColumn());
  var dsShtHdrsRngA = dsShtHdrsRng.getValues();
  var dsheaders = dsShtHdrsRngA[0];
  var prelaunch = [];
  var outreach = [];
  var brochuresent = [];
  var callbooked = [];
  var dsi = clientheaders.indexOf('Deal Stage');
  var ni = clientheaders.indexOf('Name');
  for(var i=1;i<rngA.length;i++)
  {

    var dsv = rngA[i][dsi];
    var nv = rngA[i][ni]
    if(dsv!='')
    {
        switch(dsv)
        {
          case('Pre-Launch'):
            prelaunch.push([nv]);
            break;
          case('Out-Reach'):
            outreach.push([nv]);
            break;
          case('Brochure-Sent'):
            brochuresent.push([nv]);
            break;
          case('Call-Booked'):
            callbooked.push([nv]);
            break;
        }
    }
  }
  var dsstartrow = dsSht.getLastRow()+1;
  for(var i=0;i<dsheaders.length;i++)
  {
    var hdr = dsheaders[i];
    switch(hdr)
    {
      case('Pre-Launch'):
        if(prelaunch.length>0)dsSht.getRange(dsstartrow,i+1,prelaunch.length,1).setValues(prelaunch);
        break;
      case('Out-Reach'):
        if(outreach.length>0)dsSht.getRange(dsstartrow,i+1,outreach.length,1).setValues(outreach);
        break;
      case('Brochure-Sent'):
        if(brochuresent.length>0)dsSht.getRange(dsstartrow,i+1,brochuresent.length,1).setValues(brochuresent);
        break;
      case('Call-Booked'):
        if(callbooked.length>0)dsSht.getRange(dsstartrow,i+1,callbooked.length,1).setValues(callbooked);
        break;
    }
  }
  SpreadsheetApp.flush();
}
</code>```

ClientData Sheet:

DealStage Sheet:

Validation Sheet:

Body:
I'm trying to create a basic CRM using Google Sheets that holds all the client's data in one sheet and shows which part of the deal stage they're in on another sheet. Below is an example of what I mean.

Sheet 1:

Name |  Email  |  Deal Stage |
Ian     ian@..  >>Pre-launch << dropdown list
Ken     ken@..  >>Pre-launch << dropdown list
Dan     dan@..  >>Out-Reach  << dropdown list
Ben     ben@..  >>Call Booked<< dropdown list

Sheet 2:

Pre-Launch | Out-Reach | Brochure Sent | Call Booked |
Ian          Dan                         Ben
Ken

I'm looking to create a script that fires onEdit of any item in the dropdown cells. Is this possible, and what's the cleanest way?

I have created this Example Sheet which only includes the feature in question.

Body:
One more try.

function dealStage(e)
{
  //var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ss = e.source;
  var sht = ss.getSheetByName('ClientData');
  var rng = sht.getDataRange();
  var rngA = rng.getValues();
  var clientheaders = rngA[0];
  var dsSht = ss.getSheetByName('DealStage');
  var dsShtRng = dsSht.getRange(2, 1, dsSht.getLastRow(), dsSht.getLastColumn());
  dsShtRng.clearContent();
  var dsShtHdrsRng = dsSht.getRange(1, 1, 1, dsSht.getLastColumn());
  var dsShtHdrsRngA = dsShtHdrsRng.getValues();
  var dsheaders = dsShtHdrsRngA[0];
  var prelaunch = [];
  var outreach = [];
  var brochuresent = [];
  var callbooked = [];
  var dsi = clientheaders.indexOf('Deal Stage');
  var ni = clientheaders.indexOf('Name');
  for(var i=1;i<rngA.length;i++)
  {

    var dsv = rngA[i][dsi];
    var nv = rngA[i][ni]
    if(dsv!='')
    {
        switch(dsv)
        {
          case('Pre-Launch'):
            prelaunch.push([nv]);
            break;
          case('Out-Reach'):
            outreach.push([nv]);
            break;
          case('Brochure-Sent'):
            brochuresent.push([nv]);
            break;
          case('Call-Booked'):
            callbooked.push([nv]);
            break;
        }
    }
  }
  var dsstartrow = dsSht.getLastRow()+1;
  for(var i=0;i<dsheaders.length;i++)
  {
    var hdr = dsheaders[i];
    switch(hdr)
    {
      case('Pre-Launch'):
        if(prelaunch.length>0)dsSht.getRange(dsstartrow,i+1,prelaunch.length,1).setValues(prelaunch);
        break;
      case('Out-Reach'):
        if(outreach.length>0)dsSht.getRange(dsstartrow,i+1,outreach.length,1).setValues(outreach);
        break;
      case('Brochure-Sent'):
        if(brochuresent.length>0)dsSht.getRange(dsstartrow,i+1,brochuresent.length,1).setValues(brochuresent);
        break;
      case('Call-Booked'):
        if(callbooked.length>0)dsSht.getRange(dsstartrow,i+1,callbooked.length,1).setValues(callbooked);
        break;
    }
  }
  SpreadsheetApp.flush();
}

ClientData Sheet:

DealStage Sheet:

Validation Sheet:


问:
Interrupt 'Play' and start recording as soon as the user starts talking
I am programming a conversational IVR which plays a prompt and records user answer. Then our service would transcript, analyze it and provide the corresponding answer, like an automated conversation.

As you can imagine, most of our users start talking before the message is actually finished. How can we set Twilio to stop the 'Play' command as soon as it hears the user talking?

That would make the conversation incredibly more interactive.

Thank you very much,

答:
Twilio developer evangelist here.

If you are using <Gather> and the recently launched speech recognition feature for it then you are able to nest your <Play> within the <Gather> and start listening as soon as the user speaks.

If you are using another method to record the user, perhaps <Play> followed by <Record>, then you cannot interrupt the <Play>. If this is the case, I recommend you investigate the latest abilities of <Gather>.


问:
How to call npm version (to update my own package's version and then commit)
Nothing happens when I run

```<code>npm version minor -m "test"
</code>```

As a note, there is output if I run npm version without any arguments:

```<code>$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }
</code>```

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?

答:
Not sure what version of npm you are using but in version 3.10.10 the npm version command takes one argument only, see the help page by typing version --help

```<code>[<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]
</code>```

These values relate to SemVer http://semver.org/

For example if your package.json was

```<code>{
  "name": "adventure-game",
  "version": "1.1.0",
  "description": "Bring back Monkey Island"
}
</code>```

Then the following commands would cause the version property in the package.json to be updated.

```<code>npm version major // version: "2.1.0"
npm version minor // version: "1.2.0"
npm version 2.3.4 // version: "2.3.4"
npm version patch // version: "1.1.1"
npm version premajor // version: "2.0.0-0"
</code>```

and so on...

Body:
Nothing happens when I run

npm version minor -m "test"

As a note, there is output if I run npm version without any arguments:

$ npm version
{ 'my-app': '0.7.0',
  npm: '4.2.0',
  ares: '1.10.1-DEV',
  cldr: '30.0.3',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '51',
  node: '7.10.0',
  openssl: '1.0.2k',
  tz: '2016j',
  unicode: '9.0',
  uv: '1.11.0',
  v8: '5.5.372.43',
  zlib: '1.2.11' }

How am I supposed to use npm-version? I expect it to update the version number in package.json, run the 'version' script that I've specified in the package.json scripts list, and then commit. I can use npm run version to execute the 'version' script that I specified, but how do I run npm-version correctly?

Body:
Not sure what version of npm you are using but in version 3.10.10 the npm version command takes one argument only, see the help page by typing version --help

[<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]

These values relate to SemVer http://semver.org/

For example if your package.json was

{
  "name": "adventure-game",
  "version": "1.1.0",
  "description": "Bring back Monkey Island"
}

Then the following commands would cause the version property in the package.json to be updated.

npm version major // version: "2.1.0"
npm version minor // version: "1.2.0"
npm version 2.3.4 // version: "2.3.4"
npm version patch // version: "1.1.1"
npm version premajor // version: "2.0.0-0"

and so on...


问:
Find all tables in database By primaryKey
I'm searching for a query that can retrieve all the tables by the specified key/keys name on a specific database.
Something like this:

```<code>SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
AND    Constraint_Type = 'PRIMARY KEY'
</code>```

I've been searching and the best I could find was:

```<code>SELECT Col.Column_Name from
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'
</code>```

this retrieves the PK's of a specific table, I want to find table_name BY PK name.

```<code>SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
and    ordinal_position = 1;
</code>```

also found this but this gives me the first column of the table, which doesn't ensure me that it it the PK.

Couldn't find any duplicate either.

答:
Would this work for you?</p>

```<code>DECLARE @ColName AS VARCHAR(MAX)
SET @ColName = 'CourseId'
SELECT
    TABLE_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    AND COLUMN_NAME = @ColName
</code>```

Body:
I'm searching for a query that can retrieve all the tables by the specified key/keys name on a specific database.
Something like this:

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
AND    Constraint_Type = 'PRIMARY KEY'

I've been searching and the best I could find was:

SELECT Col.Column_Name from
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'

this retrieves the PK's of a specific table, I want to find table_name BY PK name.

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
and    ordinal_position = 1;

also found this but this gives me the first column of the table, which doesn't ensure me that it it the PK.

Couldn't find any duplicate either.

Body:
Would this work for you?

DECLARE @ColName AS VARCHAR(MAX)
SET @ColName = 'CourseId'
SELECT
    TABLE_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    AND COLUMN_NAME = @ColName


问:
Why does the code below return 4:14 PM instead of 3:14 PM?
I'm trying to convert a UTC to a CST by using the 'ConvertTimeFromUtc' method.  However, the result is off by 1 hour compared to what I got when I try to convert it manually online.</p>

```<code>StatusDatetime is 2017-06-05 21:14:39.6216795
TimeZoneInfo.ConvertTimeFromUtc(StatusDatetime.Value,
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")).ToString("hh:mm
tt")
</code>```

答: Try using Central Daylight Time instead of Central Standard Time, as we are in daylight savings time.</p>

Body:
I'm trying to convert a UTC to a CST by using the 'ConvertTimeFromUtc' method.  However, the result is off by 1 hour compared to what I got when I try to convert it manually online.

StatusDatetime is 2017-06-05 21:14:39.6216795
TimeZoneInfo.ConvertTimeFromUtc(StatusDatetime.Value,
TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")).ToString("hh:mm
tt")


问:
What do DateTime? and using(var x = new y()) mean?
I don't understand what the following lines mean, please explain them to me.

1.

```<code>DateTime? pInsertDate;
</code>```

At this variable declaration, What does ? mean?

2.

```<code>using (TransactionScope scope = new TransactionScope())
</code>```

At this object creation, What does using mean?

答:
The ? suffix is syntactic sugar for using Nullable<T>. So your declaration is equivalent to:

```<code>Nullable<DateTime> pInsertDate;
</code>```

See the MSDN documentation for nullable value types for more information. Basically a nullable value type value can represent any of the values of the non-nullable underlying type (DateTime in this case) as well as the special "null" value. This isn't a null reference, but it's usually used with the same sort of connotations - "no value". For example, a Person class might have a DateTime DateOfBirth property, but a DateTime? DateOfDeath property, which would be null if the person was still alive.

A using statement is a way of automatically calling Dispose on the reference acquired in the first part of the statement at the end of the body. So your code is broadly equivalent to:

```<code>TransactionScope scope = new TransactionScope();
try
{
    // Body of the using statement
}
finally
{
    if (scope != null)
    {
        scope.Dispose();
    }
}
</code>```

In this case of course we know thatscope won't be null because we're calling a constructor, but that's the general expansion. (You could have used a method call to obtain the transaction scope, for example - in which case it could have returned null, but the generated code won't throw a NullReferenceException.)

Body:
I don't understand what the following lines mean, please explain them to me.

1.

DateTime? pInsertDate;

At this variable declaration, What does ? mean?

2.

using (TransactionScope scope = new TransactionScope())

At this object creation, What does using mean?

Body:
The ? suffix is syntactic sugar for using Nullable<T>. So your declaration is equivalent to:

Nullable<DateTime> pInsertDate;

See the MSDN documentation for nullable value types for more information. Basically a nullable value type value can represent any of the values of the non-nullable underlying type (DateTime in this case) as well as the special "null" value. This isn't a null reference, but it's usually used with the same sort of connotations - "no value". For example, a Person class might have a DateTime DateOfBirth property, but a DateTime? DateOfDeath property, which would be null if the person was still alive.

A using statement is a way of automatically calling Dispose on the reference acquired in the first part of the statement at the end of the body. So your code is broadly equivalent to:

TransactionScope scope = new TransactionScope();
try
{
    // Body of the using statement
}
finally
{
    if (scope != null)
    {
        scope.Dispose();
    }
}

In this case of course we know thatscope won't be null because we're calling a constructor, but that's the general expansion. (You could have used a method call to obtain the transaction scope, for example - in which case it could have returned null, but the generated code won't throw a NullReferenceException.)


问:
cannot set property 'color' of undefined
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

```<code><div class="input-field inline center-align">
  <input id="quantity" name="quantity" type="number" class="">
  <label for="qty" data-error="wrong" data-success="right"
       class="active">Qty</label>
  <span id="qty-error">really?</span>
</div>
</code>```

JS:

```<code>$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});
</code>```

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined

答: $Label is a jQuery object, not a standard node element, so you can either do $Label[0].style.color = '#8e8ef5'; or $Label.css('color', '#8e8ef5');

Body:
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

  <input id="quantity" name="quantity" type="number" class="">
  Qty
  really?

JS:

$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined


答:
.style is property of an element. With jQuery you've that element in array. More like [elem]. So, use:

```<code>$Label.css('color', '#f96d63');
</code>```

or

```<code>$Label.get(0).style.color = '#8e8ef5';
</code>```

But the first one is more jQueryish.

Title: cannot set property 'color' of undefined

Body:
.style is property of an element. With jQuery you've that element in array. More like [elem]. So, use:

$Label.css('color', '#f96d63');

or

$Label.get(0).style.color = '#8e8ef5';

But the first one is more jQueryish.


问:
Trigger jquery plugin onclick automatically
I have a jquery plugin that shows a hidden div and animate when you click the button. I've used the jquery.fn prototype.

This is the jquery plugin

```<code> (function($) {
            'use strict';
            $.fn.launchBtn = function(options) {
               var mainBtn, panel, clicks, settings, launchPanelAnim, closePanelAnim, openPanel, boxClick, panelBody, panelMedia;
               mainBtn = $(".proactive-chat-button");
               panel = $("#proactive-chat .panel");
               panelMedia = $("#proactive-chat .panel-media");
               panelBody = $("#proactive-chat .panel-body");
               clicks = 0;
               //default settings
               settings = $.extend({
                  openDuration: 600,
                  closeDuration: 200,
                  rotate: true
               }, options);
               //Open panel animation
               launchPanelAnim = function() {
                  $(panel).removeClass('swift-out');
                  $(panelMedia).removeClass('swift-out');
                  $(panelBody).removeClass('swift-out');
                  panel.animate({
                     opacity: "show",
                     width: "show",
                     height: "show",
                  }, settings.openDuration);
                  $(panel).addClass('swift-in');
                  $(panelMedia).addClass('swift-in');
                  $(panelBody).addClass('swift-in');
                  panelMedia.animate({
                     opacity: "show",
                     width: "slideDown",
                     height: "slideDown",
                     transitionDelay: "0.1s"
                  }, settings.openDuration);

                  calculate();
                  $('.proactive-chat-button').addClass('shadow-3');

               };
               //Close panel animation
               closePanelAnim = function() {
                  $(panel).removeClass('swift-in');
                  $(panelMedia).removeClass('swift-in');
                  $(panelBody).removeClass('swift-in');
                  $(panel).addClass('swift-out');
                  $(panelMedia).addClass('swift-out');
                  $(panelBody).addClass('swift-out');
                  panel.animate({
                     opacity: "hide",
                     width: "hide",
                     height: "hide"
                  }, settings.closeDuration);
                  panelMedia.animate({
                     opacity: "hide",
                     width: "slideDown",
                     height: "slideDown",
                     transitionDelay: "0.02s"
                  }, settings.openDuration);
                  $('.proactive-chat-button').removeClass('shadow-3');
                  $('.modal-overlay').fadeOut(100);
               };
               //Open panel and rotate icon
               openPanel = function(e) {
                  if (clicks === 0) {
                     if (settings.rotate) {
                        // $('.proactive-chat-icon').removeClass('rotateBackward').toggleClass('rotateForward');
                     }
                     launchPanelAnim();
                     clicks++;
                  } else {
                     if (settings.rotate) {
                        //$('.proactive-chat-icon').removeClass('rotateForward').toggleClass('rotateBackward');
                     }
                     closePanelAnim();
                     clicks--;
                  }
                  e.preventDefault();
                  return false;
               };
               //Allow clicking in panel
               boxClick = function(e) {
                  e.stopPropagation();
               };
               //Main button click
               mainBtn.on('click', openPanel);
               //Prevent closing panel when clicking inside
               panel.click(boxClick);
               $('.proactive-chat-icon').click(function() {
                  $('.proactive-chat-icon .procty').toggleClass('proactive-procty-close').toggleClass('proactive-procty');
               });
               $('.panel-heading-button').click(function() {
                  if (clicks === 0) {
                     if (settings.rotate) {
                        // $('.proactive-chat-icon').removeClass('rotateBackward').toggleClass('rotateForward');
                        $('.proactive-chat-icon .procty').toggleClass('proactive-procty-close').toggleClass('proactive-procty');
                     }
                     launchPanelAnim();
                     clicks++;
                  } else {
                     if (settings.rotate) {
                        //$('.proactive-chat-icon').removeClass('rotateForward').toggleClass('rotateBackward');
                        $('.proactive-chat-icon .procty').toggleClass('proactive-procty').toggleClass('proactive-procty-close');
                     }
                     closePanelAnim();
                     clicks--;
                  }
               });
               $(document).click(function() {
                  closePanelAnim();
                  if (clicks === 1) {
                     $('.proactive-chat-icon .procty').toggleClass('proactive-procty').toggleClass('proactive-procty-close');

                  }
                  clicks = 0;
               });
            };
         }(jQuery));
</code>```

and to use that I've called the method launchBtn()

```<code> $("#proactive-chat").click().launchBtn({
                    openDuration: 250,
                    closeDuration: 300
                 });
</code>```

My concern is I want to trigger it automatically when an interval or condition is met. I've used $('#proactive-chat').trigger('click') however it doesn't work. Is there any way I can trigger it automatically? Thank you in advance.

答:
.click() returns the jQuery object and thus your function is never called on a click event. If you want it to fire during clicks you need to add a handler function as a parameter to click() like so:

```<code>$("#proactive-chat").click(function(){
    $(this).launchBtn({
        openDuration: 250,
        closeDuration: 300
    });
});
</code>```

In this form .trigger('click') should work, although I don't quite understand why you would use the $.fn prototype when you don't reference this anywhere in your plugin. This could have been a simple function.

Body:
I have a jquery plugin that shows a hidden div and animate when you click the button. I've used the jquery.fn prototype.

This is the jquery plugin

 (function($) {
            'use strict';
            $.fn.launchBtn = function(options) {
               var mainBtn, panel, clicks, settings, launchPanelAnim, closePanelAnim, openPanel, boxClick, panelBody, panelMedia;
               mainBtn = $(".proactive-chat-button");
               panel = $("#proactive-chat .panel");
               panelMedia = $("#proactive-chat .panel-media");
               panelBody = $("#proactive-chat .panel-body");
               clicks = 0;
               //default settings
               settings = $.extend({
                  openDuration: 600,
                  closeDuration: 200,
                  rotate: true
               }, options);
               //Open panel animation
               launchPanelAnim = function() {
                  $(panel).removeClass('swift-out');
                  $(panelMedia).removeClass('swift-out');
                  $(panelBody).removeClass('swift-out');
                  panel.animate({
                     opacity: "show",
                     width: "show",
                     height: "show",
                  }, settings.openDuration);
                  $(panel).addClass('swift-in');
                  $(panelMedia).addClass('swift-in');
                  $(panelBody).addClass('swift-in');
                  panelMedia.animate({
                     opacity: "show",
                     width: "slideDown",
                     height: "slideDown",
                     transitionDelay: "0.1s"
                  }, settings.openDuration);

                  calculate();
                  $('.proactive-chat-button').addClass('shadow-3');

               };
               //Close panel animation
               closePanelAnim = function() {
                  $(panel).removeClass('swift-in');
                  $(panelMedia).removeClass('swift-in');
                  $(panelBody).removeClass('swift-in');
                  $(panel).addClass('swift-out');
                  $(panelMedia).addClass('swift-out');
                  $(panelBody).addClass('swift-out');
                  panel.animate({
                     opacity: "hide",
                     width: "hide",
                     height: "hide"
                  }, settings.closeDuration);
                  panelMedia.animate({
                     opacity: "hide",
                     width: "slideDown",
                     height: "slideDown",
                     transitionDelay: "0.02s"
                  }, settings.openDuration);
                  $('.proactive-chat-button').removeClass('shadow-3');
                  $('.modal-overlay').fadeOut(100);
               };
               //Open panel and rotate icon
               openPanel = function(e) {
                  if (clicks === 0) {
                     if (settings.rotate) {
                        // $('.proactive-chat-icon').removeClass('rotateBackward').toggleClass('rotateForward');
                     }
                     launchPanelAnim();
                     clicks++;
                  } else {
                     if (settings.rotate) {
                        //$('.proactive-chat-icon').removeClass('rotateForward').toggleClass('rotateBackward');
                     }
                     closePanelAnim();
                     clicks--;
                  }
                  e.preventDefault();
                  return false;
               };
               //Allow clicking in panel
               boxClick = function(e) {
                  e.stopPropagation();
               };
               //Main button click
               mainBtn.on('click', openPanel);
               //Prevent closing panel when clicking inside
               panel.click(boxClick);
               $('.proactive-chat-icon').click(function() {
                  $('.proactive-chat-icon .procty').toggleClass('proactive-procty-close').toggleClass('proactive-procty');
               });
               $('.panel-heading-button').click(function() {
                  if (clicks === 0) {
                     if (settings.rotate) {
                        // $('.proactive-chat-icon').removeClass('rotateBackward').toggleClass('rotateForward');
                        $('.proactive-chat-icon .procty').toggleClass('proactive-procty-close').toggleClass('proactive-procty');
                     }
                     launchPanelAnim();
                     clicks++;
                  } else {
                     if (settings.rotate) {
                        //$('.proactive-chat-icon').removeClass('rotateForward').toggleClass('rotateBackward');
                        $('.proactive-chat-icon .procty').toggleClass('proactive-procty').toggleClass('proactive-procty-close');
                     }
                     closePanelAnim();
                     clicks--;
                  }
               });
               $(document).click(function() {
                  closePanelAnim();
                  if (clicks === 1) {
                     $('.proactive-chat-icon .procty').toggleClass('proactive-procty').toggleClass('proactive-procty-close');

                  }
                  clicks = 0;
               });
            };
         }(jQuery));

and to use that I've called the method launchBtn()

 $("#proactive-chat").click().launchBtn({
                    openDuration: 250,
                    closeDuration: 300
                 });

My concern is I want to trigger it automatically when an interval or condition is met. I've used $('#proactive-chat').trigger('click') however it doesn't work. Is there any way I can trigger it automatically? Thank you in advance.

Body:
.click() returns the jQuery object and thus your function is never called on a click event. If you want it to fire during clicks you need to add a handler function as a parameter to click() like so:

$("#proactive-chat").click(function(){
    $(this).launchBtn({
        openDuration: 250,
        closeDuration: 300
    });
});

In this form .trigger('click') should work, although I don't quite understand why you would use the $.fn prototype when you don't reference this anywhere in your plugin. This could have been a simple function.


问:
Issues when trying to run Envoy front-proxy example
I'm new with all this technologies and environments.
I tried to run the lyft/envoy example that locate in the github repository .

I followed their guide , step by step, and its not working.
I'm using Docker as container platform ( as mention in the guide), python version 2.7.13 installed.

When i execute 'docker-compose up --build -d' as mentioned in the guide, I suppose to see when i execute 'docker-compose ps' that the envoy-fronproxy and the other two services are UP and running, but in my case , the envoy-frontproxy is UP and the other two services failed with 'Exit 127'.
Additionally, when I execute 'docker-compose up --build -d' I get somewhere in the middle of the output log the following error(maybe its relevant):

I'll just say I did not change any configuration or any file in the supplied example folder.

Update 2/6/17:
I adding docker logs screen shots:

Thanks a lot!

答:
After a lot of research and debugging, and with little help from @Robert , i managed to solve the issue.

The missing file start_service.sh was not found , because it was not UNIX EOL conversion .

Simple dos2unix solved the issue.

@Robert, thanks! and i hope it will save time for others.


问:
How can I make a java program always running?
How can I make a java program such that it is always running on the system (such as a daemon or service), but only allow one instance of the program to run? I would like it to start either when I run the program or when the system starts (either is fine).</p>

答: I've used this to run a Java program as Windows service service : http://wrapper.tanukisoftware.com/ , with good results.</p>


问:
Deployment slot specific appsettin in ARM template?
I'm trying to get into that Visual Studio Resource Group template.
So far it's looking good, and I have added some appsettings for a web app, but my question is, how can I make them deployment slot specific? Is there something in the json for the template or the parameter file?</p>

答:
The accepted answer is correct, but leaves out an important piece of information.  Under its current implementation, when swapping slots the AppSettings configuration for the slot will be swapped along with the deployment.  If you are concerned about slot-specific configuration then this probably is not desirable for you.

To make the configuration "Sticky" to a slot, use the following resource in your ARM template.  Note that the slotconfignames section has been added to the ARM template snippet from Tom's answer above.

```<code>"resources": [
        {
          "apiVersion": "2015-08-01",
          "name": "appsettings",
          "type": "config",
          "dependsOn": [
            "[resourceId('Microsoft.Web/Sites/Slots', variables('webSiteName'), 'Staging')]"
          ],
          "properties": {
            "AppSettingKey1": "Some staging value",
            "AppSettingKey2": "My second staging setting",
            "AppSettingKey3": "My third staging setting"
          },
      {
        "apiVersion": "2015-08-01",
        "name": "slotconfignames",
        "type": "config",
        "dependsOn": [
          "[resourceId('Microsoft.Web/Sites', variables('webSiteName'))]"
        ],
        "properties": {
          "appSettingNames": [ "AppSettingKey1", "AppSettingKey2" ]
        }
      }
    ]
</code>```

This will make AppSettingKey1 and AppSettingKey2 sticky to the Staging slot (They will not swap along with the deployment).

See "Azure Resource Manager Templates Tips and Tricks" from Anthony Chu for more details on sticky slot settings as well as other ARM template tips.

Body:
The accepted answer is correct, but leaves out an important piece of information.  Under its current implementation, when swapping slots the AppSettings configuration for the slot will be swapped along with the deployment.  If you are concerned about slot-specific configuration then this probably is not desirable for you.

To make the configuration "Sticky" to a slot, use the following resource in your ARM template.  Note that the slotconfignames section has been added to the ARM template snippet from Tom's answer above.

"resources": [
        {
          "apiVersion": "2015-08-01",
          "name": "appsettings",
          "type": "config",
          "dependsOn": [
            "[resourceId('Microsoft.Web/Sites/Slots', variables('webSiteName'), 'Staging')]"
          ],
          "properties": {
            "AppSettingKey1": "Some staging value",
            "AppSettingKey2": "My second staging setting",
            "AppSettingKey3": "My third staging setting"
          },
      {
        "apiVersion": "2015-08-01",
        "name": "slotconfignames",
        "type": "config",
        "dependsOn": [
          "[resourceId('Microsoft.Web/Sites', variables('webSiteName'))]"
        ],
        "properties": {
          "appSettingNames": [ "AppSettingKey1", "AppSettingKey2" ]
        }
      }
    ]

This will make AppSettingKey1 and AppSettingKey2 sticky to the Staging slot (They will not swap along with the deployment).

See "Azure Resource Manager Templates Tips and Tricks" from Anthony Chu for more details on sticky slot settings as well as other ARM template tips.


问:
how to open screen on full screen
how i can open my asp.net program on full screen (like i press F11)

Through C# code ?

thanks

答:
Use javascript

```<code>Button1.Attributes.Add("onclick","window.open('Default.aspx','','fullscreen=yes')");
</code>```

not exactly full screen  but pretty similar

Title: how to open screen on full screen

Body:
Use javascript

Button1.Attributes.Add("onclick","window.open('Default.aspx','','fullscreen=yes')");

not exactly full screen  but pretty similar


问:
Getting runtime error 1004 after putting error handler?
Why does this not suppress errors?

```<code>For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I
</code>```

This is what I get:

答:
Before we begin, your code is not set up properly for error handling.

I found that once the GoTo errohandler1 had been executed in the first instance, future calls were ignored so that's when the errors were thrown.

You current code is set up to ignore errors when opening workbooks, you can achieve this using Resume Next, and then GoTo 0 to reset the error handling method.

```<code>    For i = 1 To Last_row

        On Error Resume Next
        Set wkb = Workbooks.Open(Filename:=l)
        On Error GoTo 0

        If Not wkb Is Nothing Then
            '' my code
        End If
    next I
</code>```

If you want to actually deal with errors -- rather than ignore them, you should do so outside of your loop (strongly encouraged!)

```<code>    For i = 1 To Last_row
        On Error GoTo CleanFail
        Set wkb = Workbooks.Open(Filename:=l)
        '' my code
    next I

    Exit Sub

CleanFail:
    'deal with error
</code>```

Body:
Why does this not suppress errors?

For i = 1 To Last_row

    On Error GoTo errorhandler1
    Set wkb = Workbooks.Open(Filename:=l)

    '' my code

errorhandler1:

next I

This is what I get:

Body:
Before we begin, your code is not set up properly for error handling.

I found that once the GoTo errohandler1 had been executed in the first instance, future calls were ignored so that's when the errors were thrown.

You current code is set up to ignore errors when opening workbooks, you can achieve this using Resume Next, and then GoTo 0 to reset the error handling method.

    For i = 1 To Last_row

        On Error Resume Next
        Set wkb = Workbooks.Open(Filename:=l)
        On Error GoTo 0

        If Not wkb Is Nothing Then
            '' my code
        End If
    next I

If you want to actually deal with errors -- rather than ignore them, you should do so outside of your loop (strongly encouraged!)

    For i = 1 To Last_row
        On Error GoTo CleanFail
        Set wkb = Workbooks.Open(Filename:=l)
        '' my code
    next I

    Exit Sub

CleanFail:
    'deal with error


问:
Rounding a double value to x number of decimal places in swift
Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

```<code>var totalWorkTimeInHours = (totalWorkTime/60/60)
</code>```

With totalWorkTime being an NSTimeInterval (double) in second.

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

答:
The best way to format a double property is to use the Apple predefined methods.

```<code>mutating func round(_ rule: FloatingPointRoundingRule)
</code>```

FloatingPointRoundingRule is a enum which has following possibilities

Enumeration Cases:

case awayFromZero
Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

case down
Round to the closest allowed value that is less than or equal to the source.

case toNearestOrAwayFromZero
Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

case toNearestOrEven
Round to the closest allowed value; if two values are equally close, the even one is chosen.

case towardZero
Round to the closest allowed value whose magnitude is less than or equal to that of the source.

case up
Round to the closest allowed value that is greater than or equal to the source.

```<code>var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0
</code>```

Body:
Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With totalWorkTime being an NSTimeInterval (double) in second.

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

Body:
The best way to format a double property is to use the Apple predefined methods.

mutating func round(_ rule: FloatingPointRoundingRule)

FloatingPointRoundingRule is a enum which has following possibilities

Enumeration Cases:

case awayFromZero
Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

case down
Round to the closest allowed value that is less than or equal to the source.

case toNearestOrAwayFromZero
Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

case toNearestOrEven
Round to the closest allowed value; if two values are equally close, the even one is chosen.

case towardZero
Round to the closest allowed value whose magnitude is less than or equal to that of the source.

case up
Round to the closest allowed value that is greater than or equal to the source.

var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0


问:
Java 8 peek vs map
I have following case: there is a list of objects - ProductData which contains several fields:

```<code>public class ProductData
{
....
  private String name;
  private String xref;

  //getters
  //setters
}
</code>```

and there is API which returns list of following objects:

```<code>public class RatingTableRow
{
  private String planName;
  private String planXref;
  private int fromAge;
  private int toAge;
  private int ratingRegion;

 //constructor
 //getters
 //setters

}
</code>```

but it returns objects with empty plan name field because it's not allowed during extraction of this object. I need to link product data with RatingTableRow by the xref in order to set plan name into the RatingTableRow because I need to use this object later so I created following code to do that:

```<code>Map<String, ProductData> productByXref = plans.stream()
        .collect(toMap(ProductData::getInternalCode, Function.identity()));

return getRatingTableRows(...).stream
        .filter(ratingRow -> productByXref.containsKey(ratingRow.getPlanXref()))
        .peek(row -> {
                ProductData product = productByXref.get(row.getPlanXref());
                row.setPlanName(product.getName());
        })....;
</code>```

I know that java docs say that peek doesn't fit these needs but want to get your suggestions on how to make this task in more correct way.

答:
There is a reason peek is documented to be mainly for debugging purposes.

Something that ends up being processed inside peek might not be eligible for the terminal operation at all and streams are executed only by a terminal operation.

Suppose a trivial example first:

```<code>    List<Integer> list = new ArrayList<>();
    List<Integer> result = Stream.of(1, 2, 3, 4)
            .peek(x -> list.add(x))
            .map(x -> x * 2)
            .collect(Collectors.toList());

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

Everything looks fine right? Because peek will run for all elements in this case. But what happens when you add a filter (and forget about what peek did):

```<code> .peek(x -> list.add(x))
 .map(x -> x * 2)
 .filter(x -> x > 8) // you have inserted a filter here
</code>```

You are executing peek for every element, but collecting none. You sure you want that?

This can get even trickier:

```<code>    long howMany = Stream.of(1, 2, 3, 4)
            .peek(x -> list.add(x))
            .count();

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

In java-8 the list is populated, but in jdk-9 peek is not called at all. Since you are not using filter or flatmap you are not modifying the size of the Stream and count only needs it's size; thus peek is not called at all. Thus relying on peek is a very bad strategy.

Title: Java 8 peek vs map

Body:
I have following case: there is a list of objects - ProductData which contains several fields:

public class ProductData
{
....
  private String name;
  private String xref;

  //getters
  //setters
}

and there is API which returns list of following objects:

public class RatingTableRow
{
  private String planName;
  private String planXref;
  private int fromAge;
  private int toAge;
  private int ratingRegion;

 //constructor
 //getters
 //setters

}

but it returns objects with empty plan name field because it's not allowed during extraction of this object. I need to link product data with RatingTableRow by the xref in order to set plan name into the RatingTableRow because I need to use this object later so I created following code to do that:

Map<String, ProductData> productByXref = plans.stream()
        .collect(toMap(ProductData::getInternalCode, Function.identity()));

return getRatingTableRows(...).stream
        .filter(ratingRow -> productByXref.containsKey(ratingRow.getPlanXref()))
        .peek(row -> {
                ProductData product = productByXref.get(row.getPlanXref());
                row.setPlanName(product.getName());
        })....;

I know that java docs say that peek doesn't fit these needs but want to get your suggestions on how to make this task in more correct way.

Body:
There is a reason peek is documented to be mainly for debugging purposes.

Something that ends up being processed inside peek might not be eligible for the terminal operation at all and streams are executed only by a terminal operation.

Suppose a trivial example first:

    List<Integer> list = new ArrayList<>();
    List<Integer> result = Stream.of(1, 2, 3, 4)
            .peek(x -> list.add(x))
            .map(x -> x * 2)
            .collect(Collectors.toList());

    System.out.println(list);
    System.out.println(result);

Everything looks fine right? Because peek will run for all elements in this case. But what happens when you add a filter (and forget about what peek did):

 .peek(x -> list.add(x))
 .map(x -> x * 2)
 .filter(x -> x > 8) // you have inserted a filter here

You are executing peek for every element, but collecting none. You sure you want that?

This can get even trickier:

    long howMany = Stream.of(1, 2, 3, 4)
            .peek(x -> list.add(x))
            .count();

    System.out.println(list);
    System.out.println(howMany);

In java-8 the list is populated, but in jdk-9 peek is not called at all. Since you are not using filter or flatmap you are not modifying the size of the Stream and count only needs it's size; thus peek is not called at all. Thus relying on peek is a very bad strategy.


问:
Getting list of running containers from a cluster
I am running docker containers on an AWS via ECS. I have setup a cluster with some basic configuration.

Now I am looking forward to get no. of all running containers on this cluster (spread across 2-3 EC2 instances)? Does AWS / Docker provide any API for this?

I know on a container instance, doing docker ps -a will return me list of all running / stopped containers, while docker ps will return running containers on one system. But I want an API (which can be called from outside) or command (which I can run on any of the instance part of the cluster) and it shows me total number of running containers across cluster?

答:
In ECS you're looking at tasks. You can list all running tasks with the ECS API. With the aws cli, for example, you can do:

```<code>aws ecs list-tasks --cluster <cluster_name>
</code>```

If you use one of the SDKs, for example boto3, you can obtain the count easily:

```<code>import boto3

client = boto3.client('ecs')

tasks = client.list_tasks(cluster='YouCluster')

print(len(tasks['taskArns'])
</code>```

Body:
In ECS you're looking at tasks. You can list all running tasks with the ECS API. With the aws cli, for example, you can do:

aws ecs list-tasks --cluster <cluster_name>

If you use one of the SDKs, for example boto3, you can obtain the count easily:

import boto3

client = boto3.client('ecs')

tasks = client.list_tasks(cluster='YouCluster')

print(len(tasks['taskArns'])


问:
protractor FOR loop using expectations
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

```<code>myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });
</code>```

答: Full test-case code would help, but I assume that you've forgot to either return a promise from 'it' or define and call 'done' callback, since what you're doing - is an async operation.</p>

Title: protractor FOR loop using expectations

Body:
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });


问:
Insert in vector after each even value specific number
I need to insert -20 after each even element, but my code not workint correctly,
what i'm doing wrong?</p>

```<code>srand(time(NULL));
vector <int> v;

for (int i = 0; i < 15; i++)
{
    v.push_back(rand()%100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i]%2==0)
    {
        v.insert(v.begin()+i, -20);

    }
    cout << v[i] << endl;
    i = i + 1;
}
</code>```

答:
```<code>vector <int> v;

v.reserve(15);
for (int i = 0; i < 15; i++)
{
    v.push_back(rand() % 100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i] % 2 == 0)
    {
        v.insert(v.begin() + i + 1, -20); // We insert at the next position
        i++; // We make additional increment only if insertion took place
    }
}

for (int i = 0; i < v.size(); i++)
{
    cout << v[i] << endl;
}
</code>```

The output (with spaces intead of linebreaks)

```<code>41 67 34 0 69 24 78 58 62 64 5 45 81 27 61

Vector after inserting new value:

41 67 34 -20 0 -20 69 24 -20 78 -20 58 -20 62 -20 64 -20 5 45 81 27 61
</code>```

Body:
I need to insert -20 after each even element, but my code not workint correctly,
what i'm doing wrong?

srand(time(NULL));
vector <int> v;

for (int i = 0; i < 15; i++)
{
    v.push_back(rand()%100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i]%2==0)
    {
        v.insert(v.begin()+i, -20);

    }
    cout << v[i] << endl;
    i = i + 1;
}

Body:
vector <int> v;

v.reserve(15);
for (int i = 0; i < 15; i++)
{
    v.push_back(rand() % 100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i] % 2 == 0)
    {
        v.insert(v.begin() + i + 1, -20); // We insert at the next position
        i++; // We make additional increment only if insertion took place
    }
}

for (int i = 0; i < v.size(); i++)
{
    cout << v[i] << endl;
}

The output (with spaces intead of linebreaks)

41 67 34 0 69 24 78 58 62 64 5 45 81 27 61

Vector after inserting new value:

41 67 34 -20 0 -20 69 24 -20 78 -20 58 -20 62 -20 64 -20 5 45 81 27 61


问:
Using RecyclerView with DataBase
```<code>public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}
</code>```

Contact class is use to save value

```<code>public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}
</code>```

Recycler Adapter class DataManager

```<code>import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}
</code>```

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code

答:
A few weeks ago I was trying use a Cursor to populate a RecyclerView. There is not something like a CursorAdapter for a RecyclerView, you must create your own implementation.

I found a nice tutorial where use a Cursor and a CursorLoader to populate the recView asynchronously. The tutorial is in Spanish but the code is pretty clear a works nice for my app.

http://www.hermosaprogramacion.com/2016/01/recyclerview-con-cursor-en-android/

Title: Using RecyclerView with DataBase

Body:
public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}

Contact class is use to save value

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}

Recycler Adapter class DataManager

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code


答:
Here you go, join TABLE_CONSTRAINTS to CONSTRAINT_COLUMN_USAGE to tie the constraint name to the column then return your TABLE_NAME:</p>

```<code>SELECT CCU.COLUMN_NAME,
       CONS.TABLE_NAME
FROM   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
       JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS
         ON CONS.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
WHERE  CONS.CONSTRAINT_TYPE = 'PRIMARY KEY'
       AND CCU.COLUMN_NAME = 'ID_UNICO'
</code>```

Title: Find all tables in database By primaryKey

Body:
I'm searching for a query that can retrieve all the tables by the specified key/keys name on a specific database.
Something like this:

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
AND    Constraint_Type = 'PRIMARY KEY'

I've been searching and the best I could find was:

SELECT Col.Column_Name from
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'

this retrieves the PK's of a specific table, I want to find table_name BY PK name.

SELECT table_name
FROM   information_Schema.columns
WHERE  column_name='ID_UNICO'
and    ordinal_position = 1;

also found this but this gives me the first column of the table, which doesn't ensure me that it it the PK.

Couldn't find any duplicate either.

Body:
Here you go, join TABLE_CONSTRAINTS to CONSTRAINT_COLUMN_USAGE to tie the constraint name to the column then return your TABLE_NAME:

SELECT CCU.COLUMN_NAME,
       CONS.TABLE_NAME
FROM   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
       JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS
         ON CONS.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
WHERE  CONS.CONSTRAINT_TYPE = 'PRIMARY KEY'
       AND CCU.COLUMN_NAME = 'ID_UNICO'