问:
Pandas: sum values in column if multiple values match str/contains/join
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.

In my sample code, "term2" has entries with both code 'AAAA' and 'CCCC'.

```<code>    df1 = pd.DataFrame(
        {
        'term' : ['term1','term2','term3','term4','term1','term3','term2'],
        'code': ['ZZZZ', 'AAAA','XXXX','QQQQ','ZZZZ','XXXX','CCCC'],
        'count':['1','3','1','1','1','1','3']
        }
        )
df1 = df1[['term'] + df1.columns[:-1].tolist()]
df2 = pd.DataFrame(
        {
        'name': ['Dan','Sara','Conroy','Steve'],
        'rate': ['3','3.5','5.2','3'],
        'location': ['FL','OH','NM','NM'],
        'code': ['XXXX','BBBB','PPPP','TTTT'],
        'allcodes': ['XXXX,YYYY,ZZZZ','AAAA,BBBB,CCCC','PPPP,QQQQ,RRRR','SSSS,TTTT,UUUU']
         }
         )

df2 = df2[['name','rate','location','code','allcodes']]
pmissnlist = df1['code'].values.tolist()
df3 = df2[df2['allcodes'].str.contains('|'.join(pmissnlist))].reset_index()

df4 = pd.DataFrame(df3['allcodes'].str.split(',').tolist(),
                            index=df3.code).stack(level=0).reset_index(level=0)
matches = df4[df4[0].isin(df1.code)]
df5 = df3[df3.code.isin(matches.code)]
df5 = df5.drop_duplicates()#drops duplicate rows

df5_temp = df5.set_index(['name','rate','location','code']).allcodes.str.split(',',expand = True)\
                                  .stack().reset_index(4,drop = True).reset_index(name = 'allcodes')
df5 = pd.merge(df1, df5_temp, left_on = 'code', right_on = 'allcodes')
df5 = df5.drop('allcodes', 1).groupby(['code_y','term','count','name','rate','location']).code_x.\
                                    apply(','.join).reset_index().sort_values(by='count', ascending=False)
print(df5)
</code>```

The output is:

```<code>      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  3      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  1      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  1      Dan    3     FL        XXXX,XXXX
</code>```

There are two instances of term2 associated with Sara, so I want her count to be 6, not 3. The counts should be 2 for each of Dan's rows, too. If I understand the dataframe correctly, this is expected: the dataframe contains the data that satisfies the condition of the first term2. When the second instance is compared, the related data already exists in the dataframe.

How do I sum the count values where multiple codes are matched in the "allcode" field of df2?

EDIT: Adding desired outcome

```<code>      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  6      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  2      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  2      Dan    3     FL        XXXX,XXXX
</code>```

EDIT2:
The problem is with the groupby.

Here is the output of df5 BEFORE the statement with the groupby:

```<code>    term code_x  count    name rate location code_y allcodes
0  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
1  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
2  term2   AAAA      3    Sara  3.5       OH   BBBB     AAAA
3  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
4  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
5  term4   QQQQ      1  Conroy  5.2       NM   PPPP     QQQQ
6  term2   CCCC      2    Sara  3.5       OH   BBBB     CCCC
7  term6   TTTT      1   Steve    3       NM   TTTT     TTTT
</code>```

So, essentially I want counts for the column with the same term (term2 for Sara, and term3 & term4 for Dan) before the groupby.

答:
IIUC , By using str.split and len

```<code>df['count']*=df['code_x'].str.split(',').apply(len)
df
Out[1105]:
  code_y   term  count    name  rate location     code_x
0   BBBB  term2      6    Sara   3.5       OH  AAAA,CCCC
1   PPPP  term4      1  Conroy   5.2       NM       QQQQ
2   XXXX  term1      2     Dan   3.0       FL  ZZZZ,ZZZZ
3   XXXX  term3      2     Dan   3.0       FL  XXXX,XXXX
</code>```

EDIT :

```<code>    df.groupby(['code_y','term'],as_index=False).agg({'count':'sum','name':'first','rate':'first','location':'first','code_x':lambda x : ','.join(x),'allcodes':'first'})
Out[1130]:
  code_y   term  count    name  rate location     code_x allcodes
0   BBBB  term2      5    Sara   3.5       OH  AAAA,CCCC     AAAA
1   PPPP  term4      1  Conroy   5.2       NM       QQQQ     QQQQ
2   TTTT  term6      1   Steve   3.0       NM       TTTT     TTTT
3   XXXX  term1      2     Dan   3.0       FL  ZZZZ,ZZZZ     ZZZZ
4   XXXX  term3      2     Dan   3.0       FL  XXXX,XXXX     XXXX
</code>```

Body:
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.

In my sample code, "term2" has entries with both code 'AAAA' and 'CCCC'.

    df1 = pd.DataFrame(
        {
        'term' : ['term1','term2','term3','term4','term1','term3','term2'],
        'code': ['ZZZZ', 'AAAA','XXXX','QQQQ','ZZZZ','XXXX','CCCC'],
        'count':['1','3','1','1','1','1','3']
        }
        )
df1 = df1[['term'] + df1.columns[:-1].tolist()]
df2 = pd.DataFrame(
        {
        'name': ['Dan','Sara','Conroy','Steve'],
        'rate': ['3','3.5','5.2','3'],
        'location': ['FL','OH','NM','NM'],
        'code': ['XXXX','BBBB','PPPP','TTTT'],
        'allcodes': ['XXXX,YYYY,ZZZZ','AAAA,BBBB,CCCC','PPPP,QQQQ,RRRR','SSSS,TTTT,UUUU']
         }
         )

df2 = df2[['name','rate','location','code','allcodes']]
pmissnlist = df1['code'].values.tolist()
df3 = df2[df2['allcodes'].str.contains('|'.join(pmissnlist))].reset_index()

df4 = pd.DataFrame(df3['allcodes'].str.split(',').tolist(),
                            index=df3.code).stack(level=0).reset_index(level=0)
matches = df4[df4[0].isin(df1.code)]
df5 = df3[df3.code.isin(matches.code)]
df5 = df5.drop_duplicates()#drops duplicate rows

df5_temp = df5.set_index(['name','rate','location','code']).allcodes.str.split(',',expand = True)\
                                  .stack().reset_index(4,drop = True).reset_index(name = 'allcodes')
df5 = pd.merge(df1, df5_temp, left_on = 'code', right_on = 'allcodes')
df5 = df5.drop('allcodes', 1).groupby(['code_y','term','count','name','rate','location']).code_x.\
                                    apply(','.join).reset_index().sort_values(by='count', ascending=False)
print(df5)

The output is:

      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  3      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  1      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  1      Dan    3     FL        XXXX,XXXX

There are two instances of term2 associated with Sara, so I want her count to be 6, not 3. The counts should be 2 for each of Dan's rows, too. If I understand the dataframe correctly, this is expected: the dataframe contains the data that satisfies the condition of the first term2. When the second instance is compared, the related data already exists in the dataframe.

How do I sum the count values where multiple codes are matched in the "allcode" field of df2?

EDIT: Adding desired outcome

      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  6      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  2      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  2      Dan    3     FL        XXXX,XXXX

EDIT2:
The problem is with the groupby.

Here is the output of df5 BEFORE the statement with the groupby:

    term code_x  count    name rate location code_y allcodes
0  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
1  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
2  term2   AAAA      3    Sara  3.5       OH   BBBB     AAAA
3  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
4  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
5  term4   QQQQ      1  Conroy  5.2       NM   PPPP     QQQQ
6  term2   CCCC      2    Sara  3.5       OH   BBBB     CCCC
7  term6   TTTT      1   Steve    3       NM   TTTT     TTTT

So, essentially I want counts for the column with the same term (term2 for Sara, and term3 & term4 for Dan) before the groupby.

Body:
IIUC , By using str.split and len

df['count']*=df['code_x'].str.split(',').apply(len)
df
Out[1105]:
  code_y   term  count    name  rate location     code_x
0   BBBB  term2      6    Sara   3.5       OH  AAAA,CCCC
1   PPPP  term4      1  Conroy   5.2       NM       QQQQ
2   XXXX  term1      2     Dan   3.0       FL  ZZZZ,ZZZZ
3   XXXX  term3      2     Dan   3.0       FL  XXXX,XXXX

EDIT :

    df.groupby(['code_y','term'],as_index=False).agg({'count':'sum','name':'first','rate':'first','location':'first','code_x':lambda x : ','.join(x),'allcodes':'first'})
Out[1130]:
  code_y   term  count    name  rate location     code_x allcodes
0   BBBB  term2      5    Sara   3.5       OH  AAAA,CCCC     AAAA
1   PPPP  term4      1  Conroy   5.2       NM       QQQQ     QQQQ
2   TTTT  term6      1   Steve   3.0       NM       TTTT     TTTT
3   XXXX  term1      2     Dan   3.0       FL  ZZZZ,ZZZZ     ZZZZ
4   XXXX  term3      2     Dan   3.0       FL  XXXX,XXXX     XXXX


来源: stackexchange

问:
how to use rails path in href for jquerymobile button
I am working in rails using jquery.mobile button.(/view/sessions/new.html.erb)

I have a hard code path which I tried to change to rails routes path.
Here original hard code:

```<code> <a href="/password_resets/new" data-role="button" data-icon="info" data-mini="true">Forgotten password?</a>
</code>```

My button is OK as expected in 2 nd button

The problem when replaced with rails path (from rake routes) is the link. It only work at the text "Forgotten password", not the button itself.
Here that code:

```<code><div class="actions" data-role="button" data-icon="info" data-mini="true"><%= link_to 'Forgotten password?', new_password_reset_path %></div>
</code>```

