问:
Unit Testing issue with Moq and Include (EF6)
I have done fair bit research and tried all sorts of different ways of getting the Test to pass but now i need some help.

I am trying to test the following repository method:

```<code>public class PortalsRepository : BaseRepository<PortalDomainRole>, IPortalsRepository
{
    public PortalsRepository(IAuthDbContext context) : base(context)
    {

    }

    public IEnumerable<PortalRole> GetRoles(string domainName)
    {
        return Set.Include(x => x.PortalDomain)
            .Include(x => x.PortalRole)
            .Where(x => x.PortalDomain.Name.ToLower() == domainName)
            .Select(x => x.PortalRole)
            .ToList();
    }
}
</code>```

The Context looks like:

```<code>public interface IAuthDbContext : IDbContextBase
{

}

public interface IDbContextBase
{
    IDbSet<T> Set<T>() where T : class;
    IEnumerable<DbValidationError> GetEntityValidationErrors();
    int SaveChanges();
    Task<int> SaveChangesAsync();
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
</code>```

My Unit Test Set-up Looks like:

```<code>    protected override void GivenThat()
    {
        var mockRolesSet = GetMockDbSet(PortalRoles().AsQueryable());
        mockRolesSet.Setup(x => x.Include("PortalRole")).Returns(mockRolesSet.Object);

        var mockDomainsSet = GetMockDbSet(PortalDomains().AsQueryable());
        mockDomainsSet.Setup(x => x.Include("PortalDomain")).Returns(mockDomainsSet.Object);

        var mockPortalDomanRolesSet = GetMockDbSet(PortalDomainRoles().AsQueryable());

        mockPortalDomanRolesSet.Setup(x => x.Include("PortalRole")).Returns(mockPortalDomanRolesSet.Object);
        mockPortalDomanRolesSet.Setup(x => x.Include("PortalDomain")).Returns(mockPortalDomanRolesSet.Object);

        var customDbContextMock = new Mock<IAuthDbContext>();
        customDbContextMock.Setup(x => x.Set<PortalRole>()).Returns(mockRolesSet.Object);
        customDbContextMock.Setup(x => x.Set<PortalDomain>()).Returns(mockDomainsSet.Object);
        customDbContextMock.Setup(x => x.Set<PortalDomainRole>()).Returns(mockPortalDomanRolesSet.Object);

        ClassUnderTest = new PortalsRepository(customDbContextMock.Object);
    }
</code>```

My Unit Test Supporting Methods:

```<code>public List<PortalDomainRole> PortalDomainRoles()
        {
            var data = new List<PortalDomainRole>
            {
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 1},
                new PortalDomainRole { PortalRoleId = 1, PortalDomainId = 2},
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 2}
            };
            return data;
        }

    public List<PortalDomain> PortalDomains()
    {
        var data = new List<PortalDomain>
        {
            new PortalDomain { Name = "google.co.uk", PortalDomainId = 1 },
            new PortalDomain { Name = "bbc.com", PortalDomainId = 2 }
        };
        return data;
    }

    public List<PortalRole> PortalRoles()
    {
        var data = new List<PortalRole>
        {
            new PortalRole {Name = "New Products", PortalRoleId = 1},
            new PortalRole {Name = "Classic Products", PortalRoleId = 2}
        };
        return data;
    }
</code>```

When the unit test executes the method in question, i get:

System.NullReferenceException : Object reference not set to an instance of an object.

Most likely it does not know how to handle the nested include statements - i have followed many online questions and tutorials and now i am stuck.

答:
My answer is probably a bit controversial, but in my experience, the best way to test your repository layer (or whatever you call the code that does the actual data access), is by having it actually call the database during testing.

When you are writing your unit test, you are assuming that Entity Framework works in a specific way. But sometimes it works in different ways than you expect, and thus a test may pass, even though the code doesn't work correctly.

Take this example, that illustrates the problem (the last EF version I worked with was version 4, but I assume that my statement is still true for EF6)

```<code>public class Foo {
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public bool Active {
        get { return StartDate < DateTime.Now && EndDate > DateTime.Now }
    }
}

public class FooRepository {
    public IEnumerable<Foo> ActiveFoos { get { return DataContext.Foos.Where(x => x.Active) } }
}
</code>```

Testing this FooRepository against a mocked data access will pass, but executing against a real database will throw an exception. That is because EF will try to create an SQL clause for the Where(x => x.Active), but because Active is not a field in the database, EF will have no idea how to translate the query to SQL.

So your unit test provides a false positive. Executing the tests against the database will make it fail, as it should.

Body:
I have done fair bit research and tried all sorts of different ways of getting the Test to pass but now i need some help.

I am trying to test the following repository method:

public class PortalsRepository : BaseRepository<PortalDomainRole>, IPortalsRepository
{
    public PortalsRepository(IAuthDbContext context) : base(context)
    {

    }

    public IEnumerable<PortalRole> GetRoles(string domainName)
    {
        return Set.Include(x => x.PortalDomain)
            .Include(x => x.PortalRole)
            .Where(x => x.PortalDomain.Name.ToLower() == domainName)
            .Select(x => x.PortalRole)
            .ToList();
    }
}

The Context looks like:

public interface IAuthDbContext : IDbContextBase
{

}

public interface IDbContextBase
{
    IDbSet<T> Set<T>() where T : class;
    IEnumerable<DbValidationError> GetEntityValidationErrors();
    int SaveChanges();
    Task<int> SaveChangesAsync();
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}

My Unit Test Set-up Looks like:

    protected override void GivenThat()
    {
        var mockRolesSet = GetMockDbSet(PortalRoles().AsQueryable());
        mockRolesSet.Setup(x => x.Include("PortalRole")).Returns(mockRolesSet.Object);

        var mockDomainsSet = GetMockDbSet(PortalDomains().AsQueryable());
        mockDomainsSet.Setup(x => x.Include("PortalDomain")).Returns(mockDomainsSet.Object);

        var mockPortalDomanRolesSet = GetMockDbSet(PortalDomainRoles().AsQueryable());

        mockPortalDomanRolesSet.Setup(x => x.Include("PortalRole")).Returns(mockPortalDomanRolesSet.Object);
        mockPortalDomanRolesSet.Setup(x => x.Include("PortalDomain")).Returns(mockPortalDomanRolesSet.Object);

        var customDbContextMock = new Mock<IAuthDbContext>();
        customDbContextMock.Setup(x => x.Set<PortalRole>()).Returns(mockRolesSet.Object);
        customDbContextMock.Setup(x => x.Set<PortalDomain>()).Returns(mockDomainsSet.Object);
        customDbContextMock.Setup(x => x.Set<PortalDomainRole>()).Returns(mockPortalDomanRolesSet.Object);

        ClassUnderTest = new PortalsRepository(customDbContextMock.Object);
    }

My Unit Test Supporting Methods:

public List<PortalDomainRole> PortalDomainRoles()
        {
            var data = new List<PortalDomainRole>
            {
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 1},
                new PortalDomainRole { PortalRoleId = 1, PortalDomainId = 2},
                new PortalDomainRole { PortalRoleId = 2, PortalDomainId = 2}
            };
            return data;
        }

    public List<PortalDomain> PortalDomains()
    {
        var data = new List<PortalDomain>
        {
            new PortalDomain { Name = "google.co.uk", PortalDomainId = 1 },
            new PortalDomain { Name = "bbc.com", PortalDomainId = 2 }
        };
        return data;
    }

    public List<PortalRole> PortalRoles()
    {
        var data = new List<PortalRole>
        {
            new PortalRole {Name = "New Products", PortalRoleId = 1},
            new PortalRole {Name = "Classic Products", PortalRoleId = 2}
        };
        return data;
    }

When the unit test executes the method in question, i get:

System.NullReferenceException : Object reference not set to an instance of an object.

Most likely it does not know how to handle the nested include statements - i have followed many online questions and tutorials and now i am stuck.

Body:
My answer is probably a bit controversial, but in my experience, the best way to test your repository layer (or whatever you call the code that does the actual data access), is by having it actually call the database during testing.

When you are writing your unit test, you are assuming that Entity Framework works in a specific way. But sometimes it works in different ways than you expect, and thus a test may pass, even though the code doesn't work correctly.

Take this example, that illustrates the problem (the last EF version I worked with was version 4, but I assume that my statement is still true for EF6)

public class Foo {
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public bool Active {
        get { return StartDate < DateTime.Now && EndDate > DateTime.Now }
    }
}

public class FooRepository {
    public IEnumerable<Foo> ActiveFoos { get { return DataContext.Foos.Where(x => x.Active) } }
}

Testing this FooRepository against a mocked data access will pass, but executing against a real database will throw an exception. That is because EF will try to create an SQL clause for the Where(x => x.Active), but because Active is not a field in the database, EF will have no idea how to translate the query to SQL.

So your unit test provides a false positive. Executing the tests against the database will make it fail, as it should.


来源: stackexchange

问:
Publishing a C# console application as an Azure web job
I've got a console application, with logging, scheduling, etc., running on a VM. It works with Entity Framework, Azure SQL Server, Azure blob storage and a bunch of external APIs.

I'd like to turn it into a service.

I understand that this can be done with worker roles, but looking at various tutorials for worker roles, it seems like it would be a ton of work to rewrite the whole thing.

If I just publish it as a web job, will this be secure, assuming I don't have any exposed endpoints? I need to make sure that nobody outside our active directory can access it.

Is there a way that I can create a dummy app service which will have no endpoints and publish it there?

