问:
how to use node js to combine data from two jsons
I want to merge data from two tables and then send the result as the response.

I'm new to nodejs and lambda and I'm unable to figure out how I can merge json data from both scan calls and send it as the response.

If I uncomment the callback then response for only one table is sent.

My code is below, can someone please help in completing it

```<code>'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}

}
</code>```

答:
You can use the following modification to the code so that you can send the response in a single callback.</p>

```<code>'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

var firstResultData = false;
function runAfterBothCallbacks(data){
  if(!firstResultData){
     firstResultData = data;
  }else{
     // Combine firstResultData with data and return in the callback
     callback(null,{ dataX: firstResultData, dataY: data });
     // Note: The order of scan and scan1 result coming cannot be guaranteed so, dataX can be the results of scan or scan1. If you can identify the result based on the scan, either pass it as another parameter to the runAfterBothCallbacks method or identify the scan based on data result (If possible).
  }

}

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{
        runAfterBothCallbacks(data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{
        runAfterBothCallbacks(data);
   }
}

}
</code>```

Body:
I want to merge data from two tables and then send the result as the response.

I'm new to nodejs and lambda and I'm unable to figure out how I can merge json data from both scan calls and send it as the response.

If I uncomment the callback then response for only one table is sent.

My code is below, can someone please help in completing it

'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{

        //callback(null, data);
   }
}

}

Body:
You can use the following modification to the code so that you can send the response in a single callback.

'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = function(event, ctx, callback) {

var params=  {
       TableName:'x',
       FilterExpression:'SessionId = :SessionId',
ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

var params1=  {
    TableName:'y',
    FilterExpression:'sessionid = :SessionId',
    ExpressionAttributeValues:{ ":SessionId" : 'ca47a131'},
};

docClient.scan(params, onScan);
docClient.scan(params1, onScan1);

var firstResultData = false;
function runAfterBothCallbacks(data){
  if(!firstResultData){
     firstResultData = data;
  }else{
     // Combine firstResultData with data and return in the callback
     callback(null,{ dataX: firstResultData, dataY: data });
     // Note: The order of scan and scan1 result coming cannot be guaranteed so, dataX can be the results of scan or scan1. If you can identify the result based on the scan, either pass it as another parameter to the runAfterBothCallbacks method or identify the scan based on data result (If possible).
  }

}

function onScan(err, data){
    if(err){
        callback(err, null);
    }else{
        runAfterBothCallbacks(data);
   }
}
function onScan1(err, data){
    if(err){
        callback(err, null);
    }else{
        runAfterBothCallbacks(data);
   }
}

}


来源: stackexchange

问:
Resetting generator object in Python
I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

```<code>y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)
</code>```

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?

See also: How to look ahead one element (peek) in a Python generator?

答:
You can now use more_itertools.seekable (a third-party tool) which enables resetting iterators.

Install via > pip install more_itertools

```<code>import more_itertools as mit

y = mit.seekable(FunctionWithYield())
for x in y:
    print(x)

y.seek(0)                                              # reset iterator
for x in y:
    print(x)
</code>```

Note: memory consumption grows while advancing the iterator, so be wary of large iterables.

ContentLicense: CC BY-SA 4.0

Title: Resetting generator object in Python

Body:
I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?

See also: How to look ahead one element (peek) in a Python generator?

Body:
You can now use more_itertools.seekable (a third-party tool) which enables resetting iterators.

Install via > pip install more_itertools

import more_itertools as mit

y = mit.seekable(FunctionWithYield())
for x in y:
    print(x)

y.seek(0)                                              # reset iterator
for x in y:
    print(x)

Note: memory consumption grows while advancing the iterator, so be wary of large iterables.

ContentLicense: CC BY-SA 3.0


问:
Can I use a lambda function or std::function object in place of a function pointer?
I've got a library that I need to use that defines the following:

```<code>typedef void CallbackFunction(const int& i);
</code>```

and has a function to register your callback that looks like:

```<code>void registerCallback(CallbackFunction* pCallback);
</code>```

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

```<code>auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);
</code>```

instead I get the error:

```<code>error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
</code>```

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!

答:
Since you capture nothing, you are supposed to be able to do what you're trying to do, namely assign a lambda expression as a function pointer (though your syntax is wrong there).

Since you're using VS2010 though, you won't be able to.  The feature of lambda that you're trying to use did not come to be until after VS2010 was released: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3043.html

So while yes, it's supposed to work it in fact does not.

Of course, while you are not, in fact, capturing anything you do state that you want to.  Lambdas that capture data cannot be converted to function pointers even in the post VS2010 state of the C++ draft standard.

ContentLicense: CC BY-SA 2.5

Body:
I've got a library that I need to use that defines the following:

typedef void CallbackFunction(const int& i);

and has a function to register your callback that looks like:

void registerCallback(CallbackFunction* pCallback);

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);

instead I get the error:

error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!


问:
Getting Checkbox Value in ASP.NET MVC 4
I'm working on an ASP.NET MVC 4 app. This app has a basic form. The model for my form looks like the following:

```<code>public class MyModel
{
    public string Name { get; set; }
    public bool Remember { get; set; }
}
</code>```

In my form, I have the following HTML.

```<code><input id="Name" name="Name" type="text" value="@Model.Name" />
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
<label for="Remember"> Remember Me?</label>
</code>```

When I post the form, the Remember value in the model is always false. However, the Name property in the model has a value. I've tested this by setting a breakpoint in the following:

```<code>[HttpPost]
public ActionResult MyAction(MyModel model)
{
  Console.WriteLine(model.Remember.ToString());
}
</code>```

I can't figure it out. Why isn't the Checkbox value getting set?

答:
For the MVC using Model.
Model:

```<code>public class UserInfo
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}
</code>```

HTML:

```<code><input type="checkbox" value="true" id="checkbox1" name="RememberMe" checked="@Model.RememberMe"/>
<label for="checkbox1"></label>
</code>```

In [HttpPost] function, we can get its properties.

```<code>[HttpPost]
public ActionResult Login(UserInfo user)
{
   //...
   return View(user);
}
</code>```

Title: Getting Checkbox Value in ASP.NET MVC 4

Body:
I'm working on an ASP.NET MVC 4 app. This app has a basic form. The model for my form looks like the following:

public class MyModel
{
    public string Name { get; set; }
    public bool Remember { get; set; }
}

In my form, I have the following HTML.

<input id="Name" name="Name" type="text" value="@Model.Name" />
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
 Remember Me?

When I post the form, the Remember value in the model is always false. However, the Name property in the model has a value. I've tested this by setting a breakpoint in the following:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
  Console.WriteLine(model.Remember.ToString());
}

I can't figure it out. Why isn't the Checkbox value getting set?

Body:
For the MVC using Model.
Model:

public class UserInfo
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

HTML:

<input type="checkbox" value="true" id="checkbox1" name="RememberMe" checked="@Model.RememberMe"/>
<label for="checkbox1"></label>

In [HttpPost] function, we can get its properties.

[HttpPost]
public ActionResult Login(UserInfo user)
{
   //...
   return View(user);
}


问:
Rails Background Jobs running twice
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

```<code>scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end
</code>```

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

答: Start only the scheduler on instance A.</p>

Title: Rails Background Jobs running twice

Body:
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

Body: Start only the scheduler on instance A.


问:
filter javascript listing with an age range input
I want to be able to search for an age range e.g 10-20 from an input field and get a result of who is in that search, their name and age.

this is how my data is structured

```<code>var customers = [
{
    name: "Rocky Green",
    birthdate: "1988-10-01"
},
{
    name: "Sara Pink",
    birthdate: "1982-03-15"
},
{
    name: "Tom Black",
    birthdate: "1995-01-25"
},
]
</code>```

This the code i currently have which calculates the age from a date string

```<code>function getAge(dateString)
    {
        var today = new Date();
        var birthDate = new Date(dateString);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
        {
            age--;
        }
        return age;
    }
    getAge("1995-01-25");
    console.log(getAge("1995-01-25"));
</code>```

But this a little advanced for me.

答:
You can use the array .filter() method to create a new array that contains only the elements that match your condition.

The following does that (using your existing getAge() function). For demo purposes I've just used a simple button and input accessed via .querySelector() without bothering with element IDs or anything, and I haven't included any input validation - in your real project you'd want to add some code to make sure the user entered a valid range.

Given a string "10-20", you can extract the "10" and the "20" by using the string .split() method, splitting on the "-". The result of that will be an array containing the two numbers as strings, so I've converted these to numbers using the unary plus operator so that they can be compared to the age of each person.