How to use rails path inside href?

答:
You can try:</p>

```<code><%= link_to 'Forgotten password?', new_password_reset_path, data: {icon: 'info', mini: 'true', role: 'button'} %>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working in rails using jquery.mobile button.(/view/sessions/new.html.erb)

I have a hard code path which I tried to change to rails routes path.
Here original hard code:

 Forgotten password?

My button is OK as expected in 2 nd button

The problem when replaced with rails path (from rake routes) is the link. It only work at the text "Forgotten password", not the button itself.
Here that code:

<%= link_to 'Forgotten password?', new_password_reset_path %>

How to use rails path inside href?

Body:
You can try:

<%= link_to 'Forgotten password?', new_password_reset_path, data: {icon: 'info', mini: 'true', role: 'button'} %>


问:
Get all conflict dates in a rails query
everyone!

I'm creating a rails app to manage and schedule vacations in a government institution.

The system has to filter the vacations and load them into a grid (see the grid in the link below, in portuguese, sorry for that).

The problem is: I've got to filter all vacations that are in conflict.

Example: (MM-dd-yyyy)

John's vacation: starts in 01-01-2018, ends 01-15-2018.
Marie's vacation start in 01-01-2018, ends 01-10-2018.

John's vacation and Marie's vacation are in conflict.

A person can split your vacation through the year.

How can i write a rails query to get all vacations that are in conflict?

Vacation's schema:

```<code>t.integer "fs_manager_id", limit: 19, precision: 19
t.integer "year", precision: 38
t.date "date_ini"
t.date "date_end"
t.integer "days", precision: 38
t.boolean "approved", default: false
t.datetime "date_approved", precision: 6
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "fs_balance_id", precision: 38
t.integer "fs_person_id", precision: 38
t.index ["fs_balance_id"], name: "i_fs_vacations_fs_balance_id"
t.index ["fs_manager_id"], name: "i_fs_vacations_fs_manager_id"
t.index ["fs_person_id"], name: "i_fs_vacations_fs_person_id"
</code>```

Image: Grid with all vacations and vacation's owner dd/MM/yyyy

EDIT : The problem is: I've got to filter all vacations that are in conflict and show them to user.

答:
The following is how you can do this in ActiveRecord version 5 or above, broken up and assembled in a few chunks.  You need to join vacations to itself, which I have done with the alias conflicts:

# Match only on differing ids because each vacation will conflict with itself in the result
conflict_join = Vacation.joins("LEFT JOIN vacations AS conflicts ON conflicts.id != vacations.id")

conflict_by_start_date = conflict_join.where("conflicts.start_date >= vacations.start_date AND conflicts.start_date <= vacations.end_date")
conflict_by_end_date = conflict_join.where("conflicts.end_date >= vacataions.start_date AND conflicts.end_date <= vacations.end_date")

# Can only use the .or function in ActiveRecord 5 or above
conflicts = conflict_by_start_date.or(conflict_by_end_date)
```

The result will be all vacations that have another conflicting vacation.  If vacation A conflicts with vacation B, then A and B will be included in the results.  In the case of multiple conflicts, like A conflicts with B and conflicts with C, then A would appear multiple times so you may want to handle that somehow.

This query could also be used to get a result which will show which specific vacations conflict with one another via a select like conflicts.select("vacations.id AS vacation_id, conflicts.id AS conflicting_vacation_id")

Title: Get all conflict dates in a rails query

Body:
everyone!

I'm creating a rails app to manage and schedule vacations in a government institution.

The system has to filter the vacations and load them into a grid (see the grid in the link below, in portuguese, sorry for that).

The problem is: I've got to filter all vacations that are in conflict.

Example: (MM-dd-yyyy)

John's vacation: starts in 01-01-2018, ends 01-15-2018.
Marie's vacation start in 01-01-2018, ends 01-10-2018.

John's vacation and Marie's vacation are in conflict.

A person can split your vacation through the year.

How can i write a rails query to get all vacations that are in conflict?

Vacation's schema:

t.integer "fs_manager_id", limit: 19, precision: 19
t.integer "year", precision: 38
t.date "date_ini"
t.date "date_end"
t.integer "days", precision: 38
t.boolean "approved", default: false
t.datetime "date_approved", precision: 6
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "fs_balance_id", precision: 38
t.integer "fs_person_id", precision: 38
t.index ["fs_balance_id"], name: "i_fs_vacations_fs_balance_id"
t.index ["fs_manager_id"], name: "i_fs_vacations_fs_manager_id"
t.index ["fs_person_id"], name: "i_fs_vacations_fs_person_id"

Image: Grid with all vacations and vacation's owner dd/MM/yyyy

EDIT : The problem is: I've got to filter all vacations that are in conflict and show them to user.

Body:
The following is how you can do this in ActiveRecord version 5 or above, broken up and assembled in a few chunks.  You need to join vacations to itself, which I have done with the alias conflicts:

# Match only on differing ids because each vacation will conflict with itself in the result
conflict_join = Vacation.joins("LEFT JOIN vacations AS conflicts ON conflicts.id != vacations.id")

conflict_by_start_date = conflict_join.where("conflicts.start_date >= vacations.start_date AND conflicts.start_date <= vacations.end_date")
conflict_by_end_date = conflict_join.where("conflicts.end_date >= vacataions.start_date AND conflicts.end_date <= vacations.end_date")

# Can only use the .or function in ActiveRecord 5 or above
conflicts = conflict_by_start_date.or(conflict_by_end_date)

The result will be all vacations that have another conflicting vacation.  If vacation A conflicts with vacation B, then A and B will be included in the results.  In the case of multiple conflicts, like A conflicts with B and conflicts with C, then A would appear multiple times so you may want to handle that somehow.

This query could also be used to get a result which will show which specific vacations conflict with one another via a select like conflicts.select("vacations.id AS vacation_id, conflicts.id AS conflicting_vacation_id")


问:
"Cannot read property 'parentNode' of undefined"- Angular, HTML, Typescript
I'm getting an error which reads:
"Cannot read property 'parentNode' of undefined". I am using Angular. I have Typescript and HTML files. The code is below.

Typescript:

```<code>public deleteRow(btn) {
    console.log("parentNode:" + btn.parentNode);
    var row = btn.parentNode.parentNode;
    row.parentNode.removeChild(row);
  }
</code>```

HTML:

```<code><tr bg-color="#2b5dd1" *ngFor="let row of rows; let even = even; let odd = odd" [ngClass]="{ odd: odd, even: even}" class = "even">
      <td><input type="text" [(contenteditableModel)]="text1"  tabindex="1"></td>
      <td><input type="text" [(contenteditableModel)]="text2" tabindex="2"></td>
      <td><input type="text" [(contenteditableModel)]="text2" tabindex="3"></td>
      <td class="actions">
        <input type="button" value="Delete" (click)="deleteRow(this)">
      </td>
    </tr>
</code>```

I am not sure what's going wrong, it should work perfectly.
I'm working on putting together a Stackblitz to demonstrate how it works.
Any comments or suggestions would be appreciated.

Thank you.

答:
the keyword this doesn't work like that in Angular templates, you generally won't be accessing the DOM directly, as Angular handles that for you, the idea is you update the model and angular takes care of the view.  Try it like this instead:

```<code><tr bg-color="#2b5dd1" *ngFor="let row of rows; let even = even; let odd = odd; let index = index" [ngClass]="{ odd: odd, even: even}" class = "even">
  <td><input type="text" [(contenteditableModel)]="text1"  tabindex="1"></td>
  <td><input type="text" [(contenteditableModel)]="text2" tabindex="2"></td>
  <td><input type="text" [(contenteditableModel)]="text2" tabindex="3"></td>
  <td class="actions">
    <input type="button" value="Delete" (click)="deleteRow(index)">
  </td>
</tr>

public deleteRow(index) {
    this.rows.splice(index,1);
}
</code>```

working plunk: https://plnkr.co/edit/jAHT4CXQcpRgIOxw4eR6?p=preview

Body:
I'm getting an error which reads:
"Cannot read property 'parentNode' of undefined". I am using Angular. I have Typescript and HTML files. The code is below.

Typescript:

public deleteRow(btn) {
    console.log("parentNode:" + btn.parentNode);
    var row = btn.parentNode.parentNode;
    row.parentNode.removeChild(row);
  }

HTML:

      <input type="text" [(contenteditableModel)]="text1"  tabindex="1">
      <input type="text" [(contenteditableModel)]="text2" tabindex="2">
      <input type="text" [(contenteditableModel)]="text2" tabindex="3">

        <input type="button" value="Delete" (click)="deleteRow(this)">

I am not sure what's going wrong, it should work perfectly.
I'm working on putting together a Stackblitz to demonstrate how it works.
Any comments or suggestions would be appreciated.

Thank you.

Body:
the keyword this doesn't work like that in Angular templates, you generally won't be accessing the DOM directly, as Angular handles that for you, the idea is you update the model and angular takes care of the view.  Try it like this instead:

<tr bg-color="#2b5dd1" *ngFor="let row of rows; let even = even; let odd = odd; let index = index" [ngClass]="{ odd: odd, even: even}" class = "even">
  <td><input type="text" [(contenteditableModel)]="text1"  tabindex="1"></td>
  <td><input type="text" [(contenteditableModel)]="text2" tabindex="2"></td>
  <td><input type="text" [(contenteditableModel)]="text2" tabindex="3"></td>
  <td class="actions">
    <input type="button" value="Delete" (click)="deleteRow(index)">
  </td>
</tr>