答:
If I just publish it as a web job, will this be secure, assuming I don't have any exposed endpoints? I need to make sure that nobody outside our active directory can access it.

As Peter Bons said, if it does not expose an API or endpoint, nobody can access it.

Is there a way that I can create a dummy app service which will have no endpoints and publish it there?

Normally we run WebJobs in a Azure App Service web app, and that Azure App Service web app can be accessed/browsed via URL. If you want to prevent users from browsing to that Azure App Service web app, you can add a rewrite rule to site’s web.config to block web access.

```<code><rule name="Block unauthorized traffic to staging sites" stopProcessing="true">
<match url=".*" />
<conditions>
<!-- Enter your site host name here as the pattern-->
<add input="{HTTP_HOST}" pattern="^sitehostname\." />
<!-- Enter your white listed IP addresses -->
<add input="{REMOTE_ADDR}" pattern="123\.123\.123\.1" negate="true"/>
<!-- Add the white listed IP addresses with a new condition as seen below -->
<!-- <add input="{REMOTE_ADDR}" pattern="123\.123\.123\.2" negate="true"/> -->
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden"
statusDescription="Site is not accessible" />
</rule>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I just publish it as a web job, will this be secure, assuming I don't have any exposed endpoints? I need to make sure that nobody outside our active directory can access it.

As Peter Bons said, if it does not expose an API or endpoint, nobody can access it.

Is there a way that I can create a dummy app service which will have no endpoints and publish it there?

Normally we run WebJobs in a Azure App Service web app, and that Azure App Service web app can be accessed/browsed via URL. If you want to prevent users from browsing to that Azure App Service web app, you can add a rewrite rule to site’s web.config to block web access.

<rule name="Block unauthorized traffic to staging sites" stopProcessing="true">
<match url=".*" />
<conditions>
<!-- Enter your site host name here as the pattern-->
<add input="{HTTP_HOST}" pattern="^sitehostname\." />
<!-- Enter your white listed IP addresses -->
<add input="{REMOTE_ADDR}" pattern="123\.123\.123\.1" negate="true"/>
<!-- Add the white listed IP addresses with a new condition as seen below -->
<!-- <add input="{REMOTE_ADDR}" pattern="123\.123\.123\.2" negate="true"/> -->
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden"
statusDescription="Site is not accessible" />
</rule>


问:
How to output html files from pug templates with webpack?
I'm trying to output individual html files from pug templates in my webpack project. The problem I'm having is in getting pug-loader to render html into the files.

My webpack.config:

```<code>const path = require('path');
const glob = require('glob');
const webpack = require('webpack');

const src = path.resolve(__dirname, 'src');
const dist = path.resolve(__dirname, 'dist');

module.exports = {
  context: src,

  entry: {
    pug: glob.sync('./**/*.pug', {
      cwd: src
    }),
    index: path.resolve(src, 'index.js')
  },

  output: {
    path: dist,
    filename: '[name].js'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015'].map(dep =>
              require.resolve(`babel-preset-${dep}`)
            ) // Fix for lerna symlinked deps
          }
        }
      },
      {
        test: /\.pug$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].html'
            }
          },
          'extract-loader',
          'html-loader',
          'apply-loader',
          'pug-loader'
        ]
      }
    ]
  }
};
</code>```

This correctly generates files for each pug template in my project, but the files do not contain html. Rather, each file looks something like:

```<code>var req = require("!!<absolute-path-to-project>/node_modules/pug-loader/index.js!<absolute-path-to-pug-file>/index.pug");
module.exports = (req['default'] || req).apply(req, [])
</code>```

My installed dependency versions:

```<code>{
  "apply-loader": "^2.0.0",
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.0",
  "babel-preset-es2015": "^6.24.1",
  "extract-loader": "^0.1.0",
  "file-loader": "^0.11.1",
  "glob": "^7.1.2",
  "html-loader": "^0.4.5",
  "pug-loader": "^2.3.0",
  "webpack": "^3.0.0"
}
</code>```

答:
Try to use pug-html-loader instead of pug-loader.

Here an example:

```<code>{
    test: /\.pug$/,
    use: [
      "file-loader?name=[path][name].html",
      "extract-loader",
      "html-loader",
      "pug-html-loader"
    ]
  }
</code>```

Body:
I'm trying to output individual html files from pug templates in my webpack project. The problem I'm having is in getting pug-loader to render html into the files.

My webpack.config:

const path = require('path');
const glob = require('glob');
const webpack = require('webpack');

const src = path.resolve(__dirname, 'src');
const dist = path.resolve(__dirname, 'dist');

module.exports = {
  context: src,

  entry: {
    pug: glob.sync('./**/*.pug', {
      cwd: src
    }),
    index: path.resolve(src, 'index.js')
  },

  output: {
    path: dist,
    filename: '[name].js'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015'].map(dep =>
              require.resolve(`babel-preset-${dep}`)
            ) // Fix for lerna symlinked deps
          }
        }
      },
      {
        test: /\.pug$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].html'
            }
          },
          'extract-loader',
          'html-loader',
          'apply-loader',
          'pug-loader'
        ]
      }
    ]
  }
};

This correctly generates files for each pug template in my project, but the files do not contain html. Rather, each file looks something like:

var req = require("!!<absolute-path-to-project>/node_modules/pug-loader/index.js!<absolute-path-to-pug-file>/index.pug");
module.exports = (req['default'] || req).apply(req, [])

My installed dependency versions:

{
  "apply-loader": "^2.0.0",
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.0",
  "babel-preset-es2015": "^6.24.1",
  "extract-loader": "^0.1.0",
  "file-loader": "^0.11.1",
  "glob": "^7.1.2",
  "html-loader": "^0.4.5",
  "pug-loader": "^2.3.0",
  "webpack": "^3.0.0"
}

Body:
Try to use pug-html-loader instead of pug-loader.

Here an example:

{
    test: /\.pug$/,
    use: [
      "file-loader?name=[path][name].html",
      "extract-loader",
      "html-loader",
      "pug-html-loader"
    ]
  }


问:
A checked checkbox is not displaying checked? Laravel
i have a problem where a checked checkbox is not displaying checked.

My view:

```<code>@if(in_array($searchgroup->id.','.$searchtag->id, session()->get('zoektermen')))
    {{ Form::checkbox($searchtag->naam,$searchgroup->id. ',' .$searchtag->id, true, ['class' => 'search-checkbox']) }} {{ $searchtag->naam }}
@else
    {{ Form::checkbox($searchtag->naam,$searchgroup->id. ',' .$searchtag->id, null,['class' => 'search-checkbox']) }} {{ $searchtag->naam }}
@endif
</code>```

I'm using laravel collective.

I'm using this code on other places on the website in different scenario's, where this works perfectly and the checkboxes display checked.

I'm using firefox but i also tried safari, no difference.

Any help is appreciated..

答:
If you have included "uniform.default.js" in your project, it can create such an issue. Please use the following code to resolve it.

```<code>$('#checkbox').prop('checked',true).uniform('refresh');
</code>```

Further reading: jQuery Uniform Checkbox does not (un)check

Thanks.

Body:
i have a problem where a checked checkbox is not displaying checked.

My view:

@if(in_array($searchgroup->id.','.$searchtag->id, session()->get('zoektermen')))
    {{ Form::checkbox($searchtag->naam,$searchgroup->id. ',' .$searchtag->id, true, ['class' => 'search-checkbox']) }} {{ $searchtag->naam }}
@else
    {{ Form::checkbox($searchtag->naam,$searchgroup->id. ',' .$searchtag->id, null,['class' => 'search-checkbox']) }} {{ $searchtag->naam }}
@endif

I'm using laravel collective.

I'm using this code on other places on the website in different scenario's, where this works perfectly and the checkboxes display checked.

I'm using firefox but i also tried safari, no difference.

Any help is appreciated..

Body:
If you have included "uniform.default.js" in your project, it can create such an issue. Please use the following code to resolve it.

$('#checkbox').prop('checked',true).uniform('refresh');

Further reading: jQuery Uniform Checkbox does not (un)check

Thanks.


问:
How to create modules in C
I have an interface with which I want to be able to statically link modules. For example, I want to be able to call all functions (albeit in seperate files) called FOO or that match a certain prototype, ultimately make a call into a function in the file without a header in the other files. Dont say that it is impossible since I found a hack that can do it, but I want a non hacked method. (The hack is to use nm to get functions and their prototypes then I can dynamically call the function). Also, I know you can do this with dynamic linking, however, I want to statically link the files. Any ideas?</p>

答:
I really don't think you can do it. C isn't exactly capable of late-binding or the sort of introspection you seem to be requiring.

Although I don't really understand your question. Do you want the features of dynamically linked libraries while statically linking? Because that doesn't make sense to me... to static link, you need to already have the binary in hand, which would make dynamic loading of functions a waste of time, even if you could easily do it.

ContentLicense: CC BY-SA 2.5

Title: How to create modules in C


问:
text with input in one row
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:50%;height:100%;float: left;padding-left:20%">
            <form style="text-align:center;">
                <b>dfsdfsdfsdf</b>
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>
        </div></code>```

But text is over input.

I need to make text in one row with input.
How I can do this?

答:
Wrap the input tag inside a div.
Use label tag instead of b tag  (it helps screen readers)
then give css "float:left" for the label and div(wrapping the input)

atlast remove the margin from your input and giv some margin-top for the label
and after float, clear it

