问:
JavaScript: Simple subtraction returns NaN
I have a problem,
my collision detection function sometimes sets entity position to NaN.
When I open console (on chrome) position of entity and collision are valid numbers but subtracting them from each other sometimes returns NaN.

```<code>updateCollision = function(entity,rect) {
var a = entity.x - rect.x; // a = NaN , entity.x = 3117.2646499953607 , rect.x = 3296.976967651385
var b = entity.y - rect.y; // b = NaN , entity.y = 3024.105915848102 , rect.y = 3144.4270586199345

if( isNaN(a) ) // isNaN(a) = true
{
    console.log("not again >:("); // but console doesn't log
}

//the code continues but its not important
</code>```

screenshot of console:

So I am really confused, and don't know what to do with this issue.

答: I need to see more of your code, to see what is actually wrong, but surely NaN is a result of math operations on an undefined type, so take a good look if something is undefined

Body:
I have a problem,
my collision detection function sometimes sets entity position to NaN.
When I open console (on chrome) position of entity and collision are valid numbers but subtracting them from each other sometimes returns NaN.

updateCollision = function(entity,rect) {
var a = entity.x - rect.x; // a = NaN , entity.x = 3117.2646499953607 , rect.x = 3296.976967651385
var b = entity.y - rect.y; // b = NaN , entity.y = 3024.105915848102 , rect.y = 3144.4270586199345

if( isNaN(a) ) // isNaN(a) = true
{
    console.log("not again >:("); // but console doesn't log
}

//the code continues but its not important

screenshot of console:

So I am really confused, and don't know what to do with this issue.


来源: stackexchange

问:
Calculating the value of a unit in a game
I'm currently working on a game where each unit has a value for health, shields and agility as well as a certain number of six types of weapon.

e.g. Unit B has 2 lasers, 2 heavy lasers, and 1 missile launcher, no ion blaster, no heavy ion blaster, no nuclear missiles, 5 health, 2 shield, and 40 agility.

I have gone through a good 20 different algorithms trying to get MS Excel to balance these all these factors to give the ship a score. My current algorithm works great for some of the smaller units, but gets very unbalanced with the bigger units

Each ship has a damage value, where each type of weaponry is multiplied by the damage of that weapon and added together.

```<code>damage = weapon1*damage1 + weapon2*damage2 + ...
</code>```

The damage value is multiplied by health + 2*shield + 2*agility. Agility and shield are multiplied to give them weight over health (a unit cant lose health if it can't be hit). I also subtract the cost of the unit. So my current equation for one of my units looks like:

```<code>value = damage*(health + 2*shield + 2*agility) - 3*cost
</code>```

Here are some examples:

Unit 1 - 1 laser, 1 health, 93 agility, and costs 1. Total score is 233.

Unit 2 - 2 lasers, a missile launcher, and 3 health, but only 76 agility. Score is 200.

Unit 3 - 6 lasers, 30 health and 15 shields, 37 agility - scores 585.

I want the scores of unit 3 to be higher, but the scores for units 1 and 2 are pretty good. Can anyone suggest a better equation that will smooth out the values?

答:
I think a genetic programming algorithm is a good approach to solving the issue you describe. Genetic programming evolves an algorithm's computations through iteration to minimize a cost function. This is done by creating a set of "mutations" to apply to the algorithm, for instance your idea of decreasing by the cost of the unit as 3R could be one of the mutations. The cost function would be something that increases/decreases relative to the concept of balance. Mutations would be evaluated in light of this cost function. </p>

<p>See the book Programming Collective Intelligence for Python code to do this type of problem solving. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm currently working on a game where each unit has a value for health, shields and agility as well as a certain number of six types of weapon.

e.g. Unit B has 2 lasers, 2 heavy lasers, and 1 missile launcher, no ion blaster, no heavy ion blaster, no nuclear missiles, 5 health, 2 shield, and 40 agility.

I have gone through a good 20 different algorithms trying to get MS Excel to balance these all these factors to give the ship a score. My current algorithm works great for some of the smaller units, but gets very unbalanced with the bigger units

Each ship has a damage value, where each type of weaponry is multiplied by the damage of that weapon and added together.

damage = weapon1*damage1 + weapon2*damage2 + ...

The damage value is multiplied by health + 2*shield + 2*agility. Agility and shield are multiplied to give them weight over health (a unit cant lose health if it can't be hit). I also subtract the cost of the unit. So my current equation for one of my units looks like:

value = damage*(health + 2*shield + 2*agility) - 3*cost

Here are some examples:

Unit 1 - 1 laser, 1 health, 93 agility, and costs 1. Total score is 233.

Unit 2 - 2 lasers, a missile launcher, and 3 health, but only 76 agility. Score is 200.

Unit 3 - 6 lasers, 30 health and 15 shields, 37 agility - scores 585.

I want the scores of unit 3 to be higher, but the scores for units 1 and 2 are pretty good. Can anyone suggest a better equation that will smooth out the values?

Body:
I think a genetic programming algorithm is a good approach to solving the issue you describe. Genetic programming evolves an algorithm's computations through iteration to minimize a cost function. This is done by creating a set of "mutations" to apply to the algorithm, for instance your idea of decreasing by the cost of the unit as 3R could be one of the mutations. The cost function would be something that increases/decreases relative to the concept of balance. Mutations would be evaluated in light of this cost function.

See the book Programming Collective Intelligence for Python code to do this type of problem solving.


问:
Cursor position in relation to self.view
There are many answers to get cursor CGPoint within UITextView. But I need to find a position of cursor in relation to self.view (or phone screen borders). Is there a way to do so in Objective-C?</p>

答:
UIView has a convert(_:to:) method that does exactly that. It converts coordinates from the receiver coordinate space to another view coordinate space.

Here is an example:

Objective-C

```<code>UITextView *textView = [[UITextView alloc] initWithFrame:CGRectZero];
UITextRange *selectedTextRange = textView.selectedTextRange;
if (selectedTextRange != nil)
{
    // `caretRect` is in the `textView` coordinate space.
    CGRect caretRect = [textView caretRectForPosition:selectedTextRange.end];

    // Convert `caretRect` in the main window coordinate space.
    // Passing `nil` for the view converts to window base coordinates.
    // Passing any `UIView` object converts to that view coordinate space.
    CGRect windowRect = [textView convertRect:caretRect toView:nil];
}
else {
    // No selection and no caret in UITextView.
}
</code>```

Swift

```<code>let textView = UITextView()
if let selectedRange = textView.selectedTextRange
{
    // `caretRect` is in the `textView` coordinate space.
    let caretRect = textView.caretRect(for: selectedRange.end)

    // Convert `caretRect` in the main window coordinate space.
    // Passing `nil` for the view converts to window base coordinates.
    // Passing any `UIView` object converts to that view coordinate space.
    let windowRect = textView.convert(caretRect, to: nil)
}
else {
    // No selection and no caret in UITextView.
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
UIView has a convert(_:to:) method that does exactly that. It converts coordinates from the receiver coordinate space to another view coordinate space.

Here is an example:

Objective-C

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectZero];
UITextRange *selectedTextRange = textView.selectedTextRange;
if (selectedTextRange != nil)
{
    // `caretRect` is in the `textView` coordinate space.
    CGRect caretRect = [textView caretRectForPosition:selectedTextRange.end];

    // Convert `caretRect` in the main window coordinate space.
    // Passing `nil` for the view converts to window base coordinates.
    // Passing any `UIView` object converts to that view coordinate space.
    CGRect windowRect = [textView convertRect:caretRect toView:nil];
}
else {
    // No selection and no caret in UITextView.
}

Swift

let textView = UITextView()
if let selectedRange = textView.selectedTextRange
{
    // `caretRect` is in the `textView` coordinate space.
    let caretRect = textView.caretRect(for: selectedRange.end)

    // Convert `caretRect` in the main window coordinate space.
    // Passing `nil` for the view converts to window base coordinates.
    // Passing any `UIView` object converts to that view coordinate space.
    let windowRect = textView.convert(caretRect, to: nil)
}
else {
    // No selection and no caret in UITextView.
}


问:
C# SocketException doesn't get caught
i have a really weird sitation going on in my code. I'm developping a c# chat client-server application. When i close the server i want the client to be automatically closed. The client is reading from the TcpClient object using a StremReader. The client is in a while loop where it reads a line(StreamReader.ReadLine()) and then doing some operations with the line it reads.
When the serever gets closed, i also close the tcp connection server-side. So, i'm expecting the client to see a SocketException caused by the readline, catch it and exit. But the exception doesn't get caught!
Here's the client loop code:

```<code> while (true)
 {
     try
     {
          ricev = read.ReadLine();
     }
     catch(SocketException exc)
     {
         //It never gets in here
     }
     chat.Invoke(showMessage, ricev);
 }
</code>```

When i close the server, visual studio tells me that a "System.Net.Sockets.SocketException" first-chance exception was raised in System.dll, but i cannot catch it. Why does that happen? i also tried to catch any generic exception with a

```<code>catch
{
}
</code>```

block, but that doesn't work either.

Any help will be appreciated!

EDIT: after trying some more times, i actually found out that SocketException doesn't get raised at all. That's so weird, as i said in a comment, in the opposite situation, when the client gets closed before the server, the exception gets raised and i can canth it.
I don't really know what's going on....

答:
I've this problem before and turn's out that I've been activate "Break when CLR Exception thrown and didn't uncheck it back"

So,check of you didn't uncheck this feature by

Press Alt+Ctr + E
scroll down to Common Runtime Language Exception and make sure to uncheck "Thrown" Check box.
I hope this help you.

Title: C# SocketException doesn't get caught

Body:
i have a really weird sitation going on in my code. I'm developping a c# chat client-server application. When i close the server i want the client to be automatically closed. The client is reading from the TcpClient object using a StremReader. The client is in a while loop where it reads a line(StreamReader.ReadLine()) and then doing some operations with the line it reads.
When the serever gets closed, i also close the tcp connection server-side. So, i'm expecting the client to see a SocketException caused by the readline, catch it and exit. But the exception doesn't get caught!
Here's the client loop code:

 while (true)
 {
     try
     {
          ricev = read.ReadLine();
     }
     catch(SocketException exc)
     {
         //It never gets in here
     }
     chat.Invoke(showMessage, ricev);
 }

When i close the server, visual studio tells me that a "System.Net.Sockets.SocketException" first-chance exception was raised in System.dll, but i cannot catch it. Why does that happen? i also tried to catch any generic exception with a

catch
{
}

block, but that doesn't work either.

Any help will be appreciated!

EDIT: after trying some more times, i actually found out that SocketException doesn't get raised at all. That's so weird, as i said in a comment, in the opposite situation, when the client gets closed before the server, the exception gets raised and i can canth it.
I don't really know what's going on....


问:
Find All Classes with Selenium Python
Hi I want to know how I can get element by class name where every class partially same like

class = "cursor earn_pages_button profile_view_img_xxxx" where xxxx is undefined

I just want to get all images from this class name profile_view_img_xxxx

some where it is profile_view_img_32487 or profile_view_img_86732 or profile_view_img_3278324

答:
You can use this:

```<code>driver.find_elements_by_xpath("//*[contains(@class,"cursor earn_pages_button profile_view_img_")]").
</code>```

It will match all classes with that text. Just try to iterate through it using a for-loop.

Title: Find All Classes with Selenium Python

Body:
You can use this:

driver.find_elements_by_xpath("//*[contains(@class,"cursor earn_pages_button profile_view_img_")]").

It will match all classes with that text. Just try to iterate through it using a for-loop.

ContentLicense: CC BY-SA 4.0


问:
AJAX/prototype reset call
I have an AJAX / prototype related question. I have an AJAX call currently placed inline, in the onclick (i promise i'll move it out of there :) event, looking like this:

```<code>onclick="var pn = $('yards').value; $('inventory').update('Working...');
new Ajax.Updater('inventory','ajax.php?ac=checkInventory&productID='.$someproductid.'&yards='+pn,{method:'get', evalScripts: true, asynchronous: true, onComplete:function(tr){$('inventory').update(tr.responseText);}});"
</code>```

File called ajax.php then gets the data from $_GET[], displays a small text input field. When filled in and clicked on a submit button, it calls a function which reads the relevant data from the file, and prints a result on the screen. The purpose of all this code is inventory check.

So, when a user clicks on the "get inventory" button with the onclick defined as above, everything works nice, the user fills the yardage, the right result pops up, everybody happy. But what makes it less usable is the fact that in case a user wants to do another inventory check, the entire page needs to be refreshed. If it's not, then when clicking on "get inventory" button, the user will be getting the same result of the last check again, not the text input field.

So, my question is, how do I make that after one inventory check, the whole thing sort of resets itself so that the next time a user clicks on "get inventory" button, he'll be offered to fill the text input field again, and hence get the new result.

I'm sorry if I didn't make myself clear enough. I'm very new to AJAX and prototype, and this is my colleague's work I need to finish...Thanks!

答:
Since you've promised to move the code out of the onclick handler do:

```<code>var inv = $('inventory');

inv.update('Working...');

new Ajax.Request('ajax.php', {
    method:'get',
    parameters:{
        ac:'checkInventory',
        yards:$('yards').value
    },
    onSuccess: function(response)
        {
            inv.update(response.responseText);
        }
});
</code>```

Title: AJAX/prototype reset call

Body:
I have an AJAX / prototype related question. I have an AJAX call currently placed inline, in the onclick (i promise i'll move it out of there :) event, looking like this:

onclick="var pn = $('yards').value; $('inventory').update('Working...');
new Ajax.Updater('inventory','ajax.php?ac=checkInventory&productID='.$someproductid.'&yards='+pn,{method:'get', evalScripts: true, asynchronous: true, onComplete:function(tr){$('inventory').update(tr.responseText);}});"

File called ajax.php then gets the data from $_GET[], displays a small text input field. When filled in and clicked on a submit button, it calls a function which reads the relevant data from the file, and prints a result on the screen. The purpose of all this code is inventory check.

So, when a user clicks on the "get inventory" button with the onclick defined as above, everything works nice, the user fills the yardage, the right result pops up, everybody happy. But what makes it less usable is the fact that in case a user wants to do another inventory check, the entire page needs to be refreshed. If it's not, then when clicking on "get inventory" button, the user will be getting the same result of the last check again, not the text input field.

So, my question is, how do I make that after one inventory check, the whole thing sort of resets itself so that the next time a user clicks on "get inventory" button, he'll be offered to fill the text input field again, and hence get the new result.

I'm sorry if I didn't make myself clear enough. I'm very new to AJAX and prototype, and this is my colleague's work I need to finish...Thanks!

Body:
Since you've promised to move the code out of the onclick handler do:

var inv = $('inventory');

inv.update('Working...');

new Ajax.Request('ajax.php', {
    method:'get',
    parameters:{
        ac:'checkInventory',
        yards:$('yards').value
    },
    onSuccess: function(response)
        {
            inv.update(response.responseText);
        }
});


问:
Stop Rigidbody Movement/Rotation instantly after collision
I want my sphere to jump from one position to another but don't want it to translate afterward. I can't figure out how to do that. Here's my code:</p>

```<code>void Update()
{
    if (!thrown && ((Input.touchCount > 0
    && Input.GetTouch(0).phase == TouchPhase.Ended)
    || Input.GetMouseButtonDown(0)))
    {
        rb.isKinematic = false;
        rb.AddForce(new Vector3(0.0f, 15.0f, 5.0f) );
        thrown = true;
    }
}
</code>```

答:
There are many ways to make Object stop immediately after collison. I will give you two ways:

Method 1:

Set the velocity of the Rigidbody to 0 when you detect a collison.

If the object is also rotating, set the angularVelocity to 0 too.

```<code>void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Rigidbody rbdy = collision.gameObject.GetComponent<Rigidbody>();

        //Stop Moving/Translating
        rbdy.velocity = Vector3.zero;

        //Stop rotating
        rbdy.angularVelocity = Vector3.zero;
    }
}
</code>```

Method 2:

Use Physic Material to control the amount of friction during collison.

Go to Assets > Create > Physic Material

Change the Bounciness to 0.

Change the Dynamic and Static Frictions to values equals or more than 1.

Then attach it to the Material slot on your Collider.

Body:
I want my sphere to jump from one position to another but don't want it to translate afterward. I can't figure out how to do that. Here's my code:

void Update()
{
    if (!thrown && ((Input.touchCount > 0
    && Input.GetTouch(0).phase == TouchPhase.Ended)
    || Input.GetMouseButtonDown(0)))
    {
        rb.isKinematic = false;
        rb.AddForce(new Vector3(0.0f, 15.0f, 5.0f) );
        thrown = true;
    }
}

Body:
There are many ways to make Object stop immediately after collison. I will give you two ways:

Method 1:

Set the velocity of the Rigidbody to 0 when you detect a collison.

If the object is also rotating, set the angularVelocity to 0 too.

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Rigidbody rbdy = collision.gameObject.GetComponent<Rigidbody>();

        //Stop Moving/Translating
        rbdy.velocity = Vector3.zero;

        //Stop rotating
        rbdy.angularVelocity = Vector3.zero;
    }
}

Method 2:

Use Physic Material to control the amount of friction during collison.

Go to Assets > Create > Physic Material

Change the Bounciness to 0.

Change the Dynamic and Static Frictions to values equals or more than 1.

Then attach it to the Material slot on your Collider.


问:
jQuery on click event partially working
```<code>var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});
</code>```

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

答:
It seems there was a glitch with the syntax for

```<code>$("#SidebarToggle").on("click",function(){}).
</code>```

Replacing it with
 $("#SidebarToggle").click(function(){}) did the trick and now it's working perfectly.

Title: jQuery on click event partially working

Body:
var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

Body:
It seems there was a glitch with the syntax for

$("#SidebarToggle").on("click",function(){}).

Replacing it with
 $("#SidebarToggle").click(function(){}) did the trick and now it's working perfectly.


问:
What is the difference between "lea eax, [ebx + eax]" and "add eax, ebx" in x86-32 assembly?
GCC made me some assembly code, and inside theres this statement:

```<code>lea eax, [ebx+eax]
</code>```

(Intel Syntax)
Just curious, what would the difference between that, and:

```<code>add eax, ebx
</code>```

Be?

eax, and ebx contains return values from functions :)

```<code>mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]
</code>```

答:
In terms of the numeric result, there is no difference.

However, there is more to an instruction than the actual result that is stored in the destination register:

As aix pointed out, lea does not set the flags based on the result of the addition.  This is occasionally useful for instruction scheduling purposes.

There are also timing differences on some micro-architectures (early Atom cores); specifically, there are stalls involved in forwarding results between the arithmetic and address-generation units, and using either add or lea depending on context can eliminate these (very small) stalls.

Body:
GCC made me some assembly code, and inside theres this statement:

lea eax, [ebx+eax]

(Intel Syntax)
Just curious, what would the difference between that, and:

add eax, ebx

Be?

eax, and ebx contains return values from functions :)

mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]


问:
Upgrading from Ansi to Unicode version of Inno Setup (any disadvantages)
Are there any disadvantages of the Inno Setup Unicode version compared to the Ansi version?

Or what is the reason that still both versions are offered in parallel and not only the Unicode one is left?

Are there any potentials problems, when using the Unicode version for my existing Inno Setup project developed with the Ansi version?

答:
After the clear answer here that there is not a real reason to stay with the Ansi Inno Setup version, we switched the beta setup of our product to the Unicode version yesterday and did not see any problems in our own tests.

But one of our beta tester reported now today that this version crashes while creating a firewall exception with following code:

```<code>try
  FirewallObject := CreateOleObject('HNetCfg.FwAuthorizedApplication');
  FirewallObject.ProcessImageFileName := 'C:\Program Files (x86)\FS-FlightControl\FS-FlightControl.exe';
  FirewallObject.Name := 'FS-FlightControl';
  FirewallObject.Scope := NET_FW_SCOPE_ALL;
  FirewallObject.IpVersion := NET_FW_IP_VERSION_ANY;
  FirewallObject.Enabled := True;
  FirewallManager := CreateOleObject('HNetCfg.FwMgr');
  FirewallProfile := FirewallManager.LocalPolicy.CurrentProfile;
  FirewallProfile.AuthorizedApplications.Add(FirewallObject);
