问:
Connect a web form to MySQL database
Using a MySQL database, I add users to the database like this test data:

```<code>INSERT INTO `database_users`.`Members` (`ID`, `Username`, `Password`,
 `First Name`, `Last Name`, `Email Address`, `Telephone Number`,
 `Address Line 1`, `Address Line 2`, `Town/City`, `Postcode`,
 `Mailing-list`, `Terms`) VALUES (NULL, 'Test', '', '', '', '', '', '',
 NULL, '', '', NULL, '');"
</code>```

My HTML form looks like this:

```<code><input type="submit" value="Join!">
    <div class="col-lg-6">
        <input type="text" placeholder="Town/City" id="Town/City">
    </div>
    <div class="col-lg-6">
        <input type="text" placeholder="Postcode" id="Postcode">
    </div>
</input>
</code>```

I am looking to submit the form on my website and have the data upload to my MySQL database. Can anyone advise on what I am missing from my form?

答:
Your sql query seems to be good, but if you don't know how to use PHP you'll be blocked often.

The best thing to do is learn basic PHP to know how to implemant youself your register page, and ask on stackoverflow if you have an issue during the development.

http://www.learn-php.org/

And your form isn't correct: You need a <form> input and define on it the method (post or get), and the action (the file where the datas goes).

Basically, your code have to be like:

HTML (form.html)

```<code><form method="POST" action="save.php">
    <input type="text" name="pseudo">
    <input type="submit">
</form>
</code>```

PHP (save.php)

```<code><?php
    if(isset($_POST['pseudo'])){ // Test if the variable exists
        $pseudo = $_POST['pseudo'];
        // Your SQL query here which save the pseudo. Don't forget to test your variables.
    }
    else {
        echo "pseudo is required";
    }
?>
</code>```

Don't forget to escape your variables and use prepared statements. Else, your site will be many flaws like XSS or SQL injections.

Some links

A prepared statement with Mysqli

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Prevent XSS attacks

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

What is a SQL injection?

http://php.net/manual/en/security.database.sql-injection.php

Title: Connect a web form to MySQL database

Body:
Using a MySQL database, I add users to the database like this test data:

INSERT INTO `database_users`.`Members` (`ID`, `Username`, `Password`,
 `First Name`, `Last Name`, `Email Address`, `Telephone Number`,
 `Address Line 1`, `Address Line 2`, `Town/City`, `Postcode`,
 `Mailing-list`, `Terms`) VALUES (NULL, 'Test', '', '', '', '', '', '',
 NULL, '', '', NULL, '');"

My HTML form looks like this:

<input type="submit" value="Join!">

        <input type="text" placeholder="Town/City" id="Town/City">

        <input type="text" placeholder="Postcode" id="Postcode">

</input>

I am looking to submit the form on my website and have the data upload to my MySQL database. Can anyone advise on what I am missing from my form?

Body:
Your sql query seems to be good, but if you don't know how to use PHP you'll be blocked often.

The best thing to do is learn basic PHP to know how to implemant youself your register page, and ask on stackoverflow if you have an issue during the development.

http://www.learn-php.org/

And your form isn't correct: You need a <form> input and define on it the method (post or get), and the action (the file where the datas goes).

Basically, your code have to be like:

HTML (form.html)

<form method="POST" action="save.php">
    <input type="text" name="pseudo">
    <input type="submit">
</form>

PHP (save.php)

<?php
    if(isset($_POST['pseudo'])){ // Test if the variable exists
        $pseudo = $_POST['pseudo'];
        // Your SQL query here which save the pseudo. Don't forget to test your variables.
    }
    else {
        echo "pseudo is required";
    }
?>

Don't forget to escape your variables and use prepared statements. Else, your site will be many flaws like XSS or SQL injections.

Some links

A prepared statement with Mysqli

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Prevent XSS attacks

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

What is a SQL injection?

http://php.net/manual/en/security.database.sql-injection.php


来源: stackexchange

问:
jquery if checkbox checked add value true
How to make jquery click function if checkBox checked then status value set to 'true', if not cheked value set to 'false'?

if I check checkbox 1 , then status 1 set to true
if I check checkbox 2 , then status 2 set to true
if I check checkbox 3 , then status 3 set to true

  <input name="checkBox[]" type="checkbox" value="1"> Checkbox 1
   <input name="status[]" type="text" value="">

   <input name="checkBox[]" type="checkbox" value="2"> Checkbox 2
   <input name="status[]" type="text" value="">

  <input name="checkBox[]" type="checkbox" value="3"> Checkbox 3
   <input name="status[]" type="text" value="">

```

答:
You can try this

```<code><div class="form-group">
   <input name="checkBox" type="checkbox" value="1">
   <input name="status" type="text" value="">
</div>
<div class="form-group">
   <input name="checkBox" type="checkbox" value="2">
   <input name="status" type="text" value="">
</div>
<div class="form-group">
   <input name="checkBox" type="checkbox" value="3">
   <input name="status" type="text" value="">
</div>
</code>```

and the jquery script

```<code>$('input[type="checkbox"]').change(function() {
    if ($(this).is(':checked')) {
        $(this).next('input[type="text"]').val('true');
    } else {
        $(this).next('input[type="text"]').val('false');
    }
}).change();
</code>```

https://jsfiddle.net/831mjzr1/

ContentLicense: CC BY-SA 3.0

Body:
You can try this

<div class="form-group">
   <input name="checkBox" type="checkbox" value="1">
   <input name="status" type="text" value="">
</div>
<div class="form-group">
   <input name="checkBox" type="checkbox" value="2">
   <input name="status" type="text" value="">
</div>
<div class="form-group">
   <input name="checkBox" type="checkbox" value="3">
   <input name="status" type="text" value="">
</div>

and the jquery script

$('input[type="checkbox"]').change(function() {
    if ($(this).is(':checked')) {
        $(this).next('input[type="text"]').val('true');
    } else {
        $(this).next('input[type="text"]').val('false');
    }
}).change();

https://jsfiddle.net/831mjzr1/


问:
punctuation marks in javascript
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...</p>

```<code>function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “<img src=\”" + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}
</code>```

答:
You should avoid eval, and declare the content variable, as well as declare a reference to the imagepreview element:

```<code>function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,"/");
  imgname = imgname.replace(/\'/g,"\\'"); //Is this really necessary?
  var content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
  var img = document.getElementById("imagepreview");
  img.innerHTML = content;
  img.style.visibility ='visible';
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: punctuation marks in javascript

Body:
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...

function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}

Body:
You should avoid eval, and declare the content variable, as well as declare a reference to the imagepreview element:

function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,"/");
  imgname = imgname.replace(/\'/g,"\\'"); //Is this really necessary?
  var content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
  var img = document.getElementById("imagepreview");
  img.innerHTML = content;
  img.style.visibility ='visible';
}


问:
How does httputility.htmlencode() work?
I am trying to implement HttpUtility.HtmlEncode (). The string that this method will encode will be used for rendering into html. if it is encoded then how will it render correctly? do I need to decode it again before using it to render? In that case what is the point of encoding if we have to decode it again to render it correctly?</p>

答:
You should only encode it if you have arbitrary text you want to make sure it doesn't contain HTML elements. HtmlEncode will make it render as text, rather than HTML.

If you don't want to do that, don't encode or decode.