```<code><div style="width:50%;height:100%;float: left;padding-left:20%">
    <form style="text-align:center;">
        <label style="float:left; margin-top:6px">dfsdfsdfsdf</label>
        <div style="float:left">
            <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="border-radius:50px;border-width: 1px;">
        </div>
        <div style="clear:left">
    </form>
</div>
</code>```

Title: text with input in one row

Body:
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

            <form style="text-align:center;">
                dfsdfsdfsdf
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>

But text is over input.

I need to make text in one row with input.
How I can do this?

Body:
Wrap the input tag inside a div.
Use label tag instead of b tag  (it helps screen readers)
then give css "float:left" for the label and div(wrapping the input)

atlast remove the margin from your input and giv some margin-top for the label
and after float, clear it

<div style="width:50%;height:100%;float: left;padding-left:20%">
    <form style="text-align:center;">
        <label style="float:left; margin-top:6px">dfsdfsdfsdf</label>
        <div style="float:left">
            <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="border-radius:50px;border-width: 1px;">
        </div>
        <div style="clear:left">
    </form>
</div>


问:
Random number generation in R with multiple conditions
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

```<code>Defect Table :

Length

6355
6236
1345
3123
</code>```

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

```<code> DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length
</code>```

Final data should something like this(values could be different as long as it satisfies above conditions)

```<code> Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120
</code>```

答:
Psuedocode:</p>

```<code>i for (1 to length(df){
  df[i,DefectStarts]=sample(df[i,Length],1,T)
  df[i,DefectEnds]=sample(df[i,Length]-df[i,DefectStarts],1,T)
}
</code>```

Body:
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

Defect Table :

Length

6355
6236
1345
3123

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

 DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length

Final data should something like this(values could be different as long as it satisfies above conditions)

 Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120

Body:
Psuedocode:

i for (1 to length(df){
  df[i,DefectStarts]=sample(df[i,Length],1,T)
  df[i,DefectEnds]=sample(df[i,Length]-df[i,DefectStarts],1,T)
}


问:
replace json result with form in ajax mvc
my view is the same as this

```<code>  <div class="col-sm-3 ">
     @{Html.RenderAction("Subscribe", "Home");}
  </div>
</code>```

on other hand my action is

```<code>public ActionResult Subscribe()
    {
        return PartialView("_Subscribe");
    }

    [HttpPost]
    public ActionResult Subscribe(Subscribe subscribe)
    {
        if (ModelState.IsValid)
        {
            subscribe.Active = false;
            subscribe.IpAddress = Request.UserHostName;
            Guid gui = Guid.NewGuid();
            subscribe.ActiveCode = gui;
            subscribe.SubmitDate = DateTime.Now;
            //_db.SaveChanges();
            return Json("subscribe is complate, please check your email", JsonRequestBehavior.AllowGet);

        }
        return Json("error", JsonRequestBehavior.AllowGet);

    }
</code>```

in partialview is

```<code>@model Jar.Models.Subscribe
            <div Id="subForm" class="single-widget">
                @using (Html.BeginForm()) {
                @Html.TextBoxFor(x => x.Email, new { htmlAttributes = new {
                @class = "form-control", @placeholder = "email" } })

            <button type = "submit" id = "btn_Subscribe" class="btn btn-default"><i class="fa fa-arrow-circle-o-left"></i></button>
}
</code>```

and in ajax

```<code>$(document).ready(function() {

$("#btn_Subscribe").click(function() {

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Subscribe")',
        dataType: 'json',
        data: { Email: $("#Email").val() },
        success: function(data) {
            alert(data);
        }
    });
});
</code>```

});

ok i want when click on subscribe button email send to database and return json and replace json with all subscribe form(textbox and button ),
now when i click on subscribe, email registered, but return to new page with simple text  "subscribe is complate, please check your email"
how can i change this code to replace subscribe form with json text ?

答:
Firstly I'd suggest hooking your event to the submit method of the form element.

Secondly you should change your response type to an object so that it can be encoded to JSON more effectively, and the response is more consistent:

```<code>[HttpPost]
public ActionResult Subscribe(Subscribe subscribe)
{
    if (ModelState.IsValid)
    {
        // your code...
        return Json(new { Message = "subscribe is complate, please check your email" }, JsonRequestBehavior.AllowGet);
    }
    return Json(new { Message = "error" }, JsonRequestBehavior.AllowGet);
}
</code>```

Lastly, to achieve your goal you can use the text() method to see the content of the div containing the form, which will replace the content. Try this:

```<code>$("#subForm form").on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: '@Url.Action("Subscribe")',
    dataType: 'json',
    data: {
      Email: $("#Email").val()
    },
    success: function(data) {
      $('#subForm').text(data.Message); // note the use of text() here
    }
  });
});
</code>```

Body:
my view is the same as this

     @{Html.RenderAction("Subscribe", "Home");}

on other hand my action is

public ActionResult Subscribe()
    {
        return PartialView("_Subscribe");
    }

    [HttpPost]
    public ActionResult Subscribe(Subscribe subscribe)
    {
        if (ModelState.IsValid)
        {
            subscribe.Active = false;
            subscribe.IpAddress = Request.UserHostName;
            Guid gui = Guid.NewGuid();
            subscribe.ActiveCode = gui;
            subscribe.SubmitDate = DateTime.Now;
            //_db.SaveChanges();
            return Json("subscribe is complate, please check your email", JsonRequestBehavior.AllowGet);

        }
        return Json("error", JsonRequestBehavior.AllowGet);

    }

in partialview is

@model Jar.Models.Subscribe

                @using (Html.BeginForm()) {
                @Html.TextBoxFor(x => x.Email, new { htmlAttributes = new {
                @class = "form-control", @placeholder = "email" } })

            <button type = "submit" id = "btn_Subscribe" class="btn btn-default"></button>
}

and in ajax

$(document).ready(function() {

$("#btn_Subscribe").click(function() {

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Subscribe")',
        dataType: 'json',
        data: { Email: $("#Email").val() },
        success: function(data) {
            alert(data);
        }
    });
});

});

ok i want when click on subscribe button email send to database and return json and replace json with all subscribe form(textbox and button ),
now when i click on subscribe, email registered, but return to new page with simple text  "subscribe is complate, please check your email"
how can i change this code to replace subscribe form with json text ?

Body:
Firstly I'd suggest hooking your event to the submit method of the form element.

Secondly you should change your response type to an object so that it can be encoded to JSON more effectively, and the response is more consistent:

[HttpPost]
public ActionResult Subscribe(Subscribe subscribe)
{
    if (ModelState.IsValid)
    {
        // your code...
        return Json(new { Message = "subscribe is complate, please check your email" }, JsonRequestBehavior.AllowGet);
    }
    return Json(new { Message = "error" }, JsonRequestBehavior.AllowGet);
}

Lastly, to achieve your goal you can use the text() method to see the content of the div containing the form, which will replace the content. Try this:

$("#subForm form").on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: '@Url.Action("Subscribe")',
    dataType: 'json',
    data: {
      Email: $("#Email").val()
    },
    success: function(data) {
      $('#subForm').text(data.Message); // note the use of text() here
    }
  });
});


问:
Javascript sending data via POST in firefox addon
I have a mysql database, with a php form.  Normally, people use the php form on my website to add to the mysql database.  I have been building a firefox addon to let them use the form without visiting the site directly to add data to the mysql database.  Now I am stuck...

I have the form data I want to add to the mysql database, but how can I send it to the mysql database from the addon?  What's the best way to do this?  Would you send it to the php form first or is there a direct way?  Is it possible to go straight to mysql?  The firefox addon is coded in javascript.

Thanks!

答:
Use Ajax to send data but do not use xmlHttpRequest directly in your code.

Use a popular javascript library like jquery to send data to the server.

Edit: Removed irrelevant parts about browser compatibility.


问:
How to read the source code for what `react-native run-android` is doing?
I want to see what react-native run-androidis doing under the hood. where can I read what this is doing?

答:
```<code>'use strict';

const { getProjectCommands } = require('./core');

import type { RNConfig } from './core';

export type CommandT = {
  name: string,
  description?: string,
  usage?: string,
  func: (argv: Array<string>, config: RNConfig, args: Object) => ?Promise<void>,
  options?: Array<{
    command: string,
    description?: string,
    parse?: (val: string) => any,
    default?: (config: RNConfig) => any | any,
  }>,
  examples?: Array<{
    desc: string,
    cmd: string,
  }>,
  pkg?: {
    version: string,
    name: string,
  },
};

const documentedCommands = [
  require('./server/server'),
  require('./runIOS/runIOS'),
  require('./runAndroid/runAndroid'),
  require('./library/library'),
  require('./bundle/bundle'),
  require('./bundle/unbundle'),
  require('./eject/eject'),
  require('./link/link'),
  require('./link/unlink'),
  require('./install/install'),
  require('./install/uninstall'),
  require('./upgrade/upgrade'),
  require('./logAndroid/logAndroid'),
  require('./logIOS/logIOS'),
  require('./dependencies/dependencies'),
];

// The user should never get here because projects are inited by
// using `react-native-cli` from outside a project directory.
const undocumentedCommands = [
  {
    name: 'init',
    func: () => {
      console.log([
        'Looks like React Native project already exists in the current',
        'folder. Run this command from a different folder or remove node_modules/react-native',
      ].join('\n'));
    },
  },
];

const commands: Array<CommandT> = [
  ...documentedCommands,
  ...undocumentedCommands,
  ...getProjectCommands(),
];

module.exports = commands;
</code>```

I think this is you wanted?