public deleteRow(index) {
    this.rows.splice(index,1);
}

working plunk: https://plnkr.co/edit/jAHT4CXQcpRgIOxw4eR6?p=preview


问:
"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."
I'm using code first with entity framework. I have been getting the error below and can't figure out how to fix it:

"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."

I've read that setting Sql("SET IDENTITY_INSERT Movies ON") and OFF around my migration query should fix this however I did not run any queries on the Movies table.

Movies table:

```<code>{
    public class Movies
    {
        public byte Id { get; set; }

        [Display (Name = "Movie Name")]
        public string MovieName { get; set; }

        public Genre Genre { get; set; }

        [Required]
        public byte GenreId { get; set; }

        [Display (Name = "Release Date")]
        public DateTime ReleaseDate { get; set; }

        public DateTime DateAdded { get; set; }

        [Display (Name = "Numbers in Stock")]
        public int NumberInStock { get; set; }
    }
}
</code>```

My Movies controller:

```<code>public ActionResult Save(Movies movies) {
        if (movies.Id == 0)
        {
            _context.Movies.Add(movies);
        }
        else {
            var moviesInDb = _context.Movies.Single(c => c.Id == movies.Id);
            moviesInDb.MovieName = movies.MovieName;
            moviesInDb.ReleaseDate = movies.ReleaseDate;
            moviesInDb.GenreId = movies.GenreId;
            moviesInDb.NumberInStock = movies.NumberInStock;
        }

        _context.SaveChanges();

        return RedirectToAction("Index, Movies");
    }
</code>```

I am getting the error on _context.SaveChanges();

I do have queries for my Genre table which is as below

```<code>public partial class PopulateGenreTable : DbMigration
{
    public override void Up()
    {
        Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
    }

    public override void Down()
    {
    }
}
</code>```

That's the only place I've seeded the dabase

How do I fix this? Please explain clearly as I am an absolute beginner. Thanks

答:
You have to first turn it ON, then do your insert and then turn it OFF

```<code>Sql("SET IDENTITY_INSERT Genres ON");

Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");

Sql("SET IDENTITY_INSERT Genres OFF");
</code>```

But, the point of having an identity column is that we don't choose what values the identity holds (read up on surrogate keys).  In that case, you just remove the ID column from your insert

```<code>Sql("INSERT INTO Genres (Name) VALUES ('Action')");
Sql("INSERT INTO Genres (Name) VALUES ('Thriller')");
Sql("INSERT INTO Genres (Name) VALUES ('Family')");
Sql("INSERT INTO Genres (Name) VALUES ('Romance')");
Sql("INSERT INTO Genres (Name) VALUES ('Comedy')");
</code>```

Body:
I'm using code first with entity framework. I have been getting the error below and can't figure out how to fix it:

"Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF."

I've read that setting Sql("SET IDENTITY_INSERT Movies ON") and OFF around my migration query should fix this however I did not run any queries on the Movies table.

Movies table:

{
    public class Movies
    {
        public byte Id { get; set; }

        [Display (Name = "Movie Name")]
        public string MovieName { get; set; }

        public Genre Genre { get; set; }

        [Required]
        public byte GenreId { get; set; }

        [Display (Name = "Release Date")]
        public DateTime ReleaseDate { get; set; }

        public DateTime DateAdded { get; set; }

        [Display (Name = "Numbers in Stock")]
        public int NumberInStock { get; set; }
    }
}

My Movies controller:

public ActionResult Save(Movies movies) {
        if (movies.Id == 0)
        {
            _context.Movies.Add(movies);
        }
        else {
            var moviesInDb = _context.Movies.Single(c => c.Id == movies.Id);
            moviesInDb.MovieName = movies.MovieName;
            moviesInDb.ReleaseDate = movies.ReleaseDate;
            moviesInDb.GenreId = movies.GenreId;
            moviesInDb.NumberInStock = movies.NumberInStock;
        }

        _context.SaveChanges();

        return RedirectToAction("Index, Movies");
    }

I am getting the error on _context.SaveChanges();

I do have queries for my Genre table which is as below

public partial class PopulateGenreTable : DbMigration
{
    public override void Up()
    {
        Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
        Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
    }

    public override void Down()
    {
    }
}

That's the only place I've seeded the dabase

How do I fix this? Please explain clearly as I am an absolute beginner. Thanks

Body:
You have to first turn it ON, then do your insert and then turn it OFF

Sql("SET IDENTITY_INSERT Genres ON");

Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");

Sql("SET IDENTITY_INSERT Genres OFF");

But, the point of having an identity column is that we don't choose what values the identity holds (read up on surrogate keys).  In that case, you just remove the ID column from your insert

Sql("INSERT INTO Genres (Name) VALUES ('Action')");
Sql("INSERT INTO Genres (Name) VALUES ('Thriller')");
Sql("INSERT INTO Genres (Name) VALUES ('Family')");
Sql("INSERT INTO Genres (Name) VALUES ('Romance')");
Sql("INSERT INTO Genres (Name) VALUES ('Comedy')");


问:
Trouble Understanding Haskell Trees
I'm having a few issues with trees, I was trying to make a simplified Family tree (genealogy tree) where I start with only 1 person, let's say Grandpa Bob, I'll try my best drawing this:

```<code>                                        BOB
                                         |
                                     /        \
                                 SIMON         RUDY
                                /    \         /  \
                            ROBBIE  MARTHA  TOM   ISABEL
</code>```