except
  Log('Error setting firewall exception: ' + GetExceptionMessage);
end;
</code>```

If this code is executed the setup crashes with

```<code>Exception code: 0xc0000005
Error offset: 0x0005584c
</code>```

in the Windows event log. I asked the beta tester to run the setup with "/LOG" parameter and there is no error shown there at all. Just the complete setup crashes.

To be sure it was the change from Ansi to Unicode causing this problem, we send the beta tester another identical build, just compiled with the Ansi version and no crash there.

So there seems to be some more (negative) side effects of the Unicode version.

We could not reproduce this issue ourselves, just one of our beta testers using this setup:
https://www.fs-flightcontrol.com/download/FS-FlightControl-Beta-InnoUnicode.exe
Just keep the firewall exception checked and it should crash somewhere near the end of the setup process.

Based on the setup log file the tester sent he has Windows version 10.0.14393. As I wrote no traces of this problem can be found in the log, it just crashes.

Body:
After the clear answer here that there is not a real reason to stay with the Ansi Inno Setup version, we switched the beta setup of our product to the Unicode version yesterday and did not see any problems in our own tests.

But one of our beta tester reported now today that this version crashes while creating a firewall exception with following code:

try
  FirewallObject := CreateOleObject('HNetCfg.FwAuthorizedApplication');
  FirewallObject.ProcessImageFileName := 'C:\Program Files (x86)\FS-FlightControl\FS-FlightControl.exe';
  FirewallObject.Name := 'FS-FlightControl';
  FirewallObject.Scope := NET_FW_SCOPE_ALL;
  FirewallObject.IpVersion := NET_FW_IP_VERSION_ANY;
  FirewallObject.Enabled := True;
  FirewallManager := CreateOleObject('HNetCfg.FwMgr');
  FirewallProfile := FirewallManager.LocalPolicy.CurrentProfile;
  FirewallProfile.AuthorizedApplications.Add(FirewallObject);
except
  Log('Error setting firewall exception: ' + GetExceptionMessage);
end;

If this code is executed the setup crashes with

Exception code: 0xc0000005
Error offset: 0x0005584c

in the Windows event log. I asked the beta tester to run the setup with "/LOG" parameter and there is no error shown there at all. Just the complete setup crashes.

To be sure it was the change from Ansi to Unicode causing this problem, we send the beta tester another identical build, just compiled with the Ansi version and no crash there.

So there seems to be some more (negative) side effects of the Unicode version.

We could not reproduce this issue ourselves, just one of our beta testers using this setup:
https://www.fs-flightcontrol.com/download/FS-FlightControl-Beta-InnoUnicode.exe
Just keep the firewall exception checked and it should crash somewhere near the end of the setup process.

Based on the setup log file the tester sent he has Windows version 10.0.14393. As I wrote no traces of this problem can be found in the log, it just crashes.


问:
Send-MailMessage - from parameter error?
I'm trying to send a mail using PowerShell  with below command:

```<code>powershell -command "& {Send-MailMessage -To "xxxxx@xx.com" -From "xxxx@domain.com" -SMTPServer xxx.xx.com -Subject "report" -Body "service is running"}"
</code>```

but I'm getting this error:

```
Send-MailMessage : A positional parameter cannot be found that accepts argument
'xxx@xx.com'.
At line:1 char:20
+ & {Send-MailMessage <<<<  -To "xxx@xx.com -From "xxx@xx.com -SMTPServer xxxx.xx.com -Subject "Daily report" -Body "service is running"}
    + CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SendMailMessage
