答:
```<code><Linear
    orientation="vertical"
        <Linear
            orientation=horizontal
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
        </Linear>
</linear>
</code>```

you can go like this way.

Title: How can I write XML which is divided into three horizontal columns and four vertical rows?

Body:
<Linear
    orientation="vertical"
        <Linear
            orientation=horizontal
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
                <Linear
                    orientation=vertical
                    <textview>
                    <imageview>
                    <textview>
                    <Textview>
                </linear>
        </Linear>
</linear>

you can go like this way.


来源: stackexchange

问:
adding user to a Database using mongo c# driver
I want to add a user to a newly created database in mongodb. I am using db.addUser(username,password).
But it is giving mongoAuthentication Exception. Please tell me the reason. I want to add a user so that next time when I use the same database, I can use it with the same set of crednetials as I passed to create a user</p>

答:
Start mongod.exe with --auth parameter. This will start your MongoDB with authentication mode enabled.

Since there will be no users when you start MongoDB for the first time, it will be considered as "localhost exception" (You should see a message saying "no users configured in admin.system.users, allowing localhost access" in the console). This means that, it is allowing you to create the first user in admin database (admin user), who will then have the authority to create other regular users.

To create admin user start mongo.exe and type following commands:

```<code>> use admin
> var user = {
    "user" : "adminUser",
    "pwd" : "adminPass",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

> db.createUser(user);
</code>```

You can also accomplish this using C# code as follows:

```<code>private static bool fnCreateAdminUser()
{
    try
    {
        var user = new BsonDocument { { "createUser", "adminUser" }, { "pwd", "adminPass" }, { "roles", new BsonArray { new BsonDocument { { "role", "userAdminAnyDatabase" }, { "db", "admin" } } } } };
        new MongoClient().GetDatabase("admin").RunCommand<BsonDocument>(user);
        return true;
    }
    catch (MongoCommandException) { return true; }
    catch { return false; }
}
</code>```

Now your admin user is created and you can create other regular users for your database using this admin user. You can either use C# code or command line etc. depending on your implementation. Following is the sample C# method which creates a user for the specified database:

```<code>private static bool CreateUser(string strDBName)
{
    try
    {
        if (!string.IsNullOrEmpty(strDBName))
        {
            // prepare admin credentials
            MongoCredential cred = MongoCredential.CreateCredential("admin", "adminUser", "adminPass");
            MongoClientSettings setting = new MongoClientSettings();
            setting.Credentials = new[] { cred };

            var user = new BsonDocument { { "createUser", "regularUser" }, { "pwd", "regularPass" }, { "roles", new BsonArray { new BsonDocument { { "role", "readWrite" }, { "db", strDBName } } } } };
            new MongoClient(setting).GetDatabase(strDBName).RunCommand<BsonDocument>(user);
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (MongoCommandException) { return true; } // if user already exists
    catch { return false; }
}
</code>```

You can also refer this blog post for more details on this. It explains other things too, like adding/changing user roles etc.

ContentLicense: CC BY-SA 3.0

Body:
Start mongod.exe with --auth parameter. This will start your MongoDB with authentication mode enabled.

Since there will be no users when you start MongoDB for the first time, it will be considered as "localhost exception" (You should see a message saying "no users configured in admin.system.users, allowing localhost access" in the console). This means that, it is allowing you to create the first user in admin database (admin user), who will then have the authority to create other regular users.

To create admin user start mongo.exe and type following commands:

> use admin
> var user = {
    "user" : "adminUser",
    "pwd" : "adminPass",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

> db.createUser(user);

You can also accomplish this using C# code as follows:

private static bool fnCreateAdminUser()
{
    try
    {
        var user = new BsonDocument { { "createUser", "adminUser" }, { "pwd", "adminPass" }, { "roles", new BsonArray { new BsonDocument { { "role", "userAdminAnyDatabase" }, { "db", "admin" } } } } };
        new MongoClient().GetDatabase("admin").RunCommand<BsonDocument>(user);
        return true;
    }
    catch (MongoCommandException) { return true; }
    catch { return false; }
}

Now your admin user is created and you can create other regular users for your database using this admin user. You can either use C# code or command line etc. depending on your implementation. Following is the sample C# method which creates a user for the specified database:

private static bool CreateUser(string strDBName)
{
    try
    {
        if (!string.IsNullOrEmpty(strDBName))
        {
            // prepare admin credentials
            MongoCredential cred = MongoCredential.CreateCredential("admin", "adminUser", "adminPass");
            MongoClientSettings setting = new MongoClientSettings();
            setting.Credentials = new[] { cred };

            var user = new BsonDocument { { "createUser", "regularUser" }, { "pwd", "regularPass" }, { "roles", new BsonArray { new BsonDocument { { "role", "readWrite" }, { "db", strDBName } } } } };
            new MongoClient(setting).GetDatabase(strDBName).RunCommand<BsonDocument>(user);
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (MongoCommandException) { return true; } // if user already exists
    catch { return false; }
}

You can also refer this blog post for more details on this. It explains other things too, like adding/changing user roles etc.


问:
What type of application that allowed to auto-start in iPhone?
i wonder what type of application that are allowed to be started in the background/foreground when the iPhone boot , and are they limited to iOS 4 ? </p>

答: Only Apple apps are allowed at startup, all others must be manually started.</p>

ContentLicense: CC BY-SA 2.5


问:
How to change active configuration all projects in eclipse?
I have more than 50 projects in my eclipse work space. I would like to know if there is a way to change active configuration of all the projects with single setting instead of doing it for each project individually</p>

答:
"Ctrl+A" to select all projects in project explorer. Right click and select Build Configurations -> Set Active ->

This way you can change Active configuration of all projects in the workspace


问:
Auto refresh few attributes of an object using spring MVC
Have a table in jsp in which i am populating all object attributes using spring MVC. Getting list of DTO's from backend and putting that DTO list into ModelView .
In jsp we are Iterating that dto list  and displaying in the table. Now the requirement is to come up with auto refresh to update a few attributes of all objects for every 5 seconds. All the attributes has to be retrieved only when user do manual refresh.

Please suggest me some better approach for the same

答:
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.

The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:

```<code>public void setIntHeader(String header, int headerValue)
</code>```

This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.

The example below refresh's the page every second updating the time.

```<code>    <%@ page import="java.io.*,java.text.*,java.util.*"%>
<html>

<head>
<title>Auto Refresh Header Example</title>
</head>

<body>
<h2>Auto Refresh Header Example</h2>
<%
// Page will be auto refresh after 1 seconds
response.setIntHeader("Refresh", 1);

// Get Current Time
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
out.println(dateFormat.format(cal.getTime()));
%>
</body>
</html>
</code>```

This is the key line to refresh: <%  response.setIntHeader("Refresh", 1); %>

Body:
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.

The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:

public void setIntHeader(String header, int headerValue)

This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.

The example below refresh's the page every second updating the time.

    <%@ page import="java.io.*,java.text.*,java.util.*"%>
<html>

<head>
<title>Auto Refresh Header Example</title>
</head>

<body>
<h2>Auto Refresh Header Example</h2>
<%
// Page will be auto refresh after 1 seconds
response.setIntHeader("Refresh", 1);

// Get Current Time
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
out.println(dateFormat.format(cal.getTime()));
%>
</body>
</html>

This is the key line to refresh: <%  response.setIntHeader("Refresh", 1); %>


问:
Elasticsearch and Drupal : how to add filter lowercase and asciifolding
I created an index in Drupal, and my queries works.
Now I try to add filters lowercase and asciifolding in the elasticsearch.yml file, but unsuccessfully:

I add these lines :

```<code>index:
 analysis:
  analyzer:
   default:
    filter : [standard, lowercase, asciifolding]
</code>```

I have an error : IndexCreationException: [myindex] failed to create index.
But 'myindex' already exist, I just try to add filters to this existing index.

How I can add these filters so that the indexation is correct for me?

Thank you very much for your help.

答:
The reason that you get this exception is because it's not possible to update the settings of an index by calling the general create index endpoint. In order to update analyzers you will have to call the '_settings' endpoint.

I've made a small example for you on how to do this:

```<code>PUT test
{
  "settings": {
    "analysis": {
      "analyzer": {
        "new_analyzer": {
          "tokenizer": "standard"
        }
      }
    }
  }
}

GET test/_analyze
{
  "analyzer": "new_analyzer",
  "text": "NoLowercasse"
}

POST test/_close

PUT test/_settings
{
  "analysis": {
    "analyzer": {
      "new_analyzer": {
        "tokenizer": "standard",
        "filter": [
          "asciifolding",
          "lowercase"
        ]
      }
    }
  }
}

POST test/_open

GET test/_analyze
{
  "analyzer": "new_analyzer",
  "text": "LowerCaseAdded"
}
</code>```

Response:

```<code>{
  "tokens": [
    {
      "token": "lowercaseadded",
      "start_offset": 0,
      "end_offset": 14,
      "type": "<ALPHANUM>",
      "position": 0
    }
  ]
}
</code>```

You can see that after the second analysis, the lowercase filter is being applied. The reason that you have to close your index is because it needs to rebuild the analyzer. You will notice that the new analyzer won't work as expected since the previously added documents weren't indexed with this analyzer, but rather the one without the asciifolding and lowercase.
In order to fix this, you'll have to rebuild your index (with the Reindex-API for example)

Hope this helps!

Edit: I maybe was a bit too quick in responding, as this is not a Drupal-Elastic solution, but it might point you in the right direction. To be honest I'm not familiar with running ES in combination with Drupal.

Body:
I created an index in Drupal, and my queries works.
Now I try to add filters lowercase and asciifolding in the elasticsearch.yml file, but unsuccessfully:

I add these lines :

index:
 analysis:
  analyzer:
   default:
    filter : [standard, lowercase, asciifolding]

I have an error : IndexCreationException: [myindex] failed to create index.
But 'myindex' already exist, I just try to add filters to this existing index.

How I can add these filters so that the indexation is correct for me?

Thank you very much for your help.

Body:
The reason that you get this exception is because it's not possible to update the settings of an index by calling the general create index endpoint. In order to update analyzers you will have to call the '_settings' endpoint.

I've made a small example for you on how to do this:

PUT test
{
  "settings": {
    "analysis": {
      "analyzer": {
        "new_analyzer": {
          "tokenizer": "standard"
        }
      }
    }
  }
}

GET test/_analyze
{
  "analyzer": "new_analyzer",
  "text": "NoLowercasse"
}

POST test/_close

PUT test/_settings
{
  "analysis": {
    "analyzer": {
      "new_analyzer": {
        "tokenizer": "standard",
        "filter": [
          "asciifolding",
          "lowercase"
        ]
      }
    }
  }
}

POST test/_open

GET test/_analyze
{
  "analyzer": "new_analyzer",
  "text": "LowerCaseAdded"
}

Response:

{
  "tokens": [
    {
      "token": "lowercaseadded",
      "start_offset": 0,
      "end_offset": 14,
      "type": "<ALPHANUM>",
      "position": 0
    }
  ]
}

You can see that after the second analysis, the lowercase filter is being applied. The reason that you have to close your index is because it needs to rebuild the analyzer. You will notice that the new analyzer won't work as expected since the previously added documents weren't indexed with this analyzer, but rather the one without the asciifolding and lowercase.
In order to fix this, you'll have to rebuild your index (with the Reindex-API for example)

Hope this helps!

Edit: I maybe was a bit too quick in responding, as this is not a Drupal-Elastic solution, but it might point you in the right direction. To be honest I'm not familiar with running ES in combination with Drupal.


问:
Is there any way to set DataGrid limit count of Rows?
At runtime, I got data from DB that will be use to bind in DataGrid first.

And, I don't want to show over 30 rows.

For example, if number of data is 78 , then I show only 30 recently rows.

And if number of data is 14, then I show all 14 rows.

I mean, I want to set limit rows count in DataGrid.

In addition, if the row added, I want to hide last row and show new row.

Also, if the row deleted, I want to add last another row.

I want to keep 30 rows or less than.

How can I do this?

Here is a part of my code, but it can help only one case when a row added while the program executing.

```<code>private void IncidentList_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        IEditableCollectionView itemsView = this.incidentList.Items;
        if (this.incidentList.Items.Count == max_RowCount + 1 && itemsView.IsAddingNew == true)
        { // max_RowCount = 30
            itemsView.CommitNew();
            this.incidentList.CanUserAddRows = false;
        }
    }
</code>```

答:
Use ICollectionView and bind your ObservableCollection to it.

Now you can apply filter on this collection view and put your condition there.

Body:
At runtime, I got data from DB that will be use to bind in DataGrid first.

And, I don't want to show over 30 rows.

For example, if number of data is 78 , then I show only 30 recently rows.

And if number of data is 14, then I show all 14 rows.

I mean, I want to set limit rows count in DataGrid.

In addition, if the row added, I want to hide last row and show new row.

Also, if the row deleted, I want to add last another row.

I want to keep 30 rows or less than.

How can I do this?

Here is a part of my code, but it can help only one case when a row added while the program executing.

private void IncidentList_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        IEditableCollectionView itemsView = this.incidentList.Items;
        if (this.incidentList.Items.Count == max_RowCount + 1 && itemsView.IsAddingNew == true)
        { // max_RowCount = 30
            itemsView.CommitNew();
            this.incidentList.CanUserAddRows = false;
        }
    }


问:
Asp.net if session value = 'something' change class in css
I have to give a display:none to a class called "plus" whenever the variable boolean = true in my session.

I'm working with asp.net. In my code behind I can't get my classes. In javascript I can't get my session.

Does anyone has a possible solution (without having to use runat=server" and call it on the behind code with the ID?

答:
You can add code something like below. Basically injecting Javascript code based on condition in the server side:</p>

```<code>if ((bool)Session[""])
        {
            var script = "jQuery('.plus').hide();";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "hideplus", script, true);
        }
</code>```

Body:
You can add code something like below. Basically injecting Javascript code based on condition in the server side:

if ((bool)Session[""])
        {
            var script = "jQuery('.plus').hide();";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "hideplus", script, true);
        }


问:
Accessing JSON field with dot in Angular2
Being the newbie to angular2, I wanna know how to access the JSON field with the dot in it.

JSON file

```<code> [
   {
      "s.no":0,
      "amt.pledged":15823,
      "blurb":"'Catalysts, Explorers & Secret Keepers: Women of Science Fiction' is a take-home exhibit & anthology by the Museum of Science Fiction.",
      "by":"Museum of Science Fiction",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-01T23:59:00-04:00",
      "location":"Washington, DC",
      "percentage.funded":186,
      "num.backers":"219382",
      "state":"DC",
      "title":"Catalysts, Explorers & Secret Keepers: Women of SF",
      "type":"Town",
      "url":"/projects/1608905146/catalysts-explorers-and-secret-keepers-women-of-sf?ref=discovery"
   },
   {
      "s.no":1,
      "amt.pledged":6859,
      "blurb":"A unique handmade picture book for kids & art lovers about a nervous monster who finds his courage with the help of a brave little girl",
      "by":"Tyrone Wells & Broken Eagle, LLC",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-25T01:13:33-05:00",
      "location":"Portland, OR",
      "percentage.funded":8,
      "num.backers":"154926",
      "state":"OR",
      "title":"The Whatamagump (a hand-crafted story picture book)",
      "type":"Town",
      "url":"/projects/thewhatamagump/the-whatamagump-a-hand-crafted-story-picture-book?ref=discovery"
   }]
</code>```

user.component.ts

```<code>import { Component } from '@angular/core';
import {PostsService} from '../services/posts.service';

@Component({
    moduleId:module.id,
  selector: 'user',
  templateUrl:'user.component.html',

    providers:[PostsService]

})
export class UserComponent  {

    posts:Post[];

    constructor(private postsService: PostsService){

    this.postsService.getPosts().subscribe(posts => {
        this.posts=posts;
            });
    }

    }

interface Post{

      title:string;
      by:string;
      blurb:string;
      location:string;
      state:string;
      country:string;
      currency:string;
      type:string;
      url:string;

}
</code>```

When I try to add amt.pledged:number; in the interface post above.I am getting error as "unused label".I cannot access the fields with dot(.) in my HTML file.

user.component.html

```<code><div class="container">

    <h3>Projects</h3>
    <div *ngFor="let post of posts" class="col-sm-4 a">
        <h3><a href="{{post.url}}" target="_blank">{{post.title}}</a></h3>
        <p>By {{post.by}}</p>
        <p>{{post.blurb}}</p>

        <p>{{post.location}}</p>

        <button class="btn btn-success"><a href="/about" class="b">Know more!</a></button>

    </div>

    </div>
</code>```

Thanks!

答:
you can declare a variable with a dot like this

```<code>interface Post{
       title:string;
       "amt.pledged": string;
}
</code>```

in order to access the property within html file you can use bracket notation

```<code>object['amt.pledged']
</code>```

Body:
Being the newbie to angular2, I wanna know how to access the JSON field with the dot in it.

JSON file

 [
   {
      "s.no":0,
      "amt.pledged":15823,
      "blurb":"'Catalysts, Explorers & Secret Keepers: Women of Science Fiction' is a take-home exhibit & anthology by the Museum of Science Fiction.",
      "by":"Museum of Science Fiction",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-01T23:59:00-04:00",
      "location":"Washington, DC",
      "percentage.funded":186,
      "num.backers":"219382",
      "state":"DC",
      "title":"Catalysts, Explorers & Secret Keepers: Women of SF",
      "type":"Town",
      "url":"/projects/1608905146/catalysts-explorers-and-secret-keepers-women-of-sf?ref=discovery"
   },
   {
      "s.no":1,
      "amt.pledged":6859,
      "blurb":"A unique handmade picture book for kids & art lovers about a nervous monster who finds his courage with the help of a brave little girl",
      "by":"Tyrone Wells & Broken Eagle, LLC",
      "country":"US",
      "currency":"usd",
      "end.time":"2016-11-25T01:13:33-05:00",
      "location":"Portland, OR",
      "percentage.funded":8,
      "num.backers":"154926",
      "state":"OR",
      "title":"The Whatamagump (a hand-crafted story picture book)",
      "type":"Town",
      "url":"/projects/thewhatamagump/the-whatamagump-a-hand-crafted-story-picture-book?ref=discovery"
   }]

user.component.ts

import { Component } from '@angular/core';
import {PostsService} from '../services/posts.service';

@Component({
    moduleId:module.id,
  selector: 'user',
  templateUrl:'user.component.html',

    providers:[PostsService]

})
export class UserComponent  {

    posts:Post[];

    constructor(private postsService: PostsService){

    this.postsService.getPosts().subscribe(posts => {
        this.posts=posts;
            });
    }

    }

interface Post{

      title:string;
      by:string;
      blurb:string;
      location:string;
      state:string;
      country:string;
      currency:string;
      type:string;
      url:string;

}

When I try to add amt.pledged:number; in the interface post above.I am getting error as "unused label".I cannot access the fields with dot(.) in my HTML file.

user.component.html

Projects

{{post.title}}

By {{post.by}}

{{post.blurb}}

{{post.location}}

        <button class="btn btn-success">Know more!</button>

Thanks!

Body:
you can declare a variable with a dot like this

interface Post{
       title:string;
       "amt.pledged": string;
}

in order to access the property within html file you can use bracket notation

object['amt.pledged']


问:
How to share a namespace between projects in .NET/C#/VS2008. Receiving error: "are you missing an assembly reference?"
What is the protocol to share a namespace between two projects when consequential projects will reference both of the namespaces?

Obviously this is possible (System, mscorlib)...

I've gotten different errors depending on the things I've tried.  Right now I have two projects Blueprint and Domain that share the MainApp namespace (for instance Blueprint has MainApp.IEntity and Domain has MainApp.EntityImpl).  They are both referenced by a third project, Repositories.  Repositories relies on both IRepository (in Blueprint) and EntityImpl (in Domain).  Blueprint builds first, followed by Domain and then Repositories.  For every reference to a class in the Domain project, I get a "The type or namespace name Domain does not exist in the namespace 'MainApp' (are you missing an assembly reference?)...

The assembly references are all correct.

I made sure there was a common assembly name between all the projects and adding an AssemblyInfo class in one of them with 'add link references to the root.  This did nothing, and so I removed it.

I could merge these two projects, but there are circumstances in which that would be detrimental.  I appreciate any guidance y'all can offer.

In response to the comment, Blueprint has no inter-project references,
Domain has a dependency on Blueprint
Repositories has a dependency on Blueprint and Domain

I have done all the deleting the dlls, building rebuilding cleaning repeating..no dice..

答: I can't explain why, but I have a project with two class library projects defining same namespace and using framework 3.5. I referred them in a project using NET Framework 4.0 client profile and got the error you got. When setting it to NET Framework 4.0 it worked.</p>


问:
How to implement sql coalesce in pandas
I have a data frame like

```<code>df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7
</code>```

I want to add a new column 'D'. Expected output is

```<code>     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0
</code>```

Thanks in advance!

答:
Another way is to explicitly fill column D with A,B,C in that order.</p>

```<code>df['D'] = np.nan
df['D'] = df.D.fillna(df.A).fillna(df.B).fillna(df.C)
</code>```

Title: How to implement sql coalesce in pandas

Body:
I have a data frame like

df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7

I want to add a new column 'D'. Expected output is

     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0

Thanks in advance!

Body:
Another way is to explicitly fill column D with A,B,C in that order.

df['D'] = np.nan
df['D'] = df.D.fillna(df.A).fillna(df.B).fillna(df.C)


问:
return sample date between min date and max date in R in a dataframe
How to return sample date between min date and max date in R in a dataframe as an additional column?</p>

```<code>Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017
</code>```

答:
assuming you're working on a data frame named mydata, you could use the following snippet:

```<code>mydata$sampledate <- sample(seq(as.Date(mydata$MinEnrollmentDate), as.Date(mydata$MinEnrollmentDate), by="day"), 1)
</code>```

basically, what this does is first generate a sequence of all days between the start and end date, and then takes a random sample of size 1 from that sequence, and writes it to your dataframe.

Body:
How to return sample date between min date and max date in R in a dataframe as an additional column?

Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017

Body:
assuming you're working on a data frame named mydata, you could use the following snippet:

mydata$sampledate <- sample(seq(as.Date(mydata$MinEnrollmentDate), as.Date(mydata$MinEnrollmentDate), by="day"), 1)

basically, what this does is first generate a sequence of all days between the start and end date, and then takes a random sample of size 1 from that sequence, and writes it to your dataframe.


问:
jquery radio button check tick mark should be fired in the div
```<code>$(document).ready(function(){
  $('#gender').change(function(){
    var resultnill="";
    $("#stat5").html(resultnill);
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
    {
      $("#stat5").append("<img src='tick.png'/>");
    }

  });
 });

<div class="form-group">
  <label for="gender" class="control-label col-xs-4">Gender:</label>
    <div class="col-xs-6">
    <label class="radio-inline"><input type="radio" name="gender" id="gender" value="M" required/>Male</label>
    <label class="radio-inline"><input type="radio" name="gender" id="gender" value="F" required/>Female</label>
    </div><div id="stat5"></div>
</div>
</code>```

when i check male radio button tick marks is appearing but if i check female tick box is not appearing.

答:
Why not simplify life with a css style declaration:

```<code>#stat5 {display: none;}
</code>```

Then change your #stat5 element line to this

```<code></div><img id="stat5" src='tick.png'/>
</code>```

Then use jQuery hide() and show()

```<code>$(document).ready(function(){
  $('#gender').change(function(){
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
      $("#stat5").hide();
    else
     $("#stat5").show();
</code>```

Body:
$(document).ready(function(){
  $('#gender').change(function(){
    var resultnill="";
    $("#stat5").html(resultnill);
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
    {
      $("#stat5").append("");
    }

  });
 });

  Gender:

    <input type="radio" name="gender" id="gender" value="M" required/>Male
    <input type="radio" name="gender" id="gender" value="F" required/>Female

when i check male radio button tick marks is appearing but if i check female tick box is not appearing.

Body:
Why not simplify life with a css style declaration:

#stat5 {display: none;}

Then change your #stat5 element line to this

</div><img id="stat5" src='tick.png'/>

Then use jQuery hide() and show()

$(document).ready(function(){
  $('#gender').change(function(){
    var result=$('input[type="radio"]:checked');
    if(result.length>0)
      $("#stat5").hide();
    else
     $("#stat5").show();


答:
Id selector affect only for first element with that id in html document, you can use name selector as following</p>

```<code>$('input[name=gender]').change(function(){
 //your code
});
</code>```

Title: jquery radio button check tick mark should be fired in the div

Body:
Id selector affect only for first element with that id in html document, you can use name selector as following

$('input[name=gender]').change(function(){
 //your code
});


问:
Is there an alternate/better way to do this simple logic in java?
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

```<code>    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }
</code>```

This works. But I was wondering if there is a better way to do this preferably not involving any flags.

答:
Yes, you should really be using something from java.util.concurrent.locks  Your example isn't quite strictly correct, that boolean needs to be volatile.

```<code>ReentrantLock lock = new ReentrantLock();

    void method1()
    {
        if(lock.tryLock())
        {
           try {
             if (!(lock.getHoldCount() > 1)) {
               //do Some Stuff
             }
          } finally {
            lock.unlock();
          }
        }
    }
</code>```

Edited to handle skipping execution on reentrance as inidicated in your comment.  Unfortunatly there isn't really a great way to do that with the built in library, as it's a bit of an odd usecase, but I still think using the built in library is a better option.

Body:
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }

This works. But I was wondering if there is a better way to do this preferably not involving any flags.

Body:
Yes, you should really be using something from java.util.concurrent.locks  Your example isn't quite strictly correct, that boolean needs to be volatile.

ReentrantLock lock = new ReentrantLock();

    void method1()
    {
        if(lock.tryLock())
        {
           try {
             if (!(lock.getHoldCount() > 1)) {
               //do Some Stuff
             }
          } finally {
            lock.unlock();
          }
        }
    }

Edited to handle skipping execution on reentrance as inidicated in your comment.  Unfortunatly there isn't really a great way to do that with the built in library, as it's a bit of an odd usecase, but I still think using the built in library is a better option.


问:
How to create an NPM package with Visual Studio 2017?
I like to create and deploy NPM packages with Visual Studio 2017.

I'm using TypeScript to create the JavaScript files.

What project template should I use for this project?

答:
I don't think you need Visual Studio to create a NPM package (it is a little disproportionate) but if you want to use it,  the best is the basic html page template.

For this king of project, for me the best is to use visual studio code and arrange the folders & subfolder as you want. You can look to other NPM project in github as Bootstrap for exemple to know how other users arrange their code.

I did a simple NPM package with TypeScript, you can have a look to my code organisation if you want :

https://github.com/AlexTeixeira/Askmethat-Rating


问:
How does Google Calendar update the content of an email AFTER it is sent?
Google calendar invite emails will update after they are sent if the original event has been changed... how does Google achieve this? Is there a general technique for anyone to do this? Or is this only possible because Google owns both gMail/gCalendar and the two systems are integrated behind the scenes outside of SMTP?

My first guess was that they used an iframe or an image that was loaded when the email was opened, but inspecting the source of the gMail page doesn't show any signs of that.

Here's a screenshot of the updated text:

And here's the HTML for that section of the page when reading the email within gMail:

答:
Note :

Inspecting Source wil give you nothing other than the markup of the content you see in the page after all dynamic operations including ajax.

To check the actual source, you want to visit view-source:url.

Now the question

That information is updated automatically at Run time via a JavaScript code.

In the image, you checked on Inspect element, which show the code of live view and so, you saw the updated content.

It is done by JavaScript DOM and text manipulation.

To verify this,

Click on the address bar.

add view-source: before the url. So, it will look like view-source:https://url

Then press ctrl+f or the corresponding key to find.

Search for the <div id=":8hg" which will show 0 results.

The view-source is load the source of the file without any ajax or JavaScript manipulation.

The div is not present in the source. So, we can understand that it is done dynamically.

When checking in detail,

in the source, we can see a link https://www.google.com/calendar/event?action\u003dVIEW\u0026eid\u003db..... which is stored in an array.

From this link, the content is taken.

(I blacked out some text for privacy).

Based on the return of the url, the content on mail is upated.

To verify this,

In the mail, you can see This invitation is out of date

But in the view-source: page, search for This invitation is out of date and it will return 0 results.

So, it is sure that the Calendar details are taken via an API call by Gmail to the G Calendar API.


问:
Django - how to save method apply only on new data
How do I manipulate this method to be applied only on new entries and does not have a previous entry.

When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again.

```<code>def save(self):
    p = Product.objects.last()
    if p:
        self.productnumber = 1000 + p.id
    else:
        self.productnumber = 1000
    super(Product, self).save()
</code>```

答:
Two ways are there.

1. post_save

```<code>@receiver(post_save, sender= Product)
def my_callback(sender, instance, created, *args, **kwargs):
    if created:
        #new
    else:
        #update
</code>```

2. check primary key exists

```<code>def save(self):
    if self.pk: #or id
        #update
    else:
        #new
</code>```

Body:
How do I manipulate this method to be applied only on new entries and does not have a previous entry.

When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again.

def save(self):
    p = Product.objects.last()
    if p:
        self.productnumber = 1000 + p.id
    else:
        self.productnumber = 1000
    super(Product, self).save()

Body:
Two ways are there.

1. post_save

@receiver(post_save, sender= Product)
def my_callback(sender, instance, created, *args, **kwargs):
    if created:
        #new
    else:
        #update

2. check primary key exists

def save(self):
    if self.pk: #or id
        #update
    else:
        #new


问:
Can't Add TableRowSorter to JTable Produced By SwingWorker
Thank You Hovercraft Full Of Eels for making note of the fact that my question was full of a jumbled mess of code that was unlikely to be solved. Since then, I have created a "minimal" Test Program to display the issue:

The Issue

What I am looking to do is have a GUI that displays a table containing employee information, and also allows a user to do a live search of said table by typing into a jtextfield at the top of the gui.

So I currently have a java class that creates a table and fills that table with employee information. This information is placed into the table via an SQL statement that is processed by a SwingWorker. The GUI works perfectly fine, until I try and add a TableRowSorter to the table that contains the info, this produces an error:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid range
    at javax.swing.DefaultRowSorter.checkAgainstModel(Unknown Source)
    at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
    at javax.swing.JTable.notifySorter(Unknown Source)
    at javax.swing.JTable.sortedTableChanged(Unknown Source)
    at javax.swing.JTable.tableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
    at tesPackage.WorkerTest$JDBCModel$JDBCWorker.process(WorkerTest.java:276)
</code>```

Based on this example, here's a

Working Example

```<code>package tesPackage;

import java.awt.BorderLayout;
import java.util.concurrent.ThreadLocalRandom;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
* @see https://stackoverflow.com/a/34742409/230513
* @see https://stackoverflow.com/a/24762078/230513
*/
public class WorkerTest {

private static final int N = 25;
private static final String URL = "jdbc:h2:mem:test";
private static final Random r = new Random();

private JPanel contentPane;
private static JTable tblSchedule;
private JScrollPane scrollSchedTable;
private JDBCModel model;
private JPanel panel;
private JTextField textField;

private static TableRowSorter<TableModel> rowSorter;

private void display() {

    createTestDatabase(N);  //Create the Test Database

    //Create the GUI
    JFrame f = new JFrame("WorkerTest");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setBounds(100, 100, 780, 450);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    f.setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));
    {
        scrollSchedTable = new JScrollPane();
        scrollSchedTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contentPane.add(scrollSchedTable);
        {
            tblSchedule = new JTable();
            tblSchedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            tblSchedule.setShowHorizontalLines(true);
            tblSchedule.setShowVerticalLines(true);
            tblSchedule.setFillsViewportHeight(true);
            model = new JDBCModel(getConnection(), "select * from city");
            tblSchedule.setModel(model);
            rowSorter = new TableRowSorter<TableModel>(model);  //IF UNCOMMENT THESE 2 LINES GUI WILL RUN
            tblSchedule.setRowSorter(rowSorter);                //BUT IF TYPE IN SEARCH BOX THERE IS AN ERROR
            scrollSchedTable.setViewportView(tblSchedule);
        }
        {
            panel = new JPanel();
            contentPane.add(panel, BorderLayout.NORTH);
            panel.setLayout(new BorderLayout(0, 0));
            {
                textField = new JTextField();
                panel.add(textField, BorderLayout.EAST);
                textField.setColumns(10);
            }
            {
                panel.add(model.jpb, BorderLayout.CENTER);
            }
            {
                textField.getDocument().addDocumentListener(new DocumentListener(){

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        String text = textField.getText().trim();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        String text = textField.getText();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        String text = textField.getText();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                });
            }
        }
    }
    f.setVisible(true);
}

private static class Row {
    String lname;
    String fname;
    String monTime;
    String tueTime;
    String wedTime;
    String thuTime;
    String friTime;
    String satTime;
    String sunTime;
    String totalTime;
}

private static class JDBCModel extends AbstractTableModel {

    private final JProgressBar jpb = new JProgressBar();
    private static final long serialVersionUID = 1L;
    private final List<Row> data = new ArrayList<>();
    private ResultSet rs = null;
    private ResultSetMetaData meta;

    public JDBCModel(Connection conn, String query) {
        try {
            Statement s = conn.createStatement();
            rs = s.executeQuery(query);
            meta = rs.getMetaData();
            JDBCWorker worker = new JDBCWorker();
            jpb.setIndeterminate(true);
            worker.execute();

        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return 10;
    }

    @Override
    public Object getValueAt(int rowIndex, int colIndex) {
        Row row = data.get(rowIndex);
        switch (colIndex) {
            case 0:
                return row.lname;
            case 1:
                return row.fname;
            case 2:
                return row.monTime;
            case 3:
                return row.tueTime;
            case 4:
                return row.wedTime;
            case 5:
                return row.thuTime;
            case 6:
                return row.friTime;
            case 7:
                return row.satTime;
            case 8:
                return row.sunTime;
            case 9:
                return row.totalTime;
        }
        return null;
    }

    @Override
    public String getColumnName(int colIndex) {
        String name = null;
        switch(colIndex){
        case 0: name = "Last Name";
            return name;
        case 1: name = "First Name";
            return name;
        case 2: name = "Monday";
            return name;
        case 3: name = "Tuesday";
            return name;
        case 4: name = "Wednesday";
            return name;
        case 5: name = "Thursday";
            return name;
        case 6: name = "Friday";
            return name;
        case 7: name = "Saturday";
            return name;
        case 8: name = "Sunday";
            return name;
        case 9: name = "Total";
            return name;
        }
        return name;
    }

    private class JDBCWorker extends SwingWorker<List<Row>, Row> {

        @Override
        protected List<Row> doInBackground() {
            try {
                while (rs.next()) {
                    Row r = new Row();
                    Integer total = 0;
                    r.lname = rs.getString(2);
                    r.fname = rs.getString(1);
                    r.monTime = String.valueOf(rs.getInt(3) + " - " + rs.getInt(4));
                    total += rs.getInt(4) - rs.getInt(3);
                    r.tueTime = String.valueOf(rs.getInt(5) + " - " + rs.getInt(6));
                    total += rs.getInt(6) - rs.getInt(5);
                    r.wedTime = String.valueOf(rs.getInt(7) + " - " + rs.getInt(8));
                    total += rs.getInt(8) - rs.getInt(7);
                    r.thuTime = String.valueOf(rs.getInt(9) + " - " + rs.getInt(10));
                    total += rs.getInt(10) - rs.getInt(9);
                    r.friTime = String.valueOf(rs.getInt(11) + " - " + rs.getInt(12));
                    total += rs.getInt(12) - rs.getInt(11);
                    r.satTime = String.valueOf(rs.getInt(13) + " - " + rs.getInt(14));
                    total += rs.getInt(14) - rs.getInt(13);
                    r.sunTime = String.valueOf(rs.getInt(15) + " - " + rs.getInt(16));
                    total += rs.getInt(16) - rs.getInt(15);
                    r.totalTime = String.valueOf(total);
                    publish(r);
                }
            } catch (SQLException e) {
                e.printStackTrace(System.err);
            }
            return data;
        }

        @Override
        protected void process(List<Row> chunks) {
            int n = getRowCount() + 1;
            System.out.println("Row Count = " + n);
            System.out.println("Chunks Size = " + chunks.size());
            for (Row row : chunks) {
                data.add(row);
            }
            fireTableRowsInserted(n, n + chunks.size());
        }

        @Override
        protected void done(){
            jpb.setIndeterminate(false);
            jpb.setValue(100);
        }
    }
}

//Creates the Test DB with test names and working hours
private static void createTestDatabase(int n) {
    Connection conn = getConnection();
    try {
        Statement st = conn.createStatement();
        st.execute("create table city(fname varchar(10), lname varchar(10), mons int(2), mone int(2), tues int(2), tuee int(2), weds int(2), wede int(2), thus int(2), thue int(2), fris int(2), frie int(2), sats int(2), sate int(2), suns int(2), sune int(2))");
        Random gen = new Random();
        PreparedStatement ps = conn.prepareStatement(
            "insert into city values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        for (int i = 0; i < n; i++) {
            ps.setString(1, "First" + i);
            ps.setString(2, "Last" + i);
            ps.setInt(3, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(4, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(5, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(6, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(7, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(8, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(9, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(10, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(11, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(12, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(13, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(14, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(15, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(16, ThreadLocalRandom.current().nextInt(13, 22));
            ps.execute();
        }
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
}

private static Connection getConnection() {
    try {
        return DriverManager.getConnection(URL, "", "");
    } catch (SQLException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

public static void main(String[] args) {
    EventQueue.invokeLater(new WorkerTest()::display);
}
}
</code>```

EDIT (Only 5 Min Later)

So I started to use the debug function in eclipse and as I was stepping through the program, I found that some event called EDT.pumpOneEventForFilters(int) had a variable called arg0(it's only argument) with a value of -1. Once stepping into this event, the Exception is thrown. I'm not sure if this is useful information, but I thought I'd toss it out there just in case.

答:
The original example notified the listening JTable of new rows in the implementation of process():

```<code>fireTableRowsInserted(n, n + chunks.size());
</code>```

Because the table needs to consider all rows when sorting and filtering, the model should notify "listeners that all cell values in the table's rows may have changed."

```<code>fireTableDataChanged();
</code>```

As an aside, a single instance of ThreadLocalRandom is sufficient in createTestDatabase().

Code, as tested:

```<code>import java.awt.BorderLayout;
import java.util.concurrent.ThreadLocalRandom;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * @see https://stackoverflow.com/q/43161033/230513
 * @see https://stackoverflow.com/a/34742409/230513
 * @see https://stackoverflow.com/a/24762078/230513
 */
public class WorkerTest {

    private static final int N = 256;
    private static final String URL = "jdbc:h2:mem:test";
    private static final Random r = new Random();

    private JPanel contentPane;
    private static JTable tblSchedule;
    private JScrollPane scrollSchedTable;
    private JDBCModel model;
    private JPanel panel;
    private JTextField textField;

    private static TableRowSorter<TableModel> rowSorter;

    private void display() {

        createTestDatabase(N);  //Create the Test Database

        //Create the GUI
        JFrame f = new JFrame("WorkerTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setBounds(100, 100, 780, 450);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        f.setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        scrollSchedTable = new JScrollPane();
        scrollSchedTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contentPane.add(scrollSchedTable);

        tblSchedule = new JTable();
        tblSchedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tblSchedule.setShowHorizontalLines(true);
        tblSchedule.setShowVerticalLines(true);
        tblSchedule.setFillsViewportHeight(true);
        model = new JDBCModel(getConnection(), "select * from city");
        tblSchedule.setModel(model);
        rowSorter = new TableRowSorter<TableModel>(model);
        tblSchedule.setRowSorter(rowSorter);
        scrollSchedTable.setViewportView(tblSchedule);

        panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);
        panel.setLayout(new BorderLayout(0, 0));

        textField = new JTextField();
        panel.add(textField, BorderLayout.EAST);
        textField.setColumns(10);

        panel.add(model.jpb, BorderLayout.CENTER);

        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = textField.getText().trim();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = textField.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                String text = textField.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

        });
        f.setVisible(true);
    }

    private static class Row {

        String lname;
        String fname;
        String monTime;
        String tueTime;
        String wedTime;
        String thuTime;
        String friTime;
        String satTime;
        String sunTime;
        String totalTime;
    }

    private static class JDBCModel extends AbstractTableModel {

        private final JProgressBar jpb = new JProgressBar();
        private static final long serialVersionUID = 1L;
        private final List<Row> data = new ArrayList<>();
        private ResultSet rs = null;
        private ResultSetMetaData meta;

        public JDBCModel(Connection conn, String query) {
            try {
                Statement s = conn.createStatement();
                rs = s.executeQuery(query);
                meta = rs.getMetaData();
                JDBCWorker worker = new JDBCWorker();
                jpb.setIndeterminate(true);
                worker.execute();

            } catch (SQLException e) {
                e.printStackTrace(System.err);
            }
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return 10;
        }

        @Override
        public Object getValueAt(int rowIndex, int colIndex) {
            Row row = data.get(rowIndex);
            switch (colIndex) {
                case 0:
                    return row.lname;
                case 1:
                    return row.fname;
                case 2:
                    return row.monTime;
                case 3:
                    return row.tueTime;
                case 4:
                    return row.wedTime;
                case 5:
                    return row.thuTime;
                case 6:
                    return row.friTime;
                case 7:
                    return row.satTime;
                case 8:
                    return row.sunTime;
                case 9:
                    return row.totalTime;
            }
            return null;
        }

        @Override
        public String getColumnName(int colIndex) {
            String name = null;
            switch (colIndex) {
                case 0:
                    name = "Last Name";
                    return name;
                case 1:
                    name = "First Name";
                    return name;
                case 2:
                    name = "Monday";
                    return name;
                case 3:
                    name = "Tuesday";
                    return name;
                case 4:
                    name = "Wednesday";
                    return name;
                case 5:
                    name = "Thursday";
                    return name;
                case 6:
                    name = "Friday";
                    return name;
                case 7:
                    name = "Saturday";
                    return name;
                case 8:
                    name = "Sunday";
                    return name;
                case 9:
                    name = "Total";
                    return name;
            }
            return name;
        }

        private class JDBCWorker extends SwingWorker<List<Row>, Row> {

            @Override
            protected List<Row> doInBackground() {
                try {
                    while (rs.next()) {
                        Row r = new Row();
                        Integer total = 0;
                        r.lname = rs.getString(2);
                        r.fname = rs.getString(1);
                        r.monTime = String.valueOf(rs.getInt(3) + " - " + rs.getInt(4));
                        total += rs.getInt(4) - rs.getInt(3);
                        r.tueTime = String.valueOf(rs.getInt(5) + " - " + rs.getInt(6));
                        total += rs.getInt(6) - rs.getInt(5);
                        r.wedTime = String.valueOf(rs.getInt(7) + " - " + rs.getInt(8));
                        total += rs.getInt(8) - rs.getInt(7);
                        r.thuTime = String.valueOf(rs.getInt(9) + " - " + rs.getInt(10));
                        total += rs.getInt(10) - rs.getInt(9);
                        r.friTime = String.valueOf(rs.getInt(11) + " - " + rs.getInt(12));
                        total += rs.getInt(12) - rs.getInt(11);
                        r.satTime = String.valueOf(rs.getInt(13) + " - " + rs.getInt(14));
                        total += rs.getInt(14) - rs.getInt(13);
                        r.sunTime = String.valueOf(rs.getInt(15) + " - " + rs.getInt(16));
                        total += rs.getInt(16) - rs.getInt(15);
                        r.totalTime = String.valueOf(total);
                        publish(r);
                    }
                } catch (SQLException e) {
                    e.printStackTrace(System.err);
                }
                return data;
            }

            @Override
            protected void process(List<Row> chunks) {
                int n = getRowCount() + 1;
                System.out.println("Row Count = " + n);
                System.out.println("Chunks Size = " + chunks.size());
                for (Row row : chunks) {
                    data.add(row);
                }
                fireTableDataChanged();
            }

            @Override
            protected void done() {
                jpb.setIndeterminate(false);
                jpb.setValue(100);
            }
        }
    }

//Creates the Test DB with test names and working hours
    private static void createTestDatabase(int n) {
        ThreadLocalRandom r = ThreadLocalRandom.current();
        Connection conn = getConnection();
        try {
            Statement st = conn.createStatement();
            st.execute("create table city(fname varchar(10), lname varchar(10), mons int(2), mone int(2), tues int(2), tuee int(2), weds int(2), wede int(2), thus int(2), thue int(2), fris int(2), frie int(2), sats int(2), sate int(2), suns int(2), sune int(2))");
            Random gen = new Random();
            PreparedStatement ps = conn.prepareStatement(
                "insert into city values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            for (int i = 0; i < n; i++) {
                ps.setString(1, "First" + i);
                ps.setString(2, "Last" + i);
                ps.setInt(3, r.nextInt(6, 12));
                ps.setInt(4, r.nextInt(13, 22));
                ps.setInt(5, r.nextInt(6, 12));
                ps.setInt(6, r.nextInt(13, 22));
                ps.setInt(7, r.nextInt(6, 12));
                ps.setInt(8, r.nextInt(13, 22));
                ps.setInt(9, r.nextInt(6, 12));
                ps.setInt(10, r.nextInt(13, 22));
                ps.setInt(11, r.nextInt(6, 12));
                ps.setInt(12, r.nextInt(13, 22));
                ps.setInt(13, r.nextInt(6, 12));
                ps.setInt(14, r.nextInt(13, 22));
                ps.setInt(15, r.nextInt(6, 12));
                ps.setInt(16, r.nextInt(13, 22));
                ps.execute();
            }
        } catch (SQLException ex) {
            ex.printStackTrace(System.err);
        }
    }

    private static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, "", "");
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new WorkerTest()::display);
    }
}
</code>```

Body:
Thank You Hovercraft Full Of Eels for making note of the fact that my question was full of a jumbled mess of code that was unlikely to be solved. Since then, I have created a "minimal" Test Program to display the issue:

The Issue

What I am looking to do is have a GUI that displays a table containing employee information, and also allows a user to do a live search of said table by typing into a jtextfield at the top of the gui.

So I currently have a java class that creates a table and fills that table with employee information. This information is placed into the table via an SQL statement that is processed by a SwingWorker. The GUI works perfectly fine, until I try and add a TableRowSorter to the table that contains the info, this produces an error:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid range
    at javax.swing.DefaultRowSorter.checkAgainstModel(Unknown Source)
    at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
    at javax.swing.JTable.notifySorter(Unknown Source)
    at javax.swing.JTable.sortedTableChanged(Unknown Source)
    at javax.swing.JTable.tableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
    at tesPackage.WorkerTest$JDBCModel$JDBCWorker.process(WorkerTest.java:276)

Based on this example, here's a

Working Example

package tesPackage;

import java.awt.BorderLayout;
import java.util.concurrent.ThreadLocalRandom;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
* @see https://stackoverflow.com/a/34742409/230513
* @see https://stackoverflow.com/a/24762078/230513
*/
public class WorkerTest {

private static final int N = 25;
private static final String URL = "jdbc:h2:mem:test";
private static final Random r = new Random();

private JPanel contentPane;
private static JTable tblSchedule;
private JScrollPane scrollSchedTable;
private JDBCModel model;
private JPanel panel;
private JTextField textField;

private static TableRowSorter<TableModel> rowSorter;

private void display() {

    createTestDatabase(N);  //Create the Test Database

    //Create the GUI
    JFrame f = new JFrame("WorkerTest");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setBounds(100, 100, 780, 450);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    f.setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));
    {
        scrollSchedTable = new JScrollPane();
        scrollSchedTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contentPane.add(scrollSchedTable);
        {
            tblSchedule = new JTable();
            tblSchedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            tblSchedule.setShowHorizontalLines(true);
            tblSchedule.setShowVerticalLines(true);
            tblSchedule.setFillsViewportHeight(true);
            model = new JDBCModel(getConnection(), "select * from city");
            tblSchedule.setModel(model);
            rowSorter = new TableRowSorter<TableModel>(model);  //IF UNCOMMENT THESE 2 LINES GUI WILL RUN
            tblSchedule.setRowSorter(rowSorter);                //BUT IF TYPE IN SEARCH BOX THERE IS AN ERROR
            scrollSchedTable.setViewportView(tblSchedule);
        }
        {
            panel = new JPanel();
            contentPane.add(panel, BorderLayout.NORTH);
            panel.setLayout(new BorderLayout(0, 0));
            {
                textField = new JTextField();
                panel.add(textField, BorderLayout.EAST);
                textField.setColumns(10);
            }
            {
                panel.add(model.jpb, BorderLayout.CENTER);
            }
            {
                textField.getDocument().addDocumentListener(new DocumentListener(){

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        String text = textField.getText().trim();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        String text = textField.getText();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        String text = textField.getText();
                        if (text.trim().length() == 0) {
                            rowSorter.setRowFilter(null);
                        } else {
                            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                        }
                    }

                });
            }
        }
    }
    f.setVisible(true);
}

private static class Row {
    String lname;
    String fname;
    String monTime;
    String tueTime;
    String wedTime;
    String thuTime;
    String friTime;
    String satTime;
    String sunTime;
    String totalTime;
}

private static class JDBCModel extends AbstractTableModel {

    private final JProgressBar jpb = new JProgressBar();
    private static final long serialVersionUID = 1L;
    private final List<Row> data = new ArrayList<>();
    private ResultSet rs = null;
    private ResultSetMetaData meta;

    public JDBCModel(Connection conn, String query) {
        try {
            Statement s = conn.createStatement();
            rs = s.executeQuery(query);
            meta = rs.getMetaData();
            JDBCWorker worker = new JDBCWorker();
            jpb.setIndeterminate(true);
            worker.execute();

        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return 10;
    }

    @Override
    public Object getValueAt(int rowIndex, int colIndex) {
        Row row = data.get(rowIndex);
        switch (colIndex) {
            case 0:
                return row.lname;
            case 1:
                return row.fname;
            case 2:
                return row.monTime;
            case 3:
                return row.tueTime;
            case 4:
                return row.wedTime;
            case 5:
                return row.thuTime;
            case 6:
                return row.friTime;
            case 7:
                return row.satTime;
            case 8:
                return row.sunTime;
            case 9:
                return row.totalTime;
        }
        return null;
    }

    @Override
    public String getColumnName(int colIndex) {
        String name = null;
        switch(colIndex){
        case 0: name = "Last Name";
            return name;
        case 1: name = "First Name";
            return name;
        case 2: name = "Monday";
            return name;
        case 3: name = "Tuesday";
            return name;
        case 4: name = "Wednesday";
            return name;
        case 5: name = "Thursday";
            return name;
        case 6: name = "Friday";
            return name;
        case 7: name = "Saturday";
            return name;
        case 8: name = "Sunday";
            return name;
        case 9: name = "Total";
            return name;
        }
        return name;
    }

    private class JDBCWorker extends SwingWorker<List<Row>, Row> {

        @Override
        protected List<Row> doInBackground() {
            try {
                while (rs.next()) {
                    Row r = new Row();
                    Integer total = 0;
                    r.lname = rs.getString(2);
                    r.fname = rs.getString(1);
                    r.monTime = String.valueOf(rs.getInt(3) + " - " + rs.getInt(4));
                    total += rs.getInt(4) - rs.getInt(3);
                    r.tueTime = String.valueOf(rs.getInt(5) + " - " + rs.getInt(6));
                    total += rs.getInt(6) - rs.getInt(5);
                    r.wedTime = String.valueOf(rs.getInt(7) + " - " + rs.getInt(8));
                    total += rs.getInt(8) - rs.getInt(7);
                    r.thuTime = String.valueOf(rs.getInt(9) + " - " + rs.getInt(10));
                    total += rs.getInt(10) - rs.getInt(9);
                    r.friTime = String.valueOf(rs.getInt(11) + " - " + rs.getInt(12));
                    total += rs.getInt(12) - rs.getInt(11);
                    r.satTime = String.valueOf(rs.getInt(13) + " - " + rs.getInt(14));
                    total += rs.getInt(14) - rs.getInt(13);
                    r.sunTime = String.valueOf(rs.getInt(15) + " - " + rs.getInt(16));
                    total += rs.getInt(16) - rs.getInt(15);
                    r.totalTime = String.valueOf(total);
                    publish(r);
                }
            } catch (SQLException e) {
                e.printStackTrace(System.err);
            }
            return data;
        }

        @Override
        protected void process(List<Row> chunks) {
            int n = getRowCount() + 1;
            System.out.println("Row Count = " + n);
            System.out.println("Chunks Size = " + chunks.size());
            for (Row row : chunks) {
                data.add(row);
            }
            fireTableRowsInserted(n, n + chunks.size());
        }

        @Override
        protected void done(){
            jpb.setIndeterminate(false);
            jpb.setValue(100);
        }
    }
}

//Creates the Test DB with test names and working hours
private static void createTestDatabase(int n) {
    Connection conn = getConnection();
    try {
        Statement st = conn.createStatement();
        st.execute("create table city(fname varchar(10), lname varchar(10), mons int(2), mone int(2), tues int(2), tuee int(2), weds int(2), wede int(2), thus int(2), thue int(2), fris int(2), frie int(2), sats int(2), sate int(2), suns int(2), sune int(2))");
        Random gen = new Random();
        PreparedStatement ps = conn.prepareStatement(
            "insert into city values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        for (int i = 0; i < n; i++) {
            ps.setString(1, "First" + i);
            ps.setString(2, "Last" + i);
            ps.setInt(3, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(4, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(5, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(6, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(7, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(8, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(9, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(10, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(11, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(12, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(13, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(14, ThreadLocalRandom.current().nextInt(13, 22));
            ps.setInt(15, ThreadLocalRandom.current().nextInt(6, 12));
            ps.setInt(16, ThreadLocalRandom.current().nextInt(13, 22));
            ps.execute();
        }
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
}

private static Connection getConnection() {
    try {
        return DriverManager.getConnection(URL, "", "");
    } catch (SQLException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

public static void main(String[] args) {
    EventQueue.invokeLater(new WorkerTest()::display);
}
}

EDIT (Only 5 Min Later)

So I started to use the debug function in eclipse and as I was stepping through the program, I found that some event called EDT.pumpOneEventForFilters(int) had a variable called arg0(it's only argument) with a value of -1. Once stepping into this event, the Exception is thrown. I'm not sure if this is useful information, but I thought I'd toss it out there just in case.

Body:
The original example notified the listening JTable of new rows in the implementation of process():

fireTableRowsInserted(n, n + chunks.size());

Because the table needs to consider all rows when sorting and filtering, the model should notify "listeners that all cell values in the table's rows may have changed."

fireTableDataChanged();

As an aside, a single instance of ThreadLocalRandom is sufficient in createTestDatabase().

Code, as tested:

import java.awt.BorderLayout;
import java.util.concurrent.ThreadLocalRandom;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * @see https://stackoverflow.com/q/43161033/230513
 * @see https://stackoverflow.com/a/34742409/230513
 * @see https://stackoverflow.com/a/24762078/230513
 */
public class WorkerTest {

    private static final int N = 256;
    private static final String URL = "jdbc:h2:mem:test";
    private static final Random r = new Random();

    private JPanel contentPane;
    private static JTable tblSchedule;
    private JScrollPane scrollSchedTable;
    private JDBCModel model;
    private JPanel panel;
    private JTextField textField;

    private static TableRowSorter<TableModel> rowSorter;

    private void display() {

        createTestDatabase(N);  //Create the Test Database

        //Create the GUI
        JFrame f = new JFrame("WorkerTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setBounds(100, 100, 780, 450);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        f.setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        scrollSchedTable = new JScrollPane();
        scrollSchedTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contentPane.add(scrollSchedTable);

        tblSchedule = new JTable();
        tblSchedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tblSchedule.setShowHorizontalLines(true);
        tblSchedule.setShowVerticalLines(true);
        tblSchedule.setFillsViewportHeight(true);
        model = new JDBCModel(getConnection(), "select * from city");
        tblSchedule.setModel(model);
        rowSorter = new TableRowSorter<TableModel>(model);
        tblSchedule.setRowSorter(rowSorter);
        scrollSchedTable.setViewportView(tblSchedule);

        panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);
        panel.setLayout(new BorderLayout(0, 0));

        textField = new JTextField();
        panel.add(textField, BorderLayout.EAST);
        textField.setColumns(10);

        panel.add(model.jpb, BorderLayout.CENTER);

        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = textField.getText().trim();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = textField.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                String text = textField.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

        });
        f.setVisible(true);
    }

    private static class Row {

        String lname;
        String fname;
        String monTime;
        String tueTime;
        String wedTime;
        String thuTime;
        String friTime;
        String satTime;
        String sunTime;
        String totalTime;
    }

    private static class JDBCModel extends AbstractTableModel {

        private final JProgressBar jpb = new JProgressBar();
        private static final long serialVersionUID = 1L;
        private final List<Row> data = new ArrayList<>();
        private ResultSet rs = null;
        private ResultSetMetaData meta;

        public JDBCModel(Connection conn, String query) {
            try {
                Statement s = conn.createStatement();
                rs = s.executeQuery(query);
                meta = rs.getMetaData();
                JDBCWorker worker = new JDBCWorker();
                jpb.setIndeterminate(true);
                worker.execute();

            } catch (SQLException e) {
                e.printStackTrace(System.err);
            }
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return 10;
        }

        @Override
        public Object getValueAt(int rowIndex, int colIndex) {
            Row row = data.get(rowIndex);
            switch (colIndex) {
                case 0:
                    return row.lname;
                case 1:
                    return row.fname;
                case 2:
                    return row.monTime;
                case 3:
                    return row.tueTime;
                case 4:
                    return row.wedTime;
                case 5:
                    return row.thuTime;
                case 6:
                    return row.friTime;
                case 7:
                    return row.satTime;
                case 8:
                    return row.sunTime;
                case 9:
                    return row.totalTime;
            }
            return null;
        }

        @Override
        public String getColumnName(int colIndex) {
            String name = null;
            switch (colIndex) {
                case 0:
                    name = "Last Name";
                    return name;
                case 1:
                    name = "First Name";
                    return name;
                case 2:
                    name = "Monday";
                    return name;
                case 3:
                    name = "Tuesday";
                    return name;
                case 4:
                    name = "Wednesday";
                    return name;
                case 5:
                    name = "Thursday";
                    return name;
                case 6:
                    name = "Friday";
                    return name;
                case 7:
                    name = "Saturday";
                    return name;
                case 8:
                    name = "Sunday";
                    return name;
                case 9:
                    name = "Total";
                    return name;
            }
            return name;
        }

        private class JDBCWorker extends SwingWorker<List<Row>, Row> {

            @Override
            protected List<Row> doInBackground() {
                try {
                    while (rs.next()) {
                        Row r = new Row();
                        Integer total = 0;
                        r.lname = rs.getString(2);
                        r.fname = rs.getString(1);
                        r.monTime = String.valueOf(rs.getInt(3) + " - " + rs.getInt(4));
                        total += rs.getInt(4) - rs.getInt(3);
                        r.tueTime = String.valueOf(rs.getInt(5) + " - " + rs.getInt(6));
                        total += rs.getInt(6) - rs.getInt(5);
                        r.wedTime = String.valueOf(rs.getInt(7) + " - " + rs.getInt(8));
                        total += rs.getInt(8) - rs.getInt(7);
                        r.thuTime = String.valueOf(rs.getInt(9) + " - " + rs.getInt(10));
                        total += rs.getInt(10) - rs.getInt(9);
                        r.friTime = String.valueOf(rs.getInt(11) + " - " + rs.getInt(12));
                        total += rs.getInt(12) - rs.getInt(11);
                        r.satTime = String.valueOf(rs.getInt(13) + " - " + rs.getInt(14));
                        total += rs.getInt(14) - rs.getInt(13);
                        r.sunTime = String.valueOf(rs.getInt(15) + " - " + rs.getInt(16));
                        total += rs.getInt(16) - rs.getInt(15);
                        r.totalTime = String.valueOf(total);
                        publish(r);
                    }
                } catch (SQLException e) {
                    e.printStackTrace(System.err);
                }
                return data;
            }

            @Override
            protected void process(List<Row> chunks) {
                int n = getRowCount() + 1;
                System.out.println("Row Count = " + n);
                System.out.println("Chunks Size = " + chunks.size());
                for (Row row : chunks) {
                    data.add(row);
                }
                fireTableDataChanged();
            }

            @Override
            protected void done() {
                jpb.setIndeterminate(false);
                jpb.setValue(100);
            }
        }
    }

//Creates the Test DB with test names and working hours
    private static void createTestDatabase(int n) {
        ThreadLocalRandom r = ThreadLocalRandom.current();
        Connection conn = getConnection();
        try {
            Statement st = conn.createStatement();
            st.execute("create table city(fname varchar(10), lname varchar(10), mons int(2), mone int(2), tues int(2), tuee int(2), weds int(2), wede int(2), thus int(2), thue int(2), fris int(2), frie int(2), sats int(2), sate int(2), suns int(2), sune int(2))");
            Random gen = new Random();
            PreparedStatement ps = conn.prepareStatement(
                "insert into city values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            for (int i = 0; i < n; i++) {
                ps.setString(1, "First" + i);
                ps.setString(2, "Last" + i);
                ps.setInt(3, r.nextInt(6, 12));
                ps.setInt(4, r.nextInt(13, 22));
                ps.setInt(5, r.nextInt(6, 12));
                ps.setInt(6, r.nextInt(13, 22));
                ps.setInt(7, r.nextInt(6, 12));
                ps.setInt(8, r.nextInt(13, 22));
                ps.setInt(9, r.nextInt(6, 12));
                ps.setInt(10, r.nextInt(13, 22));
                ps.setInt(11, r.nextInt(6, 12));
                ps.setInt(12, r.nextInt(13, 22));
                ps.setInt(13, r.nextInt(6, 12));
                ps.setInt(14, r.nextInt(13, 22));
                ps.setInt(15, r.nextInt(6, 12));
                ps.setInt(16, r.nextInt(13, 22));
                ps.execute();
            }
        } catch (SQLException ex) {
            ex.printStackTrace(System.err);
        }
    }

    private static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, "", "");
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new WorkerTest()::display);
    }
}


问:
How can I match common rows?
I have a table like this:

```<code>// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+
</code>```

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

```<code>| Peter  |
| Martin |
</code>```

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

答:
Try this: </p>

```<code>SELECT friend
FROM friends
WHERE user_id IN (1, 3)
GROUP BY friend HAVING COUNT(DISTINCT friend) = 2;
</code>```

Title: How can I match common rows?

Body:
I have a table like this:

// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

| Peter  |
| Martin |

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

Body:
Try this:

SELECT friend
FROM friends
WHERE user_id IN (1, 3)
GROUP BY friend HAVING COUNT(DISTINCT friend) = 2;


问:
android: I used dlib to get facial landlandmarks in real-time, Want help in increasing speed when face landmarks detection
After face detected, it takes 100ms to get facial landmarks. FPS is about 6，full_object_detection shape = sp(img, det); this codes costs 100ms, how can I increase speed in face landmarkes detection?

答:
Even I had the same problem initially.

I suggest you do 2 things :

Resize the frame for detection task(ex: 1280*960 frame to 320*240 resolution)
You can make use of opencv method :

#define FACE_DOWNSAMPLE_RATIO 4

cv::resize(image, image_small, cv::Size(), 1.0/FACE_DOWNSAMPLE_RATIO, 1.0/FACE_DOWNSAMPLE_RATIO);

Skip the frames in detection process :

#define SKIP_FRAMES 4

static int counts=0;

if ( counts % SKIP_FRAMES == 0 ) {

faces = detector(cimg_small);

}

cimg_small is image of dlib type:(pixel_traits: bgr_pixel)

Refer this link : Here. If you do these two process in your native method you will get 13-17 fps. If you still want to raise the rate of FPS/detection should be faster you can do detection in specific ROI like MSQRD App. Further, if there are any other techniques please do suggest. It will help me too. Thank you. Good luck.


问:
Best way to handle false unused imports in intellij
Intellij falsely marked some import of Scala implicits as not being use.
Is there a way to prevent it from deleting those import when optimized them explicitly for a specific import and not prevent optimized import for the entire project ? </p>

答:
I'm afraid there isn't, I had similar issues especially when using akka and importing the implicit execution context from an ActorSystem in some cases. I recommend defining the value instead of importing. One such example would be:

// Avoid importing the execution context like this
class MyActor extends Actor {
  import context.system.dispatcher
}

// Define it explicitly instead
class MyActor extends Actor {
  implicit val ec = context.system.dispatcher
}
```

I hope this helps you.

Body:
I'm afraid there isn't, I had similar issues especially when using akka and importing the implicit execution context from an ActorSystem in some cases. I recommend defining the value instead of importing. One such example would be:

// Avoid importing the execution context like this
class MyActor extends Actor {
  import context.system.dispatcher
}

// Define it explicitly instead
class MyActor extends Actor {
  implicit val ec = context.system.dispatcher
}

I hope this helps you.


问:
Select Date from Calendar in Android Espresso
I am testing an Android app with Espresso.  I have an EditText widget with androidInputType=date.  When I touch this control with my finger, a calendar pops up for me to select the date.

How do I automate this in Espresso?  I've looked all over the place and I can't figure it out.  typeText() certainly does not work.

答:
Original answered by me here, but in the scope of another question: Recording an Espresso test with a DatePicker - so I repost my adapted answer from there:

Use this line to set the date in a datepicker:

```<code>onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
</code>```

This uses the PickerActions which is part of the espresso support library - the espresso-contrib. To use it, add it like this to your gradle file (You need several excludes to prevent compile errors due to mismatching support library version):

```<code>androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude module: 'support-annotations'
    exclude module: 'support-v4'
    exclude module: 'support-v13'
    exclude module: 'recyclerview-v7'
    exclude module: 'appcompat-v7'
}
</code>```

Then you could create a helper method which clicks the view that opens the datepicker, sets the date and confirms it by clicking the ok button:

```<code>public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
    onView(withParent(withId(buttonContainer)), withId(datePickerLaunchViewId)).perform(click());
    onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
    onView(withId(android.R.id.button1)).perform(click());
}
</code>```

And then use it like this in your tests:

```<code>TestHelper.setDate(R.id.date_button, 2017, 1, 1);
//TestHelper is my helper class that contains the helper method above
</code>```

Body:
Original answered by me here, but in the scope of another question: Recording an Espresso test with a DatePicker - so I repost my adapted answer from there:

Use this line to set the date in a datepicker:

onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));

This uses the PickerActions which is part of the espresso support library - the espresso-contrib. To use it, add it like this to your gradle file (You need several excludes to prevent compile errors due to mismatching support library version):

androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude module: 'support-annotations'
    exclude module: 'support-v4'
    exclude module: 'support-v13'
    exclude module: 'recyclerview-v7'
    exclude module: 'appcompat-v7'
}

Then you could create a helper method which clicks the view that opens the datepicker, sets the date and confirms it by clicking the ok button:

public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
    onView(withParent(withId(buttonContainer)), withId(datePickerLaunchViewId)).perform(click());
    onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
    onView(withId(android.R.id.button1)).perform(click());
}

And then use it like this in your tests:

TestHelper.setDate(R.id.date_button, 2017, 1, 1);
//TestHelper is my helper class that contains the helper method above


问:
How can I transload data between two delphi applications over internet?
Hi
let me make my question clear. Two people using my app are connected to the internet. Both have each other's IP and they want to chat (like Y!messanger) with each other.
I think I need to use Indy components; right? Which component should I use?
Thanks in advance</p>

答:
Similar to what Scott said, I think that your biggest problem is getting them talking to each other. My computers at home go through a router, which blocks all incoming connection requests (i.e. requests to start a conversation between two computers) from the Internet. My computers can send connection requests OUT, and start a conversation that way, but unless you modify the router (port forwarding) my computers can not receive connection requests.

You need a server somewhere to which both people will connect, that can then relay messages back and forth. To get really tricky, once the connection is made to the server the two computers can then be put into direct contact, but that involves UDP packets and some clever magic.


问:
Docker-machine resource limit
I made docker-machine like below

docker-machine create --driver virtualbox --virtualbox-cpu-count 2
  --virtualbox-memory 2048 default

As I known, docker container is on this docker-machine host.
I made some container on this docker-machine host, and somehow seems docker container use more resource than setting resource on docker-machine (actullay cpu).

Is this possible? If so, What is actually do 'virtualbox-memory' and 'cpu-count'?

Here is 'docker stats' output. Why is cpu usage more than 100%?

答:
In the docker stats every container gets 100% added to the CPU% column for every core allocated.

It means couple of things:

the percentage per line might be more than 100%

the total sum of percentages can be more than number of cores in the server

Title: Docker-machine resource limit