For example, this string that was put in a text field by a lovely user of your application (assuming your framework doesn't prevent XSS injection for you already):

```<code>string s = "<script>alert('dangerous');</script>";
</code>```

When it is put on the page without HtmlEncode, it will show you the alert in a browser dialog (it executes the Javascript for that). If you call HtmlEncode on it, it will render as text. The Javascript isn't executed.

```<code><script>alert('dangerous');</script>
</code>```

Title: How does httputility.htmlencode() work?

Body:
You should only encode it if you have arbitrary text you want to make sure it doesn't contain HTML elements. HtmlEncode will make it render as text, rather than HTML.

If you don't want to do that, don't encode or decode.

For example, this string that was put in a text field by a lovely user of your application (assuming your framework doesn't prevent XSS injection for you already):

string s = "<script>alert('dangerous');</script>";

When it is put on the page without HtmlEncode, it will show you the alert in a browser dialog (it executes the Javascript for that). If you call HtmlEncode on it, it will render as text. The Javascript isn't executed.

<script>alert('dangerous');</script>


问:
Regular expression in java always return true
Can you please help me with regex for the following string in android:

```<code>1.0.2 Build S6B5
</code>```

How it should be:

```<code>{number}.{number}.{number}{space}Build{space}{S or D orT}{anything up 3 to 4 chars}
</code>```

With help of some king people from here I`ve tried the flowing code:

```<code>if (name.matches("\\d+\\.\\d+\\.\\d+\\s+Build\\s[SDT].{3,4}"));
</code>```

but it always return True even for:

```<code>1.0.1 4C0

1.0.1 B 4BD

1.0.4.52A
</code>```

etc.

答:
Try the following code:

```<code>public static void main (String[] args) {

    String name1 = "1.0.1 4C0";
    String name2 = "1.0.1 B 4BD";
    String name3 = "1.0.4.52A";
    String name4 = "1.0.2 Build S6B5";

    check(name1);
    check(name2);
    check(name3);
    check(name4);
}

private static void check(String name) {

    Pattern p = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\s+Build\\s+([SDT]\\w{3,4})");
    Matcher m = p.matcher(name);

    if (m.find()) {
        System.out.println("num1: " + m.group(1));
        System.out.println("num2: " + m.group(2));
        System.out.println("num3: " + m.group(3));
        System.out.println("build: " + m.group(4));
    } else {
        System.out.println("not found");
    }
}
</code>```

Use Matcher.find() method to match parts of the test string and then Matcher.group() method to access the parts captured by the round brackets.

Resulting output:

```<code>not found
not found
not found
num1: 1
num2: 0
num3: 2
build: S6B5
</code>```

Body:
Can you please help me with regex for the following string in android:

1.0.2 Build S6B5

How it should be:

{number}.{number}.{number}{space}Build{space}{S or D orT}{anything up 3 to 4 chars}

With help of some king people from here I`ve tried the flowing code:

if (name.matches("\\d+\\.\\d+\\.\\d+\\s+Build\\s[SDT].{3,4}"));

but it always return True even for:

1.0.1 4C0

1.0.1 B 4BD

1.0.4.52A

etc.

Body:
Try the following code:

public static void main (String[] args) {

    String name1 = "1.0.1 4C0";
    String name2 = "1.0.1 B 4BD";
    String name3 = "1.0.4.52A";
    String name4 = "1.0.2 Build S6B5";

    check(name1);
    check(name2);
    check(name3);
    check(name4);
}

private static void check(String name) {

    Pattern p = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\s+Build\\s+([SDT]\\w{3,4})");
    Matcher m = p.matcher(name);

    if (m.find()) {
        System.out.println("num1: " + m.group(1));
        System.out.println("num2: " + m.group(2));
        System.out.println("num3: " + m.group(3));
        System.out.println("build: " + m.group(4));
    } else {
        System.out.println("not found");
    }
}

Use Matcher.find() method to match parts of the test string and then Matcher.group() method to access the parts captured by the round brackets.

Resulting output:

not found
not found
not found
num1: 1
num2: 0
num3: 2
build: S6B5


问:
Jquery: how to trigger click event on pressing enter key
I need to execute a button click event upon pressing key enter.

As it is at the moment the event is not firing.

Please Help me with the syntax if possible.

```<code>$(document).on("click", "input[name='butAssignProd']", function () {
   //all the action
});
</code>```

this is my attempt to fire click event on enter.

```<code>$("#txtSearchProdAssign").keydown(function (e) {
  if (e.keyCode == 13) {
    $('input[name = butAssignProd]').click();
  }
});
</code>```

答:
Try This</p>

```<code><button class="click_on_enterkey" type="button" onclick="return false;">
<script>
$('.click_on_enterkey').on('keyup',function(event){
  if(event.keyCode == 13){
    $(this).click();
  }
});
<script>
</code>```

Body:
I need to execute a button click event upon pressing key enter.

As it is at the moment the event is not firing.

Please Help me with the syntax if possible.

$(document).on("click", "input[name='butAssignProd']", function () {
   //all the action
});

this is my attempt to fire click event on enter.

$("#txtSearchProdAssign").keydown(function (e) {
  if (e.keyCode == 13) {
    $('input[name = butAssignProd]').click();
  }
});

Body:
Try This

<button class="click_on_enterkey" type="button" onclick="return false;">
<script>
$('.click_on_enterkey').on('keyup',function(event){
  if(event.keyCode == 13){
    $(this).click();
  }
});
<script>


问:
Is md5 value language dependent?
If I generate md5 of a file in java and javascript -Will both the values be same?
I have to generate md5 in javascript and send it to the server and the server matches it. I am getting a hash mismatch error.

Actually, I need 'base64 encoded 128-bit MD5 digest' to send to S3 using javascript.

Thanks

答:
NO. MD5 is language independent.

But as I understood you are creating the hash code from one computer and reading it using another, which may cause into a charset chaos. Make sure you are using the same charset UTF-8 recommended.
And also I found this helpful, try using this without storing the hash in your database.

```<code>public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }
</code>```

Title: Is md5 value language dependent?

Body:
NO. MD5 is language independent.

But as I understood you are creating the hash code from one computer and reading it using another, which may cause into a charset chaos. Make sure you are using the same charset UTF-8 recommended.
And also I found this helpful, try using this without storing the hash in your database.

public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }


问:
How does one setup a pipe between two child processes in Win32?
For the life of me I can't figure out why this is not working. Basically, I created the pipe with the inherit bit set to true, and created two child processes, and used the STARTUPINFO structure to set the input and output handles as one would need, but the pipe seems broken (the second process writes no output to the console, even though output is expected)

I know the problem does not lie in my test program (BitTwiddler.exe) because I performed the same operation using CMD.exe, and everything works as expected.

Below is a minimal reproduction of what I have. What have I done incorrectly?

```<code>#include "windows.h"

int main()
{
    PROCESS_INFORMATION piSource, piDest;
    HANDLE hPipeIn, hPipeOut;
    HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    STARTUPINFOW suSource, suDest;
    ZeroMemory(&suSource, sizeof(suSource));
    ZeroMemory(&suDest, sizeof(suDest));
    suSource.cb = suDest.cb = sizeof(STARTUPINFOW);
    suSource.dwFlags = suDest.dwFlags = STARTF_USESTDHANDLES;
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = 0;
    sa.bInheritHandle = TRUE;
    if (CreatePipe(&hPipeIn, &hPipeOut, &sa, 0) == 0)
    {
        return GetLastError();
    }
    suSource.hStdInput = hIn;
    suSource.hStdError = suSource.hStdOutput = hPipeIn;
    suDest.hStdInput = hPipeOut;
    suDest.hStdError = suDest.hStdOutput = hOut;
    std::wstring cmdLineA(L"BitTwiddler 1"), cmdLineB(L"BitTwiddler 0");
    cmdLineA.push_back(0); cmdLineB.push_back(0);
    if (CreateProcessW(0, &cmdLineA[0], 0, 0, TRUE, 0, 0, 0, &suSource, &piSource) == 0)
    {
        return GetLastError();
    }
    CloseHandle(piSource.hThread);
    if (CreateProcessW(0, &cmdLineB[0], 0, 0, TRUE, 0, 0, 0, &suDest, &piDest) == 0)
    {
        return GetLastError();
    }
    CloseHandle(piDest.hThread);
    HANDLE hArray[2];
    hArray[0] = piSource.hProcess;
    hArray[1] = piDest.hProcess;
    WaitForMultipleObjects(2, hArray, TRUE, INFINITE);
    CloseHandle(hArray[0]);
    CloseHandle(hArray[1]);
    return 0;
}
</code>```

(In case anyone's interested, BitTwiddler is:

```<code>#include <windows.h>
#include <sstream>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    std::size_t opt = 0;
    argc--; argv++;
    if (argc == 0)
    {
        return 0;
    }
    else
    {
        std::istringstream converter(*argv);
        converter >> opt;
    }
    switch(opt)
    {
    case 0:
        {
            std::wstring currentLine;
            while(std::getline(std::wcin, currentLine))
            {
                std::wcout << "Got somepin: " << currentLine << std::endl;
            }
        }
        break;
    case 1:
        for (;;)
        {
            std::wcout << L"Hello World!" << std::endl;
            Sleep(1000);
        }
        break;
    case 2:
        return -1;
    default:
        std::wcout << "Unknown option.";
        return 0;
    }
    return 0;
}
</code>```

), but I really don't think that matters.

答:
You misplaced the read and write ends :)

CreatePipe has the prototype

```<code>BOOL CreatePipe(
  PHANDLE hReadPipe,  // can only read from this
  PHANDLE hWritePipe,  // can only write to this
  LPSECURITY_ATTRIBUTES lpPipeAttributes,
  DWORD nSize
);
</code>```

You can't call ReadFile (or in your case std::getline) from a Write-only handle, and vice versa. If you replaced your std::getline calls with a simple ReadFile call, you'd get an ACCESS_DENIED error, confirming this fact, since your STD_INPUT_HANDLE in the child process was not opened for GENERIC_READ.

The fix is as follows:

```<code>suSource.hStdError = suSource.hStdOutput = hPipeOut;  // must be the write pipe!
suDest.hStdInput = hPipeIn;  // must be the read pipe.
</code>```

Perhaps the names you assigned are confusing. If you called them as per the formal parameters, the error would be clearer:

```<code>suSource.hStdError = suSource.hStdOutput = hReadPipe;  // clearly wrong.
suDest.hStdInput = hWritePipe;  // as above -- expects a read-handle.
</code>```

Body:
For the life of me I can't figure out why this is not working. Basically, I created the pipe with the inherit bit set to true, and created two child processes, and used the STARTUPINFO structure to set the input and output handles as one would need, but the pipe seems broken (the second process writes no output to the console, even though output is expected)