```

答:
As others have already mentioned, your quoting is broken. You're trying to nest double quotes inside a double-quoted string without escaping them. The unescaped nested double quotes prematurely terminate your string, causing the error you observed.

The simplest fix for this problem is to replace the nested double quotes with single quotes, since you don't seem to be using variables in that command anyway:

```<code>powershell.exe -Command "& {Send-MailMessage -To 'xxxxx@xx.com' -From ..."
</code>```

If you want to keep using nested double quotes (e.g. because you have variables in your scriptblock, which wouldn't be expanded in single-quoted strings) you need to escape them. If you're running the command from outside PowerShell (e.g. from CMD) you can do so by using backslashes:

```<code>powershell.exe -Command "& {Send-MailMessage -To \"xxxxx@xx.com\" -From ..."
</code>```

If you're running the command from within PowerShell you need to escape the nested double quotes twice (once for PowerShell when it's parsing the commandline, and once for the actual command invocation):

```<code>powershell.exe -Command "& {Send-MailMessage -To \`"xxxxx@xx.com\`" -From ..."
</code>```

However, if you're actually running it from PowerShell you don't need the powershell.exe -Command in the first place. Just invoke Send-MailMessage directly:

```<code>Send-MailMessage -To "xxxxx@xx.com" -From ...
</code>```

Body:
I'm trying to send a mail using PowerShell  with below command:

powershell -command "& {Send-MailMessage -To "xxxxx@xx.com" -From "xxxx@domain.com" -SMTPServer xxx.xx.com -Subject "report" -Body "service is running"}"

but I'm getting this error:

Send-MailMessage : A positional parameter cannot be found that accepts argument
'xxx@xx.com'.
At line:1 char:20
+ & {Send-MailMessage <<<<  -To "xxx@xx.com -From "xxx@xx.com -SMTPServer xxxx.xx.com -Subject "Daily report" -Body "service is running"}
    + CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SendMailMessage

Body:
As others have already mentioned, your quoting is broken. You're trying to nest double quotes inside a double-quoted string without escaping them. The unescaped nested double quotes prematurely terminate your string, causing the error you observed.

The simplest fix for this problem is to replace the nested double quotes with single quotes, since you don't seem to be using variables in that command anyway:

powershell.exe -Command "& {Send-MailMessage -To 'xxxxx@xx.com' -From ..."

If you want to keep using nested double quotes (e.g. because you have variables in your scriptblock, which wouldn't be expanded in single-quoted strings) you need to escape them. If you're running the command from outside PowerShell (e.g. from CMD) you can do so by using backslashes:

powershell.exe -Command "& {Send-MailMessage -To \"xxxxx@xx.com\" -From ..."

If you're running the command from within PowerShell you need to escape the nested double quotes twice (once for PowerShell when it's parsing the commandline, and once for the actual command invocation):

powershell.exe -Command "& {Send-MailMessage -To \`"xxxxx@xx.com\`" -From ..."

However, if you're actually running it from PowerShell you don't need the powershell.exe -Command in the first place. Just invoke Send-MailMessage directly:

Send-MailMessage -To "xxxxx@xx.com" -From ...


问:
Recursive SQL Query·
I have the following relation:

CompanyInfo(company, role, employee)

What I'm trying to do is to find the shortest "path" between two employees.

Example

I need to find the distance between Joe and Peter.
Joe is the CEO of Company A, and a person named Alex is a board member.
Alex is the CEO of Company B, and Peter is a vice president at Company B. Then, the distance between Joe and Peter will be 2. If Joe and Peter had roles in the same company, it would be 1.

I need to solve this using recursive SQL. So far I've come up with the base case and the final select string, but I can't for the life of me figure out the recursive part.

```<code>WITH RECURSIVE shortest_path(c1,p1,c2,p2, path) AS (
  -- Basecase --
  SELECT c1.company, c1.person, c2.company, c2.person, array[c1.person, c2.person]
  FROM CompanyInfo c1
  INNER JOIN CompanyInfo c2 ON c1.company = c2.company
  WHERE c1.person = 'Joe'
  AND c1.person <> c2.person
UNION ALL
  -- Recursive --
  -- This is where I'm stuck.
)

SELECT p1, p2, array_length(path,1) -1 as distance
FROM shortest_path
WHERE p2 = 'Peter'
ORDER BY distance
LIMIT 1;
</code>```

Sample Data

```<code>CREATE TABLE CompanyInfo (
  company text,
  role text,
  employee text,
  primary key (company, role, employee)
);

insert into CompanyInfo values('Company A', 'CEO', 'Joe');
insert into CompanyInfo values('Company A', 'Board member', 'Alex');
insert into CompanyInfo values('Company B', 'CEO', 'Alex');
insert into CompanyInfo values('Company B', 'Board member', 'Peter');
</code>```

Expected Output

```<code>person 1 | person 2 | distance
Joe        Peter      2
</code>```

答:
Try this. Keep running till new employee can be added to the path.</p>

```<code>CREATE TABLE CompanyInfo (
  company text,
  role text,
  employee text,
  primary key (company, role, employee)
);