```<code>'use strict';

const adb = require('./adb');
const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const isPackagerRunning = require('../util/isPackagerRunning');
const isString = require('lodash/isString');
const path = require('path');
const Promise = require('promise');

// Verifies this is an Android project
function checkAndroid(root) {
  return fs.existsSync(path.join(root, 'android/gradlew'));
}

/**
 * Starts the app on a connected Android emulator or device.
 */
function runAndroid(argv, config, args) {
  if (!checkAndroid(args.root)) {
    console.log(chalk.red('Android project not found. Maybe run react-native android first?'));
    return;
  }

  if (!args.packager) {
    return buildAndRun(args);
  }

  return isPackagerRunning().then(result => {
    if (result === 'running') {
      console.log(chalk.bold('JS server already running.'));
    } else if (result === 'unrecognized') {
      console.warn(chalk.yellow('JS server not recognized, continuing with build...'));
    } else {
      // result == 'not_running'
      console.log(chalk.bold('Starting JS server...'));
      startServerInNewWindow();
    }
    return buildAndRun(args);
  });
}

function getAdbPath() {
  return process.env.ANDROID_HOME
    ? process.env.ANDROID_HOME + '/platform-tools/adb'
    : 'adb';
}

// Runs ADB reverse tcp:8081 tcp:8081 to allow loading the jsbundle from the packager
function tryRunAdbReverse(device) {
  try {
    const adbPath = getAdbPath();
    const adbArgs = ['reverse', 'tcp:8081', 'tcp:8081'];

    // If a device is specified then tell adb to use it
    if (device) {
      adbArgs.unshift('-s', device);
    }

    console.log(chalk.bold(
      `Running ${adbPath} ${adbArgs.join(' ')}`
    ));

    child_process.execFileSync(adbPath, adbArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.yellow(`Could not run adb reverse: ${e.message}`));
  }
}

// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args) {
  process.chdir(path.join(args.root, 'android'));
  const cmd = process.platform.startsWith('win')
    ? 'gradlew.bat'
    : './gradlew';

  const packageName = fs.readFileSync(
      `${args.appFolder}/src/main/AndroidManifest.xml`,
      'utf8'
    ).match(/package="(.+?)"/)[1];

  const packageNameWithSuffix = args.appIdSuffix ? packageName + '.' + args.appIdSuffix : packageName;

  const adbPath = getAdbPath();
  if (args.deviceId) {
    if (isString(args.deviceId)) {
        runOnSpecificDevice(args, cmd, packageNameWithSuffix, packageName, adbPath);
    } else {
      console.log(chalk.red('Argument missing for parameter --deviceId'));
    }
  } else {
    runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath);
  }
}

function runOnSpecificDevice(args, gradlew, packageNameWithSuffix, packageName, adbPath) {
  let devices = adb.getDevices();
  if (devices && devices.length > 0) {
    if (devices.indexOf(args.deviceId) !== -1) {
      buildApk(gradlew);
      installAndLaunchOnDevice(args, args.deviceId, packageNameWithSuffix, packageName, adbPath);
    } else {
      console.log('Could not find device with the id: "' + args.deviceId + '".');
      console.log('Choose one of the following:');
      console.log(devices);
    }
  } else {
    console.log('No Android devices connected.');
  }
}

function buildApk(gradlew) {
  try {
    console.log(chalk.bold('Building the app...'));

    // using '-x lint' in order to ignore linting errors while building the apk
    child_process.execFileSync(gradlew, ['build', '-x', 'lint'], {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red('Could not build the app, read the error above for details.\n'));
  }
}

function tryInstallAppOnDevice(args, device) {
  try {
    const pathToApk = `${args.appFolder}/build/outputs/apk/${args.appFolder}-debug.apk`;
    const adbPath = getAdbPath();
    const adbArgs = ['-s', device, 'install', pathToApk];
    console.log(chalk.bold(
      `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`
    ));
    child_process.execFileSync(adbPath, adbArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(e.message);
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n'
    ));
  }
}

function tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, mainActivity) {
  try {
    const adbArgs = ['-s', device, 'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.' + mainActivity];
    console.log(chalk.bold(
      `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`
    ));
    child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
  } catch (e) {
    console.log(chalk.red(
      'adb invocation failed. Do you have adb in your PATH?'
    ));
  }
}

function installAndLaunchOnDevice(args, selectedDevice, packageNameWithSuffix, packageName, adbPath) {
  tryRunAdbReverse(selectedDevice);
  tryInstallAppOnDevice(args, selectedDevice);
  tryLaunchAppOnDevice(selectedDevice, packageNameWithSuffix, packageName, adbPath, args.mainActivity);
}

function runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath){
  try {
    const gradleArgs = [];
    if (args.variant) {
      gradleArgs.push('install' +
        args.variant[0].toUpperCase() + args.variant.slice(1)
      );
    } else if (args.flavor) {
      console.warn(chalk.yellow(
        '--flavor has been deprecated. Use --variant instead'
      ));
      gradleArgs.push('install' +
        args.flavor[0].toUpperCase() + args.flavor.slice(1)
      );
    } else {
      gradleArgs.push('installDebug');
    }

    if (args.installDebug) {
      gradleArgs.push(args.installDebug);
    }

    console.log(chalk.bold(
      `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join(' ')})...`
    ));

    child_process.execFileSync(cmd, gradleArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n' +
      'Make sure you have an Android emulator running or a device connected and have\n' +
      'set up your Android development environment:\n' +
      'https://facebook.github.io/react-native/docs/android-setup.html'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    return Promise.reject();
  }
    const devices = adb.getDevices();
    if (devices && devices.length > 0) {
      devices.forEach((device) => {
        tryRunAdbReverse(device);
        tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, args.mainActivity);
      });
    } else {
      try {
        // If we cannot execute based on adb devices output, fall back to
        // shell am start
        const fallbackAdbArgs = [
          'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.MainActivity'
        ];
        console.log(chalk.bold(
          `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`
        ));
        child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'});
      } catch (e) {
        console.log(chalk.red(
          'adb invocation failed. Do you have adb in your PATH?'
        ));
        // stderr is automatically piped from the gradle process, so the user
        // should see the error already, there is no need to do
        // `console.log(e.stderr)`
        return Promise.reject();
      }
    }
}

function startServerInNewWindow() {
  const yargV = require('yargs').argv;
  const scriptFile = /^win/.test(process.platform) ?
    'launchPackager.bat' :
    'launchPackager.command';
  const packagerDir = path.resolve(__dirname, '..', '..', 'packager');
  const launchPackagerScript = path.resolve(packagerDir, scriptFile);
  const procConfig = {cwd: packagerDir};

  if (process.platform === 'darwin') {
    if (yargV.open) {
      return child_process.spawnSync('open', ['-a', yargV.open, launchPackagerScript], procConfig);
    }
    return child_process.spawnSync('open', [launchPackagerScript], procConfig);

  } else if (process.platform === 'linux') {
    procConfig.detached = true;
    if (yargV.open){
      return child_process.spawn(yargV.open,['-e', 'sh', launchPackagerScript], procConfig);
    }
    return child_process.spawn('sh', [launchPackagerScript], procConfig);

  } else if (/^win/.test(process.platform)) {
    procConfig.detached = true;
    procConfig.stdio = 'ignore';
    return child_process.spawn('cmd.exe', ['/C', launchPackagerScript], procConfig);
  } else {
    console.log(chalk.red(`Cannot start the packager. Unknown platform ${process.platform}`));
  }
}

module.exports = {
  name: 'run-android',
  description: 'builds your app and starts it on a connected Android emulator or device',
  func: runAndroid,
  options: [{
    command: '--install-debug',
  }, {
    command: '--root [string]',
    description: 'Override the root directory for the android build (which contains the android directory)',
    default: '',
  }, {
    command: '--flavor [string]',
    description: '--flavor has been deprecated. Use --variant instead',
  }, {
    command: '--variant [string]',
  }, {
    command: '--appFolder [string]',
    description: 'Specify a different application folder name for the android source.',
    default: 'app',
  }, {
    command: '--appIdSuffix [string]',
    description: 'Specify an applicationIdSuffix to launch after build.',
    default: '',
  }, {
    command: '--main-activity [string]',
    description: 'Name of the activity to start',
    default: 'MainActivity',
  }, {
    command: '--deviceId [string]',
    description: 'builds your app and starts it on a specific device/simulator with the ' +
      'given device id (listed by running "adb devices" on the command line).',
  }, {
    command: '--no-packager',
    description: 'Do not launch packager while building',
  }],
};
</code>```

They are just in the /node_modules/react-native

Body:
'use strict';

const { getProjectCommands } = require('./core');

import type { RNConfig } from './core';

export type CommandT = {
  name: string,
  description?: string,
  usage?: string,
  func: (argv: Array<string>, config: RNConfig, args: Object) => ?Promise<void>,
  options?: Array<{
    command: string,
    description?: string,
    parse?: (val: string) => any,
    default?: (config: RNConfig) => any | any,
  }>,
  examples?: Array<{
    desc: string,
    cmd: string,
  }>,
  pkg?: {
    version: string,
    name: string,
  },
};

const documentedCommands = [
  require('./server/server'),
  require('./runIOS/runIOS'),
  require('./runAndroid/runAndroid'),
  require('./library/library'),
  require('./bundle/bundle'),
  require('./bundle/unbundle'),
  require('./eject/eject'),
  require('./link/link'),
  require('./link/unlink'),
  require('./install/install'),
  require('./install/uninstall'),
  require('./upgrade/upgrade'),
  require('./logAndroid/logAndroid'),
  require('./logIOS/logIOS'),
  require('./dependencies/dependencies'),
];