I know the problem does not lie in my test program (BitTwiddler.exe) because I performed the same operation using CMD.exe, and everything works as expected.

Below is a minimal reproduction of what I have. What have I done incorrectly?

#include "windows.h"

int main()
{
    PROCESS_INFORMATION piSource, piDest;
    HANDLE hPipeIn, hPipeOut;
    HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    STARTUPINFOW suSource, suDest;
    ZeroMemory(&suSource, sizeof(suSource));
    ZeroMemory(&suDest, sizeof(suDest));
    suSource.cb = suDest.cb = sizeof(STARTUPINFOW);
    suSource.dwFlags = suDest.dwFlags = STARTF_USESTDHANDLES;
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = 0;
    sa.bInheritHandle = TRUE;
    if (CreatePipe(&hPipeIn, &hPipeOut, &sa, 0) == 0)
    {
        return GetLastError();
    }
    suSource.hStdInput = hIn;
    suSource.hStdError = suSource.hStdOutput = hPipeIn;
    suDest.hStdInput = hPipeOut;
    suDest.hStdError = suDest.hStdOutput = hOut;
    std::wstring cmdLineA(L"BitTwiddler 1"), cmdLineB(L"BitTwiddler 0");
    cmdLineA.push_back(0); cmdLineB.push_back(0);
    if (CreateProcessW(0, &cmdLineA[0], 0, 0, TRUE, 0, 0, 0, &suSource, &piSource) == 0)
    {
        return GetLastError();
    }
    CloseHandle(piSource.hThread);
    if (CreateProcessW(0, &cmdLineB[0], 0, 0, TRUE, 0, 0, 0, &suDest, &piDest) == 0)
    {
        return GetLastError();
    }
    CloseHandle(piDest.hThread);
    HANDLE hArray[2];
    hArray[0] = piSource.hProcess;
    hArray[1] = piDest.hProcess;
    WaitForMultipleObjects(2, hArray, TRUE, INFINITE);
    CloseHandle(hArray[0]);
    CloseHandle(hArray[1]);
    return 0;
}

(In case anyone's interested, BitTwiddler is:

#include <windows.h>
#include <sstream>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    std::size_t opt = 0;
    argc--; argv++;
    if (argc == 0)
    {
        return 0;
    }
    else
    {
        std::istringstream converter(*argv);
        converter >> opt;
    }
    switch(opt)
    {
    case 0:
        {
            std::wstring currentLine;
            while(std::getline(std::wcin, currentLine))
            {
                std::wcout << "Got somepin: " << currentLine << std::endl;
            }
        }
        break;
    case 1:
        for (;;)
        {
            std::wcout << L"Hello World!" << std::endl;
            Sleep(1000);
        }
        break;
    case 2:
        return -1;
    default:
        std::wcout << "Unknown option.";
        return 0;
    }
    return 0;
}

), but I really don't think that matters.

Body:
You misplaced the read and write ends :)

CreatePipe has the prototype

BOOL CreatePipe(
  PHANDLE hReadPipe,  // can only read from this
  PHANDLE hWritePipe,  // can only write to this
  LPSECURITY_ATTRIBUTES lpPipeAttributes,
  DWORD nSize
);

You can't call ReadFile (or in your case std::getline) from a Write-only handle, and vice versa. If you replaced your std::getline calls with a simple ReadFile call, you'd get an ACCESS_DENIED error, confirming this fact, since your STD_INPUT_HANDLE in the child process was not opened for GENERIC_READ.

The fix is as follows:

suSource.hStdError = suSource.hStdOutput = hPipeOut;  // must be the write pipe!
suDest.hStdInput = hPipeIn;  // must be the read pipe.

Perhaps the names you assigned are confusing. If you called them as per the formal parameters, the error would be clearer:

suSource.hStdError = suSource.hStdOutput = hReadPipe;  // clearly wrong.
suDest.hStdInput = hWritePipe;  // as above -- expects a read-handle.


问:
Model undefined when passing Model from View to Controller using AJAX
When I tried to used debugger; in ajax to check if I'm able to serialize the form it say it is "undefined". I don't encounter an error but The value i input in the view does not pass to the controller. This is my reference https://stick2basic.wordpress.com/2013/04/14/how-to-pass-model-from-view-to-controller-using-jquery/

VIEW

```<code><script type="text/javascript">
    $(document).ready(function () {
        $('#btnsubmit').click(function (e) {
            e.preventDefault();
            if ($("#OrderForm").valid()) { //if you use validation
                $.ajax({
                    url: $("#OrderForm").attr('action'),
                    type: $("#OrderForm").attr('method'),
                    data: $("#OrderForm").serialize(),
                    success: function (data) {
                        alert("success");
                    }
                });
            }
        });
    });
</script>

@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
}
</code>```

Controller

```<code>[AllowAnonymous]
        [HttpPost]
        public ActionResult _Order(OrderModel model)
        {
List<OrderModel> orderlist = new List<OrderModel>();
            if (Session["OrderList"] != null)
            {
                orderlist = Session["OrderList"] as List<OrderModel>;
                orderlist.Add(model);
            }
            Session["OrderList"] = orderlist;
            return PartialView();
}
</code>```

MODEL

```<code>public class OrderModel
    {
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [StringLength(35)]
        public string FirstName { get; set; }
        [StringLength(35)]
        public string MiddleName { get; set; }
        [StringLength(35)]
        public string LastName { get; set; }
        [StringLength(255)]
        public string Address { get; set; }
        [StringLength(40)]
        public string Province { get; set; }
        [StringLength(40)]
        public string Town { get; set; }
        [StringLength(13)]
        public string MobileNo { get; set; }

        [Required(ErrorMessage = "Please fill up Merchant Email.")]
        [DataType(DataType.EmailAddress)]
        public string MerchantEmail { get; set; }

        [Required(ErrorMessage = "Please enter the exact amount.")]
        [DataType(DataType.Currency)]
        public float OrderAmount { get; set; }

        public string OrderSkuCode { get; set; }

        [Required(ErrorMessage = "Please fill up order details.")]
        [StringLength(5000)]
        public string OrderDetails { get; set; }

    }
</code>```

答:
There are two things you are doing at the same time, you can have ajax or post the data directly to the controller.

```<code>@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
}
</code>```

Here you are posting the data directly to the controller (Ajax is for Asynchronous Transfer) , this will by pass the Ajax request in the script.

If you want to post it through Ajax here is the code changes you need to do

```<code><form id="form1">
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
 </form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnsubmit').click(function (e) {
            e.preventDefault();
            var data = new FormData($("#form1")[0]);
            if ($("#OrderForm").valid()) { //if you use validation
                $.ajax({
                    url: '@Url.Action("_Order","Your Controller Name")',
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        alert("success");
                    }
                });
            }
        });
    });
</script>
</code>```

Body:
When I tried to used debugger; in ajax to check if I'm able to serialize the form it say it is "undefined". I don't encounter an error but The value i input in the view does not pass to the controller. This is my reference https://stick2basic.wordpress.com/2013/04/14/how-to-pass-model-from-view-to-controller-using-jquery/

VIEW

@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{

                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })

                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />

}

Controller

[AllowAnonymous]
        [HttpPost]
        public ActionResult _Order(OrderModel model)
        {
List<OrderModel> orderlist = new List<OrderModel>();
            if (Session["OrderList"] != null)
            {
                orderlist = Session["OrderList"] as List<OrderModel>;
                orderlist.Add(model);
            }
            Session["OrderList"] = orderlist;
            return PartialView();
}

MODEL

public class OrderModel
    {
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [StringLength(35)]
        public string FirstName { get; set; }
        [StringLength(35)]
        public string MiddleName { get; set; }
        [StringLength(35)]
        public string LastName { get; set; }
        [StringLength(255)]
        public string Address { get; set; }
        [StringLength(40)]
        public string Province { get; set; }
        [StringLength(40)]
        public string Town { get; set; }
        [StringLength(13)]
        public string MobileNo { get; set; }

        [Required(ErrorMessage = "Please fill up Merchant Email.")]
        [DataType(DataType.EmailAddress)]
        public string MerchantEmail { get; set; }

        [Required(ErrorMessage = "Please enter the exact amount.")]
        [DataType(DataType.Currency)]
        public float OrderAmount { get; set; }

        public string OrderSkuCode { get; set; }

        [Required(ErrorMessage = "Please fill up order details.")]
        [StringLength(5000)]
        public string OrderDetails { get; set; }

    }

Body:
There are two things you are doing at the same time, you can have ajax or post the data directly to the controller.

@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
}

Here you are posting the data directly to the controller (Ajax is for Asynchronous Transfer) , this will by pass the Ajax request in the script.

If you want to post it through Ajax here is the code changes you need to do

<form id="form1">
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
 </form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnsubmit').click(function (e) {
            e.preventDefault();
            var data = new FormData($("#form1")[0]);
            if ($("#OrderForm").valid()) { //if you use validation
                $.ajax({
                    url: '@Url.Action("_Order","Your Controller Name")',
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        alert("success");
                    }
                });
            }
        });
    });
</script>


问:
Changing the attribute of each element in a v-for array
I am attempting to figure things out with Vue way of writing javascript.