insert into CompanyInfo values('Company A', 'CEO', 'Joe');
insert into CompanyInfo values('Company A', 'Board member', 'Alex');
insert into CompanyInfo values('Company B', 'CEO', 'Alex');
insert into CompanyInfo values('Company B', 'Board member', 'Peter');

WITH RECURSIVE shortest_path(c1,p1,c2,p2, path) AS (
  -- Basecase --
  SELECT c1.company, c1.employee, c2.company, c2.employee, array[c1.employee, c2.employee]
  FROM CompanyInfo c1
  JOIN CompanyInfo c2 ON c1.company = c2.company
      AND c1.employee = 'Joe'
      AND c1.employee <> c2.employee
  UNION ALL
  -- Recursive --
  SELECT c1, p1, c3.company, c3.employee, path || c3.employee
  FROM shortest_path c1
  JOIN CompanyInfo c2 ON c1.p2 = c2.employee
  JOIN CompanyInfo c3 ON c3.company = c2.company
      AND NOT c3.employee = ANY (c1.path)
)

SELECT *, array_length(path,1) -1 as distance
FROM shortest_path
WHERE p2 = 'Peter'
ORDER BY distance
LIMIT 1;
</code>```

Title: Recursive SQL Query·

Body:
I have the following relation:

CompanyInfo(company, role, employee)

What I'm trying to do is to find the shortest "path" between two employees.

Example

I need to find the distance between Joe and Peter.
Joe is the CEO of Company A, and a person named Alex is a board member.
Alex is the CEO of Company B, and Peter is a vice president at Company B. Then, the distance between Joe and Peter will be 2. If Joe and Peter had roles in the same company, it would be 1.

I need to solve this using recursive SQL. So far I've come up with the base case and the final select string, but I can't for the life of me figure out the recursive part.

WITH RECURSIVE shortest_path(c1,p1,c2,p2, path) AS (
  -- Basecase --
  SELECT c1.company, c1.person, c2.company, c2.person, array[c1.person, c2.person]
  FROM CompanyInfo c1
  INNER JOIN CompanyInfo c2 ON c1.company = c2.company
  WHERE c1.person = 'Joe'
  AND c1.person <> c2.person
UNION ALL
  -- Recursive --
  -- This is where I'm stuck.
)

SELECT p1, p2, array_length(path,1) -1 as distance
FROM shortest_path
WHERE p2 = 'Peter'
ORDER BY distance
LIMIT 1;

Sample Data

CREATE TABLE CompanyInfo (
  company text,
  role text,
  employee text,
  primary key (company, role, employee)
);

insert into CompanyInfo values('Company A', 'CEO', 'Joe');
insert into CompanyInfo values('Company A', 'Board member', 'Alex');
insert into CompanyInfo values('Company B', 'CEO', 'Alex');
insert into CompanyInfo values('Company B', 'Board member', 'Peter');

Expected Output

person 1 | person 2 | distance
Joe        Peter      2

Body:
Try this. Keep running till new employee can be added to the path.

CREATE TABLE CompanyInfo (
  company text,
  role text,
  employee text,
  primary key (company, role, employee)
);

insert into CompanyInfo values('Company A', 'CEO', 'Joe');
insert into CompanyInfo values('Company A', 'Board member', 'Alex');
insert into CompanyInfo values('Company B', 'CEO', 'Alex');
insert into CompanyInfo values('Company B', 'Board member', 'Peter');

WITH RECURSIVE shortest_path(c1,p1,c2,p2, path) AS (
  -- Basecase --
  SELECT c1.company, c1.employee, c2.company, c2.employee, array[c1.employee, c2.employee]
  FROM CompanyInfo c1
  JOIN CompanyInfo c2 ON c1.company = c2.company
      AND c1.employee = 'Joe'
      AND c1.employee <> c2.employee
  UNION ALL
  -- Recursive --
  SELECT c1, p1, c3.company, c3.employee, path || c3.employee
  FROM shortest_path c1
  JOIN CompanyInfo c2 ON c1.p2 = c2.employee
  JOIN CompanyInfo c3 ON c3.company = c2.company
      AND NOT c3.employee = ANY (c1.path)
)

SELECT *, array_length(path,1) -1 as distance
FROM shortest_path
WHERE p2 = 'Peter'
ORDER BY distance
LIMIT 1;


问:
Add description to each dropdown options dynamically in Django-widget-tweaks form
I have this form select dropdown, rendered using Django-tweak's render_field.
In my template, I have this form like so:

```<code><form method="POST" action="" class="org-member-edit" id='organization_permissions' data-parsley-validate>

    {% csrf_token %}

    <div class="form-group member-role{% if org_role_form.org_role.errors %} has-error{% endif %}">

        <label class="control-label" for="{{ org_role_form.org_role.id_for_label }}">{% trans "Role" %}</label>

    {% render_field org_role_form.org_role class+="form-control" data-parsley-required="true" %}

        <div class="error-block">{{ org_role_form.org_role.errors }}</div>

   </div>

</form>
</code>```

in the 5th line above, i.e the render_field org_role_form.org_role in the template tag, the org_role takes up values from the following form:

```<code>class EditOrganizationMemberForm(SuperUserCheck, forms.Form):

    org_role = forms.ChoiceField(choices=ADMIN_CHOICES)
</code>```

which takes choice fields from another file choices.py like so:

```<code>ADMIN_CHOICES = (
             ('A', _('Administrator')),
             ('M', _('Member'))
            )
</code>```

and so the dropdown looks like:

I want it to look something like this:

When I inspect the element (dev tools in browser), I can see that this select option gets rendered up like this:

so, I tried attempting for the solution using jQuery like so:

```<code>$('#id_org_role option').each( function(){
  if ($(this).val() == 'M') {
    $(this).text().append("<br/> description here");
  }
  else if ($(this).val() == 'A'){
    $(this).text().append("<br/> description here");
  }
});
</code>```

But it didnt help. however, If I do:

```<code>$('#id_org_role option').each( function(){
  if ($(this).val() == 'M') {
    alert($(this).val());
  }
});
</code>```

it works,and generates an alert with value 'M' which means the code is running correclty till and after if statement but for appending the text, it doesn't work.

I am really stuck. please help.

答:
So, here's how I resolved the whole thing using jquery-select2 as suggested by Rory in the comments:

First, include all the necessary select2 files inside the template:

```<code>{% block extra_head %}
<link href="https://select2.github.io/css/bootstrap.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/dist/css/select2.min.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/css/font-awesome.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/css/s2-docs.css" type="text/css" rel="stylesheet" />
{% endblock %}

{% block extra_script %}
<script type="text/javascript" src="https://select2.github.io/vendor/js/jquery.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/dist/js/select2.full.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/prettify.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/anchor.min.js"></script>
</code>```

then inside the JavaScript block above, under the last file included, add the following jQuery to define a width and add a title attribute for each option like so:

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

  $('select').each(function(){
    $(this).css('width','250px');
  }); //give a width to each dropdown.

  $('select option').each(function(){
    if($(this).val() === 'M'){
      $(this).attr('title','Members can view all the public projects in the organization. Additional permissions are assigned on a project level.');
    }
    else if ($(this).val() === 'A') {
      $(this).attr('title','Administrators have full access to all organizational details and projects.');
    }
    else if ($(this).val() === 'Pb') {
      $(this).attr('title','Members can view all public project data.');
    }
    else if ($(this).val() === 'PU') {
      $(this).attr('title','Members can view both public and private project data.');
    }
    else if ($(this).val() === 'DC') {
      $(this).attr('title','Members can access all project data and upload any field data.');
    }
    else if ($(this).val() === 'PM') {
      $(this).attr('title','Members can edit all project data.');
    }
  }); // add title attributes for each dropdown option.
</code>```

Then include the Select2 code to add the description for each option under the above jQuery code like so:

```<code>function formatOption (option) {
  var $option = $(
    '<div><strong>' + option.text + '</strong></div><div>' + option.title + '</div>'
// takes each option's title, and makes it appear as description just below it.
  );
  return $option;
};

$("select").select2({
  templateResult: formatOption,
  minimumResultsForSearch: -1 // hides the default select2 search bar
});
</code>```

then close the extra_script block tag:

```<code>{% endblock %}
</code>```

and that's all.

Body:
I have this form select dropdown, rendered using Django-tweak's render_field.
In my template, I have this form like so:

<form method="POST" action="" class="org-member-edit" id='organization_permissions' data-parsley-validate>

    {% csrf_token %}

        {% trans "Role" %}

    {% render_field org_role_form.org_role class+="form-control" data-parsley-required="true" %}

{{ org_role_form.org_role.errors }}

</form>

in the 5th line above, i.e the render_field org_role_form.org_role in the template tag, the org_role takes up values from the following form:

class EditOrganizationMemberForm(SuperUserCheck, forms.Form):

    org_role = forms.ChoiceField(choices=ADMIN_CHOICES)

which takes choice fields from another file choices.py like so:

ADMIN_CHOICES = (
             ('A', _('Administrator')),
             ('M', _('Member'))
            )

and so the dropdown looks like:

I want it to look something like this:

When I inspect the element (dev tools in browser), I can see that this select option gets rendered up like this:

so, I tried attempting for the solution using jQuery like so:

$('#id_org_role option').each( function(){
  if ($(this).val() == 'M') {
    $(this).text().append("
 description here");
  }
  else if ($(this).val() == 'A'){
    $(this).text().append("
 description here");
  }
});

But it didnt help. however, If I do:

$('#id_org_role option').each( function(){
  if ($(this).val() == 'M') {
    alert($(this).val());
  }
});

it works,and generates an alert with value 'M' which means the code is running correclty till and after if statement but for appending the text, it doesn't work.

I am really stuck. please help.

Body:
So, here's how I resolved the whole thing using jquery-select2 as suggested by Rory in the comments:

First, include all the necessary select2 files inside the template:

{% block extra_head %}
<link href="https://select2.github.io/css/bootstrap.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/dist/css/select2.min.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/css/font-awesome.css" type="text/css" rel="stylesheet" />
<link href="https://select2.github.io/css/s2-docs.css" type="text/css" rel="stylesheet" />
{% endblock %}

{% block extra_script %}
<script type="text/javascript" src="https://select2.github.io/vendor/js/jquery.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/dist/js/select2.full.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/prettify.min.js"></script>
<script type="text/javascript" src="https://select2.github.io/vendor/js/anchor.min.js"></script>

then inside the JavaScript block above, under the last file included, add the following jQuery to define a width and add a title attribute for each option like so:

$(document).ready(function(){

  $('select').each(function(){
    $(this).css('width','250px');
  }); //give a width to each dropdown.

  $('select option').each(function(){
    if($(this).val() === 'M'){
      $(this).attr('title','Members can view all the public projects in the organization. Additional permissions are assigned on a project level.');
    }
    else if ($(this).val() === 'A') {
      $(this).attr('title','Administrators have full access to all organizational details and projects.');
    }
    else if ($(this).val() === 'Pb') {
      $(this).attr('title','Members can view all public project data.');
    }
    else if ($(this).val() === 'PU') {
      $(this).attr('title','Members can view both public and private project data.');
    }
    else if ($(this).val() === 'DC') {
      $(this).attr('title','Members can access all project data and upload any field data.');
    }
    else if ($(this).val() === 'PM') {
      $(this).attr('title','Members can edit all project data.');
    }
  }); // add title attributes for each dropdown option.

Then include the Select2 code to add the description for each option under the above jQuery code like so:

function formatOption (option) {
  var $option = $(
    '<div><strong>' + option.text + '</strong></div><div>' + option.title + '</div>'
// takes each option's title, and makes it appear as description just below it.
  );
  return $option;
};

$("select").select2({
  templateResult: formatOption,
  minimumResultsForSearch: -1 // hides the default select2 search bar
});

then close the extra_script block tag:

{% endblock %}

and that's all.


问:
Algorithm with maximum flow in one-way directed graph
Thank you for attention. I have a problem with the following task.

There are n vertices and we have (n * (n-1)) / 2 connections between vertices,  i.e. if we have a graph of 3 vertices, they are connected: 1-> 2 1-> 3 2-> 3. If 4 vertices are connected: 1 -> 2 1-> 3 1-> 4 2-> 3 2-> 4 3-> 4.

P is the number of places in the train, n are the number of cities we have to visit.

We also have data on the number of passengers (Wi) who are willing to travel and the price of the ticket (Vi).

I need to find a way to get the highest amount for tickets sold.

Example

Input: P = 40 n = 3 W1 = 20 v1 = 2 W2 = 50 v2 = 3 W3 = 30 v3 = 3

Output: 160 (20x2, 10x3, 30x3).

Only maximum flow must be corrected because there are many solutions of paths. I was thinking of the Edmond Carp algorithm.

Can you present some ideas?

答: I think about algorithm Busackera-Gowena. Can this be a good choice?</p>


问:
Custom contact form does not work Yii2
I tried to redo the default contact form to form that sends a message and save it to database table. But something went wrong and i can't realize why.I already made same register form without problems and it is working good. Can you guys give me advance? Where is my mistake?

ContactForm model:

```<code><?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * This is the model class for table 'users_messages'.
 *
 * @params int $message_id
 * @params string $message_title
 * @params string $message_content
 * @params string $message_author
 * @params int $user_id
 */
class ContactForm extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author'], 'required']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
           'message_title' => 'Title',
           'message_author' => 'Author',
           'message_content' => 'Content'
        ];
    }
}
</code>```

actionContact:

```<code>/**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        $message = new UsersMessages();

        if(isset($_POST['send_message']))
        {
            $model->attributes = $_POST['ContactForm'];

            if($model->validate())
            {
                $message->message_author = $model->message_author;
                $message->message_title = $model->message_title;
                $message->message_content = $model->message_content;

                $message->save();

                return $this->refresh();
            }
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }
</code>```

When i debug actionContact it shows me that there is not data in $model->message_author, title and content.

Thank you in advance!

EDIT: with the advices of Brizkey i've reached this point:
actionContact:

```<code>public function actionContact()
    {
        $model = new UsersMessages();

        if($model->load($_POST) && $model->save())
        {
            return $this->redirect('contact');
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }
</code>```

and left only one model:
UserMessages model:

```<code><?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "users_messages".
 *
 * @property int $message_id
 * @property string $message_title
 * @property string $message_content
 * @property string $message_author
 * @property int $user_id
 *
 * @property Users $user
 */
class UsersMessages extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author', 'user_id'], 'required'],
            [['message_content'], 'string'],
            [['user_id'], 'integer'],
            [['message_title'], 'string', 'max' => 100],
            [['message_author'], 'string', 'max' => 50],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'message_id' => 'Message ID',
            'message_title' => 'Title:',
            'message_content' => 'Content:',
            'message_author' => 'Author:',
            'user_id' => 'User ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Users::className(), ['id' => 'user_id']);
    }
}
</code>```

The problem is in the $model->save() part. It can't pass through it!

EDIT-2: I reached some success(if i can call it like that)! Gave the save() method param of false. Result of this action was:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (anthonyl_fbpj.comments, CONSTRAINT fk_comments_projects1 FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE NO ACTION ON UPDATE NO ACTION)

From this error i understood that the problem is with the foreign_key. So i removed it and all flows good now! (I removed it because i realized that i do not need it in my situation)

答:
There are some things here to correct / be explained.

There is model called ContactForm that is the Active Record for users_messages table. So what is UsersMessages model and what does it do?

If I guess correctly and these two models are doing the same thing just remove one ot at least extend ContactForm from UsersMessages.

There is method load() that will take care of checking if $_POST is populated with data and on top of it will verify if data can be validated so only attributes with validation rules can be assigned - use it instead of assigning attributes directly with POST data.

With only one model taking care of processing the data from the form you don't have to assign attributes again by hand which you are doing here - safer and less places to make mistake.

I've seen this a lot on Stack Overflow - you guys don't check if save() is successful - WHY? This can go wrong, don't ever assume it's always true.

Without knowing this other model I cannot say for sure what is going on here. Maybe validation of $message went wrong. You need to check it first.

Hopefully with all the points above you can fix it.

Title: Custom contact form does not work Yii2

Body:
I tried to redo the default contact form to form that sends a message and save it to database table. But something went wrong and i can't realize why.I already made same register form without problems and it is working good. Can you guys give me advance? Where is my mistake?

ContactForm model:

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;

/**
 * This is the model class for table 'users_messages'.
 *
 * @params int $message_id
 * @params string $message_title
 * @params string $message_content
 * @params string $message_author
 * @params int $user_id
 */
class ContactForm extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author'], 'required']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
           'message_title' => 'Title',
           'message_author' => 'Author',
           'message_content' => 'Content'
        ];
    }
}

actionContact:

/**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        $message = new UsersMessages();

        if(isset($_POST['send_message']))
        {
            $model->attributes = $_POST['ContactForm'];

            if($model->validate())
            {
                $message->message_author = $model->message_author;
                $message->message_title = $model->message_title;
                $message->message_content = $model->message_content;

                $message->save();

                return $this->refresh();
            }
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }

When i debug actionContact it shows me that there is not data in $model->message_author, title and content.

Thank you in advance!

EDIT: with the advices of Brizkey i've reached this point:
actionContact:

public function actionContact()
    {
        $model = new UsersMessages();

        if($model->load($_POST) && $model->save())
        {
            return $this->redirect('contact');
        }

        return $this->render('contact', [
            'model' => $model,
        ]);
    }

and left only one model:
UserMessages model:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "users_messages".
 *
 * @property int $message_id
 * @property string $message_title
 * @property string $message_content
 * @property string $message_author
 * @property int $user_id
 *
 * @property Users $user
 */
class UsersMessages extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users_messages';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_title', 'message_content', 'message_author', 'user_id'], 'required'],
            [['message_content'], 'string'],
            [['user_id'], 'integer'],
            [['message_title'], 'string', 'max' => 100],
            [['message_author'], 'string', 'max' => 50],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'message_id' => 'Message ID',
            'message_title' => 'Title:',
            'message_content' => 'Content:',
            'message_author' => 'Author:',
            'user_id' => 'User ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Users::className(), ['id' => 'user_id']);
    }
}

The problem is in the $model->save() part. It can't pass through it!

EDIT-2: I reached some success(if i can call it like that)! Gave the save() method param of false. Result of this action was:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (anthonyl_fbpj.comments, CONSTRAINT fk_comments_projects1 FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE NO ACTION ON UPDATE NO ACTION)

From this error i understood that the problem is with the foreign_key. So i removed it and all flows good now! (I removed it because i realized that i do not need it in my situation)


问:
ASP.NET MVC Check state for just some properties
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

```<code>public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}
</code>```

In my ModifyAccount view, i have 2 form:

```<code>@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}
</code>```

And this is my Model

```<code>public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }
</code>```

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

答:
Create a dedicated view model for update password:

```<code>public class ModifyPasswordViewModel
{
    [Display(Name = "Mật khẩu cũ")]
    [Required]
    public string OldPassword { get; set; }

    [Display(Name = "Mật khẩu mới")]
    [Required]
    public string NewPassword { get; set; }

    [Display(Name = "Xác nhận mật khẩu mới")]
    [Required]
    [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
    public string NewPasswordConfirm { get; set; }
}
</code>```

Create a partial view  _ModifyPasswordViewModel.cshtml. Since you display multiple views on the same page, I would use Ajax.BeginForm instead of Html.BeginForm just for modifying password via ajax and not via full form post.

_ModifyPasswordViewModel.cshtml:

```<code>@model ModifyPasswordViewModel

@using (Ajax.BeginForm("ModifyPassword", "Account", new AjaxOptions { OnSuccess = "changePasswordSuccess"}))
{
    <div class="form-group">
       @Html.LabelFor(m=>m.OldPassword)
       @Html.PasswordFor(m=>m.OldPassword)
       @Html.ValidationMessageFor(m=>m.OldPassword)
    </div>
    ...
}
</code>```

In your main view render partial:

```<code><div id="changePassword-container">
  @{Html.RenderPartial("_ModifyPasswordViewModel", new ModifyPasswordViewModel());}
<div/>
</code>```

Controller action:

```<code>[HttpPost]
public ActionResult ModifyPassword(ModifyPasswordViewModel model)
{
     if ( this.ModelState.IsValid )
     {
        ...
     }
}
</code>```

P.S. in order for client side validation to work you need to include jquery.validate.js and jquery.validate.unobtrusive.js in the view (layout page) and to enable it in web config:

```<code><configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>
</code>```

Body:
I'm new to MVC and I'm facing this problem.

I'm designing a view that allows user to modify their profile and password in 2 different forms.

This is my main action:

public ActionResult ModifyAccount()
{
    User user = this._userManager.FindById(User.Identity.GetUserId());
    ViewBag.User = user;
    return View(new AccountViewModel
    {
        User = user
    });
}

In my ModifyAccount view, i have 2 form:

@using (Html.BeginForm("ModifyPassword", "Account", FormMethod.Post))
{
    // Change password
}

@using (Html.BeginForm("ModifyProfile", "Account", FormMethod.Post))
{
    // Change profile
}

And this is my Model

public class AccountViewModel
    {
        public User User { get; set; } // For change profile

        // For change password
        [Display(Name = "Mật khẩu cũ")]
        public string OldPassword { get; set; }
        [Display(Name = "Mật khẩu mới")]
        public string NewPassword { get; set; }
        [Display(Name = "Xác nhận mật khẩu mới")]
        [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
        public string NewPasswordConfirm { get; set; }
    }

I know that when we use ModelState.IsValid, the whole model will be validated. What I want is if the user submits the ModifyPassword form, only 3 properties OldPassword, NewPassword, NewPasswordConfirm will be validated. Please help, thank you!

Body:
Create a dedicated view model for update password:

public class ModifyPasswordViewModel
{
    [Display(Name = "Mật khẩu cũ")]
    [Required]
    public string OldPassword { get; set; }

    [Display(Name = "Mật khẩu mới")]
    [Required]
    public string NewPassword { get; set; }

    [Display(Name = "Xác nhận mật khẩu mới")]
    [Required]
    [Compare("NewPassword", ErrorMessage = "Mật khẩu xác nhận không trùng khớp")]
    public string NewPasswordConfirm { get; set; }
}

Create a partial view  _ModifyPasswordViewModel.cshtml. Since you display multiple views on the same page, I would use Ajax.BeginForm instead of Html.BeginForm just for modifying password via ajax and not via full form post.

_ModifyPasswordViewModel.cshtml:

@model ModifyPasswordViewModel

@using (Ajax.BeginForm("ModifyPassword", "Account", new AjaxOptions { OnSuccess = "changePasswordSuccess"}))
{
    <div class="form-group">
       @Html.LabelFor(m=>m.OldPassword)
       @Html.PasswordFor(m=>m.OldPassword)
       @Html.ValidationMessageFor(m=>m.OldPassword)
    </div>
    ...
}

In your main view render partial:

<div id="changePassword-container">
  @{Html.RenderPartial("_ModifyPasswordViewModel", new ModifyPasswordViewModel());}
<div/>

Controller action:

[HttpPost]
public ActionResult ModifyPassword(ModifyPasswordViewModel model)
{
     if ( this.ModelState.IsValid )
     {
        ...
     }
}

P.S. in order for client side validation to work you need to include jquery.validate.js and jquery.validate.unobtrusive.js in the view (layout page) and to enable it in web config:

<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>


问:
SerializationException when setting instance of one class to another
I'm trying to pass an instance of a class between two separate classes, like the following.

```<code>//classes
public class A
{
  public string name;
  public string data;
}

public class B : MarshalByRefObject
{
  public A _a;
}

public class C : MarshalByRefObject
{
  public A _a;
}

//main program
static void Main(string[] args)
{
  B _b = new B();
  C _c = new C();

  _b._a = new A();

  _c._a = _b._a;
}
</code>```

A exists in both classes B and C and I want to make the instance of class A that is in C equal to that instance of class A that is in B.  I basically want to make sure that both B and C have the same exact copy of A.

When I try to run this, however, I get a SerializationException saying that class A is not marked as Serializable.  I know I've done stuff like this before and it's never wanted it to be serialized.  Why would it need this anyways?  I thought that was for xml serialization.

I did try adding the [Serializable] attribute to class A, and the exception obviously went away.  But after doing that, making changes to A inside of class B wouldn't then propagate to the instance of A inside of C... like they are now completely separate copies.

Any ideas?

Edit:  Didn't realize that this would matter before, but after some looking around I think it does.  Classes B and C inherit from the MarshalByRefObject class.  Maybe this will help figure it out.  I've updated the classes above.

答:
I recently had a similar issue (ensuring a singleton boxed valuetype after deserialization).

To remedy my issue, I had to use ISerializationSurrogate and SurrogateSelector to fix up the reference and not let it get reboxed.

OwnerDisplayName: Adam Haile

Body:
I'm trying to pass an instance of a class between two separate classes, like the following.

//classes
public class A
{
  public string name;
  public string data;
}

public class B : MarshalByRefObject
{
  public A _a;
}

public class C : MarshalByRefObject
{
  public A _a;
}

//main program
static void Main(string[] args)
{
  B _b = new B();
  C _c = new C();

  _b._a = new A();

  _c._a = _b._a;
}

A exists in both classes B and C and I want to make the instance of class A that is in C equal to that instance of class A that is in B.  I basically want to make sure that both B and C have the same exact copy of A.

When I try to run this, however, I get a SerializationException saying that class A is not marked as Serializable.  I know I've done stuff like this before and it's never wanted it to be serialized.  Why would it need this anyways?  I thought that was for xml serialization.

I did try adding the [Serializable] attribute to class A, and the exception obviously went away.  But after doing that, making changes to A inside of class B wouldn't then propagate to the instance of A inside of C... like they are now completely separate copies.

Any ideas?

Edit:  Didn't realize that this would matter before, but after some looking around I think it does.  Classes B and C inherit from the MarshalByRefObject class.  Maybe this will help figure it out.  I've updated the classes above.

LastEditorDisplayName: Adam Haile

OwnerDisplayName: leppie


问:
How to create a method that counts how large a group is in an array?
I need some help making my Java method (getNumGroupsOfSize) work. It should tally how large an array "group" (consecutive elements that share the same value) is, and then print out how many other groups share that size. So for example, array [1,1,1,2,2,2,3,3,3,4,5,6,7] would print:

```<code>size 1=4

size 3=3
</code>```

and then would stop running.

This is what I have so far:

```<code>import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats {
  int[] numArray;
  int number;

  public ArrayStats(int[] array) {
    setArray(array);
  }

  public void setArray(int[] array) {
    numArray = array;
  }

  public int getNumGroupsOfSize() {
    int cnt = 0;
    for (int x = 0; x < numArray.length - 1; x++) {
    if (numArray[x] == numArray[x + 1]);
    cnt++;
    for (int y = 2; y <= 9; y++) {
      if (cnt == y)
        number = cnt;
      else if (cnt == 1)
        number = 1;
    }
  }
  return number;
}

public String toString() {
  return "size count" + " == " + getNumGroupsOfSize() + Arrays.toString(numArray);
}
}
</code>```

I'm pretty sure my getNumGroupsOfSize is not coded correctly, but I'm not sure how to make it work. I would genuinely appreciate any help that can be offered. If you need any more information, don't hesitate to comment. Thank you!

答:
Your method getNumGroupsSize() doesn't make much sense. For example how do you print out all the groups if you just store one number? I wrote the method new and it prints the numbers directly. You can also store them in an array if you want to.

```<code>public void getNumGroupsOfSize() {
    int cnt = 1;
    int currentNumber = numArray[0];
    for (int x = 0; x < numArray.length - 1; x++) {
        if (numArray[x] == numArray[x + 1]){
            cnt++;
        }
        else{
            System.out.println(currentNumber + ": " + cnt);
            currentNumber=numArray[x+1];
            cnt=1;
        }
    }
    System.out.println(currentNumber + ": " + cnt);

}
</code>```

Body:
I need some help making my Java method (getNumGroupsOfSize) work. It should tally how large an array "group" (consecutive elements that share the same value) is, and then print out how many other groups share that size. So for example, array [1,1,1,2,2,2,3,3,3,4,5,6,7] would print:

size 1=4

size 3=3

and then would stop running.

This is what I have so far:

import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats {
  int[] numArray;
  int number;

  public ArrayStats(int[] array) {
    setArray(array);
  }

  public void setArray(int[] array) {
    numArray = array;
  }

  public int getNumGroupsOfSize() {
    int cnt = 0;
    for (int x = 0; x < numArray.length - 1; x++) {
    if (numArray[x] == numArray[x + 1]);
    cnt++;
    for (int y = 2; y <= 9; y++) {
      if (cnt == y)
        number = cnt;
      else if (cnt == 1)
        number = 1;
    }
  }
  return number;
}

public String toString() {
  return "size count" + " == " + getNumGroupsOfSize() + Arrays.toString(numArray);
}
}

I'm pretty sure my getNumGroupsOfSize is not coded correctly, but I'm not sure how to make it work. I would genuinely appreciate any help that can be offered. If you need any more information, don't hesitate to comment. Thank you!

Body:
Your method getNumGroupsSize() doesn't make much sense. For example how do you print out all the groups if you just store one number? I wrote the method new and it prints the numbers directly. You can also store them in an array if you want to.

public void getNumGroupsOfSize() {
    int cnt = 1;
    int currentNumber = numArray[0];
    for (int x = 0; x < numArray.length - 1; x++) {
        if (numArray[x] == numArray[x + 1]){
            cnt++;
        }
        else{
            System.out.println(currentNumber + ": " + cnt);
            currentNumber=numArray[x+1];
            cnt=1;
        }
    }
    System.out.println(currentNumber + ": " + cnt);

}


问:
WSO2 Payload factory mediator shows Illegal character<D>
I have a payload factory mediator in my proxy service, which looks like below.

```<code> <payloadFactory media-type="json">
            <format>{
   "EntityTypeCode":"asx",
   "SchoolId":$1,
   "Format":"json",
   "InputData":{
      "Accounts":{
         "Account":[
            {
               "UserName":$2,
               "StudentID":$3,
               "FirstName":$4,
               "LastName":$5,
               "Email":$6,
               "DOB":$7,
               "SSN":$8,
               "Password":$9,
               "GenderCode":$10,
               "Address1":$11,
               "City":$12,
               "State":$13,
               "ZipCode":$14
            }
         ]
      }
   }
}
</format>
            <args>
               <arg evaluator="xml" expression="get-property('SchoolId')"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml" expression="get-property('first_name')"/>
               <arg evaluator="xml" expression="get-property('last_name')"/>
               <arg evaluator="xml" expression="get-property('email_address')"/>
               <arg evaluator="xml" expression="get-property('birth_date')"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml" expression="get-property('birth_date')"/>
               <arg evaluator="xml" expression="get-property('sex')"/>
               <arg evaluator="xml" expression="get-property('street_line1')"/>
               <arg evaluator="xml" expression="get-property('city')"/>
               <arg evaluator="xml" expression="get-property('stat_code')"/>
               <arg evaluator="xml" expression="get-property('zip')"/>
            </args>
         </payloadFactory>
</code>```

On executing the above payload factory mediator, I am getting the below error.

ERROR - SequenceMediator javax.xml.stream.XMLStreamException: Illegal
  character:  org.apache.axiom.om.OMException:
  javax.xml.stream.XMLStreamException: Illegal character:
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:296)
          at org.apache.axiom.om.impl.llom.OMElementImpl.buildNext(OMElementImpl.java:653)
          at org.apache.axiom.om.impl.llom.OMSourcedElementImpl.buildNext(OMSourcedElementImpl.java:880)
          at org.apache.axiom.om.impl.llom.OMNodeImpl.getNextOMSibling(OMNodeImpl.java:122)
          at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:343)
          at org.apache.axiom.om.impl.traverse.OMChildrenIterator.getNextNode(OMChildrenIterator.java:36)
          at org.apache.axiom.om.impl.traverse.OMAbstractIterator.hasNext(OMAbstractIterator.java:58)
          at org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:554)
          at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875)
          at org.apache.axiom.om.impl.llom.OMSourcedElementImpl.internalSerialize(OMSourcedElementImpl.java:686)
          at org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555)
          at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875)
          at org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:125)
          at org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:113)
          at org.apache.axiom.om.impl.llom.OMElementImpl.toString(OMElementImpl.java:988)
          at org.apache.synapse.util.xpath.SynapseXPath.stringValueOf(SynapseXPath.java:321)
          at org.apache.synapse.mediators.MediatorProperty.getEvaluatedExpression(MediatorProperty.java:138)
          at org.apache.synapse.mediators.builtin.LogMediator.setCustomProperties(LogMediator.java:223)
          at org.apache.synapse.mediators.builtin.LogMediator.getSimpleLogMessage(LogMediator.java:168)
          at org.apache.synapse.mediators.builtin.LogMediator.getLogMessage(LogMediator.java:134)
          at org.apache.synapse.mediators.builtin.LogMediator.mediate(LogMediator.java:101)
          at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:97)
          at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:59)
          at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
          at org.apache.synapse.core.axis2.ProxyServiceMessageReceiver.receive(ProxyServiceMessageReceiver.java:213)
          at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
          at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:403)
          at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:151)
          at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
          at java.lang.Thread.run(Thread.java:745) Caused by: javax.xml.stream.XMLStreamException: Illegal character:
          at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.hasNext(AbstractXMLStreamReader.java:449)
          at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.next(AbstractXMLStreamReader.java:456)
          at javax.xml.stream.util.StreamReaderDelegate.next(Unknown Source)
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681)
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214)
          ... 31 more