// The user should never get here because projects are inited by
// using `react-native-cli` from outside a project directory.
const undocumentedCommands = [
  {
    name: 'init',
    func: () => {
      console.log([
        'Looks like React Native project already exists in the current',
        'folder. Run this command from a different folder or remove node_modules/react-native',
      ].join('\n'));
    },
  },
];

const commands: Array<CommandT> = [
  ...documentedCommands,
  ...undocumentedCommands,
  ...getProjectCommands(),
];

module.exports = commands;

I think this is you wanted?

'use strict';

const adb = require('./adb');
const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const isPackagerRunning = require('../util/isPackagerRunning');
const isString = require('lodash/isString');
const path = require('path');
const Promise = require('promise');

// Verifies this is an Android project
function checkAndroid(root) {
  return fs.existsSync(path.join(root, 'android/gradlew'));
}

/**
 * Starts the app on a connected Android emulator or device.
 */
function runAndroid(argv, config, args) {
  if (!checkAndroid(args.root)) {
    console.log(chalk.red('Android project not found. Maybe run react-native android first?'));
    return;
  }

  if (!args.packager) {
    return buildAndRun(args);
  }

  return isPackagerRunning().then(result => {
    if (result === 'running') {
      console.log(chalk.bold('JS server already running.'));
    } else if (result === 'unrecognized') {
      console.warn(chalk.yellow('JS server not recognized, continuing with build...'));
    } else {
      // result == 'not_running'
      console.log(chalk.bold('Starting JS server...'));
      startServerInNewWindow();
    }
    return buildAndRun(args);
  });
}

function getAdbPath() {
  return process.env.ANDROID_HOME
    ? process.env.ANDROID_HOME + '/platform-tools/adb'
    : 'adb';
}

// Runs ADB reverse tcp:8081 tcp:8081 to allow loading the jsbundle from the packager
function tryRunAdbReverse(device) {
  try {
    const adbPath = getAdbPath();
    const adbArgs = ['reverse', 'tcp:8081', 'tcp:8081'];

    // If a device is specified then tell adb to use it
    if (device) {
      adbArgs.unshift('-s', device);
    }

    console.log(chalk.bold(
      `Running ${adbPath} ${adbArgs.join(' ')}`
    ));

    child_process.execFileSync(adbPath, adbArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.yellow(`Could not run adb reverse: ${e.message}`));
  }
}

// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args) {
  process.chdir(path.join(args.root, 'android'));
  const cmd = process.platform.startsWith('win')
    ? 'gradlew.bat'
    : './gradlew';

  const packageName = fs.readFileSync(
      `${args.appFolder}/src/main/AndroidManifest.xml`,
      'utf8'
    ).match(/package="(.+?)"/)[1];

  const packageNameWithSuffix = args.appIdSuffix ? packageName + '.' + args.appIdSuffix : packageName;

  const adbPath = getAdbPath();
  if (args.deviceId) {
    if (isString(args.deviceId)) {
        runOnSpecificDevice(args, cmd, packageNameWithSuffix, packageName, adbPath);
    } else {
      console.log(chalk.red('Argument missing for parameter --deviceId'));
    }
  } else {
    runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath);
  }
}

function runOnSpecificDevice(args, gradlew, packageNameWithSuffix, packageName, adbPath) {
  let devices = adb.getDevices();
  if (devices && devices.length > 0) {
    if (devices.indexOf(args.deviceId) !== -1) {
      buildApk(gradlew);
      installAndLaunchOnDevice(args, args.deviceId, packageNameWithSuffix, packageName, adbPath);
    } else {
      console.log('Could not find device with the id: "' + args.deviceId + '".');
      console.log('Choose one of the following:');
      console.log(devices);
    }
  } else {
    console.log('No Android devices connected.');
  }
}

function buildApk(gradlew) {
  try {
    console.log(chalk.bold('Building the app...'));

    // using '-x lint' in order to ignore linting errors while building the apk
    child_process.execFileSync(gradlew, ['build', '-x', 'lint'], {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red('Could not build the app, read the error above for details.\n'));
  }
}

function tryInstallAppOnDevice(args, device) {
  try {
    const pathToApk = `${args.appFolder}/build/outputs/apk/${args.appFolder}-debug.apk`;
    const adbPath = getAdbPath();
    const adbArgs = ['-s', device, 'install', pathToApk];
    console.log(chalk.bold(
      `Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`
    ));
    child_process.execFileSync(adbPath, adbArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(e.message);
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n'
    ));
  }
}

function tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, mainActivity) {
  try {
    const adbArgs = ['-s', device, 'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.' + mainActivity];
    console.log(chalk.bold(
      `Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`
    ));
    child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
  } catch (e) {
    console.log(chalk.red(
      'adb invocation failed. Do you have adb in your PATH?'
    ));
  }
}

function installAndLaunchOnDevice(args, selectedDevice, packageNameWithSuffix, packageName, adbPath) {
  tryRunAdbReverse(selectedDevice);
  tryInstallAppOnDevice(args, selectedDevice);
  tryLaunchAppOnDevice(selectedDevice, packageNameWithSuffix, packageName, adbPath, args.mainActivity);
}

function runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath){
  try {
    const gradleArgs = [];
    if (args.variant) {
      gradleArgs.push('install' +
        args.variant[0].toUpperCase() + args.variant.slice(1)
      );
    } else if (args.flavor) {
      console.warn(chalk.yellow(
        '--flavor has been deprecated. Use --variant instead'
      ));
      gradleArgs.push('install' +
        args.flavor[0].toUpperCase() + args.flavor.slice(1)
      );
    } else {
      gradleArgs.push('installDebug');
    }

    if (args.installDebug) {
      gradleArgs.push(args.installDebug);
    }

    console.log(chalk.bold(
      `Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join(' ')})...`
    ));

    child_process.execFileSync(cmd, gradleArgs, {
      stdio: [process.stdin, process.stdout, process.stderr],
    });
  } catch (e) {
    console.log(chalk.red(
      'Could not install the app on the device, read the error above for details.\n' +
      'Make sure you have an Android emulator running or a device connected and have\n' +
      'set up your Android development environment:\n' +
      'https://facebook.github.io/react-native/docs/android-setup.html'
    ));
    // stderr is automatically piped from the gradle process, so the user
    // should see the error already, there is no need to do
    // `console.log(e.stderr)`
    return Promise.reject();
  }
    const devices = adb.getDevices();
    if (devices && devices.length > 0) {
      devices.forEach((device) => {
        tryRunAdbReverse(device);
        tryLaunchAppOnDevice(device, packageNameWithSuffix, packageName, adbPath, args.mainActivity);
      });
    } else {
      try {
        // If we cannot execute based on adb devices output, fall back to
        // shell am start
        const fallbackAdbArgs = [
          'shell', 'am', 'start', '-n', packageNameWithSuffix + '/' + packageName + '.MainActivity'
        ];
        console.log(chalk.bold(
          `Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`
        ));
        child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'});
      } catch (e) {
        console.log(chalk.red(
          'adb invocation failed. Do you have adb in your PATH?'
        ));
        // stderr is automatically piped from the gradle process, so the user
        // should see the error already, there is no need to do
        // `console.log(e.stderr)`
        return Promise.reject();
      }
    }
}

function startServerInNewWindow() {
  const yargV = require('yargs').argv;
  const scriptFile = /^win/.test(process.platform) ?
    'launchPackager.bat' :
    'launchPackager.command';
  const packagerDir = path.resolve(__dirname, '..', '..', 'packager');
  const launchPackagerScript = path.resolve(packagerDir, scriptFile);
  const procConfig = {cwd: packagerDir};

  if (process.platform === 'darwin') {
    if (yargV.open) {
      return child_process.spawnSync('open', ['-a', yargV.open, launchPackagerScript], procConfig);
    }
    return child_process.spawnSync('open', [launchPackagerScript], procConfig);

  } else if (process.platform === 'linux') {
    procConfig.detached = true;
    if (yargV.open){
      return child_process.spawn(yargV.open,['-e', 'sh', launchPackagerScript], procConfig);
    }
    return child_process.spawn('sh', [launchPackagerScript], procConfig);

  } else if (/^win/.test(process.platform)) {
    procConfig.detached = true;
    procConfig.stdio = 'ignore';
    return child_process.spawn('cmd.exe', ['/C', launchPackagerScript], procConfig);
  } else {
    console.log(chalk.red(`Cannot start the packager. Unknown platform ${process.platform}`));
  }
}

module.exports = {
  name: 'run-android',
  description: 'builds your app and starts it on a connected Android emulator or device',
  func: runAndroid,
  options: [{
    command: '--install-debug',
  }, {
    command: '--root [string]',
    description: 'Override the root directory for the android build (which contains the android directory)',
    default: '',
  }, {
    command: '--flavor [string]',
    description: '--flavor has been deprecated. Use --variant instead',
  }, {
    command: '--variant [string]',
  }, {
    command: '--appFolder [string]',
    description: 'Specify a different application folder name for the android source.',
    default: 'app',
  }, {
    command: '--appIdSuffix [string]',
    description: 'Specify an applicationIdSuffix to launch after build.',
    default: '',
  }, {
    command: '--main-activity [string]',
    description: 'Name of the activity to start',
    default: 'MainActivity',
  }, {
    command: '--deviceId [string]',
    description: 'builds your app and starts it on a specific device/simulator with the ' +
      'given device id (listed by running "adb devices" on the command line).',
  }, {
    command: '--no-packager',
    description: 'Do not launch packager while building',
  }],
};