Considering this scenario:

at .vue template

```<code> <button  v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button>

   <div v-for="(tweet, index) in tweets">
      <div class="each_tweet">
        <textarea v-on:keyup="typing(index)"
                  v-model="tweet.content"
                  placeholder="What's happening now">{{ tweet.content }}</textarea>
      </div>
    </div>
</code>```

at .vue

答:
I believe the Vue way of doing this is using class and style bindings. For example:

<textarea v-bind:class="{ big: enlarge}">{{item}}</textarea>

https://jsfiddle.net/e064m859/

Body:
I am attempting to figure things out with Vue way of writing javascript.

Considering this scenario:

at .vue template

 <button  v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button>

        <textarea v-on:keyup="typing(index)"
                  v-model="tweet.content"
                  placeholder="What's happening now">{{ tweet.content }}</textarea>

at .vue


问:
How to max utilize my laptop memory for runing pyspark?
I create a dataframe from 800M txt file and the df has 21.3 million rows. I installed pyspark 2.0.0 on my mac with 16GB memory. I have not modify any settings.
I use 70% of df for training a mllib model and java heap memory came.
While I use 60% of df for training, it is ok and return me a model.

How can I max utilize my laptop for settings, to let me use 80% or more data for training ?
thanks.

答:
You can set spark.driver.memory for the driver program and spark.executor.memory for the spark executors. Which one is the right one depends on your application, but in your case I guess it is spark.executor.memory.

You can set this as a command line option to spark-submit and/or pyspark.

See Apache Spark Memory Docs for more information.


问:
How to run a Symfony console command automatically when certain files change
Anyone have any idea how to automatically run a Symfony console command whenever any files matching a specified pattern changes? Similar to how you can watch for file changes in other automated task runners like gulp and grunt?</p>

答:
You could write another console command that works as watch-daemon checking for the file and then running the other one as a Process.

There are also existing tools that you can use for monitoring that allow to trigger a command. One example I know is monit and the existence check.

Alternatively you can write your own shell script that uses a combination of watch and grep/awk that runs continuously and triggers the action.

I would go for monit as it seems the most hassle free and can be used for other monitoring tasks as well that are common, e.g. restart a service when it becomes unresponsive.


问:
Why Logical Name is different from .bak file in SQL Server
I am restoring a backup file and i encountered an error. It says something like

Use FileListOnly" to get logical name of file.

When I run this query,

```<code>restore filelistonly from disk='E:\MyDatabase.bak'
</code>```

I found that the logical name is completely different from the .bak file. I did for other databases and found the same thing. The logical name is same for all databases on the server.

My Questing is, is there some sort of set up to do to set same logical name for all databases on server ?

Or How SQL Server set logical name for a database ?

答:
Logical names are defined at database create time and will default to a certain pattern. They can be changed later via ALTER DATABASE

The values are stored in sys.database_files and also in sys.master_files (required for offline databases etc)

The BACKUP DATABASE command takes an arbitrary file name that often contains the type and datetime of the backup "MyDatabase_Full_20170330093654.bak" as well as server and instance name (if you use Ola Hallengran's scripts)

Why should the backup file name relate at all to the logical name defined at database create time?

Body:
I am restoring a backup file and i encountered an error. It says something like

Use FileListOnly" to get logical name of file.

When I run this query,

restore filelistonly from disk='E:\MyDatabase.bak'

I found that the logical name is completely different from the .bak file. I did for other databases and found the same thing. The logical name is same for all databases on the server.

My Questing is, is there some sort of set up to do to set same logical name for all databases on server ?

Or How SQL Server set logical name for a database ?


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
From opengroup.org on pthread_join:

The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined.

So, you really should not have several threads joining your previous insertThread.

First, as you use C++, I recommend boost.thread.  They resemble the POSIX model of threads, and also work on Windows.  And it helps you with C++, i.e. by making function-objects usable more easily.

Second, why do you want to start a new thread for inserting an element, when you always have to wait for the previous one to finish before you start the next one?  Seems not to be classical use of multiple-threads.

Although... One classical solution to this would be to have one worker-thread getting jobs from an event-queue, and other threads posting the operation onto the event-queue.

If you really just want to keep it more or less the way you have it now, you'd have to do this:

Create a condition variable, like insert_finished.

All the threads which want to do an insert, wait on the condition variable.

As soon as one thread is done with its insertion, it fires the condition variable.

As the condition variable requires a mutex, you can just notify all waiting threads, they all want start inserting, but as only one thread can acquire the mutex at a time, all threads will do the insert sequentially.

But you should take care that your synchronization is not implemented in a too ad-hoc way.  As this is called insert, I suspect you want to manipulate a data-structure, so you probably want to implement a thread-safe data-structure first, instead of sharing the synchronization between data-structure-accesses and all clients.  I also suspect that there will be more operations then just insert, which will need proper synchronization...

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly

OwnerDisplayName: gimpf


问:
Implementing extensible code in C++
I am currently busy with a project where the main focus of the application is to be extensible (allow 3rd party developers to write plugins / their own implementations of interfaces).

Until now, I have been using Java, and built the application on the NetBeans platform. This has works perfectly fine and is quite easy to implement.

However, the program is quite computationally intense, and must be run on a grid of computers. I think C++ might be better suited for massive computations like I need.

What I would like to know. Is there any libraries like the NetBeans platform for C++. Or would I have to implement everything from scratch (not that I mind, I just wat to know)? Also, how easy is it to write extensible code with C++ and implement something like an update center? This is stuff you get for free with the NetBeans platform. My experience with the using the platform is that it allows you to write very modular code, which is something I like. New modules can be installed independantly, while the platform provides discovery of services to find all the installed plugins / impementations.

Can this be done similarly in C++?

Thanks!

答: I recommend that you have a look at the Qt framework. They offer a mechanism to create plugins. Have a look at this free online book about Qt. Plugins are discussed in chapter 21.</p>

Title: Implementing extensible code in C++


问:
Android cannot update fragment datas
I am currently working with fragments,i am try to load the data from Database into fragments class,once i run the application my previous data saved my class, cannot Reload data whenever i updated database,
I am also refer this refresh fragment at reload But it not work for me,

My code was,

```<code>   `Fragment fragment;
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame,fragment);
    ft.detach(fragment);
    ft.attach(fragment);
    ft.commit();`
</code>```

And my packages
import android.support.v4.app.Fragment;
                  import android.support.v4.app.FragmentTransaction;

please help me friends!!

答:
Try my below code once and please have a look here

```<code>SomeFragment fragment = null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);

//no need to detach
//ft.detach(fragment);
//no need to attach
//ft.attach(fragment);

//just commit
ft.commit();`
</code>```

UPDATE

Lets initiate the fragment and give it some recognition through a TAG like

```<code>SomeFragment fragment = new SomeFragment();
getFragmentManager()
        .beginTransaction()
        .add(android.R.id.content, fragment, "my_fragment_tag")//now you can recognize your fragment through "my_fragment_tag"
        .commit();
</code>```

And now you can refresh your fragment when you need by your detach/attach way

```<code>// Reload current fragment
Fragment frg=getSupportFragmentManager().findFragmentByTag("my_fragment_tag");
final FragmentTransaction ft =    getSupportFragmentManager().beginTransaction();
if(frg != null){ // if fragment is removed from memory it will give null pointer exception
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
</code>```

Title: Android cannot update fragment datas

Body:
I am currently working with fragments,i am try to load the data from Database into fragments class,once i run the application my previous data saved my class, cannot Reload data whenever i updated database,
I am also refer this refresh fragment at reload But it not work for me,

My code was,

   `Fragment fragment;
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame,fragment);
    ft.detach(fragment);
    ft.attach(fragment);
    ft.commit();`

And my packages
import android.support.v4.app.Fragment;
                  import android.support.v4.app.FragmentTransaction;

please help me friends!!

Body:
Try my below code once and please have a look here

SomeFragment fragment = null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);

//no need to detach
//ft.detach(fragment);
//no need to attach
//ft.attach(fragment);

//just commit
ft.commit();`

UPDATE

Lets initiate the fragment and give it some recognition through a TAG like

SomeFragment fragment = new SomeFragment();
getFragmentManager()
        .beginTransaction()
        .add(android.R.id.content, fragment, "my_fragment_tag")//now you can recognize your fragment through "my_fragment_tag"
        .commit();

And now you can refresh your fragment when you need by your detach/attach way

// Reload current fragment
Fragment frg=getSupportFragmentManager().findFragmentByTag("my_fragment_tag");
final FragmentTransaction ft =    getSupportFragmentManager().beginTransaction();
if(frg != null){ // if fragment is removed from memory it will give null pointer exception
ft.detach(frg);
ft.attach(frg);
ft.commit();
}


问:
ADAL bearer token does not return username but aad client id
We have an desktop app which uses adal to authenticate the user, using this code:

```<code>AuthenticationResult result = null;
var context = new  AuthenticationContext(aadTenantDomain);
result = await context.AcquireTokenAsync(resourceId, clientId, returnUrl, new PlatformParameters(PromptBehavior.Auto));
</code>```