What could be the reason? Where am I going wrong?

Please help to overcome the situation.

Thanks in advance.

答:
Arguments your inserted via $1,$2 and so on - is it strings or numbers? If strings - put them into "", like:</p>

```<code>"UserName":"$2",
"StudentID":$3,
"FirstName":"$4",
</code>```

Body:
I have a payload factory mediator in my proxy service, which looks like below.

 <payloadFactory media-type="json">
            <format>{
   "EntityTypeCode":"asx",
   "SchoolId":$1,
   "Format":"json",
   "InputData":{
      "Accounts":{
         "Account":[
            {
               "UserName":$2,
               "StudentID":$3,
               "FirstName":$4,
               "LastName":$5,
               "Email":$6,
               "DOB":$7,
               "SSN":$8,
               "Password":$9,
               "GenderCode":$10,
               "Address1":$11,
               "City":$12,
               "State":$13,
               "ZipCode":$14
            }
         ]
      }
   }
}
</format>
            <args>
               <arg evaluator="xml" expression="get-property('SchoolId')"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml" expression="get-property('first_name')"/>
               <arg evaluator="xml" expression="get-property('last_name')"/>
               <arg evaluator="xml" expression="get-property('email_address')"/>
               <arg evaluator="xml" expression="get-property('birth_date')"/>
               <arg evaluator="xml"
                    expression="$body/*[local-name()='Object']/*[local-name()='Payload']/*[local-name()='ID'][*[local-name()='Type']='abc']/*[local-name()='Value']/text()"/>
               <arg evaluator="xml" expression="get-property('birth_date')"/>
               <arg evaluator="xml" expression="get-property('sex')"/>
               <arg evaluator="xml" expression="get-property('street_line1')"/>
               <arg evaluator="xml" expression="get-property('city')"/>
               <arg evaluator="xml" expression="get-property('stat_code')"/>
               <arg evaluator="xml" expression="get-property('zip')"/>
            </args>
         </payloadFactory>

On executing the above payload factory mediator, I am getting the below error.

ERROR - SequenceMediator javax.xml.stream.XMLStreamException: Illegal
  character:  org.apache.axiom.om.OMException:
  javax.xml.stream.XMLStreamException: Illegal character:
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:296)
          at org.apache.axiom.om.impl.llom.OMElementImpl.buildNext(OMElementImpl.java:653)
          at org.apache.axiom.om.impl.llom.OMSourcedElementImpl.buildNext(OMSourcedElementImpl.java:880)
          at org.apache.axiom.om.impl.llom.OMNodeImpl.getNextOMSibling(OMNodeImpl.java:122)
          at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:343)
          at org.apache.axiom.om.impl.traverse.OMChildrenIterator.getNextNode(OMChildrenIterator.java:36)
          at org.apache.axiom.om.impl.traverse.OMAbstractIterator.hasNext(OMAbstractIterator.java:58)
          at org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:554)
          at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875)
          at org.apache.axiom.om.impl.llom.OMSourcedElementImpl.internalSerialize(OMSourcedElementImpl.java:686)
          at org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555)
          at org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875)
          at org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:125)
          at org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:113)
          at org.apache.axiom.om.impl.llom.OMElementImpl.toString(OMElementImpl.java:988)
          at org.apache.synapse.util.xpath.SynapseXPath.stringValueOf(SynapseXPath.java:321)
          at org.apache.synapse.mediators.MediatorProperty.getEvaluatedExpression(MediatorProperty.java:138)
          at org.apache.synapse.mediators.builtin.LogMediator.setCustomProperties(LogMediator.java:223)
          at org.apache.synapse.mediators.builtin.LogMediator.getSimpleLogMessage(LogMediator.java:168)
          at org.apache.synapse.mediators.builtin.LogMediator.getLogMessage(LogMediator.java:134)
          at org.apache.synapse.mediators.builtin.LogMediator.mediate(LogMediator.java:101)
          at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:97)
          at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:59)
          at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
          at org.apache.synapse.core.axis2.ProxyServiceMessageReceiver.receive(ProxyServiceMessageReceiver.java:213)
          at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
          at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:403)
          at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:151)
          at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
          at java.lang.Thread.run(Thread.java:745) Caused by: javax.xml.stream.XMLStreamException: Illegal character:
          at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.hasNext(AbstractXMLStreamReader.java:449)
          at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.next(AbstractXMLStreamReader.java:456)
          at javax.xml.stream.util.StreamReaderDelegate.next(Unknown Source)
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681)
          at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214)
          ... 31 more