document.querySelector("button").addEventListener("click", function() {
  var range = document.querySelector("input").value.split("-")
  var lower = +range[0]
  var upper = +range[1]
  var results = customers.filter(function(v) {
    var age = getAge(v.birthdate)
    return age >= lower && age <= upper
  })
  console.log(results)
})

var customers = [
  { name: "Rocky Green", birthdate: "1988-10-01" },
  { name: "Sara Pink", birthdate: "1982-03-15" },
  { name: "Tom Black", birthdate: "1995-01-25" }
]

function getAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Age range: <input value="10-30"></label>
<button>Filter</button></code>```

Body:
I want to be able to search for an age range e.g 10-20 from an input field and get a result of who is in that search, their name and age.

this is how my data is structured

var customers = [
{
    name: "Rocky Green",
    birthdate: "1988-10-01"
},
{
    name: "Sara Pink",
    birthdate: "1982-03-15"
},
{
    name: "Tom Black",
    birthdate: "1995-01-25"
},
]

This the code i currently have which calculates the age from a date string

function getAge(dateString)
    {
        var today = new Date();
        var birthDate = new Date(dateString);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
        {
            age--;
        }
        return age;
    }
    getAge("1995-01-25");
    console.log(getAge("1995-01-25"));

But this a little advanced for me.

Body:
You can use the array .filter() method to create a new array that contains only the elements that match your condition.

The following does that (using your existing getAge() function). For demo purposes I've just used a simple button and input accessed via .querySelector() without bothering with element IDs or anything, and I haven't included any input validation - in your real project you'd want to add some code to make sure the user entered a valid range.

Given a string "10-20", you can extract the "10" and the "20" by using the string .split() method, splitting on the "-". The result of that will be an array containing the two numbers as strings, so I've converted these to numbers using the unary plus operator so that they can be compared to the age of each person.

document.querySelector("button").addEventListener("click", function() {
  var range = document.querySelector("input").value.split("-")
  var lower = +range[0]
  var upper = +range[1]
  var results = customers.filter(function(v) {
    var age = getAge(v.birthdate)
    return age >= lower && age <= upper
  })
  console.log(results)
})

var customers = [
  { name: "Rocky Green", birthdate: "1988-10-01" },
  { name: "Sara Pink", birthdate: "1982-03-15" },
  { name: "Tom Black", birthdate: "1995-01-25" }
]

function getAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

<label>Age range: <input value="10-30"></label>
<button>Filter</button>


问:
Creating a log file from command line
I'm using the csc command to build a dll

```<code>csc /out:Test.dll /target:library file1.cs file2.cs
</code>```

I tried adding the /fl and /flp parameters to the command to make it
the following :

```<code>csc /out:Test.dll /target:library file1.cs file2.cs /fl
/flp:logfile=MyProjectOutput.log;verbosity=normal
</code>```

. But it doesn't work as the /fl command is not recognized.
 Links-https://msdn.microsoft.com/en-us/library/ms171470.aspx

答: The link you provided is for MSBuild which will call the C# compiler. You are directly calling the C# compiler which has different flags. You need to use the /out:<file> flag to specify an our log file. You can see all of the flags by executing csc /? at the command prompt.

Title: Creating a log file from command line

Body:
I'm using the csc command to build a dll

csc /out:Test.dll /target:library file1.cs file2.cs

I tried adding the /fl and /flp parameters to the command to make it
the following :

csc /out:Test.dll /target:library file1.cs file2.cs /fl
/flp:logfile=MyProjectOutput.log;verbosity=normal

. But it doesn't work as the /fl command is not recognized.
 Links-https://msdn.microsoft.com/en-us/library/ms171470.aspx


问:
Hadoop: Processing logic close to data, rather than data close to processing logic explanation
I was having a read on an IBM article related to Hadoop and one of the points listed was

Hadoop Distributed File System has many goals. Here are some of the most notable:

Processing logic close to the data, rather than the data close to the processing logic

It sounds to me like a play of words. Is there any difference between processing logic close to the data and data close to processing logic.

答:
There is quite a difference.

Taking the processing close to the data means running the business logic on the server where the data actually sits.

Compare this to bringing data close to the processing, where maybe you query a database, and join it with some other system. In this case, the data is sent over the network.

It's argued that sending code and libraries will be significantly less overhead in network transfer than pulling out gigabytes and terabytes worth of data.

In Hadoop2, this is handled by YARN, on which the mapreduce, or Spark, etc. processes run from process containers in parallel to the datanode process.


问:
Directory.EnumerateFiles not retrieving the actual path
Am trying to loop through a folder and read all the XML files within it.

Am using the Directory.EnumerateFiles to read from the path.

My .cs file and the XML files folder lies in same path

"C:\User\Documents\Projects\TestTool"

Am using the below code to get read the files.

```<code>string path = @"..\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}
</code>```

Using this am getting exception stating

Could not find path "C:\Program Files(x86)\Common Files\Microsoft
  Shared\DevServer\TestCases"

This is pointing to the WebDev.WebServer20 path instead of the actual path.

Not sure why it is pointing to a completely different folder

I tried string path = @"\TestCases\"; But when I try like this it is throwing an exceptiopn stating

Could not find path "C:\TestCases"

What is the mistake am making? Please help

答:
Since it is running under WebDev server it will using WebDev.WebServer20.exe's path for all relative paths.

You must use: Server.MapPath("~") to get to your own root.

```<code>string path = Server.MapPath("~") + @"\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}
</code>```

Please note if Server.MapPath("~") points to bin, then use it like Directory.GetParent(Server.MapPath("~")) + @"\TestCases\";

Assuming this is your target directory C:\User\Documents\Projects\TestTool\TestCases

Body:
Am trying to loop through a folder and read all the XML files within it.

Am using the Directory.EnumerateFiles to read from the path.

My .cs file and the XML files folder lies in same path

"C:\User\Documents\Projects\TestTool"

Am using the below code to get read the files.

string path = @"..\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}

Using this am getting exception stating

Could not find path "C:\Program Files(x86)\Common Files\Microsoft
  Shared\DevServer\TestCases"

This is pointing to the WebDev.WebServer20 path instead of the actual path.

Not sure why it is pointing to a completely different folder

I tried string path = @"\TestCases\"; But when I try like this it is throwing an exceptiopn stating

Could not find path "C:\TestCases"

What is the mistake am making? Please help

Body:
Since it is running under WebDev server it will using WebDev.WebServer20.exe's path for all relative paths.

You must use: Server.MapPath("~") to get to your own root.

string path = Server.MapPath("~") + @"\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}

Please note if Server.MapPath("~") points to bin, then use it like Directory.GetParent(Server.MapPath("~")) + @"\TestCases\";

Assuming this is your target directory C:\User\Documents\Projects\TestTool\TestCases


问:
Azure Cloud App ERR_CONNECTION_TIMED_OUT
I would like to deploy a container based app in azure container service, and followed this tutorial.

https://learn.microsoft.com/en-us/azure/container-service/dcos-swarm/container-service-mesos-marathon-ui

Everything went well except that the public url is showing
ERR_CONNECTION_TIMED_OUT in browser.

When pinging the url, able to get the IP address but pings are showing as timed out.

I have verified agents LB with port 80 as allowed in the rules list.

How to access the application through public web ?

答:
When pinging the url, able to get the IP address but pings are showing
  as timed out.

Azure disable ICMP package, so you could not ping Azure public IP address. You could use telnet or tcping to check whether your service is listening.

Do you bind port 80 of the container to port 80 of the DC/OS agent? If I don't do this, I get same error log with you. Please refer to this link.

Note: I test in my lab, if I did not do this, nginx service will listen on other port. I ssh to the agent VM.

```<code>root@dcos-agent-public-65818314000001:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
7e8091548413        nginx               "nginx -g 'daemon off"   14 minutes ago      Up 14 minutes       0.0.0.0:4912->80/tcp   mesos-d7be0314-6be2-467b-8376-433a05033b17-S1.42edeac0-2aa3-4ecd-acaa-17d5f2f4ac19
</code>```

The service is listening on port 4912 not 80.

If you do this step, I suggest you also could ssh to agent VM(same user name and private key) and execute docker ps .

Body:
When pinging the url, able to get the IP address but pings are showing
  as timed out.

Azure disable ICMP package, so you could not ping Azure public IP address. You could use telnet or tcping to check whether your service is listening.

Do you bind port 80 of the container to port 80 of the DC/OS agent? If I don't do this, I get same error log with you. Please refer to this link.

Note: I test in my lab, if I did not do this, nginx service will listen on other port. I ssh to the agent VM.

root@dcos-agent-public-65818314000001:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
7e8091548413        nginx               "nginx -g 'daemon off"   14 minutes ago      Up 14 minutes       0.0.0.0:4912->80/tcp   mesos-d7be0314-6be2-467b-8376-433a05033b17-S1.42edeac0-2aa3-4ecd-acaa-17d5f2f4ac19

The service is listening on port 4912 not 80.

If you do this step, I suggest you also could ssh to agent VM(same user name and private key) and execute docker ps .


问:
Accessing value of Editable field in repeat control

How can I access the value of an computed field in a repeat control?
In the example below, I have cfT5Budget in a repeat control.  I want to be able to access the value of each of the cfT5Budget control (repeat1:0:cfT5Budget, repeat1:1:cfT5Budget, etc..)

I want to be able to have that same value replicated into my second repeat control.  I will be doing other stuff in the second control but for this example, it's just a simple code.

```<code><xp:table>
    <xp:repeat id="repeat1" var="rowItem1" indexVar="indexVar1">
        <xp:this.value><![CDATA[#{javascript:['a', 'b', 'c']}]]></xp:this.value>
        <xp:tr>
            <xp:td>
                <xp:text escape="true" id="cfT5Budget" value="#{javascript:5 + indexVar1}">
                </xp:text>
            </xp:td>

        </xp:tr>
    </xp:repeat>
</xp:table>
<xp:table>
    <xp:repeat id="repeat2" var="rowItem2" indexVar="indexVar2">
        <xp:this.value><![CDATA[#{javascript:getComponent('repeat1').getValue()}]]></xp:this.value>
        <xp:tr>
            <xp:td>
                <xp:text escape="true" id="cfT5Budget2" value="#{javascript:VALUE OF cfT5Budget GOES HERE}">
                </xp:text>
            </xp:td>

        </xp:tr>
    </xp:repeat>
</xp:table>
</code>```

Thank you in advance :)

答:
The short answer: use data binding.

The long answer:

In MVC your code should not interact with the View (a.k.a the fields), but rather the model (a.k.a the data). So instead of computing the values like in your example, you bind them using the variable name provided in the repeat.

You interact with that collection (Array) not the fields. This makes code easier and more robust since the code doesn’t need to care what UI element is used.

Hope that helps

Body:
How can I access the value of an computed field in a repeat control?
In the example below, I have cfT5Budget in a repeat control.  I want to be able to access the value of each of the cfT5Budget control (repeat1:0:cfT5Budget, repeat1:1:cfT5Budget, etc..)

I want to be able to have that same value replicated into my second repeat control.  I will be doing other stuff in the second control but for this example, it's just a simple code.

<xp:table>
    <xp:repeat id="repeat1" var="rowItem1" indexVar="indexVar1">
        <xp:this.value><![CDATA[#{javascript:['a', 'b', 'c']}]]></xp:this.value>
        <xp:tr>
            <xp:td>
                <xp:text escape="true" id="cfT5Budget" value="#{javascript:5 + indexVar1}">
                </xp:text>
            </xp:td>

        </xp:tr>
    </xp:repeat>
</xp:table>
<xp:table>
    <xp:repeat id="repeat2" var="rowItem2" indexVar="indexVar2">
        <xp:this.value><![CDATA[#{javascript:getComponent('repeat1').getValue()}]]></xp:this.value>
        <xp:tr>
            <xp:td>
                <xp:text escape="true" id="cfT5Budget2" value="#{javascript:VALUE OF cfT5Budget GOES HERE}">
                </xp:text>
            </xp:td>

        </xp:tr>
    </xp:repeat>
</xp:table>

Thank you in advance :)


问:
How to run for loop asynchronously with inquirer prompt
```<code>var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"];

function nodeMan() {
  var wrongs = 0;
  var lettersGuessed = [];
  var word = words[Math.floor(Math.random()*words.length)];
  var goldenBoy = word.split("");
  var blank = "_" * word.length;

  console.log(blank);

  for (var i = 0; wrongs < 10; i++) {
    var neem = "Question " + i;
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then(function(response) {
      console.log("print");
      lettersGuessed.push(resposne.name);
      if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
        console.log(" first if statement cleared");
        for (var u = 0; u < goldenBoy.length; u++) {
          if (goldenBoy[u] === response.name) {
            blank[u] = response.name;
            console.log(blank);
          }
        }
      }
    })
  }
}
nodeMan();
</code>```

Trying to run this asynchronously. As of rn I get an infinite loop of "Guess a letter" prompts. Need help getting inquirer to shoot one question at a time instead of infinitely. Thanks for your time!

to set up a test folder don't forget to npm init and inquirer

答:
If you're going to run your code under NodeJS 7.0+, you can declare a function as "async" function and then use "await" operator for waiting asynchronous response in for loop.</p>

```<code>var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT", "GOLF", "HOTEL", "INDIA", "JULIET", "KILO", "LIMA", "MIKE", "NOVEMBER", "OSCAR", "PAPA", "QUEBEC", "ROMEO", "SIERRA", "TANGO", "UNIFORM", "VICTOR", "WHISKEY", "XRAY", "YANKEE", "ZULU"];

// declare an async function
async function nodeMan() {
    var wrongs = 0;
    var lettersGuessed = [];
    var word = words[Math.floor(Math.random() * words.length)];
    var goldenBoy = word.split("");
    var blank = "_" + word.length;

    console.log(blank);

    for (var i = 0; wrongs < 10; i++) {
        var neem = "Question " + i;
        // wait for asynchronous response
        var response = await inquirer.prompt([{
            name: neem,
            message: "Guess a letter"
        }]);
        console.log(response)
        console.log("print");
        lettersGuessed.push(response.name);
        if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
            console.log(" first if statement cleared");
            for (var u = 0; u < goldenBoy.length; u++) {
                if (goldenBoy[u] === response.name) {
                    blank[u] = response.name;
                    console.log(blank);
                }
            }
        }
    }
}
nodeMan();
</code>```

Body:
var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"];

function nodeMan() {
  var wrongs = 0;
  var lettersGuessed = [];
  var word = words[Math.floor(Math.random()*words.length)];
  var goldenBoy = word.split("");
  var blank = "_" * word.length;

  console.log(blank);

  for (var i = 0; wrongs < 10; i++) {
    var neem = "Question " + i;
    inquirer.prompt([{name: neem, message: "Guess a letter"}]).then(function(response) {
      console.log("print");
      lettersGuessed.push(resposne.name);
      if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
        console.log(" first if statement cleared");
        for (var u = 0; u < goldenBoy.length; u++) {
          if (goldenBoy[u] === response.name) {
            blank[u] = response.name;
            console.log(blank);
          }
        }
      }
    })
  }
}
nodeMan();

Trying to run this asynchronously. As of rn I get an infinite loop of "Guess a letter" prompts. Need help getting inquirer to shoot one question at a time instead of infinitely. Thanks for your time!

to set up a test folder don't forget to npm init and inquirer

Body:
If you're going to run your code under NodeJS 7.0+, you can declare a function as "async" function and then use "await" operator for waiting asynchronous response in for loop.

var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT", "GOLF", "HOTEL", "INDIA", "JULIET", "KILO", "LIMA", "MIKE", "NOVEMBER", "OSCAR", "PAPA", "QUEBEC", "ROMEO", "SIERRA", "TANGO", "UNIFORM", "VICTOR", "WHISKEY", "XRAY", "YANKEE", "ZULU"];

// declare an async function
async function nodeMan() {
    var wrongs = 0;
    var lettersGuessed = [];
    var word = words[Math.floor(Math.random() * words.length)];
    var goldenBoy = word.split("");
    var blank = "_" + word.length;

    console.log(blank);

    for (var i = 0; wrongs < 10; i++) {
        var neem = "Question " + i;
        // wait for asynchronous response
        var response = await inquirer.prompt([{
            name: neem,
            message: "Guess a letter"
        }]);
        console.log(response)
        console.log("print");
        lettersGuessed.push(response.name);
        if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
            console.log(" first if statement cleared");
            for (var u = 0; u < goldenBoy.length; u++) {
                if (goldenBoy[u] === response.name) {
                    blank[u] = response.name;
                    console.log(blank);
                }
            }
        }
    }
}
nodeMan();


问:
how can i accept react component constructor as a function param in typescript
```<code>import { Component} from "react";

export class Test extends Component<{}, {}> {
      render() {
        return "Hello";
      }
    }

    function myFunction<P, S, C extends Component<P, S>>(c: C): void {
      console.log("ctor", c);
    }

    const s = myFunction(Test);
</code>```

Error :

Argument of type 'typeof Test' is not assignable to parameter of type
  'Component<{}, {}>'.   Property 'setState' is missing in type 'typeof
  Test'. 07:35:53 - Compilation complete. Watching for file changes.

do i need to implement all members of original react Component class using super.(..) ?

答:
You'll want to declare the type of C as something that extends a newable function returning a component:

```<code>import { Component} from "react";

export class Test extends Component<{}, {}> {
    render() {
        return "Hello";
    }
}

function myFunction<P, S, C extends new () => Component<P, S>>(c: C): void {
    console.log("ctor", c);
}

const s = myFunction(Test);
</code>```

Body:
import { Component} from "react";

export class Test extends Component<{}, {}> {
      render() {
        return "Hello";
      }
    }

    function myFunction(c: C): void {
      console.log("ctor", c);
    }

    const s = myFunction(Test);

Error :

Argument of type 'typeof Test' is not assignable to parameter of type
  'Component<{}, {}>'.   Property 'setState' is missing in type 'typeof
  Test'. 07:35:53 - Compilation complete. Watching for file changes.

do i need to implement all members of original react Component class using super.(..) ?

Body:
You'll want to declare the type of C as something that extends a newable function returning a component:

import { Component} from "react";

export class Test extends Component<{}, {}> {
    render() {
        return "Hello";
    }
}

function myFunction<P, S, C extends new () => Component<P, S>>(c: C): void {
    console.log("ctor", c);
}

const s = myFunction(Test);


问:
passing variable from controller to partial view rails
I am stuck at passing a variable value from controller to partial. I have all the  data from skill set database on @skillSetData coming from controller: SkillSetsController

```<code>def skillsetdata
    @skillSetData = SkillSet.all
end
</code>```

The code below on skill_set/skillsetdata.html.erb display all the data.

```<code><% @skillSetData.each do |single_skill| %>

    <option value="<%= single_skill.skillname %>"><%=single_skill.skillname %></option>

<% end %>
</code>```

But I am not able to pass the variable if skillsetdata.html.erb is a partial ie: _skillsetdata.html.erb. The code for the _skillsetdata I have written is:

```<code><% skills_set_data.each do |single_skill| %>
   <option value="<%= single_skill.skillname %>">
      <%=single_skill.skillname %>
   </option>
<% end %>
</code>```

I want to make it partial because it has the dropdown list that has to be rendered on various other pages. One of the pages that I want to use on is:static_pages/home.html.erb which is from different controller ie: staticPages. The code that I have tried after the help is:

```<code><%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>
</code>```

But I am getting error as:
  undefined method `each' for nil:NilClass
in skill_sets/_skillsetdata.html.erb
while trying to load home.html.erb. I am not able to pass data between different pages from a partial.

Any help with example code would be helpful.

答:
For passing instance variables to partials you can use the locals:

```<code># view from
<%= render partial: 'skillsetdata', locals: { skills_set_data: @skillSetData } %>
</code>```

While in the local you receive the value of that instance variable, which is now a local one:

```<code># partial
<% skills_set_data.each do |single_skill| %>
  <option value="<%= single_skill.skillname %>">
    <%=single_skill.skillname %>
  </option>
<% end %>
</code>```

Body:
I am stuck at passing a variable value from controller to partial. I have all the  data from skill set database on @skillSetData coming from controller: SkillSetsController

def skillsetdata
    @skillSetData = SkillSet.all
end

The code below on skill_set/skillsetdata.html.erb display all the data.

<% @skillSetData.each do |single_skill| %>

    <option value="<%= single_skill.skillname %>"><%=single_skill.skillname %></option>

<% end %>

But I am not able to pass the variable if skillsetdata.html.erb is a partial ie: _skillsetdata.html.erb. The code for the _skillsetdata I have written is:

<% skills_set_data.each do |single_skill| %>
   <option value="<%= single_skill.skillname %>">
      <%=single_skill.skillname %>
   </option>
<% end %>

I want to make it partial because it has the dropdown list that has to be rendered on various other pages. One of the pages that I want to use on is:static_pages/home.html.erb which is from different controller ie: staticPages. The code that I have tried after the help is:

<%= render partial: 'skill_sets/skillsetdata', locals: { skills_set_data:@skillSetData } %>

But I am getting error as:
  undefined method `each' for nil:NilClass
in skill_sets/_skillsetdata.html.erb
while trying to load home.html.erb. I am not able to pass data between different pages from a partial.

Any help with example code would be helpful.

Body:
For passing instance variables to partials you can use the locals:

# view from
<%= render partial: 'skillsetdata', locals: { skills_set_data: @skillSetData } %>

While in the local you receive the value of that instance variable, which is now a local one:

# partial
<% skills_set_data.each do |single_skill| %>
  <option value="<%= single_skill.skillname %>">
    <%=single_skill.skillname %>
  </option>
<% end %>


问:
Replace multiple %in% statements with a single line of dplyr code

I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

```<code>library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))
</code>```

I would like to know if there is something like

```<code>df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))
</code>```

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!

答:
NOTE: I overlooked the need for these to be in-db SQL ops. This won't work for that.</p>

```<code>library(dplyr)
library(purrrlyr)
library(purrr)