They are just in the /node_modules/react-native


问:
How to send a pdf via e-mail from Java
How do I submit a pdf file to a generic e-mail from Java application?</p>

答:
You can Send E-Mail with PDF file as Attachment using reference of this -

```<code>import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

class SendMailWithAttachment
{
    public static void main(String [] args)
    {
        String to="XYZ@abc.com"; //Email address of the recipient
        final String user="ABC@XYZ.com"; //Email address of sender
        final String password="xxxxx";  //Password of the sender's email

        //Get the session object
        Properties properties = System.getProperties();

        //Here pass your smtp server url
        properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user,password);    }   });

        //Compose message
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.setSubject("Message Aleart");

            //Create MimeBodyPart object and set your message text
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setText("This is message body");

            //Create new MimeBodyPart object and set DataHandler object to this object
            MimeBodyPart messageBodyPart2 = new MimeBodyPart();
            String filename = "YourPDFFileName.pdf";//change accordingly
            DataSource source = new FileDataSource(filename);
            messageBodyPart2.setDataHandler(new DataHandler(source));
            messageBodyPart2.setFileName(filename);

            //Create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart1);
            multipart.addBodyPart(messageBodyPart2);

            //Set the multiplart object to the message object
            message.setContent(multipart );

            //Send message
            Transport.send(message);
            System.out.println("message sent....");

        }catch (MessagingException ex) {ex.printStackTrace();}
    }
}
</code>```

You can also refer to JavaTPoint

ContentLicense: CC BY-SA 4.0

Title: How to send a pdf via e-mail from Java

Body:
You can Send E-Mail with PDF file as Attachment using reference of this -

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

class SendMailWithAttachment
{
    public static void main(String [] args)
    {
        String to="XYZ@abc.com"; //Email address of the recipient
        final String user="ABC@XYZ.com"; //Email address of sender
        final String password="xxxxx";  //Password of the sender's email

        //Get the session object
        Properties properties = System.getProperties();

        //Here pass your smtp server url
        properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user,password);    }   });

        //Compose message
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.setSubject("Message Aleart");

            //Create MimeBodyPart object and set your message text
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setText("This is message body");

            //Create new MimeBodyPart object and set DataHandler object to this object
            MimeBodyPart messageBodyPart2 = new MimeBodyPart();
            String filename = "YourPDFFileName.pdf";//change accordingly
            DataSource source = new FileDataSource(filename);
            messageBodyPart2.setDataHandler(new DataHandler(source));
            messageBodyPart2.setFileName(filename);

            //Create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart1);
            multipart.addBodyPart(messageBodyPart2);

            //Set the multiplart object to the message object
            message.setContent(multipart );

            //Send message
            Transport.send(message);
            System.out.println("message sent....");

        }catch (MessagingException ex) {ex.printStackTrace();}
    }
}

You can also refer to JavaTPoint


问:
Php - check if string is not empty or has a first character not equal to
How can I check in php if the string is empty or has a first character not equal to something.
If I do this to an empty string $key = '':

```<code>if ($key != '' || $key[0] != '_')
</code>```

I get:

Uninitialized string offset: 0

答:
```<code><?php
    //$key = "";
    $something = "h";

    if (!isset($key) || substr( $key, 0, 1) !== $something || empty($key) ) {
        echo('undefined / empty string or string starts with: '.$something);;
    } else {
        echo('b');
    }
</code>```

$something is the character you want to compare with

Example: if $key is undefined or ""

Body:
How can I check in php if the string is empty or has a first character not equal to something.
If I do this to an empty string $key = '':

if ($key != '' || $key[0] != '_')

I get:

Uninitialized string offset: 0

Body:
<?php
    //$key = "";
    $something = "h";

    if (!isset($key) || substr( $key, 0, 1) !== $something || empty($key) ) {
        echo('undefined / empty string or string starts with: '.$something);;
    } else {
        echo('b');
    }

$something is the character you want to compare with

Example: if $key is undefined or ""


问:
onItemClickListener for multiple AutoCompleteTextView
I have three AutoCompleteTextView and set onItemClickListener to it,would you please help me for know which AutoCompleteTextView is clicked </p>

```<code>public class ProductMainListViewer extends AppCompatActivity implements AdapterView.OnItemClickListener {

    CustomerDataBaseAdapter customerDataBaseAdapter;
    AutoCompleteTextView txtUserName;
    AutoCompleteTextView txtContactNo;
    AutoCompleteTextView txtSearchProduct;
    TextView txtDateAndTime;
    TextView txtQty;
    TextView txtSalePrize;
    TextView txtRunit;
    TextView txtWunit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_main_list_viewer);
        customerDataBaseAdapter = new CustomerDataBaseAdapter(this);
        customerDataBaseAdapter = customerDataBaseAdapter.open();
        ArrayList<Customer> customers = new ArrayList<>();
        ArrayList<ProductsDetails> productsDetails = new ArrayList<>();

        try {
            customers = customerDataBaseAdapter.getCustomerList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            productsDetails = customerDataBaseAdapter.getProductList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        txtUserName = (AutoCompleteTextView) findViewById(R.id.editTextUserNamecheck);
        CustomArrayAdapterAutoCmplt adapter1 = new CustomArrayAdapterAutoCmplt(this, R.layout.activity_auto_cmplt_custom, customers);
        txtUserName.setThreshold(1);
        txtUserName.setAdapter(adapter1);
        txtUserName.setOnItemClickListener(this);

        txtContactNo = (AutoCompleteTextView) findViewById(R.id.editTextPhoneNoNew);
        CustomPhoneArrayAdapterAutoCmplt adapter2 = new CustomPhoneArrayAdapterAutoCmplt(this, R.layout.activity_auto_cmplt_custom, customers);
        txtContactNo.setThreshold(1);
        txtContactNo.setAdapter(adapter2);
        txtContactNo.setOnItemClickListener(this);

        txtSearchProduct = (AutoCompleteTextView) findViewById(R.id.searchProduct);
        ProductAutoCmplt adapter3 = new ProductAutoCmplt(this, R.layout.activity_auto_cmplt_custom, productsDetails);
        txtSearchProduct.setThreshold(1);
        txtSearchProduct.setAdapter(adapter3);
        txtSearchProduct.setOnItemClickListener(this);
        txtDateAndTime = (TextView) findViewById(R.id.dateAndTime);
        txtQty = (TextView) findViewById(R.id.txtQty);
        txtSalePrize = (TextView) findViewById(R.id.txtPrize);
        txtRunit = (TextView) findViewById(R.id.txtRUnit);
        txtWunit = (TextView) findViewById(R.id.txtWUnit);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if (txtUserName.getText().equals("")) {
                Customer item = (Customer) txtContactNo.getAdapter().getItem(position);
                txtUserName.setText(item.getMember_name());

            } else {
                Customer item = (Customer) txtUserName.getAdapter().getItem(position);
                txtContactNo.setText(item.getContactType());
            }

            DateFormat df = new SimpleDateFormat("dd.MM.yyyy  'at' HH:mm:ss ");
            String date = df.format(Calendar.getInstance().getTime());
            txtDateAndTime.setText(date);

        } catch (Exception e) {
        }

    }

}
</code>```

答:
using anonymous inner classes, we can do it as follows :</p>

```<code>txtUserName.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });

txtContactNo.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });

txtSearchProduct.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });
</code>```

Body:
I have three AutoCompleteTextView and set onItemClickListener to it,would you please help me for know which AutoCompleteTextView is clicked

public class ProductMainListViewer extends AppCompatActivity implements AdapterView.OnItemClickListener {

    CustomerDataBaseAdapter customerDataBaseAdapter;
    AutoCompleteTextView txtUserName;
    AutoCompleteTextView txtContactNo;
    AutoCompleteTextView txtSearchProduct;
    TextView txtDateAndTime;
    TextView txtQty;
    TextView txtSalePrize;
    TextView txtRunit;
    TextView txtWunit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_main_list_viewer);
        customerDataBaseAdapter = new CustomerDataBaseAdapter(this);
        customerDataBaseAdapter = customerDataBaseAdapter.open();
        ArrayList<Customer> customers = new ArrayList<>();
        ArrayList<ProductsDetails> productsDetails = new ArrayList<>();

        try {
            customers = customerDataBaseAdapter.getCustomerList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            productsDetails = customerDataBaseAdapter.getProductList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        txtUserName = (AutoCompleteTextView) findViewById(R.id.editTextUserNamecheck);
        CustomArrayAdapterAutoCmplt adapter1 = new CustomArrayAdapterAutoCmplt(this, R.layout.activity_auto_cmplt_custom, customers);
        txtUserName.setThreshold(1);
        txtUserName.setAdapter(adapter1);
        txtUserName.setOnItemClickListener(this);

        txtContactNo = (AutoCompleteTextView) findViewById(R.id.editTextPhoneNoNew);
        CustomPhoneArrayAdapterAutoCmplt adapter2 = new CustomPhoneArrayAdapterAutoCmplt(this, R.layout.activity_auto_cmplt_custom, customers);
        txtContactNo.setThreshold(1);
        txtContactNo.setAdapter(adapter2);
        txtContactNo.setOnItemClickListener(this);

        txtSearchProduct = (AutoCompleteTextView) findViewById(R.id.searchProduct);
        ProductAutoCmplt adapter3 = new ProductAutoCmplt(this, R.layout.activity_auto_cmplt_custom, productsDetails);
        txtSearchProduct.setThreshold(1);
        txtSearchProduct.setAdapter(adapter3);
        txtSearchProduct.setOnItemClickListener(this);
        txtDateAndTime = (TextView) findViewById(R.id.dateAndTime);
        txtQty = (TextView) findViewById(R.id.txtQty);
        txtSalePrize = (TextView) findViewById(R.id.txtPrize);
        txtRunit = (TextView) findViewById(R.id.txtRUnit);
        txtWunit = (TextView) findViewById(R.id.txtWUnit);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if (txtUserName.getText().equals("")) {
                Customer item = (Customer) txtContactNo.getAdapter().getItem(position);
                txtUserName.setText(item.getMember_name());

            } else {
                Customer item = (Customer) txtUserName.getAdapter().getItem(position);
                txtContactNo.setText(item.getContactType());
            }

            DateFormat df = new SimpleDateFormat("dd.MM.yyyy  'at' HH:mm:ss ");
            String date = df.format(Calendar.getInstance().getTime());
            txtDateAndTime.setText(date);

        } catch (Exception e) {
        }

    }

}