This works fine and the returned AuthenticationResult has all the right user information. Now we call a web app web api controller hosted on azure with the access token obtained from AuthenticationResult:

```<code>var Client = new HttpClient();
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
</code>```

Which also correctly authorizes the user. Now in the web controller we use User.Identity.Name to get the username which was authorized by the access token. For many month til yesterday this worked well, but today User.Identity.Name returns the client id of the desktop app instead of a username. Anyone knows what migh be wrong?

This is the api auth configuration:

```<code> public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = System.Security.Claims.ClaimTypes.Role,
                }
            });
    }
</code>```

And this is an example controller function:

```<code>[Authorize]
public class dialplanController : ApiController
{
    public async Task<IHttpActionResult> GetMe()
    {
        var Me = db.dialplan.FirstOrDefault(d => d.email == User.Identity.Name);
        return Ok(Me);
    }
}
</code>```

答: Using ClaimsPrincipal.Current?.FindFirst(ClaimTypes.Upn)?.Value returns the correct UPN of the current user or null if no upn is given.</p>

Body:
We have an desktop app which uses adal to authenticate the user, using this code:

AuthenticationResult result = null;
var context = new  AuthenticationContext(aadTenantDomain);
result = await context.AcquireTokenAsync(resourceId, clientId, returnUrl, new PlatformParameters(PromptBehavior.Auto));

This works fine and the returned AuthenticationResult has all the right user information. Now we call a web app web api controller hosted on azure with the access token obtained from AuthenticationResult:

var Client = new HttpClient();
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);

Which also correctly authorizes the user. Now in the web controller we use User.Identity.Name to get the username which was authorized by the access token. For many month til yesterday this worked well, but today User.Identity.Name returns the client id of the desktop app instead of a username. Anyone knows what migh be wrong?

This is the api auth configuration:

 public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = System.Security.Claims.ClaimTypes.Role,
                }
            });
    }

And this is an example controller function:

[Authorize]
public class dialplanController : ApiController
{
    public async Task<IHttpActionResult> GetMe()
    {
        var Me = db.dialplan.FirstOrDefault(d => d.email == User.Identity.Name);
        return Ok(Me);
    }
}


问:
How to remove formated mask to a value
I want to remove formated mask(either '$' or 'S/.') to the value. I have two angular directives. those are 1st directive. and 2nd directive.

In the second directive the symbol is not at all effecting to ng-model but the first directive it is effecting to ng-model.The first directive is removing the symbol, But if the text box is contains ng-change functions, it is calling ng-change functions then it is going to directive. so the symbol is effecting to ng-model.

The second directive is the symbol is not at all effecting to ng-model. Like this I need to the first directive too.

Second directive:-

```<code>app.directive('realTimeCurrency', function ($filter, $locale) {
    var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
    var toNumberRegex = new RegExp('[^0-9\\' + decimalSep + ']', 'g');
    var trailingZerosRegex = new RegExp('\\' + decimalSep + '0+$');
    var filterFunc = function (value) {
        return $filter('currency')(value);
    };

    function getCaretPosition(input){
        if (!input) return 0;
        if (input.selectionStart !== undefined) {
            return input.selectionStart;
        } else if (document.selection) {
            // Curse you IE
            input.focus();
            var selection = document.selection.createRange();
            selection.moveStart('character', input.value ? -input.value.length : 0);
            return selection.text.length;
        }
        return 0;
    }

    function setCaretPosition(input, pos){
        if (!input) return 0;
        if (input.offsetWidth === 0 || input.offsetHeight === 0) {
            return; // Input's hidden
        }
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(pos, pos);
        }
        else if (input.createTextRange) {
            // Curse you IE
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

    function toNumber(currencyStr) {
        return parseFloat(currencyStr.replace(toNumberRegex, ''), 10);
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function postLink(scope, elem, attrs, modelCtrl) {
            modelCtrl.$formatters.push(filterFunc);
            modelCtrl.$parsers.push(function (newViewValue) {
                var oldModelValue = modelCtrl.$modelValue;
                var newModelValue = toNumber(newViewValue);
                modelCtrl.$viewValue = filterFunc(newModelValue);
                var pos = getCaretPosition(elem[0]);
                elem.val(modelCtrl.$viewValue);
                var newPos = pos + modelCtrl.$viewValue.length -
                                   newViewValue.length;
                if ((oldModelValue === undefined) || isNaN(oldModelValue)) {
                    newPos -= 3;
                }
                setCaretPosition(elem[0], newPos);
                return newModelValue;
            });
        }
    };
});
</code>```

First directive:-

```<code>app.directive('format', ['$filter', '$compile', function($filter, $compile) {
    return {
      require: 'ngModel',
      scope: {
        val: '=val'
      },
      link: function(scope, elem, attrs, ctrl) {

        if (!ctrl) return;
        ctrl.$formatters.unshift(function(a) {

          if (attrs.symbol == '$')
            return $filter(attrs.format)(ctrl.$modelValue, '$')
          else
            return $filter(attrs.format)(ctrl.$modelValue)
        });

                scope.$watch(function() {
            return elem.val()
        }, function(newVal, oldVal) {
          var a = newVal;
          var plainNumber = a.split('.').filter(function(e) {
            return (e.length > 0);
          }).join('.');
          var i = 0;
          if (isNaN(parseFloat(plainNumber))) {
            i = (attrs.symbol == '$') ? 1 : 3;
          }
          var num = plainNumber.substring(i, plainNumber.length).replace(/,/g, '');
          if (attrs.symbol == '$')
            elem.val($filter('currency')(num, attrs.symbol));
          else
            elem.val($filter('currency')(num));
          var n = parseFloat(num);
          scope.val = Number(n);
          if (!scope.$$phase) {
            $compile(elem.contents())(scope)
          }
        });
      }
    };

    // controller
  }])
</code>```

答:
If I understood your question right, you want to remove $ and/or S\. from a string which represents a number.

Hope this will work just fine:

```<code>plainNumber.replace(/(\S\/\.|\$)/g, '');
</code>```

Title: How to remove formated mask to a value

Body:
I want to remove formated mask(either '$' or 'S/.') to the value. I have two angular directives. those are 1st directive. and 2nd directive.

In the second directive the symbol is not at all effecting to ng-model but the first directive it is effecting to ng-model.The first directive is removing the symbol, But if the text box is contains ng-change functions, it is calling ng-change functions then it is going to directive. so the symbol is effecting to ng-model.

The second directive is the symbol is not at all effecting to ng-model. Like this I need to the first directive too.

Second directive:-