df %>%
  by_row(~{ as.numeric(any(. %in% match_dx)) }, .to="flag") %>%
  mutate(flag = flatten_dbl(flag))
## # A tibble: 2 x 6
##     dx1   dx2   dx3   dx4  dx13  flag
##   <chr> <chr> <chr> <chr> <chr> <dbl>
## 1   C00   C50   D20   A40   G20     1
## 2   G01   Z11   D22   C21   C30     0
</code>```

Body:
I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))

I would like to know if there is something like

df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!

Body:
NOTE: I overlooked the need for these to be in-db SQL ops. This won't work for that.

library(dplyr)
library(purrrlyr)
library(purrr)

df %>%
  by_row(~{ as.numeric(any(. %in% match_dx)) }, .to="flag") %>%
  mutate(flag = flatten_dbl(flag))
## # A tibble: 2 x 6
##     dx1   dx2   dx3   dx4  dx13  flag
##   <chr> <chr> <chr> <chr> <chr> <dbl>
## 1   C00   C50   D20   A40   G20     1
## 2   G01   Z11   D22   C21   C30     0


问:
Cannot use NHibernate Code Mapping for a private field
What is the equivalent NHibernate Code Mapping for the following Fluent NHibernate code:

```<code>Map(x => x.Orders).Access.CamelCaseField(Prefix.Underscore);
</code>```

I have spent all afternoon trying to get this to work.  Here is my code so far:

```<code>public class Customer
{
    private readonly IList<Order> _orders = new List<Order>();
    public virtual Guid ID { get; set; }
    public virtual string LastName { get; set; }
    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}