What could be the reason? Where am I going wrong?

Please help to overcome the situation.

Thanks in advance.

Body:
Arguments your inserted via $1,$2 and so on - is it strings or numbers? If strings - put them into "", like:

"UserName":"$2",
"StudentID":$3,
"FirstName":"$4",


问:
How to keep List name using Gson
I need to get JSON response

```<code>{
 "text": [
          "blabla",
          "blabla",
          "blabla"
 ]
}
</code>```

I have list of Strings

```<code>List<String> text = new ArrayList<String>();
text.add("blabla");
text.add("blabla");
text.add("blabla");
</code>```

How can I get wright result, because my solution seems to me not the best one?

```<code>Gson gson = new GsonBuilder().setPrettyPrinting().create();
String answ = gson.toJson(text);
return "{\"text\":"+answ+"}";
</code>```

答:
You need to define text as key of a map or DTOs field name

Here is how you can do this using use Guava's ImmutableMap map

```<code>return gson.toJson(ImmutableMap.of("text", text));
</code>```

Or

```<code>HashMap<String, List<String>> map = new HashMap<>();
map.put("text", text);
return gson.toJson(map);
</code>```

Or

Define a DTO named Data

```<code>public class Data {

    private List<String> text;

    public List<String> getText() {
        return text;
    }

    public void setText(List<String> text) {
        this.text = text;
    }

}
</code>```

Then use :

```<code>Data data = new Data();
data.setText(text);
return gson.toJson(data);
</code>```

Title: How to keep List name using Gson

Body:
I need to get JSON response

{
 "text": [
          "blabla",
          "blabla",
          "blabla"
 ]
}

I have list of Strings

List<String> text = new ArrayList<String>();
text.add("blabla");
text.add("blabla");
text.add("blabla");

How can I get wright result, because my solution seems to me not the best one?

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String answ = gson.toJson(text);
return "{\"text\":"+answ+"}";

Body:
You need to define text as key of a map or DTOs field name

Here is how you can do this using use Guava's ImmutableMap map

return gson.toJson(ImmutableMap.of("text", text));

Or

HashMap<String, List<String>> map = new HashMap<>();
map.put("text", text);
return gson.toJson(map);

Or

Define a DTO named Data

public class Data {

    private List<String> text;

    public List<String> getText() {
        return text;
    }

    public void setText(List<String> text) {
        this.text = text;
    }

}

Then use :

Data data = new Data();
data.setText(text);
return gson.toJson(data);


问:
JPA - FindByExample
Does anyone have a good example for how to do a findByExample in JPA that will work within a generic DAO via reflection for any entity type?   I know I can do it via my provider (Hibernate), but I don't want to break with neutrality...

Seems like the criteria API might be the way to go....but I am not sure how to handle the reflection part of it.

答:
Maybe the answer is too late. But check this. It might be of help.

https://sourceforge.net/projects/simplejpaquery/

First, include the jar into the classpath. You will have a class called com.afifi.simpleJPAQuery.entities.utility.JPAUtil.
This class uses reflection to deduct the query from the bean.
Suppose you have an entity bean as follows:

```<code>    @Entity
    public class Person {
        @Id
        private Integer personNo;

        private String personName;

        public Integer getPersonNo() {
            return personNo;
        }

        public void setPersonNo(Integer personNo) {
            this.personNo = personNo;
        }

        public String getPersonName() {
            return personName;
        }

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

Then if you want to query by person name for instance, you need to do as follows:

```<code>    //initiate entity manager (em)
    Person p=new Person();
    p.setPersonName("John");
    String sortString="";
    List<Person> result= JPAUtil.findByExample(em,p,sortString);
</code>```

The result will get all the records where the person name contained the word "John".

if you want to limit the results, you can do something like:

```<code>    List<Person> result= JPAUtil.findByExample(em, p, sortString, start, size);
</code>```

This library has other methods like:

getResultCount: to get the count of the result

createSqlStatement: to get the sql statement that is being used

getSqlWhereString: to get just the where string used

It has the native forms of these functions:

findByExampleNative, getResultCountNative, createSqlStatementNative and getSqlWhereStringNative

The library also has QueryAnnotations class that contains annotations that can be added to the Entity bean properties to give more control on how you want to query using the bean.

Title: JPA - FindByExample

Body:
Maybe the answer is too late. But check this. It might be of help.

https://sourceforge.net/projects/simplejpaquery/

First, include the jar into the classpath. You will have a class called com.afifi.simpleJPAQuery.entities.utility.JPAUtil.
This class uses reflection to deduct the query from the bean.
Suppose you have an entity bean as follows:

    @Entity
    public class Person {
        @Id
        private Integer personNo;

        private String personName;

        public Integer getPersonNo() {
            return personNo;
        }

        public void setPersonNo(Integer personNo) {
            this.personNo = personNo;
        }

        public String getPersonName() {
            return personName;
        }

        public void setPersonName(String personName) {
            this.personName = personName;
        }
    }

Then if you want to query by person name for instance, you need to do as follows:

    //initiate entity manager (em)
    Person p=new Person();
    p.setPersonName("John");
    String sortString="";
    List<Person> result= JPAUtil.findByExample(em,p,sortString);

The result will get all the records where the person name contained the word "John".

if you want to limit the results, you can do something like:

    List<Person> result= JPAUtil.findByExample(em, p, sortString, start, size);

This library has other methods like:

getResultCount: to get the count of the result

createSqlStatement: to get the sql statement that is being used

getSqlWhereString: to get just the where string used

It has the native forms of these functions:

findByExampleNative, getResultCountNative, createSqlStatementNative and getSqlWhereStringNative

The library also has QueryAnnotations class that contains annotations that can be added to the Entity bean properties to give more control on how you want to query using the bean.


问:
associative array total value count
Check array print_r() view bellow. I want to get total of only "amount" value. And output should not in array. It should be a simple integer value. So result should be 4+3+9= 16      </p>

```<code>Array
    (
        [0] => Array
            (
                [id] => 15
                [portfolio_id] => 1
                [stock_id] => 1
                [amount] => 4
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:04:30
                [updated_at] => 2017-04-02 09:04:30
            )

        [1] => Array
            (
                [id] => 14
                [portfolio_id] => 1
                [stock_id] => 3
                [amount] => 3
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:40
                [updated_at] => 2017-04-02 09:03:40
            )

        [2] => Array
            (
                [id] => 13
                [portfolio_id] => 1
                [stock_id] => 4
                [amount] => 9
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:36
                [updated_at] => 2017-04-02 09:03:36
            )

    )
</code>```

答:
Try array_sum(array_column($input, 'amount'));

array_column will return the values of amount key & array_sum calculate the sum of values in the returned array

Title: associative array total value count

Body:
Check array print_r() view bellow. I want to get total of only "amount" value. And output should not in array. It should be a simple integer value. So result should be 4+3+9= 16

Array
    (
        [0] => Array
            (
                [id] => 15
                [portfolio_id] => 1
                [stock_id] => 1
                [amount] => 4
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:04:30
                [updated_at] => 2017-04-02 09:04:30
            )

        [1] => Array
            (
                [id] => 14
                [portfolio_id] => 1
                [stock_id] => 3
                [amount] => 3
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:40
                [updated_at] => 2017-04-02 09:03:40
            )

        [2] => Array
            (
                [id] => 13
                [portfolio_id] => 1
                [stock_id] => 4
                [amount] => 9
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:36
                [updated_at] => 2017-04-02 09:03:36
            )

    )


问:
list video devices via terminal
How do you list a computer's video devices via terminal? Is there a command that lists them?</p>

Title: list video devices via terminal


问:
Difference between view_type and view_mode when defining action window?
What exacty does each of these attribute values mean when used while defining act_window, for eg;

 <record id="open_estimate_quantity_extra_request" model="ir.actions.act_window">
   <field name="name">Extra Requests</field>
   <field name="res_model">estimate.quantity.extra.request</field>
   <field name="view_type">form</field>
   <field name="view_mode">tree,form</field>
 </record>
```

In the above code what does it mean to have a value of form for view_type and a value of tree,form for view_mode.  From what i understand, view_mode tells odoo to display both tree and form views for the  estimate.quantity.extra.request model.  But what purpose does view_type have?

答:
Well, basically view mode shows the sequence and number of the views that shall be available in the view switcher at the top right corner of the tree/form view for a particular model after it is loaded from a menu item or any other way.

if you set view mode to tree,form then first tree view will be shown and then the form view will be opened after you click on one of the records, and the sequence will also be the same as first tree and then form view from left to right in the view switcher at the top right side of the view.

But the view type means how the record will be opened, means if it is set to form then when you click on one of the records in a tree view it will be opened in the form view, if you create a new record an empty form view will be opened,

But if the view type is set to tree then when you click the record it will not be opened in the form view and when you create a new record it will be created as a new row in the tree view

Body:
What exacty does each of these attribute values mean when used while defining act_window, for eg;

 <record id="open_estimate_quantity_extra_request" model="ir.actions.act_window">
   <field name="name">Extra Requests</field>
   <field name="res_model">estimate.quantity.extra.request</field>
   <field name="view_type">form</field>
   <field name="view_mode">tree,form</field>
 </record>

In the above code what does it mean to have a value of form for view_type and a value of tree,form for view_mode.  From what i understand, view_mode tells odoo to display both tree and form views for the  estimate.quantity.extra.request model.  But what purpose does view_type have?