app.directive('realTimeCurrency', function ($filter, $locale) {
    var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
    var toNumberRegex = new RegExp('[^0-9\\' + decimalSep + ']', 'g');
    var trailingZerosRegex = new RegExp('\\' + decimalSep + '0+$');
    var filterFunc = function (value) {
        return $filter('currency')(value);
    };

    function getCaretPosition(input){
        if (!input) return 0;
        if (input.selectionStart !== undefined) {
            return input.selectionStart;
        } else if (document.selection) {
            // Curse you IE
            input.focus();
            var selection = document.selection.createRange();
            selection.moveStart('character', input.value ? -input.value.length : 0);
            return selection.text.length;
        }
        return 0;
    }

    function setCaretPosition(input, pos){
        if (!input) return 0;
        if (input.offsetWidth === 0 || input.offsetHeight === 0) {
            return; // Input's hidden
        }
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(pos, pos);
        }
        else if (input.createTextRange) {
            // Curse you IE
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

    function toNumber(currencyStr) {
        return parseFloat(currencyStr.replace(toNumberRegex, ''), 10);
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function postLink(scope, elem, attrs, modelCtrl) {
            modelCtrl.$formatters.push(filterFunc);
            modelCtrl.$parsers.push(function (newViewValue) {
                var oldModelValue = modelCtrl.$modelValue;
                var newModelValue = toNumber(newViewValue);
                modelCtrl.$viewValue = filterFunc(newModelValue);
                var pos = getCaretPosition(elem[0]);
                elem.val(modelCtrl.$viewValue);
                var newPos = pos + modelCtrl.$viewValue.length -
                                   newViewValue.length;
                if ((oldModelValue === undefined) || isNaN(oldModelValue)) {
                    newPos -= 3;
                }
                setCaretPosition(elem[0], newPos);
                return newModelValue;
            });
        }
    };
});

First directive:-

app.directive('format', ['$filter', '$compile', function($filter, $compile) {
    return {
      require: 'ngModel',
      scope: {
        val: '=val'
      },
      link: function(scope, elem, attrs, ctrl) {

        if (!ctrl) return;
        ctrl.$formatters.unshift(function(a) {

          if (attrs.symbol == '$')
            return $filter(attrs.format)(ctrl.$modelValue, '$')
          else
            return $filter(attrs.format)(ctrl.$modelValue)
        });

                scope.$watch(function() {
            return elem.val()
        }, function(newVal, oldVal) {
          var a = newVal;
          var plainNumber = a.split('.').filter(function(e) {
            return (e.length > 0);
          }).join('.');
          var i = 0;
          if (isNaN(parseFloat(plainNumber))) {
            i = (attrs.symbol == '$') ? 1 : 3;
          }
          var num = plainNumber.substring(i, plainNumber.length).replace(/,/g, '');
          if (attrs.symbol == '$')
            elem.val($filter('currency')(num, attrs.symbol));
          else
            elem.val($filter('currency')(num));
          var n = parseFloat(num);
          scope.val = Number(n);
          if (!scope.$$phase) {
            $compile(elem.contents())(scope)
          }
        });
      }
    };

    // controller
  }])

Body:
If I understood your question right, you want to remove $ and/or S\. from a string which represents a number.

Hope this will work just fine:

plainNumber.replace(/(\S\/\.|\$)/g, '');


问:
How to perform range comparison for integer in java eg .x>a<y
How to perform range comparison for integer in java eg .x>a

eg . i want to check if my integer a falls between range x and y

a>30 and a<40

Thanks in advance

答:
You are almost there. If you struggling to put the correct syntax, just convert that and to &&

```<code>  int a = 35; // for ex
    if(a>30 && a<40) {
      // yes do something please
    }
</code>```

Body:
You are almost there. If you struggling to put the correct syntax, just convert that and to &&

  int a = 35; // for ex
    if(a>30 && a<40) {
      // yes do something please
    }


问:
Associating a date range with a Drupal Taxonomy
I am building a community site based on work locations and people who worked there over a period of time.
I have a taxonomy of 'locations' with 4000+ terms and a membership of 3000+ users. Each user could have worked at an unlimited number of locations over a period of many years (Mid 1950s to date).
I am stuck on how to refine attache a date range value to each users work at a location.
My intention is to programatically build relationships between users who worked at a location at any one time. e.g.
1 - User BOB worked at location SHOP between 1999 and 2004.
2 - User SUE worked at Location SHOP between 2001 and 2008 - These users have a relationship both with the location and with each other.
3 - User JIM also worked at Location SHOP between 1975 and 1997 and therefore has no relationship other that with the location.
I suspect I need to know how best to add a date range to each Users relationship with the Location and how to compare these relationships with each other.
Any ideas or guidance would be appreciated.</p>

答:
Another option on D7 (sorry don't know about D8) would be to use a module like field collections.

This would allow you to have a field collection that contains a date & taxonomy term for your location.

If you add field_collection to your user you could allow it to have an unlimited number of values.


问:
Unexpected end of JSON input - apex/ajax
In APEX i have a Dynamic Action that triggers when the page is loaded, it checks if the last page is different from the current page and then it should call a proccess with AJAX that clears the page cache with an PL/SQL function

But when i switch to the page theres a big error message:

Error: parseerror - SyntaXError: Unexpected end of JSON input

But the page cache is cleared after i refresh the page, if i use the PL/SQL function only i dont have to refresh it and all values of the page are empty

I'm fairely new to APEX/SQL and PL/SQL and i have absolutely no idea of JSON

Heres the code that i use in the Dynamic Action to call the process if the page URL is different

```<code>var ref = document.referrer;
var cur = window.location.href;

if (cur != ref)
{
    apex.server.process('refresh',
        {
            "dataType:":"script"
        }
    );
}
</code>```

Heres the proccess code

```<code>BEGIN
APEX_UTIL.CLEAR_PAGE_CACHE (NV('APP_PAGE_ID'));
END;
</code>```

For the research i did i found out that is has to be something with the AJAX call in the JavaScript. I switched the dataType to script so when the call succeeds it executes it automatically. What am i missing?

答:
You're missing the second argument to apex.server.process. The first argument is the process name, the second is an object with data to pass to the request, and the third is an object with options to pass to $.ajax.

So, to set the dataType:

```<code>apex.server.process('refresh',
    null,
    {
        "dataType:":"script"
    }
);
</code>```

However... It's really not clear why you'd do this? Why erase session state in your current page through a page-load ajax process? What's the point?

Body:
In APEX i have a Dynamic Action that triggers when the page is loaded, it checks if the last page is different from the current page and then it should call a proccess with AJAX that clears the page cache with an PL/SQL function

But when i switch to the page theres a big error message:

Error: parseerror - SyntaXError: Unexpected end of JSON input

But the page cache is cleared after i refresh the page, if i use the PL/SQL function only i dont have to refresh it and all values of the page are empty

I'm fairely new to APEX/SQL and PL/SQL and i have absolutely no idea of JSON

Heres the code that i use in the Dynamic Action to call the process if the page URL is different

var ref = document.referrer;
var cur = window.location.href;

if (cur != ref)
{
    apex.server.process('refresh',
        {
            "dataType:":"script"
        }
    );
}

Heres the proccess code

BEGIN
APEX_UTIL.CLEAR_PAGE_CACHE (NV('APP_PAGE_ID'));
END;

For the research i did i found out that is has to be something with the AJAX call in the JavaScript. I switched the dataType to script so when the call succeeds it executes it automatically. What am i missing?

Body:
You're missing the second argument to apex.server.process. The first argument is the process name, the second is an object with data to pass to the request, and the third is an object with options to pass to $.ajax.

So, to set the dataType:

apex.server.process('refresh',
    null,
    {
        "dataType:":"script"
    }
);

However... It's really not clear why you'd do this? Why erase session state in your current page through a page-load ajax process? What's the point?


问:
Disable next page on uiGrid
I am using external pagination with ui-grid and angularjs.

The server has 70 items mocked at the moment, but I will not know the items count from the server.
The pageSize is set to 50.

So it should have 2 pages (one with 50 items on it and one with 20).

The button for next page is NOT disabled on the second page but on the third one when there are no items in the grid to show.

I would like it disabled on the second page!

Link to the plunk: http://plnkr.co/edit/OuM8lN0R06Xudn1frLax?p=preview

app.js

```<code>var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.pagination']);

app.service('foo', ['$q', function ($q) {
    var items = [];
    for (var i = 0; i < 70; i++) {
        items.push({
            "firstName": "firstName" + i,
            "lastName": "lastName" + i,
            "company": "company" + i,
            "employed": i % 4 === 0
        });
    }

    this.bar = function (page, pageSize) {
        var deferred = $q.defer();

        var start = (page - 1) * pageSize;
        deferred.resolve(items.slice(start, start + pageSize));

        return deferred.promise;
    };

    return this;
}]);

app.controller('MainCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', 'foo', function ($scope, $http, $log, $timeout, uiGridConstants, foo) {
    var paginationOptions = {
        pageNumber: 1,
        pageSize: 50,
        sort: null
    };

    $scope.selectedIds = [];

    $scope.gridOptions = getOptions();

    function getOptions() {
        return {
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 2,

            enableRowSelection: true,
            enableFullRowSelection: true,
            multiSelect: true,

            paginationPageSizes: [50, 100],
            paginationPageSize: 50,
            useExternalPagination: true,

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                getPage(1, 50);

                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage;
                    paginationOptions.pageSize = pageSize;
                    getPage(newPage, pageSize);
                });
            }
        };
    }

    function getPage(page, pageSize) {
        foo.bar(page, pageSize)
            .then(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.totalItems = undefined;
            });
    }

    getPage(1, 50);
}]);
</code>```

index.html

```<code><!doctype html>
<html ng-app="app">

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-touch.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
    <script src="http://ui-grid.info/release/ui-grid.js"></script>
    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">
</head>

<body>

    <div ng-controller="MainCtrl">
        <div class="grid" ui-grid="gridOptions" ui-grid-pagination ui-grid-selection></div>
    </div>

    <script src="app.js"></script>
</body>

</html>
</code>```

答:
I have fixed it using a simple change in the getPage(page, pageSize) method.

Here is the code for the method:

```<code>function getPage(page, pageSize) {
    foo.bar(page, pageSize)
        .then(function (data) {
            $scope.gridOptions.data = data;
            $scope.gridOptions.totalItems = data.length === pageSize ? undefined : (page - 1) * pageSize + data.length;
        });
}
</code>```

Here is the working plunk

Title: Disable next page on uiGrid

Body:
I am using external pagination with ui-grid and angularjs.

The server has 70 items mocked at the moment, but I will not know the items count from the server.
The pageSize is set to 50.

So it should have 2 pages (one with 50 items on it and one with 20).

The button for next page is NOT disabled on the second page but on the third one when there are no items in the grid to show.

I would like it disabled on the second page!

Link to the plunk: http://plnkr.co/edit/OuM8lN0R06Xudn1frLax?p=preview

app.js

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.pagination']);

app.service('foo', ['$q', function ($q) {
    var items = [];
    for (var i = 0; i < 70; i++) {
        items.push({
            "firstName": "firstName" + i,
            "lastName": "lastName" + i,
            "company": "company" + i,
            "employed": i % 4 === 0
        });
    }

    this.bar = function (page, pageSize) {
        var deferred = $q.defer();

        var start = (page - 1) * pageSize;
        deferred.resolve(items.slice(start, start + pageSize));

        return deferred.promise;
    };

    return this;
}]);

app.controller('MainCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', 'foo', function ($scope, $http, $log, $timeout, uiGridConstants, foo) {
    var paginationOptions = {
        pageNumber: 1,
        pageSize: 50,
        sort: null
    };

    $scope.selectedIds = [];

    $scope.gridOptions = getOptions();

    function getOptions() {
        return {
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 2,

            enableRowSelection: true,
            enableFullRowSelection: true,
            multiSelect: true,

            paginationPageSizes: [50, 100],
            paginationPageSize: 50,
            useExternalPagination: true,

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                getPage(1, 50);

                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage;
                    paginationOptions.pageSize = pageSize;
                    getPage(newPage, pageSize);
                });
            }
        };
    }

    function getPage(page, pageSize) {
        foo.bar(page, pageSize)
            .then(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.totalItems = undefined;
            });
    }

    getPage(1, 50);
}]);