public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        Id<Guid>(x => x.Id);

        Component(x => x.LastName, y =>
        {
            y.Property<string>(z => z.LastName);
        });

        Bag(x => x._orders, collectionMapping =>
        {
            collectionMapping.Table("CustomerOrders");
            collectionMapping.Cascade(Cascade.None);
            collectionMapping.Key(k => k.Column("CustomerId"));
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}
</code>```

This answers my question: https://groups.google.com/forum/#!topic/nhusers/wiH1DPGOhgU.  I have tried copying and pasting the code from my link (see below):

```<code>  this.Bag(
                    r => "privatefieldtomap",
                    map =>
                        {
                            map.Access(Access.Field);
                            map.Table("table");
                            map.Key(k => k.Column("foreignkey"));
                        },
                    r => r.Element(m => m.Column("columntomap")));
</code>```

The error I get is: Bag cannot be inferred from the usage.

答:
You have a couple of options to map a non-visible field by code.

Here are some, please note that I haven't tested them yet as written, but should help you anyways:

```<code>// Option 1:
public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag<Order>("_orders", collectionMapping =>
        {
            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}

// Option 2: No strings, but I'm not sure if this one would really work as is.
public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag(x => x.Orders, collectionMapping =>
        {
            collectionMapping.Access(Accessor.Field),

            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}

// Option 3: No strings, but more convoluted.
public class Customer
{
    internal class PrivatePropertyAccessors
    {
        public static Expression<Func<Customer, IEnumerable<Order>>> OrdersProperty = c => c._orders;
    }

    private readonly IList<Order> _orders = new List<Order>();

    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }
}

public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag(Customer.PrivatePropertyAccessors.OrdersProperty, collectionMapping =>
        {
            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}
</code>```

Body:
What is the equivalent NHibernate Code Mapping for the following Fluent NHibernate code:

Map(x => x.Orders).Access.CamelCaseField(Prefix.Underscore);

I have spent all afternoon trying to get this to work.  Here is my code so far:

public class Customer
{
    private readonly IList<Order> _orders = new List<Order>();
    public virtual Guid ID { get; set; }
    public virtual string LastName { get; set; }
    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}

public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        Id<Guid>(x => x.Id);

        Component(x => x.LastName, y =>
        {
            y.Property<string>(z => z.LastName);
        });

        Bag(x => x._orders, collectionMapping =>
        {
            collectionMapping.Table("CustomerOrders");
            collectionMapping.Cascade(Cascade.None);
            collectionMapping.Key(k => k.Column("CustomerId"));
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}

This answers my question: https://groups.google.com/forum/#!topic/nhusers/wiH1DPGOhgU.  I have tried copying and pasting the code from my link (see below):

  this.Bag(
                    r => "privatefieldtomap",
                    map =>
                        {
                            map.Access(Access.Field);
                            map.Table("table");
                            map.Key(k => k.Column("foreignkey"));
                        },
                    r => r.Element(m => m.Column("columntomap")));

The error I get is: Bag cannot be inferred from the usage.

Body:
You have a couple of options to map a non-visible field by code.

Here are some, please note that I haven't tested them yet as written, but should help you anyways:

// Option 1:
public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag<Order>("_orders", collectionMapping =>
        {
            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}

// Option 2: No strings, but I'm not sure if this one would really work as is.
public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag(x => x.Orders, collectionMapping =>
        {
            collectionMapping.Access(Accessor.Field),

            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}

// Option 3: No strings, but more convoluted.
public class Customer
{
    internal class PrivatePropertyAccessors
    {
        public static Expression<Func<Customer, IEnumerable<Order>>> OrdersProperty = c => c._orders;
    }

    private readonly IList<Order> _orders = new List<Order>();

    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }
}

public class CustomerMap : ClassMapping<Customer>
{
    public CustomerMap()
    {
        // ...

        Bag(Customer.PrivatePropertyAccessors.OrdersProperty, collectionMapping =>
        {
            //...
        },
        map => map.ManyToMany(p => p.Column("OrderId")));
    }
}


问:
What's the problem in my code? c# winforms
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

```<code>namespace Login
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}
</code>```

Login form

```<code>namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}
</code>```

Where do you think I'm doing it wrong?
Thanks....

答:
Try This:-

namespace Login

{

static class Program

{
         ///
         /// The main entry point for the application.
        ///

```<code>   [STAThread]
   static void Main()
   {
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Login());
   }