Body:
using anonymous inner classes, we can do it as follows :

txtUserName.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });

txtContactNo.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });

txtSearchProduct.setOnItemClickListener((new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // do your stuff;
        }
    });


问:
Correct syntax in php
I'am tryig to print an id this way

```<code><form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >
</code>```

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

答:
try this :
echo should be before the condition</p>

```<code><form action="upload.php" method="post" enctype="multipart/form-data" <?php echo isset($_REQUEST['code'])? 'id="csv-form"':'id="edit-form"'; ?> >
</code>```

Title: Correct syntax in php

Body:
I'am tryig to print an id this way

<form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

Body:
try this :
echo should be before the condition

<form action="upload.php" method="post" enctype="multipart/form-data" <?php echo isset($_REQUEST['code'])? 'id="csv-form"':'id="edit-form"'; ?> >


问:
Predicted values for new data using restricted cubic splines
I have some data that I'm modeling using restricted cubic splines. I'm using the rcs transformation function in the rms package to generate the transformed variables for a linear model. Here is an example using 5 knots.

```<code>library('rms')

my_df <- data.frame(
    y = -4 * -100:100 + -1.5 * (-100:100)**2 + 3 * (-100:100)**3 + rnorm(201, 0, 1e5),
    x = -100:100
)

mod <- lm(y ~ rcs(x, 5), data = my_df)
</code>```

After I fit the data, I'd like to find the predicted y values for a specific domain of x values. Here is what I'm doing now:

```<code>new_data <- data.frame(x = -3:3)

predict(mod, newdata = new_data)
</code>```

However, this generates a warning message:

```<code>Warning message:
In rcspline.eval(x, nk = nknots, inclx = TRUE, pc = pc, fractied = fractied) :
    5 knots requested with 7 unique values of x.  knots set to 5 interior values.
</code>```

What does this mean, and what is going on? I expected that the knot locations should already be defined in mod, so I don't understand why it seems to be trying to find new knots for the seven x values that I give it. I can avoid the warning message by providing more x values in new_data, and just ignoring the ones I don't need, but I am concerned about what predict is actually doing.

答:
According to Hadley's comment on this question you shouldn't expect lm to work with rcs. A quick demonstration why there's a problem:

```<code>mod <- lm(y ~ rcs(x, 5), data = my_df)

new_data <- data.frame(x = -3:3)
new_data2 <- data.frame(x = -300:300/100)

plot(new_data2$x, predict(mod, newdata = new_data2), type='l')
lines(new_data$x,predict(mod, newdata = new_data), col='red')
</code>```

The predictions vary depending on the number of x-values, even for the same range, so definitely not a good idea to combine these functions.

Body:
I have some data that I'm modeling using restricted cubic splines. I'm using the rcs transformation function in the rms package to generate the transformed variables for a linear model. Here is an example using 5 knots.

library('rms')

my_df <- data.frame(
    y = -4 * -100:100 + -1.5 * (-100:100)**2 + 3 * (-100:100)**3 + rnorm(201, 0, 1e5),
    x = -100:100
)

mod <- lm(y ~ rcs(x, 5), data = my_df)

After I fit the data, I'd like to find the predicted y values for a specific domain of x values. Here is what I'm doing now:

new_data <- data.frame(x = -3:3)

predict(mod, newdata = new_data)

However, this generates a warning message:

Warning message:
In rcspline.eval(x, nk = nknots, inclx = TRUE, pc = pc, fractied = fractied) :
    5 knots requested with 7 unique values of x.  knots set to 5 interior values.

What does this mean, and what is going on? I expected that the knot locations should already be defined in mod, so I don't understand why it seems to be trying to find new knots for the seven x values that I give it. I can avoid the warning message by providing more x values in new_data, and just ignoring the ones I don't need, but I am concerned about what predict is actually doing.

Body:
According to Hadley's comment on this question you shouldn't expect lm to work with rcs. A quick demonstration why there's a problem:

mod <- lm(y ~ rcs(x, 5), data = my_df)

new_data <- data.frame(x = -3:3)
new_data2 <- data.frame(x = -300:300/100)

plot(new_data2$x, predict(mod, newdata = new_data2), type='l')
lines(new_data$x,predict(mod, newdata = new_data), col='red')

The predictions vary depending on the number of x-values, even for the same range, so definitely not a good idea to combine these functions.


问:
Add left/right horizontal padding to UILabel
I need to create a UILabel with a background color, and I'd like to add some left/right leading/trailing horizontal padding.

But every solution I've found seems like a nasty hack.

What is the 'standard' way to achieve this from iOS 5 forward?

A screenshot to illustrate my scenario:

答:
If you want to add padding to UILabel but not want to subclass it you can put your label in a UIView and give paddings with autolayout like:

Result:


问:
double fork using vfork
HI

I am writing a part of a server which should dispatch some other child processes.

Because I want to wait on some of the processes, and dispatch others without waiting for completion, I use double fork for the second kind of processes (thus avoiding the zombie processes).

Problem is, my server holds a lot of memory, so forking takes a long time (even the copy-on-write fork used in Linux which copies only the paging tables)

I want to replace the fork() with vfork(), and it's easy for the second fork (as it only calls execve() in the child), but I couldn't find any way I can replace the first one.

Does anyone know how I can do that?

Thanks!

The server is a linux (RH5U4), written in C++.

答: I believe you can use the answer to another question I asked, for a similar reason. You can vfork() + exec() to an executable which forks again. See setuid() before calling execv() in vfork() / clone()

Title: double fork using vfork


问:
PrimeFaces DataTable doesn't update when filtered
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>
        <p:dataTable var="car" value="#{dtCar.cars}" widgetVar="carsTable"
            emptyMessage="No cars found with given criteria"
            filteredValue="#{dtCar.filteredCars}">

            <p:column filterBy="#{car.model}" headerText="Model"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.model}" />
            </p:column>
            <p:column filterBy="#{car.color}" headerText="Color"
                footerText="contains" filterMatchMode="contains">
                <h:outputText value="#{car.color}" />
            </p:column>

        </p:dataTable>
        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>
</html>
</code>```

Here is the CarBean.java

```<code>package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}
</code>```

And here is the Car.java

```<code>package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

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

答:
As suggested by @Kukeltje I switch to lazyModel and it works very fine. I followed the example in Primefaces Showcase https://www.primefaces.org/showcase/ui/data/datatable/lazy.xhtml
With lazy model I guess that paginator must be set to true, or else my example doesn't work.

Here's the new version of pagina1.xhtml

```<code>    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form id="form">
        <p:dataTable id="dt" var="car" value="#{dtCar.lazyModel}" lazy="true" paginator="true" rows="2">
            <p:column headerText="Id">
                <h:outputText value="#{car.id}" />
            </p:column>

            <p:column filterBy="#{car.model}" headerText="Model">
                <h:outputText value="#{car.model}" />
            </p:column>
            <p:column filterBy="#{car.color}" headerText="Color">
                <h:outputText value="#{car.color}"/>
            </p:column>
        </p:dataTable>
        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>
</html>
</code>```

Here is CarBean.java

```<code>package it.caditech.testtable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.model.LazyDataModel;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private LazyDataModel<Car> lazyModel;

  @PostConstruct
  public void init() {
    lazyModel = new LazyCarDataModel();
  }

  public LazyDataModel<Car> getLazyModel() {
    return lazyModel;
  }

  public String loadNewCars() {
    ((LazyCarDataModel) lazyModel).loadNewCars();
    return null;
  }

}
</code>```

Here is the most important part, LazyCarDataModel