index.html

<!doctype html>

    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">

Body:
I have fixed it using a simple change in the getPage(page, pageSize) method.

Here is the code for the method:

function getPage(page, pageSize) {
    foo.bar(page, pageSize)
        .then(function (data) {
            $scope.gridOptions.data = data;
            $scope.gridOptions.totalItems = data.length === pageSize ? undefined : (page - 1) * pageSize + data.length;
        });
}

Here is the working plunk


问:
How to create get request using apache httpclient with "bad" symbols in url (that requere encoding)?
I'm trying to create auto test (java). Service should be able to handle request correctly: return json instead of java stack trace.

In this test i have cases like #host/some/path/?param=%

Ok, % is incorrect symbol and should be encoded. When you are developer and creating service that send requests. But this is a test.

So question is: how can i create get response with url «as is», without encoding? Currently i'm using apache httpclient (4.5.2)

Currently i have nothing really special:

```<code>public void fetchGet(String uri) {
    HttpGet getRequest = new HttpGet(uri);

    HttpClient client = HttpClientBuilder.create().build();

    try {
        response = client.execute(requestBase);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        requestBase.abort();
    }
}
</code>```

答:
Use BasicHttpRequest instead of HttpGet to compose a request message

```<code>CloseableHttpClient client = HttpClientBuilder.create().build();
BasicHttpRequest request = new BasicHttpRequest("GET", "all kind of c%.p");

try (CloseableHttpResponse response1 = client.execute(new HttpHost("www.google.com"), request)) {
    System.out.println(response1.getStatusLine());
    EntityUtils.consume(response1.getEntity());
}
</code>```

This code produces the following message exchange

```<code>[DEBUG] ProtocolExec - Unable to parse 'all kind of c%.p' as a valid URI; request URI and Host header may be inconsistent <java.lang.IllegalArgumentException: Illegal character in path at index 3: all kind of c%.p>java.lang.IllegalArgumentException: Illegal character in path at index 3: all kind of c%.p
    at java.net.URI.create(URI.java:852)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:120)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:118)
    at Testing.main(Testing.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.net.URISyntaxException: Illegal character in path at index 3: all kind of c%.p
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.parseHierarchical(URI.java:3105)
    at java.net.URI$Parser.parse(URI.java:3063)
    at java.net.URI.<init>(URI.java:588)
    at java.net.URI.create(URI.java:850)
    ... 11 more

[DEBUG] RequestAddCookies - CookieSpec selected: default
[DEBUG] RequestAuthCache - Auth cache not set in the context
[DEBUG] PoolingHttpClientConnectionManager - Connection request: [route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
[DEBUG] PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
[DEBUG] MainClientExec - Opening connection {}->http://www.google.com:80
[DEBUG] DefaultHttpClientConnectionOperator - Connecting to www.google.com/216.58.213.100:80
[DEBUG] DefaultHttpClientConnectionOperator - Connection established xx.xx.xx.xx:36088<->216.58.213.100:80
[DEBUG] MainClientExec - Executing request GET all kind of c%.p HTTP/1.1
[DEBUG] MainClientExec - Target auth state: UNCHALLENGED
[DEBUG] MainClientExec - Proxy auth state: UNCHALLENGED
[DEBUG] headers - http-outgoing-0 >> GET all kind of c%.p HTTP/1.1
[DEBUG] headers - http-outgoing-0 >> Host: www.google.com
[DEBUG] headers - http-outgoing-0 >> Connection: Keep-Alive
[DEBUG] headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_112)
[DEBUG] headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
[DEBUG] headers - http-outgoing-0 << HTTP/1.1 400 Bad Request
[DEBUG] headers - http-outgoing-0 << Cache-Control: no-cache
[DEBUG] headers - http-outgoing-0 << Pragma: no-cache
[DEBUG] headers - http-outgoing-0 << Content-Type: text/html; charset=utf-8
[DEBUG] headers - http-outgoing-0 << Connection: close
[DEBUG] headers - http-outgoing-0 << Content-Length: 1904
HTTP/1.1 400 Bad Request
[DEBUG] DefaultManagedHttpClientConnection - http-outgoing-0: Close connection
[DEBUG] MainClientExec - Connection discarded
[DEBUG] PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
</code>```

Body:
I'm trying to create auto test (java). Service should be able to handle request correctly: return json instead of java stack trace.

In this test i have cases like #host/some/path/?param=%

Ok, % is incorrect symbol and should be encoded. When you are developer and creating service that send requests. But this is a test.

So question is: how can i create get response with url «as is», without encoding? Currently i'm using apache httpclient (4.5.2)

Currently i have nothing really special:

public void fetchGet(String uri) {
    HttpGet getRequest = new HttpGet(uri);

    HttpClient client = HttpClientBuilder.create().build();

    try {
        response = client.execute(requestBase);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        requestBase.abort();
    }
}

Body:
Use BasicHttpRequest instead of HttpGet to compose a request message

CloseableHttpClient client = HttpClientBuilder.create().build();
BasicHttpRequest request = new BasicHttpRequest("GET", "all kind of c%.p");

try (CloseableHttpResponse response1 = client.execute(new HttpHost("www.google.com"), request)) {
    System.out.println(response1.getStatusLine());
    EntityUtils.consume(response1.getEntity());
}

This code produces the following message exchange