</code>```

}

}

>

namespace Login
  {
     public partial class Login : Form
     {
         public Login()
          {
              InitializeComponent();
          }

```<code>    private void Login_Load(object sender, EventArgs e)
    {

    }

    private void btnLogin_Click(object sender, EventArgs e)
    {
        // initially btnLogin has a DialogResult property set to None
        Authenticate();
    }

    private void Authenticate()
    {
        SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
        conn.Open();
        SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
        cmd.Parameters.Add("username", txtUsername.Text.Trim());
        cmd.Parameters.Add("password", txtPassword.Text.Trim());

        SqlCeDataReader dr = cmd.ExecuteReader();
        bool hasRow = dr.Read();
        if (hasRow)
        {
            Main formmain = new Main();
            formmain.Show();
            this.Dispose(); // U can also use this.Close();
        }
    }
}
</code>```

}

Body:
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

namespace Login
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}

Login form

namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}

Where do you think I'm doing it wrong?
Thanks....

Body:
Try This:-

namespace Login

{

static class Program

{
         ///
         /// The main entry point for the application.
        ///

   [STAThread]
   static void Main()
   {
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Login());
   }

}

}

>

namespace Login
  {
     public partial class Login : Form
     {
         public Login()
          {
              InitializeComponent();
          }

    private void Login_Load(object sender, EventArgs e)
    {

    }

    private void btnLogin_Click(object sender, EventArgs e)
    {
        // initially btnLogin has a DialogResult property set to None
        Authenticate();
    }

    private void Authenticate()
    {
        SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
        conn.Open();
        SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
        cmd.Parameters.Add("username", txtUsername.Text.Trim());
        cmd.Parameters.Add("password", txtPassword.Text.Trim());

        SqlCeDataReader dr = cmd.ExecuteReader();
        bool hasRow = dr.Read();
        if (hasRow)
        {
            Main formmain = new Main();
            formmain.Show();
            this.Dispose(); // U can also use this.Close();
        }
    }
}

}


问:
How to make a NSStackView/UIStackView function like a float:left in css
I'm trying to make a breadcrumb navigation section in my macOS App, but I'm limited in width space because of other views that appear on the right. So I want to somehow wrap the items to the next line if I run out of room on the first line.

So this is the basic setup I'm trying.

The StackView is in horizontal orientation.

The StackView width is fixed.

Text fields get added to the stackview via addArragnedSubView() but their frame widths are variable, meaning not equal.

I've been playing with all the fill options and it seems like StackViews try to stretch and contract the views no matter what option you choose (by design most likely). Is it fair to say StackViews aren't meant for variable widths and view wrapping?

The concept is very similar to the float:left css attribute in Web that allows elements to continue to be "stuffed" to the left of a div for example. If that element can't "fit" on that row, it gets added on a new line.

答:
I think I understand what you are trying to to. Would a UICollectionView be a better fit for that? Maybe you could try something like:

https://github.com/riteshhgupta/TagCellLayout

Sounds like you are asking for something with more of a grid layout rather than what a UIStackView provides.


问:
Trying to write `map` using `foldr`
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

```<code>map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs
</code>```

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

答:
Recursing on the structure of the list with your custom map' is unlikely to give you an answer that your exam grader will be happy with, regardless of how you manipulate f. You will essentially end up using foldr in the most trivial way possible. To see why, note that the below is an implementation of map.

```<code>map f [] = []
-- Yes you could use (:) here, but this mirrors your example better
map f (x : xs) = [f x] ++ (map f xs)
</code>```

You're already done! No foldr necessary. If we preserved this approach, you would only use foldr to create [f x] which is rather boring (something like foldr (\_ _ -> [f x]) [] would suffice, see what I mean by boring?).

So really the key is to realize that foldr takes care of the recursion for you, or equivalently that foldr already does a list traversal for you.

One possible approach for intuition is to think of foldr as accumulating into another collection, rather than folding into a single element.

```<code>-- Hmmm well this just accumulates a list into another list,
-- resulting in an identical list
foldr (\x acc -> x : acc) xs
-- What if we changed x along the way?
foldr (\x acc -> (f x) : acc) xs -- This is it!
</code>```

If you're curious how to get to (:) . f, @Ben's answer does a great job of walking through it.

Title: Trying to write `map` using `foldr`

Body:
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

Body:
Recursing on the structure of the list with your custom map' is unlikely to give you an answer that your exam grader will be happy with, regardless of how you manipulate f. You will essentially end up using foldr in the most trivial way possible. To see why, note that the below is an implementation of map.

map f [] = []
-- Yes you could use (:) here, but this mirrors your example better
map f (x : xs) = [f x] ++ (map f xs)

You're already done! No foldr necessary. If we preserved this approach, you would only use foldr to create [f x] which is rather boring (something like foldr (\_ _ -> [f x]) [] would suffice, see what I mean by boring?).

So really the key is to realize that foldr takes care of the recursion for you, or equivalently that foldr already does a list traversal for you.

One possible approach for intuition is to think of foldr as accumulating into another collection, rather than folding into a single element.

-- Hmmm well this just accumulates a list into another list,
-- resulting in an identical list
foldr (\x acc -> x : acc) xs
-- What if we changed x along the way?
foldr (\x acc -> (f x) : acc) xs -- This is it!

If you're curious how to get to (:) . f, @Ben's answer does a great job of walking through it.


问:
Google assistant in other country - pause music
I live in Poland, where Google Assistant isn't allowed (operated) and I would like to write a simple script, which allow me to say: "Ok, google, muzyka stop". Next device will stop music play. Is it possible to write this in dialogflow or other system?</p>

答:
When creating apps for the Google Assistant I'd recommend staying away from use cases already covered by the Google Assistant. In this case controlling music is already covered by the Google Assistant and will already work with most music streaming providers.

If you'd like to add the Google Assistant to your device and add the option to control your device, a conversational building tool like Dialogflow is probably not the best tool.  You may want to consider adding the Google Assistant and voice controls to you device use the Google Assistant SDK.


问:
How to initialize tf.metrics members in TensorFlow?
The below is a part of my project code.

```<code>with tf.name_scope("test_accuracy"):
    test_mean_abs_err, test_mean_abs_err_op = tf.metrics.mean_absolute_error(labels=label_pl, predictions=test_eval_predict)
    test_accuracy, test_accuracy_op         = tf.metrics.accuracy(labels=label_pl, predictions=test_eval_predict)
    test_precision, test_precision_op       = tf.metrics.precision(labels=label_pl, predictions=test_eval_predict)
    test_recall, test_recall_op             = tf.metrics.recall(labels=label_pl, predictions=test_eval_predict)
    test_f1_measure = 2 * test_precision * test_recall / (test_precision + test_recall)