So, Grandpa Bob had 2 kids with Grandma(which doesn't matter here), Simon and Rudy, then Simon and Rudy both had 2 kids each (only 1 parent matters again), note that this is not necessarily the tree I want to make but only an example which can be used by you guys to help me out. I want to have it as a data Family, then have a function that initiates the "root" which will be Grandpa Bob and then have another function that will let me add someone to the tree, as in add Simon descending from Bob.

So far this is what I have atm(I've tried other things and changed it all over):

```<code>    module Geneaology where
    data Family a = Root a [Family a] | Empty deriving (Show, Read)

    main :: IO()
    main = do
    root :: String -> Family
    root a = ((Root a) [Empty])
</code>```

Now, this doesn't work at all and gives me a parse error:

```<code>t4.hs:9:10: parse error on input ‘=’
</code>```

I've tried to fix this and change the code around looking for other ways, and saw other posts as well, but didn't make any progress...

I think I made myself clear, thanks in advance xD

答:
You have a syntax error, you can create a function in the main with a let and a lambda, and then use it

```<code>data Family a = Root a [Family a] | Empty deriving (Show, Read)

main :: IO()
main = do
  let root  = (\a  -> Root a [Empty])
  print(root "Bob")
</code>```

But you can also define functions outside the main and call them latter:

```<code>root :: String -> Family String
root a = Root a [Empty]

main :: IO()
main = do
  print(root "Bob")
</code>```

Title: Trouble Understanding Haskell Trees

Body:
I'm having a few issues with trees, I was trying to make a simplified Family tree (genealogy tree) where I start with only 1 person, let's say Grandpa Bob, I'll try my best drawing this:

                                        BOB
                                         |
                                     /        \
                                 SIMON         RUDY
                                /    \         /  \
                            ROBBIE  MARTHA  TOM   ISABEL

So, Grandpa Bob had 2 kids with Grandma(which doesn't matter here), Simon and Rudy, then Simon and Rudy both had 2 kids each (only 1 parent matters again), note that this is not necessarily the tree I want to make but only an example which can be used by you guys to help me out. I want to have it as a data Family, then have a function that initiates the "root" which will be Grandpa Bob and then have another function that will let me add someone to the tree, as in add Simon descending from Bob.

So far this is what I have atm(I've tried other things and changed it all over):

    module Geneaology where
    data Family a = Root a [Family a] | Empty deriving (Show, Read)

    main :: IO()
    main = do
    root :: String -> Family
    root a = ((Root a) [Empty])

Now, this doesn't work at all and gives me a parse error:

t4.hs:9:10: parse error on input ‘=’

I've tried to fix this and change the code around looking for other ways, and saw other posts as well, but didn't make any progress...

I think I made myself clear, thanks in advance xD

Body:
You have a syntax error, you can create a function in the main with a let and a lambda, and then use it

data Family a = Root a [Family a] | Empty deriving (Show, Read)

main :: IO()
main = do
  let root  = (\a  -> Root a [Empty])
  print(root "Bob")

But you can also define functions outside the main and call them latter:

root :: String -> Family String
root a = Root a [Empty]

main :: IO()
main = do
  print(root "Bob")


问:
Disable YouTube links with JavaScript?
I'm working on a tampermonkey script that lets you edit text on youtube just by clicking the text. I'd also like to edit the suggested videos on YouTube, but to do that, I need to disable the links temporarily. linkElement.onclick = function(e){return false;}; works for most links, but for some reason, it doesn't work on YouTube links. Would somebody know why this doesn't work?

Example of it working usually:

Test link

<button onclick='document.getElementById("testlink").onclick=function(e){return false;};'>Disable link</button>```

Like I said, this doesn't work on YouTube, and I don't know what code they use for their links. I think it has something to do with how it always seems to be one seamless page.

答:
Your best bet is probably to add a global (i.e. on the window object) event listener with useCapture and then to use event.stopImmediatePropagation().

Example, to block all clicks on anchor elements:

```<code>window.addEventListener('click', function(event) {
  var currentEl = event.target;
  while (currentEl && currentEl.tagName !== 'A') currentEl = currentEl.parentNode;
  if (!currentEl) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true); // true is for `useCapture`
</code>```

However this won't be enough, since youtube has its own loading method for switching pages without doing actual page refreshes or having to click on actual anchors.

Thus you can generalize this method to prevent click event handling for almost all elements except the ones you are controlling:

```<code>function isAllowed(el) {
  // custom logic. e.g. block everything
  return false;
}

window.addEventListener('click', function(event) {
  if (isAllowed(event.target)) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true);
</code>```

Title: Disable YouTube links with JavaScript?

Body:
I'm working on a tampermonkey script that lets you edit text on youtube just by clicking the text. I'd also like to edit the suggested videos on YouTube, but to do that, I need to disable the links temporarily. linkElement.onclick = function(e){return false;}; works for most links, but for some reason, it doesn't work on YouTube links. Would somebody know why this doesn't work?

Example of it working usually:

Test link

<button onclick='document.getElementById("testlink").onclick=function(e){return false;};'>Disable link</button>

Like I said, this doesn't work on YouTube, and I don't know what code they use for their links. I think it has something to do with how it always seems to be one seamless page.

Body:
Your best bet is probably to add a global (i.e. on the window object) event listener with useCapture and then to use event.stopImmediatePropagation().

Example, to block all clicks on anchor elements:

window.addEventListener('click', function(event) {
  var currentEl = event.target;
  while (currentEl && currentEl.tagName !== 'A') currentEl = currentEl.parentNode;
  if (!currentEl) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true); // true is for `useCapture`

However this won't be enough, since youtube has its own loading method for switching pages without doing actual page refreshes or having to click on actual anchors.

Thus you can generalize this method to prevent click event handling for almost all elements except the ones you are controlling:

function isAllowed(el) {
  // custom logic. e.g. block everything
  return false;
}

window.addEventListener('click', function(event) {
  if (isAllowed(event.target)) return;
  event.preventDefault();
  event.stopImmediatePropagation();
}, true);


问:
bash awk moving average with skipping
I am trying to calculate a moving average with a data set. But in addition, I want it to skip a few number of data each time the average 'window' moves. For example, if my data set is a column from 1 to 20 and my average window is 5, then the current calculation is the average of (1-5), (2-6), (3-7), (4-8).....
But I want to skip a few data each time the window moves, say I want to skip 2. then the new average will be (1-5), (4-8), (6-10), (8-12)......
Here is the current awk file I am using, can anyone help me edit it so that I can skip a few data each time the window moves? I want to change the skip size and window size as well. Thank you very much!</p>

```<code>#!/bin/awk

BEGIN {
    N=5          # the window size
}
{
    n[NR]=$1       # store the value in an array
}
NR>=N {            # for records where NR >= N
    x=0            # reset the sum variable
    delete n[NR-N] # delete the one out the window of N
    for(i in n)    # all array elements
        x+=n[i]    # ... must be summed
    print x/N  # print the row from the beginning of window
}
</code>```

答:
I think your ranges are not well specified, but you wanted to achieve can be done by parallel windowing as below

```<code>awk        '{sum[1]+=$1}
     !(NR%5){print NR-4"-"NR, sum[1]/5; sum[1]=0}
        NR>3{sum[4]+=$1}
      NR>3 && !((NR-3)%5){print NR-4"-"NR, sum[4]/5; sum[4]=0}' <(seq 15)
</code>```

will give, you can remove printing ranges which it there for debugging.

```<code>1-5 3
4-8 6
6-10 8
9-13 11
11-15 13
</code>```

for making window size and skip count variable

```<code>awk -v w=5 -v s=3 'function pr(x)    {print (NR-s-1)"-"NR, sum[x]/w; sum[x]=0}
                                     {sum[1]+=$1}
                   NR>s              {sum[s+1]+=$1}
                   !(NR%w)           {pr(1)}
                  NR>s && !((NR-s)%w){pr(s+1)}' file
</code>```

first window always start at 1, second window starts at s+1.  This can be generalize for more than 2 windows as well, perhaps you can find someone to do it...

Title: bash awk moving average with skipping

Body:
I am trying to calculate a moving average with a data set. But in addition, I want it to skip a few number of data each time the average 'window' moves. For example, if my data set is a column from 1 to 20 and my average window is 5, then the current calculation is the average of (1-5), (2-6), (3-7), (4-8).....
But I want to skip a few data each time the window moves, say I want to skip 2. then the new average will be (1-5), (4-8), (6-10), (8-12)......
Here is the current awk file I am using, can anyone help me edit it so that I can skip a few data each time the window moves? I want to change the skip size and window size as well. Thank you very much!

#!/bin/awk

BEGIN {
    N=5          # the window size
}
{
    n[NR]=$1       # store the value in an array
}
NR>=N {            # for records where NR >= N
    x=0            # reset the sum variable
    delete n[NR-N] # delete the one out the window of N
    for(i in n)    # all array elements
        x+=n[i]    # ... must be summed
    print x/N  # print the row from the beginning of window
}

Body:
I think your ranges are not well specified, but you wanted to achieve can be done by parallel windowing as below

awk        '{sum[1]+=$1}
     !(NR%5){print NR-4"-"NR, sum[1]/5; sum[1]=0}
        NR>3{sum[4]+=$1}
      NR>3 && !((NR-3)%5){print NR-4"-"NR, sum[4]/5; sum[4]=0}' <(seq 15)

will give, you can remove printing ranges which it there for debugging.

1-5 3
4-8 6
6-10 8
9-13 11
11-15 13

for making window size and skip count variable

awk -v w=5 -v s=3 'function pr(x)    {print (NR-s-1)"-"NR, sum[x]/w; sum[x]=0}
                                     {sum[1]+=$1}
                   NR>s              {sum[s+1]+=$1}
                   !(NR%w)           {pr(1)}
                  NR>s && !((NR-s)%w){pr(s+1)}' file

first window always start at 1, second window starts at s+1.  This can be generalize for more than 2 windows as well, perhaps you can find someone to do it...


问:
Include $key in angularfire2 v5
Actually i need to get the $key in this AngularFireList, but i don't know how i do that, actually this is my code to a list, that works but don't rerieve the data with the $key:
</p>

```<code>getAutosByPlaca(placac: string): Observable<Auto[]> {
 const placa$ = new Subject().startWith(placac);
 return placa$.switchMap(placa => {
  return this.db.list(this.dbPath, ref => ref.orderByChild('placa').equalTo(placac)).valueChanges();
 });
}
</code>```

答:
valueChanges() returns the unpacked data. To get the meta data, you need snapshotChanges(), as documented here:

https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md#angularfireaction---action-based-api

Title: Include $key in angularfire2 v5

Body:
Actually i need to get the $key in this AngularFireList, but i don't know how i do that, actually this is my code to a list, that works but don't rerieve the data with the $key:

getAutosByPlaca(placac: string): Observable<Auto[]> {
 const placa$ = new Subject().startWith(placac);
 return placa$.switchMap(placa => {
  return this.db.list(this.dbPath, ref => ref.orderByChild('placa').equalTo(placac)).valueChanges();
 });
}


问:
Stopping JobInstance through JobOperator
I'm trying to stop one job execution from a managedbean. More concretely, I'm able to get the job instance and stop the job instance as follows:

```<code>        JobOperator operator  = BatchRuntime.getJobOperator();
        List<Long> re = operator.getRunningExecutions("JobName");
        for (Long runningExecution: re) {
            operator.stop(runningExecution);
        }
</code>```

Even so, it doesn't take effect over the instance's execution that it continue running. In fact, if I try to get the job instance again it isn't possible because effectively method getRunningExecutions return no elements. In this manner, could anyone tell me what I'm doing wrong?

Thank you in advance.

答:
getRunningExecutions returns empty since the job execution is probably in STOPPING status, and thus is not considering running executions any more.

Try to call getBatchStatus() on each job execution to check the exact batch status. If your current step is a batchlet-type step, then the batchlet class should implement the stop() method to properly stop the work.

Body:
I'm trying to stop one job execution from a managedbean. More concretely, I'm able to get the job instance and stop the job instance as follows:

        JobOperator operator  = BatchRuntime.getJobOperator();
        List<Long> re = operator.getRunningExecutions("JobName");
        for (Long runningExecution: re) {
            operator.stop(runningExecution);
        }

Even so, it doesn't take effect over the instance's execution that it continue running. In fact, if I try to get the job instance again it isn't possible because effectively method getRunningExecutions return no elements. In this manner, could anyone tell me what I'm doing wrong?

Thank you in advance.


问:
The first element of my array not being displayed
So This is my javascript code. When I run it step by step using the browser's developer tools it gets all the elements from the array but it only prints the last 4. How would I fix this?

```<code>function showDuties() {
  var numDuties = document.getElementById('pfJobs').value;
  var i = numDuties - 1
  var t = ""
  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
      "Sign up new members", "File paperwork"]

  while (i >= 0) {
      document.getElementById('pfj').innerHTML = t;
      t += pfDuties[i] + "<br>";
      i--;
  }
}
</code>```

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>

window.showDuties = function() {
  var numDuties = document.getElementById('pfJobs').value;
  var i = numDuties - 1
  var t = ""
  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
      "Sign up new members", "File paperwork"]

  while (i >= 0) {
     document.getElementById('pfj').innerHTML = t;
      t += pfDuties[i] + "<br>";

      i--;
  }
}

</script>

<form>
 <input type="submit" value="Click here" onclick="showDuties(); return false;">
   to see my top
 <input type="text" id="pfJobs" />
   job duties here.
 <p id = "pfj">
 </p>
</form></code>```

答:
Because you add the element BEFORE you add it to t. You need to move it after. And better yet, do not update it on every iteration, update it when the looping is done.

```<code>while (i >= 0) {
  t += pfDuties[i] + "<br>";
  i--;
}
document.getElementById('pfj').innerHTML = t;
</code>```

Body:
So This is my javascript code. When I run it step by step using the browser's developer tools it gets all the elements from the array but it only prints the last 4. How would I fix this?

function showDuties() {
  var numDuties = document.getElementById('pfJobs').value;
  var i = numDuties - 1
  var t = ""
  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
      "Sign up new members", "File paperwork"]

  while (i >= 0) {
      document.getElementById('pfj').innerHTML = t;
      t += pfDuties[i] + "
";
      i--;
  }
}

<form>
 <input type="submit" value="Click here" onclick="showDuties(); return false;">
   to see my top
 <input type="text" id="pfJobs" />
   job duties here.

</form>

Body:
Because you add the element BEFORE you add it to t. You need to move it after. And better yet, do not update it on every iteration, update it when the looping is done.

while (i >= 0) {
  t += pfDuties[i] + "<br>";
  i--;
}
document.getElementById('pfj').innerHTML = t;


问:
Android - Switch ActionBar Back Button to Navigation Button
I am having the following problem:

I know how to set up a toolbar to show a back button icon instead of a burger button icon.

From this:

to this:

using: getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now, I want to do the reverse action, I want to go from back button icon to burger icon:

to here:

How can I do this?

Update:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
}

private void enableViews(boolean enable) {
    if(enable) {
        // Enables back button icon
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    } else {
        // TODO: Enables burger icon
    }
}
</code>```

答:
I found flexible solutions in The Google I/O 2017 Android App.

```<code>public Toolbar getToolbar() {
    if (mToolbar == null) {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
            mToolbar.setNavigationContentDescription(R.string.navdrawer_description_a11y);
            mToolbarTitle = (TextView) mToolbar.findViewById(R.id.toolbar_title);
            if (mToolbarTitle != null) {
                int titleId = getNavigationTitleId();
                if (titleId != 0) {
                    mToolbarTitle.setText(titleId);
                }
            }

            // We use our own toolbar title, so hide the default one
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }
    return mToolbar;
}

/**
 * @param clickListener The {@link android.view.View.OnClickListener} for the navigation icon of
 *                      the toolbar.
 */
protected void setToolbarAsUp(View.OnClickListener clickListener) {
    // Initialise the toolbar
    getToolbar();
    if (mToolbar != null) {
        mToolbar.setNavigationIcon(R.drawable.ic_up);
        mToolbar.setNavigationContentDescription(R.string.close_and_go_back);
        mToolbar.setNavigationOnClickListener(clickListener);
    }
}
</code>```

So the usage is really simple.

```<code>setToolbarAsUp(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // onBackPressed();
        // or navigate to parent or some other intent
    }
});
</code>```

Body:
I am having the following problem:

I know how to set up a toolbar to show a back button icon instead of a burger button icon.

From this:

to this:

using: getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now, I want to do the reverse action, I want to go from back button icon to burger icon:

to here:

How can I do this?

Update:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
}

private void enableViews(boolean enable) {
    if(enable) {
        // Enables back button icon
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    } else {
        // TODO: Enables burger icon
    }
}

Body:
I found flexible solutions in The Google I/O 2017 Android App.

public Toolbar getToolbar() {
    if (mToolbar == null) {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
            mToolbar.setNavigationContentDescription(R.string.navdrawer_description_a11y);
            mToolbarTitle = (TextView) mToolbar.findViewById(R.id.toolbar_title);
            if (mToolbarTitle != null) {
                int titleId = getNavigationTitleId();
                if (titleId != 0) {
                    mToolbarTitle.setText(titleId);
                }
            }

            // We use our own toolbar title, so hide the default one
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }
    return mToolbar;
}

/**
 * @param clickListener The {@link android.view.View.OnClickListener} for the navigation icon of
 *                      the toolbar.
 */
protected void setToolbarAsUp(View.OnClickListener clickListener) {
    // Initialise the toolbar
    getToolbar();
    if (mToolbar != null) {
        mToolbar.setNavigationIcon(R.drawable.ic_up);
        mToolbar.setNavigationContentDescription(R.string.close_and_go_back);
        mToolbar.setNavigationOnClickListener(clickListener);
    }
}

So the usage is really simple.

setToolbarAsUp(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // onBackPressed();
        // or navigate to parent or some other intent
    }
});


问:
Share Git Staging Area on local subnet(mostly wifi), now with images to explain
I know it sounds like a commit push, but what I would like to do here is have something done in code then stage but before pushing I would like to see what my local office partner(s) done, and he(they) see what I've done using the stage area (index), to work as a "caveat" for all local team members and to mentor them without the team leader leaving his seat, for example take a look at the following:

I want those connected to peek at each other using their wifi connection, but only Developers and the Team leader, anyone who is NOT A Developer shouldn't be able to see (so I can't use local shared directory)

Can  this be done or should I ask for it as an added feature?

P.S. Currently, we are exchanging files involved (Skype, duh!) but then again one can't simply do this unless those involved communicate verbally, mostly leave desk, and turn it into a real-time tutoring session, can't use diff (feature) as is, and worst of all if someone does some code that works and does a push and tests says yes, but days or weeks later turns out to be a simple-code(i.e. low conformity to design approach and how the architect wants it to be) and the need for it to be rewritten.

答:
[Edited, in response to comment from OP]

Original Question:

Can this be done or should I ask for it as an added feature?

Part 1 Answer: No, this cannot be done in Git

Part 2 Answer: It also should not be asked for as an added feature

Reasoned Advice: Use Git as intended with the mechanisms it already has to accomplish what you claim you are trying to achieve

You are free to reject the answer because you still want to do what you have apparently decided to do whether it is a good idea or not.  I do not see anything in your question or comments that explains why you cannot use additional branching and commits to have the exact same outcome that you claim you want, as explained below.

From a strictly Git perspective - no, you cannot share the index or any unstaged working directory changes directly in Git without some sort of commit (which could be a stash or normal commit).

From a Git perspective, though, this is what separate dev branches are really for.  Whatever branch is being worked on can have an infinite number of branches taken out by each individual developer and they can commit their progress on a regular basis in order to make those changes available to the team, create a restore point for additional work, and save the history.  For branches like that, you typically will want to merge with a single commit to the parent branch at the appropriate point and then delete all the "minute-by-minute" history, but some people prefer to save even the smallest level of history versus having a more clean history overall.

Going this route has a lot of benefits, specifically from a distributed perspective - people can work offline and sync up whenever needed, etc., in addition to all the SCM benefits in general - and it doesn't matter that a particular commit be "finished" or even compilable.  Pull requests can be made even if code isn't really ready to merge to provide a facility for review where the comments and action items can be tracked, depending how important that piece is to the team.  Of course, you'd need a convention to be clear about which ones are intended for merge and which are not.

Other options:

However, as the comments indicate, there are other options for more real-time sharing of current IDE status, if that's what you are really after.  But is it worth the fumbling with other tools and configurations, and setting everyone up on them, and maintaining them?  That's your call.  Perhaps one of the ones mentioned is already built-in to your environment:  Teletype for Atom or Visual Studio Live Share.


问:
Checkbox "checked" not toggling correctly
when I check the checkbox, the status changes successfully(ajax call is successful and DB reflects the chnage), the span below also shows "CHECK" but the checkbox does not get toggled, so something is not working right with the "checked" attribute. What am I missing here.

```<code><!-- ko foreach: Group-->
<tr>
  <td>
    <span data-bind="text: TourName "></span>
  </td>
  <!-- ko if: $index() == 0 -->

  <td style="vertical-align:middle" data-bind="attr: { rowspan: $parent.Group().length }">

    <!-- ko if: $parent.Status() != 'DNB' -->
    <input type="checkbox" data-bind="checked: ($parent.Status() === 'CHECK'),click: $root.editSellStatus.bind($parent)" />
    <span data-bind="text: $parent.Status()"></span>
    <!-- /ko -->

  </td>

  <!-- /ko -->
</tr>
<!-- /ko -->
</code>```

This is my edit method:

```<code>self.editStatus = function() {
  var Status = null;

  if (this.Status() == 'CHECK') {
    this.Status(null);
    Status = null;
  } else if (this.Status() == null) {
    this.Status('CHECK');
    Status = 'CHECK';
  }

  $.ajax({
    url: "SaveStatus/?ID=" + this.Id() + "&Status=" + Status,
    type: "post",
    contentType: "application/json",
    success: function(result) {
      if (result == "success") {}
      self.selectedItem(null);
    }
  });

  var test = this.Status();
}
</code>```

My KO model structure is something like this.

```<code>class MyClass {
  Name: string;
  year: string;
  Group: Array<{
    GroupName: string;
    Status: string;
    subGroup: Array<{....}>;
  }>;
}
</code>```

答:
Because you're using a click binding on a checkbox you're overriding the default click behavior which is to update the checkbox with a check-mark. To allow the browser to continue with the default behavior your click event function must return a true value.

```<code>self.editStatus = function() {
    ...
    return true;
}
</code>```

//This is my edit method:
self.editStatus = function() {
  var Status = null;

  if (this.Status() == 'CHECK') {
    this.Status(null);
    Status = null;
  } else if (this.Status() == null) {
    this.Status('CHECK');
    Status = 'CHECK';
  }

  //$.ajax()

  var test = this.Status();
  return true;
}

//My KO model structure is something like this.
function MyClass() {
  var self = this;
  this.Name = "Name";
  this.Id = "Id";
  this.year = 1999;
  this.Status = ko.observable(null);
  this.isChecked = ko.observable(false);
  this.Group = ko.observableArray([{
    GroupName: "Group 1",
    TourName: "Tour 1",
    Status: "Status",
    subGroup: [{
      //empty object
    }],
  }, {
    GroupName: "Group 2",
    TourName: "Tour 2",
    subGroup: [{
      //empty object
    }]
  }
  ]);

  this.editSellStatus = editStatus;
}

ko.applyBindings(new MyClass());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tbody>
  <!-- ko foreach: Group-->
  <tr>
    <td>
      <span data-bind="text: TourName "></span>
    </td>
    <!-- ko if: $index() == 0 -->

    <td style="vertical-align:middle" data-bind="attr: { rowspan: $parent.Group().length }">

      <!-- ko if: $parent.Status() != 'DNB' -->
      <input type="checkbox" data-bind="checked: ($parent.Status() === 'CHECK'),click: $root.editSellStatus.bind($parent)" />
      <span data-bind="text: $parent.Status()"></span>
      <!-- /ko -->
    </td>

    <!-- /ko -->
  </tr>
  <!-- /ko -->
  </tbody>
</table>
<span data-bind="text: ko.toJSON(Status)"></span></code>```

Body:
when I check the checkbox, the status changes successfully(ajax call is successful and DB reflects the chnage), the span below also shows "CHECK" but the checkbox does not get toggled, so something is not working right with the "checked" attribute. What am I missing here.

    <input type="checkbox" data-bind="checked: ($parent.Status() === 'CHECK'),click: $root.editSellStatus.bind($parent)" />

This is my edit method:

self.editStatus = function() {
  var Status = null;

  if (this.Status() == 'CHECK') {
    this.Status(null);
    Status = null;
  } else if (this.Status() == null) {
    this.Status('CHECK');
    Status = 'CHECK';
  }

  $.ajax({
    url: "SaveStatus/?ID=" + this.Id() + "&Status=" + Status,
    type: "post",
    contentType: "application/json",
    success: function(result) {
      if (result == "success") {}
      self.selectedItem(null);
    }
  });

  var test = this.Status();
}

My KO model structure is something like this.

class MyClass {
  Name: string;
  year: string;
  Group: Array<{
    GroupName: string;
    Status: string;
    subGroup: Array<{....}>;
  }>;
}

Body:
Because you're using a click binding on a checkbox you're overriding the default click behavior which is to update the checkbox with a check-mark. To allow the browser to continue with the default behavior your click event function must return a true value.

self.editStatus = function() {
    ...
    return true;
}

//This is my edit method:
self.editStatus = function() {
  var Status = null;

  if (this.Status() == 'CHECK') {
    this.Status(null);
    Status = null;
  } else if (this.Status() == null) {
    this.Status('CHECK');
    Status = 'CHECK';
  }

  //$.ajax()

  var test = this.Status();
  return true;
}

//My KO model structure is something like this.
function MyClass() {
  var self = this;
  this.Name = "Name";
  this.Id = "Id";
  this.year = 1999;
  this.Status = ko.observable(null);
  this.isChecked = ko.observable(false);
  this.Group = ko.observableArray([{
    GroupName: "Group 1",
    TourName: "Tour 1",
    Status: "Status",
    subGroup: [{
      //empty object
    }],
  }, {
    GroupName: "Group 2",
    TourName: "Tour 2",
    subGroup: [{
      //empty object
    }]
  }
  ]);

  this.editSellStatus = editStatus;
}

ko.applyBindings(new MyClass());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tbody>
  <!-- ko foreach: Group-->
  <tr>
    <td>
      <span data-bind="text: TourName "></span>
    </td>
    <!-- ko if: $index() == 0 -->

    <td style="vertical-align:middle" data-bind="attr: { rowspan: $parent.Group().length }">

      <!-- ko if: $parent.Status() != 'DNB' -->
      <input type="checkbox" data-bind="checked: ($parent.Status() === 'CHECK'),click: $root.editSellStatus.bind($parent)" />
      <span data-bind="text: $parent.Status()"></span>
      <!-- /ko -->
    </td>

    <!-- /ko -->
  </tr>
  <!-- /ko -->
  </tbody>
</table>
<span data-bind="text: ko.toJSON(Status)"></span>


问:
Convert number to tkinter color
Is there a simple way to convert a number into a tkinter color (#ffeedd).

I'm already setup to take the number and multiply it by 8 to give me a bit more color range leeway, and maybe even multiply it by 16 depending on just how much leeway I have to work with, not sure on how much leeway I will have yet... but I'm guessing I'll only be able to multiply by 8. How do I take that number and convert it over so I can use it with canvas.create_line((x,y), (x,y), fill = 'color'). I tried hex(number) but it just gives me back that color 0x0 doesn't exists... kinda figured that would happen but thought it would be worth a try.

```<code>a = 326
b = a * 8
canvas.create_line((x,y), (x,y), fill = b)
</code>```

答:
Ensure you have 3 or 6 hex digits. For instance:

```<code>frame.configure(background="#{0:06X}".format(0x808080))
</code>```

The actual permitted set of color specfications is given in the GetColor
manual page.

Title: Convert number to tkinter color

Body:
Is there a simple way to convert a number into a tkinter color (#ffeedd).

I'm already setup to take the number and multiply it by 8 to give me a bit more color range leeway, and maybe even multiply it by 16 depending on just how much leeway I have to work with, not sure on how much leeway I will have yet... but I'm guessing I'll only be able to multiply by 8. How do I take that number and convert it over so I can use it with canvas.create_line((x,y), (x,y), fill = 'color'). I tried hex(number) but it just gives me back that color 0x0 doesn't exists... kinda figured that would happen but thought it would be worth a try.

a = 326
b = a * 8
canvas.create_line((x,y), (x,y), fill = b)

Body:
Ensure you have 3 or 6 hex digits. For instance:

frame.configure(background="#{0:06X}".format(0x808080))

The actual permitted set of color specfications is given in the GetColor
manual page.


问:
onEdit installable trigger not firing when defining variable through array object
Hej!
I have a script that is supposed to be triggered onEdit.
onEdit() as a simple trigger is not an option for me, since the script needs authorizations. When setting an installable trigger with the editor the trigger is only fired when a specific variable is manually defined, but not when it is defined with an array.
Since I have no clue where the problem could be (I have tried to comment out the code part by part, but it always ends up not working when comming to the last part.

```<code>        function myFunction() {
     //Source Sheet for different sheets
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var activeSheet = ss.getActiveSheet();
      var activeRange = ss.getActiveRange();
      var activeRow = activeRange.getRowIndex();
      var CategoryValues = ss.getSheetValues(activeRow, 4, 1, 14);
      var ID = activeSheet.getRange(activeRow,2).getValue();
      var red = '#e06666'

  // Defining the sourceWeekNumber in the sourceSheet with a while loop
      var sourceWeeks = activeSheet.getRange(1,1,activeRow).getValues();
      sourceWeeks.reverse();
      var sourceWeekColor = activeSheet.getRange(1,1,activeRow).getBackgrounds();
      sourceWeekColor.reverse();
      var sourceWeekNumber = [];
      var sourceWeekIndex=1;
        while (sourceWeekColor[sourceWeekIndex-1]!=red) {
          if (sourceWeekColor[sourceWeekIndex]==red) {
          sourceWeekNumber.push(sourceWeeks[sourceWeekIndex])
          }
          sourceWeekIndex++;
      }

      //Target sheet is always mastersheet
      var ts = SpreadsheetApp.openById('ID').getSheetByName('mastersheet');

      //Finding the right spot in mastesheet
      //Validate the weeknumber
      var validWeek = ts.getRange(2, 1, ts.getLastRow()).getValues();
      var rowIndex = [];

  //-----> var sourceWeekNumber = 'v50'; <-----
  // When defining this variable manually, onEdit works fine.
  // When defining sourceWeek with the while loop above, the onEdit does not trigger.

      // Find the right week and it's row in the mastersheet
      var validWeekIndex = 1;
      while (validWeek[validWeekIndex] != sourceWeekNumber) {
        if (validWeek[validWeekIndex] == sourceWeekNumber) {
        var validID = ts.getRange(validWeekIndex+3,2, ts.getLastRow()).getValues();
        rowIndex.push(validWeekIndex);
        }
        validWeekIndex++;
      }
    }
</code>```

I have tried different things, always using Logger.log() or Browser.msgBox() trying to identify the problem. Any ideas or workarounds? I have been stuck with this for 3 days now and can't find any solution.
I have prepared a sample sheet as well, if it is needed then I can edit it in.
Thanks in advance!

Edit:
Here is the link to the sample sheet: https://docs.google.com/spreadsheets/d/1xCZur6gpfsQFPtwKcTl0XPPfG8zlTqGVlm1GZZ8X1xM/edit?usp=sharing

答:
I figured it out.
It was of course not the trigger, but different factors that made me think it was:

Trigger notifications: I was sure I set notification to immidiatly, but it was set to 4pm every day. That's the reason I didn't get the failure notifications.

The while loop: Because the while loop can't identify when the value from the 1D array turns up in the 2D array, it keeps running and times-out. Therefore the script runs for 5 minutes without possibility to cancel it.

I learned that Google got a quota of 30 min / day of script running time for triggers, so that's why I could only run 6 failed scripts before the quota was full and the script woulnd't run at all until the next day without me realizing it was an issue.

Edit: For future references, I simply used sourceWeekNumber.toString() to be able to get it to match with the other array, comparing a string instead of and object inside of an array.

Body:
Hej!
I have a script that is supposed to be triggered onEdit.
onEdit() as a simple trigger is not an option for me, since the script needs authorizations. When setting an installable trigger with the editor the trigger is only fired when a specific variable is manually defined, but not when it is defined with an array.
Since I have no clue where the problem could be (I have tried to comment out the code part by part, but it always ends up not working when comming to the last part.

        function myFunction() {
     //Source Sheet for different sheets
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var activeSheet = ss.getActiveSheet();
      var activeRange = ss.getActiveRange();
      var activeRow = activeRange.getRowIndex();
      var CategoryValues = ss.getSheetValues(activeRow, 4, 1, 14);
      var ID = activeSheet.getRange(activeRow,2).getValue();
      var red = '#e06666'

  // Defining the sourceWeekNumber in the sourceSheet with a while loop
      var sourceWeeks = activeSheet.getRange(1,1,activeRow).getValues();
      sourceWeeks.reverse();
      var sourceWeekColor = activeSheet.getRange(1,1,activeRow).getBackgrounds();
      sourceWeekColor.reverse();
      var sourceWeekNumber = [];
      var sourceWeekIndex=1;
        while (sourceWeekColor[sourceWeekIndex-1]!=red) {
          if (sourceWeekColor[sourceWeekIndex]==red) {
          sourceWeekNumber.push(sourceWeeks[sourceWeekIndex])
          }
          sourceWeekIndex++;
      }

      //Target sheet is always mastersheet
      var ts = SpreadsheetApp.openById('ID').getSheetByName('mastersheet');

      //Finding the right spot in mastesheet
      //Validate the weeknumber
      var validWeek = ts.getRange(2, 1, ts.getLastRow()).getValues();
      var rowIndex = [];

  //-----> var sourceWeekNumber = 'v50'; <-----
  // When defining this variable manually, onEdit works fine.
  // When defining sourceWeek with the while loop above, the onEdit does not trigger.

      // Find the right week and it's row in the mastersheet
      var validWeekIndex = 1;
      while (validWeek[validWeekIndex] != sourceWeekNumber) {
        if (validWeek[validWeekIndex] == sourceWeekNumber) {
        var validID = ts.getRange(validWeekIndex+3,2, ts.getLastRow()).getValues();
        rowIndex.push(validWeekIndex);
        }
        validWeekIndex++;
      }
    }

I have tried different things, always using Logger.log() or Browser.msgBox() trying to identify the problem. Any ideas or workarounds? I have been stuck with this for 3 days now and can't find any solution.
I have prepared a sample sheet as well, if it is needed then I can edit it in.
Thanks in advance!

Edit:
Here is the link to the sample sheet: https://docs.google.com/spreadsheets/d/1xCZur6gpfsQFPtwKcTl0XPPfG8zlTqGVlm1GZZ8X1xM/edit?usp=sharing


问:
Magneto 2.2.0 add header and footer to checkout page
How to add header and footer to checkout page. I used the override method. I created checkou_index_index.xml file in following path layout\override\theme\Magento\blank in my custom theme.

```<code><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="minicart" remove="false" />
    <referenceContainer name="header.panel" remove="false" />
    <referenceBlock name="top.search" remove="false" />
    <referenceBlock name="catalog.compare.link" remove="false" />
    <referenceBlock name="catalog.topnav" remove="false"/>
    <referenceContainer name="footer-container"  remove="false"/>
</body>
</page>
</code>```

But I received following error.

```<code>Overriding view file 'C:\/xampp\/htdocs\/my_website\/app\/design\/frontend\/Vendor\/basic\/Magento_Checkout\/layout\/override\/theme\/Magento\/blank\/checkout_index_index.xml' does not match to any of the files
</code>```

What is the cause of this error and how to fix this error?

答:
Try putting your custom xml file in:

```<code>C:\xampp\htdocs\my_website\app\design\frontend\Vendor\basic\Magento_Checkout\view\frontend\layout\checkout_index_index.xml
</code>```

Because, if i'm not mistaken, the file to override is in:

```<code>C:\xampp\htdocs\my_website\vendor\magento\module-checkout\view\frontend\layout\checkout_index_index.xml
</code>```

Hope this helps you.

Body:
How to add header and footer to checkout page. I used the override method. I created checkou_index_index.xml file in following path layout\override\theme\Magento\blank in my custom theme.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceBlock name="minicart" remove="false" />
    <referenceContainer name="header.panel" remove="false" />
    <referenceBlock name="top.search" remove="false" />
    <referenceBlock name="catalog.compare.link" remove="false" />
    <referenceBlock name="catalog.topnav" remove="false"/>
    <referenceContainer name="footer-container"  remove="false"/>

</page>

But I received following error.

Overriding view file 'C:\/xampp\/htdocs\/my_website\/app\/design\/frontend\/Vendor\/basic\/Magento_Checkout\/layout\/override\/theme\/Magento\/blank\/checkout_index_index.xml' does not match to any of the files

What is the cause of this error and how to fix this error?

Body:
Try putting your custom xml file in:

C:\xampp\htdocs\my_website\app\design\frontend\Vendor\basic\Magento_Checkout\view\frontend\layout\checkout_index_index.xml

Because, if i'm not mistaken, the file to override is in:

C:\xampp\htdocs\my_website\vendor\magento\module-checkout\view\frontend\layout\checkout_index_index.xml

Hope this helps you.


问:
Headless browser and locust.io
Is it possible to integrate a headless browser with locust? I need my load tests to process client side script that triggers additional requests on each page load.</p>

答:
The locust way of solving this is to add more requests to your test that mimic the requests that the javascript code will make.

I structure my locust tests to parse the JSON response from an early request in the app's workflow. I then randomly pick some interesting piece of data from that JSON, and then issue more requests that mimic what would happen in the browser if the user had clicked on that piece of data.

Title: Headless browser and locust.io


问:
Tensorflow installation using pip, import not happening
I installed tensorflow using pip, and it shows success but when I import tensorflow the following error comes.</p>

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: dlopen(/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found
Failed to load the native TensorFlow runtime.
</code>```

答:
Tensorflow tries to load the following dependency:

```<code>libcublas
</code>```

To fix this follow these steps:

Make sure that cuda for python is installed ( via pip )

Make sure that the code lib installation path was added to your env-var LD_LIBRARY_PATH

You can check the following question to see how to do so: Cannot find cuda

Body:
I installed tensorflow using pip, and it shows success but when I import tensorflow the following error comes.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: dlopen(/Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/dipendra/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found
Failed to load the native TensorFlow runtime.

Body:
Tensorflow tries to load the following dependency:

libcublas

To fix this follow these steps:

Make sure that cuda for python is installed ( via pip )

Make sure that the code lib installation path was added to your env-var LD_LIBRARY_PATH

You can check the following question to see how to do so: Cannot find cuda


问:
Use GNU m4 at compile time for large C/C++ project

Background

I have a large project that I'm currently refactoring. One of the problems is massive abuse of string literals (300+ instances) for common paths used by the product (i.e. references to /opt/dev and sub-paths of this location) all over the place, including:

C/C++ source and header files.

python scripts.

bash scripts.

systemd scripts.

Binary images (drivers).

Goal

I'd like to use GNU m4 to define a file with a set of common macros so we can "write once, use everywhere", so that if our code is branched (typical for a new product), we can just change the macros in that one file, instead of hunting down the duplicate string literals and debugging them for days. This is easy enough for simple things like scripts, as I just create a copy of the source tree in the build output path, and run M4 directly on the scripts.

Problem

The only downside so far is that it looks like this will be a massive effort for C/C++ projects, because I only want to execute the M4 macro expansion/substitution at compile time. This means that, in order to avoid modifying the source files checked out from git, I'll have to modify my build scripts (lots of Makefiles) to work on a temporary copy of the code rather than the original source files themselves. Otherwise, running M4 directly on the version-controlled source will generate a change to the local working copy, and developers are likely to commit this M4-evaluated copy of the code to version control, breaking the M4 effort.

Question

Is it possible to instruct gcc to evaluate m4 macros/expansions during compilation, either via some external tool or some feature of GCC itself? If not, my build scripts will likely require a massive overhaul to support M4 macros.

答: Use m4 to generate a project-config.h header for the C and/or C++ code.  Use that header in every file that needs to use one of the macros.  Make sure that programmers know that's what should be used.  Possibly enforce the use with code checks before checkin, or periodical scanning of the code base?  Recompile affected files when that header changes.  Don't change it unnecessarily.


问:
Environment env.getproperty is not working
I have a problem with Environment env.getproperty, env not find local properties, but it find system properties. I dont know about this so much and I need to solve it. Please, help me.
Attached my code and its configuration.

Controllers.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- Scans within the base package of the application for @Components to
    configure as beans -->
<mvc:annotation-driven />
<context:component-scan base-package="com.mret.client.controller" />
<context:component-scan base-package="com.mret.client.security" />
<context:property-placeholder   location="classpath*:paremeters.properties" />
</code>```

Paremeters.properties:

```<code>url.services.search=http://localhost:8080/mretcore/search
url.services.orderdetail=http://localhost:8080/mretcore/orderdetail?orderid=
</code>```

Controller:

```<code>@Controller
public class OrdersController {
RestClient restClient = new RestClientImpl();
@Autowired
private Environment env;
String url = env.getProperty("url.services.search");
etc....}
</code>```

enter image description here

答:
property-placeholder does not place properties into env. It is for variables set on OS level.

better use System.getProperty("property_name") which includes env, JVM properties, -D properties passed into java command line and yes - those from property-placeholder.

Also you may consider to use your url as bean property and do not get it explicitly, but by spring bean property definition like ${url.services.search}
instead of having property name in code. After time it may hard to find where what property loaded. It is better approach...

Body:
I have a problem with Environment env.getproperty, env not find local properties, but it find system properties. I dont know about this so much and I need to solve it. Please, help me.
Attached my code and its configuration.

Controllers.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.mret.client.controller" />
<context:component-scan base-package="com.mret.client.security" />
<context:property-placeholder   location="classpath*:paremeters.properties" />

Paremeters.properties:

url.services.search=http://localhost:8080/mretcore/search
url.services.orderdetail=http://localhost:8080/mretcore/orderdetail?orderid=

Controller:

@Controller
public class OrdersController {
RestClient restClient = new RestClientImpl();
@Autowired
private Environment env;
String url = env.getProperty("url.services.search");
etc....}

enter image description here


问:
ASP.NET Membership Web-Based Administration
Does anyone know if there's a way to manage users/roles in the asp.net membership database using a web-based interface you can access remotely?

I need one which doesn't require installation to the Default Website.

Thanks

答:
Here is a quick and dirty solution. Copy your ASP.NETWebAdminFiles to a directory on your server. Make it a virtual directory. Open up the App_Code/WebAdminPage.cs file and coment out lines around 488 - 495 the code will look like this:

```<code>        // Changed by Jason so I can use this remotely!!!
        //  if (!application.Context.Request.IsLocal) {
        //    SecurityException securityException = new SecurityException((string)HttpContext.GetGlobalResourceObject("GlobalResources", "WebAdmin_ConfigurationIsLocalOnly"));
        //    WebAdminPage.SetCurrentException(application.Context, securityException);
        //    application.Server.Transfer("~/error.aspx");
        //  }
</code>```

Then you can now use this tool remotely. Just user your browser to pull up the newly created virtual directory passing in the correct parameters. For example

```<code>http://myservername/WebAdminFiles/default.aspx?applicationPhysicalPath=C:\Websites\Application\&applicationUrl=/ApplicationURL
</code>```

The other thing I did was to enable windows authentication on this folder so that I have to have an admin account on the server before I can access this url. This is important because once you enable this tool anyone can browse and delete users if they pull up the url.

OwnerDisplayName: Shahin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shahin

Body:
Here is a quick and dirty solution. Copy your ASP.NETWebAdminFiles to a directory on your server. Make it a virtual directory. Open up the App_Code/WebAdminPage.cs file and coment out lines around 488 - 495 the code will look like this:

        // Changed by Jason so I can use this remotely!!!
        //  if (!application.Context.Request.IsLocal) {
        //    SecurityException securityException = new SecurityException((string)HttpContext.GetGlobalResourceObject("GlobalResources", "WebAdmin_ConfigurationIsLocalOnly"));
        //    WebAdminPage.SetCurrentException(application.Context, securityException);
        //    application.Server.Transfer("~/error.aspx");
        //  }

Then you can now use this tool remotely. Just user your browser to pull up the newly created virtual directory passing in the correct parameters. For example

http://myservername/WebAdminFiles/default.aspx?applicationPhysicalPath=C:\Websites\Application\&applicationUrl=/ApplicationURL

The other thing I did was to enable windows authentication on this folder so that I have to have an admin account on the server before I can access this url. This is important because once you enable this tool anyone can browse and delete users if they pull up the url.

OwnerDisplayName: Jason


问:
Using jquery to get all checked checkboxes with a certain class name
I know I can get all checked checkboxes on a page using this:

```<code>$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});
</code>```

But I am now using this on a page that has some other checkboxes that I don't want to include.  How would I change the above code to only look at checked checkboxes that have a certain class on them?

答:
Simple way to get all of values into an array</p>

```<code>var valores = (function () {
    var valor = [];
    $('input.className[type=checkbox]').each(function () {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);
</code>```

Body:
I know I can get all checked checkboxes on a page using this:

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

But I am now using this on a page that has some other checkboxes that I don't want to include.  How would I change the above code to only look at checked checkboxes that have a certain class on them?

Body:
Simple way to get all of values into an array

var valores = (function () {
    var valor = [];
    $('input.className[type=checkbox]').each(function () {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);

ContentLicense: CC BY-SA 4.0


问:
What does WindowsDX mean; what does WindowsGL mean, and the basic difference
I want to install some libraries, namely MonoGame, on my Windows10 computer.  There appear to be a WindowsDX and WindowsGL (or DesktopGL).  What is the basic difference between references to WindowsDX and GL. Thanks.</p>

答:
I assume WindowsGL refers to the Windows implementation of OpenGL.  OpenGL is an open, industry standard library and interface for using/programming graphics hardware.

WindowsDX probably refers to Windows DirectX.  DirectX is a suite of libraries for multimedia programming in general, including D3D for interfacing with graphics hardware, in particular.

The capabilities are comparable, but the interfaces differ.

Windows supports both, with OpenGL possibly being handled by translating commands into their DirectX equivalents at some level of the driver stack.  I don't think any non-Windows platforms support DirectX.


问:
Are underscores allowed in numeric literals in Java?
Can you use underscores in numbers in Java?  I saw this code in a blog, and it works, but will it continue to work in the future? Is it a feature or a bug? </p>

```<code>long oneBillion = 1_000_000_000L;
</code>```

答:
tl;dr

Can you use underscores in numbers in Java?

Yes.

Use in numeric literals: int, long, float,  double, and more to group digits as you desire.

Works with binary, decimal, octal, and hex notation.

will it continue to work in the future?

Yes.

Works in Java 7, Java 8, Java 9, and later.

Is it a feature or a bug?

Feature.

Details

Yes, you are using a feature added in Java 7, and continued in Java 8 and Java 9.

You can use an underscore between digits. You can even use a group of multiple underscores between digits, if you so desire. You can use them on whole numbers (integers) and on fractional numbers ( float, double ). In a fractional number, you can use them on either or both sides of the decimal point.

You can use them in hex (base 16), binary (base 2), and octal (base 8) numbers as well as base 10 numbers.

You may group any number of digits as you see fit.

The purpose is strictly readability by humans. Java sees no meaning in the underscores. The presence or absence of the underscores in a numeric literal has no effect on your code.

Read this half-page of documentation to see some helpful examples of right and wrong usages.

Body:
Can you use underscores in numbers in Java?  I saw this code in a blog, and it works, but will it continue to work in the future? Is it a feature or a bug?

long oneBillion = 1_000_000_000L;


问:
How to structure functional testing for a Django project
I would like to create functional tests to cover my Django project.  It is a multipage form that accepts input on each page.  The input on previous pages changes the content/options for the current pages.  The testing is currently set up with Splinter and PhantomJS.  I see two main ways to set this up.

For each page, create an instance of that page using stored data and point Splinter towards that.

Benefits

Allows random access testing of any page in the app

Can reuse unit test definitions to populate these synthetic pages

Downsides

Needs some kind of back end to be set up that Splinter can point to (At this point I have no idea how this would work, but it seems time consuming)

Structure the testing so that it is done in order, with the test content of page 1 passed to page 2

Benefits

Seems like it should just work out of the box

Downsides

Does not allow the tests to be run in an arbitrary order/only one at a time

Would probably take longer to run

Errors on earlier pages will affect later pages

I've found many tutorials on how to do functional testing on a small scale (individual pages/features/etc.) but I'm trying to figure out if there is an accepted way or best practice on how to structure it over a large project.  Is it one of these? Something else that I've missed?

答: What I was looking for was fixtures (https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-dumpdata).  Things just get way too complex if you're trying to pass browser state between a whole project worth of tests.  Easy to grab the DB state, easy to load in.</p>


问:
Loading HTML inside div tags
I am making a slideshow system that would show previous & next buttons for the obvious jobs. The slides however will be seperate html files, like slide1.html, slide2.html. Thickbox and other plugins load html asynchronously within them. What is the best method to do this. I am writing a jQuery plugin for the whole process.

I would love ideas from JavaScript experienced people.

Thanks a lot in advance. Appreciate all the help.

答:
Not entirely sure what you're asking. It's dead easy to load HTML snippets into a div using load:

```<code>$("selector_for_the_div").load("your_url");
</code>```

Example (live copy):

```<code>jQuery(function($) {

  var currentSlide = 0;
  var slides = [
    "http://jsbin.com/enuju4/",
    "http://jsbin.com/enuju4/2",
    "http://jsbin.com/enuju4/3"
    ];

  loadSlide(0);

  $("#btnNext").click(function() {
    loadSlide(currentSlide + 1);
  });

  $("#btnPrev").click(function() {
    loadSlide(currentSlide - 1);
  });

  function loadSlide(index) {
    if (index >= 0 && index < slides.length) {
      currentSlide = index;
      $('#slideHolder').load(slides[currentSlide]);
    }
  }

});
</code>```

You could cache the slides, or just rely on the browser's caching. Button enabling/disabling and such would obviously be nice...

Title: Loading HTML inside div tags

Body:
Not entirely sure what you're asking. It's dead easy to load HTML snippets into a div using load:

$("selector_for_the_div").load("your_url");

Example (live copy):

jQuery(function($) {

  var currentSlide = 0;
  var slides = [
    "http://jsbin.com/enuju4/",
    "http://jsbin.com/enuju4/2",
    "http://jsbin.com/enuju4/3"
    ];

  loadSlide(0);

  $("#btnNext").click(function() {
    loadSlide(currentSlide + 1);
  });

  $("#btnPrev").click(function() {
    loadSlide(currentSlide - 1);
  });

  function loadSlide(index) {
    if (index >= 0 && index < slides.length) {
      currentSlide = index;
      $('#slideHolder').load(slides[currentSlide]);
    }
  }

});

You could cache the slides, or just rely on the browser's caching. Button enabling/disabling and such would obviously be nice...