[DEBUG] ProtocolExec - Unable to parse 'all kind of c%.p' as a valid URI; request URI and Host header may be inconsistent <java.lang.IllegalArgumentException: Illegal character in path at index 3: all kind of c%.p>java.lang.IllegalArgumentException: Illegal character in path at index 3: all kind of c%.p
    at java.net.URI.create(URI.java:852)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:120)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:118)
    at Testing.main(Testing.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.net.URISyntaxException: Illegal character in path at index 3: all kind of c%.p
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.parseHierarchical(URI.java:3105)
    at java.net.URI$Parser.parse(URI.java:3063)
    at java.net.URI.<init>(URI.java:588)
    at java.net.URI.create(URI.java:850)
    ... 11 more

[DEBUG] RequestAddCookies - CookieSpec selected: default
[DEBUG] RequestAuthCache - Auth cache not set in the context
[DEBUG] PoolingHttpClientConnectionManager - Connection request: [route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
[DEBUG] PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
[DEBUG] MainClientExec - Opening connection {}->http://www.google.com:80
[DEBUG] DefaultHttpClientConnectionOperator - Connecting to www.google.com/216.58.213.100:80
[DEBUG] DefaultHttpClientConnectionOperator - Connection established xx.xx.xx.xx:36088<->216.58.213.100:80
[DEBUG] MainClientExec - Executing request GET all kind of c%.p HTTP/1.1
[DEBUG] MainClientExec - Target auth state: UNCHALLENGED
[DEBUG] MainClientExec - Proxy auth state: UNCHALLENGED
[DEBUG] headers - http-outgoing-0 >> GET all kind of c%.p HTTP/1.1
[DEBUG] headers - http-outgoing-0 >> Host: www.google.com
[DEBUG] headers - http-outgoing-0 >> Connection: Keep-Alive
[DEBUG] headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_112)
[DEBUG] headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
[DEBUG] headers - http-outgoing-0 << HTTP/1.1 400 Bad Request
[DEBUG] headers - http-outgoing-0 << Cache-Control: no-cache
[DEBUG] headers - http-outgoing-0 << Pragma: no-cache
[DEBUG] headers - http-outgoing-0 << Content-Type: text/html; charset=utf-8
[DEBUG] headers - http-outgoing-0 << Connection: close
[DEBUG] headers - http-outgoing-0 << Content-Length: 1904
HTTP/1.1 400 Bad Request
[DEBUG] DefaultManagedHttpClientConnection - http-outgoing-0: Close connection
[DEBUG] MainClientExec - Connection discarded
[DEBUG] PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://www.google.com:80][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]


问:
UI Bootstrap datepicker calendar doesn't show the date in the textbox
I have a page on my view and an option to edit that page. When the "edit" option is clicked, a child view comes up and shows all the editable field. One field is a datepicker which is binding to a modal.

The textbox contains the date, but when I open the calendar pop up, The date in the textbox is not highlighted in the calendar.
I then select a different date and close the child view.

Now, when I open the calendar popup of another item, the date previously selected is highlighted. (the date in the textbox is different)
I am stuck with this for a while now. Below is my markup

```<code> <div class="col-sm-4 ph-calendar">
                    <div class="input-group">
                        <input type="text"
                               id="duedate"
                               class="form-control"
                               datepicker-popup="{{dateFormat}}"
                               ng-model="milestone.duedate"
                               ph-validator="milestone.duedate"
                               ng-required="true"
                               is-open="datepickerOpenState.dueDateOpened"
                               datepicker-options="dateOptions"
                               ng-disabled="(isrecurring && isseries) || !permissions.canUpdateMilestones"
                               close-text="Close"
                               tooltip="dd/mm/yyyy"
                               tooltip-placement="bottom"
                               ph-datepicker-fix />

                        <span class="input-group-btn datepickerbtn">
                            <button type="button" class="btn btn-default" ng-click="openDatepicker($event, 'duedate')" ng-disabled="(isrecurring && isseries)  || !permissions.canUpdateMilestones">
                                <i class="fa fa-calendar"></i>
                            </button>
                        </span>
                    </div>
                </div>
</code>```

This is my js

```<code>$scope.openDatepicker = function ($event, dateType, date) {
            $event.preventDefault();
            $event.stopPropagation();

            switch (dateType) {
                case 'duedate':
                    $scope.datepickerOpenState.dueDateOpened = true;
                    $scope.datepickerOpenState.completionDateOpened = false;
                    $scope.datepickerOpenState.startDateOpened = false;
                    $scope.datepickerOpenState.endDateOpened = false;
                    break;
</code>```

I also do some formatting for the datepicker

```<code>  ngModelCtrl.$render = function () {

            if (ngModelCtrl.$viewValue) {
            ngModelCtrl.$viewValue = new Date(ngModelCtrl.$viewValue);
            var dateVal = ngModelCtrl.$viewValue ? $filter('date')(ngModelCtrl.$viewValue, 'dd/MM/yyyy') : '';

            $element.val(dateVal);
            } else {
                $element.val(null);
            }
        };
</code>```

答:
For me, the problem was that the input element I used for the datepicker was of type "text" and not "date".

So changing your code to this should do the trick.

```<code><input type="date" />
</code>```

Body:
I have a page on my view and an option to edit that page. When the "edit" option is clicked, a child view comes up and shows all the editable field. One field is a datepicker which is binding to a modal.

The textbox contains the date, but when I open the calendar pop up, The date in the textbox is not highlighted in the calendar.
I then select a different date and close the child view.

Now, when I open the calendar popup of another item, the date previously selected is highlighted. (the date in the textbox is different)
I am stuck with this for a while now. Below is my markup

                        <input type="text"
                               id="duedate"
                               class="form-control"
                               datepicker-popup="{{dateFormat}}"
                               ng-model="milestone.duedate"
                               ph-validator="milestone.duedate"
                               ng-required="true"
                               is-open="datepickerOpenState.dueDateOpened"
                               datepicker-options="dateOptions"
                               ng-disabled="(isrecurring && isseries) || !permissions.canUpdateMilestones"
                               close-text="Close"
                               tooltip="dd/mm/yyyy"
                               tooltip-placement="bottom"
                               ph-datepicker-fix />

                            <button type="button" class="btn btn-default" ng-click="openDatepicker($event, 'duedate')" ng-disabled="(isrecurring && isseries)  || !permissions.canUpdateMilestones">

                            </button>

This is my js

$scope.openDatepicker = function ($event, dateType, date) {
            $event.preventDefault();
            $event.stopPropagation();

            switch (dateType) {
                case 'duedate':
                    $scope.datepickerOpenState.dueDateOpened = true;
                    $scope.datepickerOpenState.completionDateOpened = false;
                    $scope.datepickerOpenState.startDateOpened = false;
                    $scope.datepickerOpenState.endDateOpened = false;
                    break;

I also do some formatting for the datepicker

  ngModelCtrl.$render = function () {

            if (ngModelCtrl.$viewValue) {
            ngModelCtrl.$viewValue = new Date(ngModelCtrl.$viewValue);
            var dateVal = ngModelCtrl.$viewValue ? $filter('date')(ngModelCtrl.$viewValue, 'dd/MM/yyyy') : '';

            $element.val(dateVal);
            } else {
                $element.val(null);
            }
        };

Body:
For me, the problem was that the input element I used for the datepicker was of type "text" and not "date".

So changing your code to this should do the trick.

<input type="date" />


问:
Launching activity on long press of volume button
I want to launch app when we press the volume button long time up or down button.When activity is not visible and app is present in background i.e in recent apps.Is there any solution for that. I am new to android so please help me to resolve this problem.</p>

答: Just look for broadcast receiver on android developer site. You will get goo explanation with example.</p>


问:
Regular expression in java always return true
Can you please help me with regex for the following string in android:

```<code>1.0.2 Build S6B5
</code>```

How it should be:

```<code>{number}.{number}.{number}{space}Build{space}{S or D orT}{anything up 3 to 4 chars}
</code>```

With help of some king people from here I`ve tried the flowing code:

```<code>if (name.matches("\\d+\\.\\d+\\.\\d+\\s+Build\\s[SDT].{3,4}"));
</code>```

but it always return True even for:

```<code>1.0.1 4C0

1.0.1 B 4BD

1.0.4.52A
</code>```

etc.

答:
Try this one instead :
(\d{1}).(\d{1}).(\d{1})\s(Build)\s([SDT])([\w\d]{3,4})

or

(\d).(\d).(\d)*\s(Build)\s([SDT])([\w\d]{3,4}) if you can have multiple numbers.

In your, the problem is the end of the regex : ".{3,4}". It means that you accept ANY character 3 to 4 times.

Body:
Can you please help me with regex for the following string in android:

1.0.2 Build S6B5

How it should be:

{number}.{number}.{number}{space}Build{space}{S or D orT}{anything up 3 to 4 chars}

With help of some king people from here I`ve tried the flowing code:

if (name.matches("\\d+\\.\\d+\\.\\d+\\s+Build\\s[SDT].{3,4}"));

but it always return True even for:

1.0.1 4C0

1.0.1 B 4BD

1.0.4.52A

etc.


问:
How do I measure the distance between UI elements in Xcode?
I'm trying to determine the distance between UI elements in my app, to check that the layout matches that specified by designers. I'm using the 'Debug UI Hierarchy' option, and I do see the representation of the phone's UI in Xcode. However, the only way I can see to determine the relative positioning of two elements is to look at the Size inspector in the right sidebar, and do a manual calculation on their provided measurements. Is there a better way to do this? Can I select one element and then select another to compare it with?</p>

答:
I now its been a while since you asked your question but I've faced the same problem and I could figure out how to measure NSConstraints between views in runtime.

First, you have to click the debug view hierarchy icon on the debug area as shown on this picture:

After pressing the button a snapshot of the Views hierarchy will be shown on the Xcode screen as follows:

You can see all the elements (UIViews) that are actually being displayed (or not, they can be in the background) on the screen of the device

After this, you can press on the show constraint icon to show the constrains that are being applied to every view on the screen, you'll have a screen pretty similar to the interface builder constraint layout:

If you select on a particular constraint (the one you actually care about), i.e in this screen I want to know the distance between the top and the ImageView that is being represented by the big square. So selecting on that particular constraint and clicking on the inspector Object inspector icon inside the Utilities panel you can actually see the constraint description.

This way you can see the constraints measures and the relation with the views and frame bounds.


问:
error after running a job in google cloud ML
I tried running a word-RNN model from github on Google Cloud ML . After submitting the job,I am getting errors in log file.

This is what i submitted for training

```<code>gcloud ml-engine jobs submit training word_pred_7 \
    --package-path trainer \
    --module-name trainer.train \
    --runtime-version 1.0 \
    --job-dir $JOB_DIR \
    --region $REGION \
    -- \
    --data_dir gs://model-development/arpit/word-rnn-tensorflow-master/data/tinyshakespeare/real1.txt \
    --save_dir gs://model-development/arpit/word-rnn-tensorflow-master/save
</code>```

This is what I get in the log file.

答:
<s>In addition to adding --job-dir as accepted argument, I think you should also move the flag after the --.

From the getting started:

Run the local train command using the --distribued option. Be sure to
  place the flag above the -- that separates the user arguments from the
  command-line arguments

where, in that case, --distribued was a command-line argument</S>

EDIT:

--job-dir IS NOT a user argument, so it is correct to place it before the --

ContentLicense: CC BY-SA 4.0

Body:
I tried running a word-RNN model from github on Google Cloud ML . After submitting the job,I am getting errors in log file.

This is what i submitted for training

gcloud ml-engine jobs submit training word_pred_7 \
    --package-path trainer \
    --module-name trainer.train \
    --runtime-version 1.0 \
    --job-dir $JOB_DIR \
    --region $REGION \
    -- \
    --data_dir gs://model-development/arpit/word-rnn-tensorflow-master/data/tinyshakespeare/real1.txt \
    --save_dir gs://model-development/arpit/word-rnn-tensorflow-master/save

This is what I get in the log file.