tf.summary.scalar('test_mean_abs_err', test_mean_abs_err)
tf.summary.scalar('test_accuracy', test_accuracy)
tf.summary.scalar('test_precision', test_precision)
tf.summary.scalar('test_recall', test_recall)
tf.summary.scalar('test_f1_measure', test_f1_measure)
# validation metric init op
validation_metrics_init_op = tf.variables_initializer(\
        var_list=[test_mean_abs_err_op, test_accuracy_op, test_precision_op, test_recall_op], \
        name='validation_metrics_init')
</code>```

However, when I run it, errors occur like this:

```<code>Traceback (most recent call last):
  File "./run_dnn.py", line 285, in <module>
    train(wnd_conf)
  File "./run_dnn.py", line 89, in train
    name='validation_metrics_init')
  File "/export/local/anaconda2/lib/python2.7/site-
packages/tensorflow/python/ops/variables.py", line 1176, in
variables_initializer
return control_flow_ops.group(*[v.initializer for v in var_list], name=name)
AttributeError: 'Tensor' object has no attribute 'initializer'
</code>```

I realize that I cannot create a validation initializer like that. I want to re-calculate the corresponding metrics when I save a new checkpoint model and apply a new round of validation. So, I have to re-initialize the metrics to be zero.

But how to reset all these metrics to be zero? Many thanks to your help!

答:
I sovled the problem in the following way after referring to the blog (Avoiding headaches with tf.metrics).</p>

```<code># validation metrics
validation_metrics_var_scope = "validation_metrics"
test_mean_abs_err, test_mean_abs_err_op = tf.metrics.mean_absolute_error(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_accuracy, test_accuracy_op         = tf.metrics.accuracy(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_precision, test_precision_op       = tf.metrics.precision(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_recall, test_recall_op             = tf.metrics.recall(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_f1_measure = 2 * test_precision * test_recall / (test_precision + test_recall)
tf.summary.scalar('test_mean_abs_err', test_mean_abs_err)
tf.summary.scalar('test_accuracy', test_accuracy)
tf.summary.scalar('test_precision', test_precision)
tf.summary.scalar('test_recall', test_recall)
tf.summary.scalar('test_f1_measure', test_f1_measure)
# validation metric init op
validation_metrics_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope=validation_metrics_var_scope)
validation_metrics_init_op = tf.variables_initializer(var_list=validation_metrics_vars, name='validation_metrics_init')
</code>```

Body:
The below is a part of my project code.

with tf.name_scope("test_accuracy"):
    test_mean_abs_err, test_mean_abs_err_op = tf.metrics.mean_absolute_error(labels=label_pl, predictions=test_eval_predict)
    test_accuracy, test_accuracy_op         = tf.metrics.accuracy(labels=label_pl, predictions=test_eval_predict)
    test_precision, test_precision_op       = tf.metrics.precision(labels=label_pl, predictions=test_eval_predict)
    test_recall, test_recall_op             = tf.metrics.recall(labels=label_pl, predictions=test_eval_predict)
    test_f1_measure = 2 * test_precision * test_recall / (test_precision + test_recall)
tf.summary.scalar('test_mean_abs_err', test_mean_abs_err)
tf.summary.scalar('test_accuracy', test_accuracy)
tf.summary.scalar('test_precision', test_precision)
tf.summary.scalar('test_recall', test_recall)
tf.summary.scalar('test_f1_measure', test_f1_measure)
# validation metric init op
validation_metrics_init_op = tf.variables_initializer(\
        var_list=[test_mean_abs_err_op, test_accuracy_op, test_precision_op, test_recall_op], \
        name='validation_metrics_init')

However, when I run it, errors occur like this:

Traceback (most recent call last):
  File "./run_dnn.py", line 285, in <module>
    train(wnd_conf)
  File "./run_dnn.py", line 89, in train
    name='validation_metrics_init')
  File "/export/local/anaconda2/lib/python2.7/site-
packages/tensorflow/python/ops/variables.py", line 1176, in
variables_initializer
return control_flow_ops.group(*[v.initializer for v in var_list], name=name)
AttributeError: 'Tensor' object has no attribute 'initializer'

I realize that I cannot create a validation initializer like that. I want to re-calculate the corresponding metrics when I save a new checkpoint model and apply a new round of validation. So, I have to re-initialize the metrics to be zero.

But how to reset all these metrics to be zero? Many thanks to your help!

Body:
I sovled the problem in the following way after referring to the blog (Avoiding headaches with tf.metrics).

# validation metrics
validation_metrics_var_scope = "validation_metrics"
test_mean_abs_err, test_mean_abs_err_op = tf.metrics.mean_absolute_error(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_accuracy, test_accuracy_op         = tf.metrics.accuracy(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_precision, test_precision_op       = tf.metrics.precision(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_recall, test_recall_op             = tf.metrics.recall(labels=label_pl, predictions=test_eval_predict, name=validation_metrics_var_scope)
test_f1_measure = 2 * test_precision * test_recall / (test_precision + test_recall)
tf.summary.scalar('test_mean_abs_err', test_mean_abs_err)
tf.summary.scalar('test_accuracy', test_accuracy)
tf.summary.scalar('test_precision', test_precision)
tf.summary.scalar('test_recall', test_recall)
tf.summary.scalar('test_f1_measure', test_f1_measure)
# validation metric init op
validation_metrics_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope=validation_metrics_var_scope)
validation_metrics_init_op = tf.variables_initializer(var_list=validation_metrics_vars, name='validation_metrics_init')


问:
BrowserDriver never restarts for each SERENITY CUCUMBER scenario
I want to have restarted my BrowserDriver for each serenity scenario runs. So every time new Driver will open for each scenario and closes the previous. But it never happens. In my framework, the browser keeps open and i don't want that. Here is my jar Versions i am using in POM.

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <serenity.version>1.1.36</serenity.version>
    <serenity.maven.version>1.1.36</serenity.maven.version>
    <serenity.cucumber.version>1.1.8</serenity.cucumber.version>
</properties>
</code>```

I am providing the versions, As this issue might be related with these versions.

Here is the serenity.properties file as well.

```<code>serenity.project.name=*****Sample Automation Project*****
Webdriver.driver=chrome
serenity.dry.run=false
serenity.logging=QUIET
</code>```

I have tried using this below property too:

```<code>serenity.restart.browser.for.each=scenario
</code>```

答:
I have resolved this problem and it was issue with Serenity jars. I have updated jars to use the latest and it resolved my issue. Now Serenity can re-instantiate the driver for each scenario.  </p>

```<code>    <serenity.version>1.8.1</serenity.version>
    <serenity.maven.version>1.8.0</serenity.maven.version>
    <serenity.cucumber.version>1.6.5</serenity.cucumber.version>
</code>```

Body:
I want to have restarted my BrowserDriver for each serenity scenario runs. So every time new Driver will open for each scenario and closes the previous. But it never happens. In my framework, the browser keeps open and i don't want that. Here is my jar Versions i am using in POM.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <serenity.version>1.1.36</serenity.version>
    <serenity.maven.version>1.1.36</serenity.maven.version>
    <serenity.cucumber.version>1.1.8</serenity.cucumber.version>
</properties>

I am providing the versions, As this issue might be related with these versions.

Here is the serenity.properties file as well.

serenity.project.name=*****Sample Automation Project*****
Webdriver.driver=chrome
serenity.dry.run=false
serenity.logging=QUIET

I have tried using this below property too:

serenity.restart.browser.for.each=scenario

Body:
I have resolved this problem and it was issue with Serenity jars. I have updated jars to use the latest and it resolved my issue. Now Serenity can re-instantiate the driver for each scenario.

    <serenity.version>1.8.1</serenity.version>
    <serenity.maven.version>1.8.0</serenity.maven.version>
    <serenity.cucumber.version>1.6.5</serenity.cucumber.version>


问:
"Exception in thread "main" java.lang.NumberFormatException:" followed by values in txt
so i just fixed an error then following that i got the exception error and not sure what to change to fix it.
i've looked at similar issues but none of them seemed to pertain to my specific problem.</p>

```<code>import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations
    String input;
    double total = 0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastname;
    String firstname;
    double minimum;
    double max;

//2) process rows
            while (sc.hasNextLine()) {
               input = sc.nextLine();
               System.out.println(input);

   //find total
               total += Double.parseDouble(input);  //compile error on using input
               count++;

               System.out.println(count); //test delete later
   //find average (decimal 2 points)
               System.out.println("hi"); //test
               average = (double)total / count;
               System.out.println("Average = " + average);

//3) class statistics

            }

     }
}
</code>```

答:
It's actually a runtime exception not a compile error.

The reason is because your Scanner is reading through the whole file, line by line, and is hitting something that cannot be parsed as a double.

```<code>// for each line in the file
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println(line);

    // split the line into pieces of data separated by the spaces
    String[] data = line.split();

    String firstName = null;
    String lastName = null;

    // get the name from data[]
    // if the array length is greater than or equal to 1
    // then it's safe to try to get something from the 1st index (0)
    if(data.length >= 1)
        firstName = data[0];
    if(data.length >= 2)
        lastName = data[1];

    // what is the meaning of the numbers?

    // get numbers
    Double d1 = null;
    if(data.length >= 3){
        try {
            d1 = Double.valueOf(data[2]);
        } catch (NumberFormatException e){
            // couldn't parse the 3rd piece of data into a double
        }
    }

    Double d2 = null;
    // do the same...

    // do something with 'firstName', 'lastName', and your numbers ...
}
</code>```

Body:
so i just fixed an error then following that i got the exception error and not sure what to change to fix it.
i've looked at similar issues but none of them seemed to pertain to my specific problem.

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class AAAAAA {
    public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
//1)
    Scanner sc = new Scanner(new File(fileName));

    //declarations
    String input;
    double total = 0;
    double num = 0;
    double count = 0;
    double average = 0;
    String lastname;
    String firstname;
    double minimum;
    double max;

//2) process rows
            while (sc.hasNextLine()) {
               input = sc.nextLine();
               System.out.println(input);

   //find total
               total += Double.parseDouble(input);  //compile error on using input
               count++;

               System.out.println(count); //test delete later
   //find average (decimal 2 points)
               System.out.println("hi"); //test
               average = (double)total / count;
               System.out.println("Average = " + average);

//3) class statistics

            }

     }
}

Body:
It's actually a runtime exception not a compile error.

The reason is because your Scanner is reading through the whole file, line by line, and is hitting something that cannot be parsed as a double.

// for each line in the file
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println(line);

    // split the line into pieces of data separated by the spaces
    String[] data = line.split();

    String firstName = null;
    String lastName = null;

    // get the name from data[]
    // if the array length is greater than or equal to 1
    // then it's safe to try to get something from the 1st index (0)
    if(data.length >= 1)
        firstName = data[0];
    if(data.length >= 2)
        lastName = data[1];

    // what is the meaning of the numbers?

    // get numbers
    Double d1 = null;
    if(data.length >= 3){
        try {
            d1 = Double.valueOf(data[2]);
        } catch (NumberFormatException e){
            // couldn't parse the 3rd piece of data into a double
        }
    }

    Double d2 = null;
    // do the same...

    // do something with 'firstName', 'lastName', and your numbers ...
}


问:
How can I manually add a Spring CacheInterceptor using Java Config?
I'm trying to work out how I can add caching to method calls on a third party Java class. I'm using Spring Boot for my application.

I've come up with this class in my attempts to get caching working.

```<code>package test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheOperation;
import org.springframework.cache.interceptor.CacheProxyFactoryBean;
import org.springframework.cache.interceptor.CacheableOperation;
import org.springframework.cache.interceptor.NameMatchCacheOperationSource;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

@SpringBootApplication
@EnableCaching
@Configuration
public class MyApp {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MyApp.class, args);
        Greeter greeter = context.getBean(Greeter.class);

        System.out.println(new Date() + " : " + greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));

        System.out.println(new Date() + " : " +greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));

        System.out.println(new Date() + " : " +greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));
    }

    @Bean
    public Greeter greeter() {
        final NameMatchCacheOperationSource nameMatchCacheOperationSource = new NameMatchCacheOperationSource();
        Collection<CacheOperation> cacheOperations = new HashSet<CacheOperation>();
        cacheOperations.add(new CacheableOperation.Builder().build());
        nameMatchCacheOperationSource.addCacheMethod("*", cacheOperations);

        CacheProxyFactoryBean cacheProxyFactoryBean = new CacheProxyFactoryBean();
        cacheProxyFactoryBean.setTarget(new MySlowGreeter());
        cacheProxyFactoryBean.setProxyInterfaces(new Class[] {Greeter.class});
        cacheProxyFactoryBean.setCacheOperationSources(nameMatchCacheOperationSource);
        cacheProxyFactoryBean.afterPropertiesSet();
        return (Greeter) cacheProxyFactoryBean.getObject();
    }

    interface Greeter {
        String getGreeting(String name);
    }

    class MySlowGreeter implements Greeter {
        public String getGreeting(String name) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello " + name;
        }
    }
}
</code>```

The hope is that I'd be able create a bean in my Spring config that wraps calls to Greeter.getGreeting(..) and returns cached results if they exist. However no caching is taking place.

Any ideas?

答:
You could simply create an Adapter/Wrapper class that delegates to the underlying 3rd party class type that you want to enable with caching.  Then, add  caching behavior to your application Adapter/Wrapper type instead.

That would be far easier to do than trying to determine the appropriate AOP Pointcut to intercept the method on the 3rd party class in which you want to advise with caching.  Of course, this approach won't work if you do not have a reference to a the object in which you want to introduce caching, in which case you will have to resort to AOP.

From your example, I get the impression that you may have a reference to this 3rd party object instance???

If not, please clarify and then I can help you with the AOP.

Body:
I'm trying to work out how I can add caching to method calls on a third party Java class. I'm using Spring Boot for my application.

I've come up with this class in my attempts to get caching working.

package test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheOperation;
import org.springframework.cache.interceptor.CacheProxyFactoryBean;
import org.springframework.cache.interceptor.CacheableOperation;
import org.springframework.cache.interceptor.NameMatchCacheOperationSource;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

@SpringBootApplication
@EnableCaching
@Configuration
public class MyApp {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MyApp.class, args);
        Greeter greeter = context.getBean(Greeter.class);

        System.out.println(new Date() + " : " + greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));

        System.out.println(new Date() + " : " +greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));

        System.out.println(new Date() + " : " +greeter.getGreeting("Bob"));
        System.out.println(new Date() + " : " +greeter.getGreeting("Fred"));
    }

    @Bean
    public Greeter greeter() {
        final NameMatchCacheOperationSource nameMatchCacheOperationSource = new NameMatchCacheOperationSource();
        Collection<CacheOperation> cacheOperations = new HashSet<CacheOperation>();
        cacheOperations.add(new CacheableOperation.Builder().build());
        nameMatchCacheOperationSource.addCacheMethod("*", cacheOperations);

        CacheProxyFactoryBean cacheProxyFactoryBean = new CacheProxyFactoryBean();
        cacheProxyFactoryBean.setTarget(new MySlowGreeter());
        cacheProxyFactoryBean.setProxyInterfaces(new Class[] {Greeter.class});
        cacheProxyFactoryBean.setCacheOperationSources(nameMatchCacheOperationSource);
        cacheProxyFactoryBean.afterPropertiesSet();
        return (Greeter) cacheProxyFactoryBean.getObject();
    }

    interface Greeter {
        String getGreeting(String name);
    }

    class MySlowGreeter implements Greeter {
        public String getGreeting(String name) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello " + name;
        }
    }
}