```<code>package it.caditech.testtable;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

public class LazyCarDataModel extends LazyDataModel<Car> {

  private List<Car> datasource = new ArrayList<>();

  public LazyCarDataModel() {
    loadNewCars();
  }

  @Override
  public Car getRowData(String rowKey) {
    for (Car car : datasource) {
      if (car.getId().equals(rowKey)) {
        return car;
      }
    }

    return null;
  }

  @Override
  public Object getRowKey(Car car) {
    return car.getId();
  }

  @Override
  public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
    List<Car> data = new ArrayList<Car>();

    // filter
    for (Car car : datasource) {
      boolean match = true;

      if (filters != null) {
        for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
          try {
            String filterProperty = it.next();
            Object filterValue = filters.get(filterProperty);
            BeanInfo info = Introspector.getBeanInfo(Car.class);
            String fieldValue = null;
            for (PropertyDescriptor p : info.getPropertyDescriptors()) {
              if (p.getName().equals(filterProperty)) {
                fieldValue = (String) p.getReadMethod().invoke(car, new Object[0]);
              }
            }
            // String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
            if (filterValue == null || fieldValue.contains(filterValue.toString())) {
              match = true;
            }
            else {
              match = false;
              break;
            }
          }
          catch (Exception e) {
            match = false;
          }
        }
      }

      if (match) {
        data.add(car);
      }
    }

    // rowCount
    int dataSize = data.size();
    setRowCount(dataSize);

    // paginate
    if (dataSize > pageSize) {
      try {
        return data.subList(first, first + pageSize);
      }
      catch (IndexOutOfBoundsException e) {
        return data.subList(first, first + dataSize % pageSize);
      }
    }
    else {
      return data;
    }
  }

  protected void loadNewCars() {
    if (datasource.isEmpty() || datasource.get(0).getModel().equals("myModel")) {
      datasource.clear();
      datasource.add(new Car("1", "gt", "giallo"));
      datasource.add(new Car("2", "scirocco", "azzurro"));
      datasource.add(new Car("3", "duna", "giallo"));
      datasource.add(new Car("4", "diablo", "griggio"));
      datasource.add(new Car("5", "cayenne", "rosso"));
      datasource.add(new Car("6", "aygo", "azzurro"));
    }
    else {
      datasource.clear();
      datasource.add(new Car("7", "myModel", "blu"));
      datasource.add(new Car("8", "punto", "blu"));
      datasource.add(new Car("9", "doblo", "grigio"));
      datasource.add(new Car("10", "smart", "blu"));
      datasource.add(new Car("11", "twingo", "rosso"));
      datasource.add(new Car("12", "twingo", "bianco"));
      datasource.add(new Car("13", "twing", "rosa"));
      datasource.add(new Car("14", "twist", "frizzante"));
      datasource.add(new Car("15", "twelf", "rose"));
      datasource.add(new Car("16", "twang", "riga"));
      datasource.add(new Car("17", "doblo", "blu"));
    }
  }
}
</code>```

I guess that the car Id property and the method getRowData() and getRowKey() can be omitted, for I don't need selection handling in this case.

Body:
I'm new to PrimeFaces and to JSF.

I need to filter a table with "contains" match mode. It works fine when the data is static, but when data changes the view doesn't update, and it still shows the old data. It updates when the user changes the filter. If no filter is applied it works fine.

Have you got any suggestions?

I post the code, inspired from the PrimeFaces 6 showcase. It is a page that displays a two columns table and a button that loads a new data for the table

Thank you, any help will be appreciated

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form>

                <h:outputText value="#{car.model}" />

                <h:outputText value="#{car.color}" />

        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>

Here is the CarBean.java

package it.caditech.testtable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private List<Car> cars;

  private List<Car> filteredCars;

  public CarBean() {
    setCars(new ArrayList<Car>());
    getCars().add(new Car("myModel", "blu"));
    getCars().add(new Car("punto", "blu"));
    getCars().add(new Car("doblo", "grigio"));
    getCars().add(new Car("smart", "blu"));
    getCars().add(new Car("twingo", "rosso"));
    getCars().add(new Car("twingo", "bianco"));
    getCars().add(new Car("doblo", "blu"));
    // add more cars
  }

  // getter setter
  public List<Car> getCars() {
    return cars;
  }

  public void setCars(List<Car> cars) {
    this.cars = cars;
  }

  public List<Car> getFilteredCars() {
    return filteredCars;
  }

  public void setFilteredCars(List<Car> filteredCars) {
    this.filteredCars = filteredCars;
  }

  public String loadNewCars() {
    if (getCars().get(0).getModel().equals("myModel")) {
      getCars().clear();
      getCars().add(new Car("gt", "giallo"));
      getCars().add(new Car("scirocco", "azzurro"));
      getCars().add(new Car("duna", "giallo"));
      getCars().add(new Car("diablo", "griggio"));
      getCars().add(new Car("cayenne", "rosso"));
      getCars().add(new Car("aygo", "azzurro"));
      setFilteredCars(null);
    }
    else {
      getCars().clear();
      getCars().add(new Car("myModel", "blu"));
      getCars().add(new Car("punto", "blu"));
      getCars().add(new Car("doblo", "grigio"));
      getCars().add(new Car("smart", "blu"));
      getCars().add(new Car("twingo", "rosso"));
      getCars().add(new Car("twingo", "bianco"));
      getCars().add(new Car("doblo", "blu"));
      setFilteredCars(null);
    }
    return null;
  }
}

And here is the Car.java

package it.caditech.testtable;
public class Car {
  private String model;

  private String color;

  public Car(String m, String c) {
    model = m;
    color = c;
  }

  public String getModel() {
    return model;
  }

  public void setModel(String model) {
    this.model = model;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}

Body:
As suggested by @Kukeltje I switch to lazyModel and it works very fine. I followed the example in Primefaces Showcase https://www.primefaces.org/showcase/ui/data/datatable/lazy.xhtml
With lazy model I guess that paginator must be set to true, or else my example doesn't work.

Here's the new version of pagina1.xhtml

    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:p="http://primefaces.org/ui">
<h:head >
Primefaces Data Table Test
</h:head>
<h:body>
    <h:form id="form">
        <p:dataTable id="dt" var="car" value="#{dtCar.lazyModel}" lazy="true" paginator="true" rows="2">
            <p:column headerText="Id">
                <h:outputText value="#{car.id}" />
            </p:column>

            <p:column filterBy="#{car.model}" headerText="Model">
                <h:outputText value="#{car.model}" />
            </p:column>
            <p:column filterBy="#{car.color}" headerText="Color">
                <h:outputText value="#{car.color}"/>
            </p:column>
        </p:dataTable>
        <h:commandButton id="myButton" value="Load" action="#{dtCar.loadNewCars()}"/>
    </h:form>

</h:body>
</html>

Here is CarBean.java

package it.caditech.testtable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.model.LazyDataModel;

@ManagedBean(name = "dtCar")
@ViewScoped
public class CarBean {

  private LazyDataModel<Car> lazyModel;

  @PostConstruct
  public void init() {
    lazyModel = new LazyCarDataModel();
  }

  public LazyDataModel<Car> getLazyModel() {
    return lazyModel;
  }

  public String loadNewCars() {
    ((LazyCarDataModel) lazyModel).loadNewCars();
    return null;
  }

}

Here is the most important part, LazyCarDataModel

package it.caditech.testtable;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

public class LazyCarDataModel extends LazyDataModel<Car> {

  private List<Car> datasource = new ArrayList<>();

  public LazyCarDataModel() {
    loadNewCars();
  }

  @Override
  public Car getRowData(String rowKey) {
    for (Car car : datasource) {
      if (car.getId().equals(rowKey)) {
        return car;
      }
    }

    return null;
  }

  @Override
  public Object getRowKey(Car car) {
    return car.getId();
  }

  @Override
  public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
    List<Car> data = new ArrayList<Car>();

    // filter
    for (Car car : datasource) {
      boolean match = true;

      if (filters != null) {
        for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
          try {
            String filterProperty = it.next();
            Object filterValue = filters.get(filterProperty);
            BeanInfo info = Introspector.getBeanInfo(Car.class);
            String fieldValue = null;
            for (PropertyDescriptor p : info.getPropertyDescriptors()) {
              if (p.getName().equals(filterProperty)) {
                fieldValue = (String) p.getReadMethod().invoke(car, new Object[0]);
              }
            }
            // String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
            if (filterValue == null || fieldValue.contains(filterValue.toString())) {
              match = true;
            }
            else {
              match = false;
              break;
            }
          }
          catch (Exception e) {
            match = false;
          }
        }
      }

      if (match) {
        data.add(car);
      }
    }

    // rowCount
    int dataSize = data.size();
    setRowCount(dataSize);

    // paginate
    if (dataSize > pageSize) {
      try {
        return data.subList(first, first + pageSize);
      }
      catch (IndexOutOfBoundsException e) {
        return data.subList(first, first + dataSize % pageSize);
      }
    }
    else {
      return data;
    }
  }

  protected void loadNewCars() {
    if (datasource.isEmpty() || datasource.get(0).getModel().equals("myModel")) {
      datasource.clear();
      datasource.add(new Car("1", "gt", "giallo"));
      datasource.add(new Car("2", "scirocco", "azzurro"));
      datasource.add(new Car("3", "duna", "giallo"));
      datasource.add(new Car("4", "diablo", "griggio"));
      datasource.add(new Car("5", "cayenne", "rosso"));
      datasource.add(new Car("6", "aygo", "azzurro"));
    }
    else {
      datasource.clear();
      datasource.add(new Car("7", "myModel", "blu"));
      datasource.add(new Car("8", "punto", "blu"));
      datasource.add(new Car("9", "doblo", "grigio"));
      datasource.add(new Car("10", "smart", "blu"));
      datasource.add(new Car("11", "twingo", "rosso"));
      datasource.add(new Car("12", "twingo", "bianco"));
      datasource.add(new Car("13", "twing", "rosa"));
      datasource.add(new Car("14", "twist", "frizzante"));
      datasource.add(new Car("15", "twelf", "rose"));
      datasource.add(new Car("16", "twang", "riga"));
      datasource.add(new Car("17", "doblo", "blu"));
    }
  }
}

I guess that the car Id property and the method getRowData() and getRowKey() can be omitted, for I don't need selection handling in this case.