The hope is that I'd be able create a bean in my Spring config that wraps calls to Greeter.getGreeting(..) and returns cached results if they exist. However no caching is taking place.

Any ideas?


问:
How to enable support for the POPCNT instruction / intrinsic on my computer?
I tried to run the following program in my computer (Fedora 17 32bit). How can I enable my system to support the popcnt instruction for fast population count?

#include <stdio.h>
#include <nmmintrin.h>

int main(void)
{
    int pop = _mm_popcnt_u32(0xf0f0f0f0ULL);
    printf("pop = %d\n", pop);
    return 0;
}
```

<p>I compiled the program, and run it, but got the following exception:</p>

```[xiliu@xiliu tmp]$ gcc -Wall -march=corei7 -m32 -msse4.2 popcnt.c -o popcnt
[xiliu@xiliu tmp]$ ./popcnt
Illegal instruction (core dumped)
```

<p>The following is the information of my processor:</p>

```[xiliu@xiliu tmp]$ cat /proc/cpuinfo
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 15
model name  : Intel(R) Pentium(R) Dual  CPU  T2370  @ 1.73GHz
stepping    : 13
microcode   : 0xa4
cpu MHz     : 800.000
cache size  : 1024 KB
physical id : 0
siblings    : 2
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fdiv_bug    : no
hlt_bug     : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 10
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm
bogomips    : 3458.20
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

[... repeated for 2nd core ...]
```

答:
Your CPU does not support POPCNT. (see https://en.wikipedia.org/wiki/SSE4)
But you can use this free and open source tool, to detect if it is supported:
https://github.com/mgorny/cpuid2cpuflags

It returns for Intel Core i7-3770 for example

```<code>CPU_FLAGS_X86: aes avx f16c mmx mmxext pclmul popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3
</code>```

Body:
I tried to run the following program in my computer (Fedora 17 32bit). How can I enable my system to support the popcnt instruction for fast population count?

#include <stdio.h>
#include <nmmintrin.h>

int main(void)
{
    int pop = _mm_popcnt_u32(0xf0f0f0f0ULL);
    printf("pop = %d\n", pop);
    return 0;
}

I compiled the program, and run it, but got the following exception:

[xiliu@xiliu tmp]$ gcc -Wall -march=corei7 -m32 -msse4.2 popcnt.c -o popcnt
[xiliu@xiliu tmp]$ ./popcnt
Illegal instruction (core dumped)

The following is the information of my processor:

[xiliu@xiliu tmp]$ cat /proc/cpuinfo
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 15
model name  : Intel(R) Pentium(R) Dual  CPU  T2370  @ 1.73GHz
stepping    : 13
microcode   : 0xa4
cpu MHz     : 800.000
cache size  : 1024 KB
physical id : 0
siblings    : 2
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fdiv_bug    : no
hlt_bug     : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 10
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm
bogomips    : 3458.20
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

[... repeated for 2nd core ...]

Body:
Your CPU does not support POPCNT. (see https://en.wikipedia.org/wiki/SSE4)
But you can use this free and open source tool, to detect if it is supported:
https://github.com/mgorny/cpuid2cpuflags

It returns for Intel Core i7-3770 for example

CPU_FLAGS_X86: aes avx f16c mmx mmxext pclmul popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3


问:
How do I strip malicious HTML (XXS etc.) from content submissions?
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

答: Use mysql_stripslashes(), htmlspecialchars() and urldecode(), for integer values you can probably just int typecast.</p>


问:
Join two git repositories with sequential history
I had a git repository (call this repository A) for a project which is nearing public release. Over time, the repository has contained information which I would not like to make public (not passwords/SSH keys, but think similar). At one point in the past (when I thought we were nearing release), I created a new repository without the old history by running git clone --depth=1 (call this repository B). No development has occurred on repository A, but development continued on repository B. Now we are actually nearing release, and my boss would like to do this again, to create repository C.

I would like to join repositories A and B together to contain a single "legacy" repository containing the entire history from the beginning of the project to the first commit of repository C. The last commit of repository A and the first commit of repository B have the same hash. How can I create a new repository AB, which contains the entire history of the project, starting from the first commit of repository A to the last commit of repository B?

I have tried the following:

Adding repo B as a remote of repo A, then fetching and mergeing B/master into A/master; git just reports Already up-to-date., but HEAD and A/master remain at the last commit of repo A.

Adding repo A as a remote of repo B, then fetching and mergeing B/master into A/master, which git only allows if I use --allow-unrelated-histories. This just generates a giant merge conflict, with every file modified since the beginning of repo B listed as in conflict. I suppose if I could resolve all conflicts in favor of repo B, this would be an acceptable solution, but I'm not actually sure what the history tree would look like after this merge.

Is there any better way to do what I'm trying to accomplish?

答:
To join repo A and repo B together with sequential history, you can use below commands:

```<code>git clone <URL for repo A>
cd A
git remote add B <URL for repo B> -f
git reset --hard B/master
</code>```

In the local repo, local master branch contains all the sequential history. If you want to push the local repo to repo C, you can use below commands:

```<code>git remote set-url origin <URL for repo C>
git push -u origin master
</code>```

Body:
To join repo A and repo B together with sequential history, you can use below commands:

git clone <URL for repo A>
cd A
git remote add B <URL for repo B> -f
git reset --hard B/master

In the local repo, local master branch contains all the sequential history. If you want to push the local repo to repo C, you can use below commands:

git remote set-url origin <URL for repo C>
git push -u origin master


问:
Identify Required Placeholders in GCMLE Model
I have deployed a model a few weeks ago and I have lost track of which input features are required for the model (yes I know I should have kept better track of this).  When I run the following command

```<code>gcloud ml-engine predict \
--model $MODEL_NAME \
--version v1 \
--json-instances \
../test.json
</code>```

I get the following err:

```<code>{
  "error": "Prediction failed: Exception during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"input size does not match signature\")"
}
</code>```

I know that my issue is because there is some "required" placeholder that I have not included in my json request (test.json) but I cannot figure out any way to retroactively find out which placeholder is missing.

The issue is the same as this question where the poster was able to submit the prediction when he included the missing "threshold" tensor.

What would be the easiest way to look at the expected inputs for a given model?

答: Assuming you have the tensorflow graph associated with your Saved Model. If you can print the graph (print the protobuffer in text format) or visualize with a tool, you can see the "signature_def" field within your graph. That should tell you the inputs and the outputs for your graph. You can compare what tensors you are sending in your request against the inputs that the graph expects. </p>

Body:
I have deployed a model a few weeks ago and I have lost track of which input features are required for the model (yes I know I should have kept better track of this).  When I run the following command

gcloud ml-engine predict \
--model $MODEL_NAME \
--version v1 \
--json-instances \
../test.json

I get the following err:

{
  "error": "Prediction failed: Exception during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"input size does not match signature\")"
}

I know that my issue is because there is some "required" placeholder that I have not included in my json request (test.json) but I cannot figure out any way to retroactively find out which placeholder is missing.

The issue is the same as this question where the poster was able to submit the prediction when he included the missing "threshold" tensor.

What would be the easiest way to look at the expected inputs for a given model?


答: Strictly define which "innocent" html tags you are going to allow - like  or . Then run a regex to accept only those you want while rejecting all others.

Title: How do I strip malicious HTML (XXS etc.) from content submissions?

Body:
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

Body: Strictly define which "innocent" html tags you are going to allow - like <strong> or <em>. Then run a regex to accept only those you want while rejecting all others.


问:
How to implement paypal recurring payment in angular2
I want to implement paypal recurring payments using angular2. I have successfully included the button for express checkout which works perfectly, but i don't have an idea of the api to use for recurring payments.

When i try to use checkout.js with this code

```<code>paypal.billingPlan.create(billingPlanAttributes, function (error, billingPlan) {
...
})
</code>```

I get billingPlan is not defined. Has anybody done this successfully, please let me know.

答:
The correct way to do Recurring payment in REST API with Paypal is that you are required to have an active billing plans.

The orders are ;

Create Billing Plans

Update Billing Plans to Active

Call Billing Agreement.

In your cases, you need an active billing plans before calling the billing agreement. PayPal use the billing plans to define the billing agreement between buyer and seller.

Body:
I want to implement paypal recurring payments using angular2. I have successfully included the button for express checkout which works perfectly, but i don't have an idea of the api to use for recurring payments.

When i try to use checkout.js with this code

paypal.billingPlan.create(billingPlanAttributes, function (error, billingPlan) {
...
})

I get billingPlan is not defined. Has anybody done this successfully, please let me know.