问:
copy and running configfiles programatically in ansible
There is a ansible code i am writing. It does two tasks, first is to copy a configuration file to target instance in groups. Second is running that config file to install the application.

I am creating configuration file and inventory programtically so that same suffix is added to both configfile name & groupname in inventory:

```<code>Configfile name example :            Equivalent group names:
myappconf1                             [myapp1]
                                       hostname
myappconf2                             [myapp2]
                                       hostname
</code>```

This is my code for copying files

```<code>hosts: all
tasks:
name: Copy file.role1 to host1
 copy: src=/tmp/myconf1 dest=/tmp
 when:
  - "'myapp1' in group_names"

name: Copy Config File two to  to Ldap2
 copy: src=/tmp/myconf2 dest=/tmp
 when:
  - "'myapp2' in group_names"
</code>```

This is my code for running conf file

```<code>hosts: myapp1
tasks:
  - command: "/tmp/mainapp/update.sh -f myappconf1"

hosts: myapp2
tasks:
  - command: "/tmp/mainapp/update.sh -f myappconf1"
</code>```

But depending on user input uncertain number of conf files and groups can be created so I would like to do task more programatically. desired code may look like:

```<code>[task for copying file]
hosts: ~(myapp)
tasks:
- copy: copy the appropriate file to the host
        example: copy myappconf4 to myapp4
- command: run the commmand with appropirate file
           example: for myapp3, command: /tmp/mainapp/update.sh -f myappconf3
</code>```

Can someone please suggest me what i can use to make my code more generic and efficient ?

答:
I populated variables with my python code in below format to resolve the issue:

```<code>[myapp]
host1 conf_file="myappconf1"
host2 conf_file="myappconf2"
</code>```

then in my code i used the variable for both copy and running configfile tasks.

Body:
There is a ansible code i am writing. It does two tasks, first is to copy a configuration file to target instance in groups. Second is running that config file to install the application.

I am creating configuration file and inventory programtically so that same suffix is added to both configfile name & groupname in inventory:

Configfile name example :            Equivalent group names:
myappconf1                             [myapp1]
                                       hostname
myappconf2                             [myapp2]
                                       hostname

This is my code for copying files

hosts: all
tasks:
name: Copy file.role1 to host1
 copy: src=/tmp/myconf1 dest=/tmp
 when:
  - "'myapp1' in group_names"

name: Copy Config File two to  to Ldap2
 copy: src=/tmp/myconf2 dest=/tmp
 when:
  - "'myapp2' in group_names"

This is my code for running conf file

hosts: myapp1
tasks:
  - command: "/tmp/mainapp/update.sh -f myappconf1"

hosts: myapp2
tasks:
  - command: "/tmp/mainapp/update.sh -f myappconf1"

But depending on user input uncertain number of conf files and groups can be created so I would like to do task more programatically. desired code may look like:

[task for copying file]
hosts: ~(myapp)
tasks:
- copy: copy the appropriate file to the host
        example: copy myappconf4 to myapp4
- command: run the commmand with appropirate file
           example: for myapp3, command: /tmp/mainapp/update.sh -f myappconf3

Can someone please suggest me what i can use to make my code more generic and efficient ?

Body:
I populated variables with my python code in below format to resolve the issue:

[myapp]
host1 conf_file="myappconf1"
host2 conf_file="myappconf2"

then in my code i used the variable for both copy and running configfile tasks.


来源: stackexchange

问:
Decrypting an AES-encrypted message with an RSA-encrypted key with EVP tool
For industrial purposes, I want to decrypt an AES-encrypted message with an RSA-encrypted key in C. At first, I thought doing it step-by-step by first, using OpenSSL libcrypto library, by first RSA decoding the key then AES decoding the data.

I have found out that EVP tools were commonly seen as a better way to do this since it actually does what the low-levels functions do but correctly.
Here is what I see the flow of the program :

Initialize OpenSSL;

Read and store the RSA private key;

Initialize the decryption by specifying the decryption algorithm (AES) and the private key;

Update the decryption by giving the key, the data, the key and their length

Finally decrypt the data and return it.

I have been a lot confused by the fact that so far we do not intend to use any IV or ADD (although IV might come up later in the project). I have followed this guide it is not very clear and does not fit the way I use EVP.

So here is my actual code :

```<code>#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include "openssl\applink.c"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

const char PRIVATE_KEY_PATH[] = "C:/Users/Local_user/privateKey.pem";

EVP_PKEY* initializePrivateKey(void)
{
    FILE* privateKeyfile;
    if ((privateKeyfile = fopen(PRIVATE_KEY_PATH, "r")) == NULL) // Check PEM file opening
    {
        perror("Error while trying to access to private key.\n");
        return NULL;
    }

    RSA *rsaPrivateKey = RSA_new();
    EVP_PKEY *privateKey = EVP_PKEY_new();

    if ((rsaPrivateKey = PEM_read_RSAPrivateKey(privateKeyfile, &rsaPrivateKey, NULL, NULL)) == NULL) // Check PEM file reading
    {
        fprintf(stderr, "Error loading RSA Private Key File.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if (!EVP_PKEY_assign_RSA(privateKey, rsaPrivateKey))
    {
        fprintf(stderr, "Error when initializing EVP private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    return privateKey;
}
const uint8_t* decodeWrappingKey(uint8_t const* data, const size_t data_len, uint8_t const* wrappingKey, const size_t wrappingKey_len)
{
    // Start Decryption
    EVP_CIPHER_CTX *ctx;
    if (!(ctx = EVP_CIPHER_CTX_new())) // Initialize context
    {
        fprintf(stderr, "Error when initializing context.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    EVP_PKEY *privateKey = initializePrivateKey();
    if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, privateKey, NULL)) // Initialize decryption
    {
        fprintf(stderr, "Error when initializing decryption.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    uint8_t* res;
    if ((res = calloc(data_len, sizeof(uint8_t))) == NULL) // Check memory allocating
    {
        perror("Memory allocating error ");
        return NULL;
    }
    puts("Initialization done. Decoding..\n");
    size_t res_len = 0;
    if (1 != EVP_DecryptUpdate(ctx, res, &res_len, data, data_len))
    {
        fprintf(stderr, "Error when preparing decryption.\n");
        ERR_print_errors_fp(stderr);
    }

    if (1 != EVP_DecryptFinal_ex(ctx, res, &res_len))
    {
        fprintf(stderr, "Error when decrypting.\n");
        ERR_print_errors_fp(stderr);
    }
    return res;
}

void hexToBytes(uint8_t *des, char const *source, const size_t size) {

    for (int i = 0; i < size - 1; i += 2)
        sscanf(source + i, "%02x", des + (i / 2));
}

int main(void) {
    char const *strWrap = "5f82c48f85054ef6a3b2621819dd0e969030c79cc00deb89........";
    char const *strData = "ca1518d44716e3a4588af741982f29ad0a3e7a8d67.....";

    uint8_t *wrap = calloc(strlen(strWrap), sizeof(uint8_t));
    hexToBytes(wrap, strWrap, strlen(strWrap)); // Converts string to raw data
    uint8_t *data = calloc(strlen(strData), sizeof(uint8_t));
    hexToBytes(data, strData, strlen(strData));

    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);
    const uint8_t *res = decodeWrappingKey(data, strlen(strData) / 2, wrap, strlen(strWrap) / 2);
    if (res == NULL)
        return 1;
    return 0;
}
</code>```

My output is the following one :

```<code>Initialization done. Decoding..

Error when preparing decryption.
Error when decrypting.
</code>```

Obviously it fails when updating and finalising the decryption but I can't figure out why and the ERR_print_errors_fp(stderr); which had always worked for me so far seems to be mute.

答:
Your key is encrypted with RSA, so you will decrypt it with RSA APIs like RSA_private_decrypt first, not with EVP* APIs.

Once you get key decrypted you need to use it with (EVP*) APIs to decrypt the data with AES.

ContentLicense: CC BY-SA 3.0

Body:
For industrial purposes, I want to decrypt an AES-encrypted message with an RSA-encrypted key in C. At first, I thought doing it step-by-step by first, using OpenSSL libcrypto library, by first RSA decoding the key then AES decoding the data.

I have found out that EVP tools were commonly seen as a better way to do this since it actually does what the low-levels functions do but correctly.
Here is what I see the flow of the program :

Initialize OpenSSL;

Read and store the RSA private key;

Initialize the decryption by specifying the decryption algorithm (AES) and the private key;

Update the decryption by giving the key, the data, the key and their length

Finally decrypt the data and return it.

I have been a lot confused by the fact that so far we do not intend to use any IV or ADD (although IV might come up later in the project). I have followed this guide it is not very clear and does not fit the way I use EVP.

So here is my actual code :

#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include "openssl\applink.c"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

const char PRIVATE_KEY_PATH[] = "C:/Users/Local_user/privateKey.pem";

EVP_PKEY* initializePrivateKey(void)
{
    FILE* privateKeyfile;
    if ((privateKeyfile = fopen(PRIVATE_KEY_PATH, "r")) == NULL) // Check PEM file opening
    {
        perror("Error while trying to access to private key.\n");
        return NULL;
    }

    RSA *rsaPrivateKey = RSA_new();
    EVP_PKEY *privateKey = EVP_PKEY_new();

    if ((rsaPrivateKey = PEM_read_RSAPrivateKey(privateKeyfile, &rsaPrivateKey, NULL, NULL)) == NULL) // Check PEM file reading
    {
        fprintf(stderr, "Error loading RSA Private Key File.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if (!EVP_PKEY_assign_RSA(privateKey, rsaPrivateKey))
    {
        fprintf(stderr, "Error when initializing EVP private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    return privateKey;
}
const uint8_t* decodeWrappingKey(uint8_t const* data, const size_t data_len, uint8_t const* wrappingKey, const size_t wrappingKey_len)
{
    // Start Decryption
    EVP_CIPHER_CTX *ctx;
    if (!(ctx = EVP_CIPHER_CTX_new())) // Initialize context
    {
        fprintf(stderr, "Error when initializing context.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    EVP_PKEY *privateKey = initializePrivateKey();
    if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, privateKey, NULL)) // Initialize decryption
    {
        fprintf(stderr, "Error when initializing decryption.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    uint8_t* res;
    if ((res = calloc(data_len, sizeof(uint8_t))) == NULL) // Check memory allocating
    {
        perror("Memory allocating error ");
        return NULL;
    }
    puts("Initialization done. Decoding..\n");
    size_t res_len = 0;
    if (1 != EVP_DecryptUpdate(ctx, res, &res_len, data, data_len))
    {
        fprintf(stderr, "Error when preparing decryption.\n");
        ERR_print_errors_fp(stderr);
    }

    if (1 != EVP_DecryptFinal_ex(ctx, res, &res_len))
    {
        fprintf(stderr, "Error when decrypting.\n");
        ERR_print_errors_fp(stderr);
    }
    return res;
}

void hexToBytes(uint8_t *des, char const *source, const size_t size) {

    for (int i = 0; i < size - 1; i += 2)
        sscanf(source + i, "%02x", des + (i / 2));
}

int main(void) {
    char const *strWrap = "5f82c48f85054ef6a3b2621819dd0e969030c79cc00deb89........";
    char const *strData = "ca1518d44716e3a4588af741982f29ad0a3e7a8d67.....";

    uint8_t *wrap = calloc(strlen(strWrap), sizeof(uint8_t));
    hexToBytes(wrap, strWrap, strlen(strWrap)); // Converts string to raw data
    uint8_t *data = calloc(strlen(strData), sizeof(uint8_t));
    hexToBytes(data, strData, strlen(strData));

    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);
    const uint8_t *res = decodeWrappingKey(data, strlen(strData) / 2, wrap, strlen(strWrap) / 2);
    if (res == NULL)
        return 1;
    return 0;
}

My output is the following one :

Initialization done. Decoding..

Error when preparing decryption.
Error when decrypting.

Obviously it fails when updating and finalising the decryption but I can't figure out why and the ERR_print_errors_fp(stderr); which had always worked for me so far seems to be mute.


问:
Vue Props not working for child component
I have root element that has logged in user data and on user profile component I am passing logged in user data as props.

But when I try to call User object properties in child component it throws error as undefined. I don't see any value in child component.

app.js

```<code>Vue.component("usersmanagment", require("./components/usersmanagment"));

const app = new Vue({
    el: "#app",
    components: {
        'v-select': vSelect
    },
    data() {
        return {
            AuthorizedUser: {
                Email : "",
                FirstName : "",
                LastName : "",
                CreatedUtcDateTime : "",
                IsActive : ""
            }
        };
    },
    mounted() {
        let vm = this;
        vm.getAuthorisedUserProfile();
    },
    methods: {
        getAuthorisedUserProfile() {
            let vm = this;
            // just return auth user data
    }

});
</code>```

Than on child component I am passing props

```<code>module.exports = {
    props : ["AuthorizedUser"],

};
</code>```

and in my view file I am Asp.Net MVC

```<code><usersmanagment inline-template>
        <input type="text" class="form-control" v-model="AuthorizedUser.FirstName">
</usersmanagment>
</code>```

I can see in vue chrome dev tools that Authorized user get updated but its value don't get updated on child component.

答:
You haven't included it here, but my guess would be that you are passing the prop using camelCase but you need to pass it using kebab-case (see: camelCase vs kebab-case). So make sure you are doing:

```<code><child-component :authorized-user="AuthorizedUser"></child-component>
</code>```

Body:
I have root element that has logged in user data and on user profile component I am passing logged in user data as props.

But when I try to call User object properties in child component it throws error as undefined. I don't see any value in child component.

app.js

Vue.component("usersmanagment", require("./components/usersmanagment"));

const app = new Vue({
    el: "#app",
    components: {
        'v-select': vSelect
    },
    data() {
        return {
            AuthorizedUser: {
                Email : "",
                FirstName : "",
                LastName : "",
                CreatedUtcDateTime : "",
                IsActive : ""
            }
        };
    },
    mounted() {
        let vm = this;
        vm.getAuthorisedUserProfile();
    },
    methods: {
        getAuthorisedUserProfile() {
            let vm = this;
            // just return auth user data
    }

});

Than on child component I am passing props

module.exports = {
    props : ["AuthorizedUser"],

};

and in my view file I am Asp.Net MVC

<usersmanagment inline-template>
        <input type="text" class="form-control" v-model="AuthorizedUser.FirstName">
</usersmanagment>

I can see in vue chrome dev tools that Authorized user get updated but its value don't get updated on child component.

Body:
You haven't included it here, but my guess would be that you are passing the prop using camelCase but you need to pass it using kebab-case (see: camelCase vs kebab-case). So make sure you are doing:

<child-component :authorized-user="AuthorizedUser"></child-component>

ContentLicense: CC BY-SA 4.0


问:
Always same page number in MigraDoc
With this code I always get the same page number on every page. How to solve this problem?</p>

```<code>    static void DefineContentSection(Document document)
    {
        Section section = document.AddSection();
        section.PageSetup.OddAndEvenPagesHeaderFooter = true;
        section.PageSetup.StartingNumber = 1;

        Paragraph paragraph = new Paragraph();
        paragraph.AddText("Page ");
        paragraph.AddPageField();
        paragraph.AddText(" of ");
        paragraph.AddNumPagesField();

        section.Footers.Primary.Add(paragraph);
        section.Footers.EvenPage.Add(paragraph.Clone());
    }
</code>```

答:
With that code, every section will start with page number 1. If all sections only have a single page, all pages will have #1. Create sections with more than just one page to also see #2 etc.

Remove section.PageSetup.StartingNumber = 1; to get a document with consecutive page numbers.

Maybe this answer is helpful:

https://stackoverflow.com/a/30206884/162529

Title: Always same page number in MigraDoc

Body:
With this code I always get the same page number on every page. How to solve this problem?

    static void DefineContentSection(Document document)
    {
        Section section = document.AddSection();
        section.PageSetup.OddAndEvenPagesHeaderFooter = true;
        section.PageSetup.StartingNumber = 1;

        Paragraph paragraph = new Paragraph();
        paragraph.AddText("Page ");
        paragraph.AddPageField();
        paragraph.AddText(" of ");
        paragraph.AddNumPagesField();

        section.Footers.Primary.Add(paragraph);
        section.Footers.EvenPage.Add(paragraph.Clone());
    }


问:
Sublime Text 'find in files' gives <binary> in the find results
HotKey: Shift+Ctrl+F

Correct result:
Error results,

you can find  the results just show as '<binary>'.I've searched this problem in google,but get nothing,

Here is log text.
Thanks for anyone give suggestion

答:
need convert control characters

```<code>java -jar replacecontrol.jar *filepath*
</code>```

replacecontrol.jar

Body:
need convert control characters

java -jar replacecontrol.jar *filepath*

replacecontrol.jar


问:
how to add padding top in CSS pseudo element class::after
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

```<code>.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}
</code>```

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

```

答:
Use display:block or display:inline-block to apply padding or margin. add margin:0 auto to get center.

.list-unstyled li::after {
  content: url(images/heartborder.png) 0 0 no-repeat;
  text-align: center;
  padding-top: 30px;
  display: block;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
  <div class="col span-1-of-3 box">
<span class="icon-small">
 <i class="fa fa-eye" aria-hidden="true"></i>
 <div class="details">
<h5 class="heading">View / Edit Profile</h5>
<p>You can view or edit your profile from here. Phone no., address, other information etc. etc.</p>
</div>
</span>
  </div>
</li></code>```

Body:
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

Body:
Use display:block or display:inline-block to apply padding or margin. add margin:0 auto to get center.

.list-unstyled li::after {
  content: url(images/heartborder.png) 0 0 no-repeat;
  text-align: center;
  padding-top: 30px;
  display: block;
  margin: 0 auto;
}

<li>
  <div class="col span-1-of-3 box">
<span class="icon-small">
 <i class="fa fa-eye" aria-hidden="true"></i>
 <div class="details">
<h5 class="heading">View / Edit Profile</h5>
<p>You can view or edit your profile from here. Phone no., address, other information etc. etc.</p>
</div>
</span>
  </div>
</li>


问:
If keypress sequence matches not working - webbrowser component
I want to trigger code were if i press ctrl + G on the keyboard, it will trigger my code! Thing is, it wont work. If i hit the letter u or g on its own, my else triggers grand! What am i doing wrong?

My question is different than others because im trying to get a keypress event off of a webbrowser component. So i have to make do with what i got and make a keypress event using document.body.keydown adding that into a eventhandler

My code:

```<code>Private Sub AdsDisplayer_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles AdsDisplayer.DocumentCompleted
    AddHandler AdsDisplayer.Document.Body.KeyDown, AddressOf AdsDisplayer_KeyDown
End Sub

Private Sub AdsDisplayer_KeyDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
    If e.CtrlKeyPressed And Chr(e.KeyPressedCode) = "G" Then
        'CTRL+G was pressed.
        MsgBox("CTRL + " & Chr(e.KeyPressedCode))
    Else
        'SomeKey was pressed without any modifier keys.
        MsgBox(Chr(e.KeyPressedCode))
    End If
End Sub
</code>```

EDIT

What i tried from below comments and not working:

```<code>If (e.KeyPressedCode And Not Keys.Modifiers) = Keys.G AndAlso e.CtrlKeyPressed = Keys.ControlKey Then
    MsgBox("Ctrl + G")
End If
</code>```

答:
KeyDown vs KeyUp

The problem here comes from the timing of the event you use.
You use the KeyDown event and this means it is fired as soon as Ctrl is down.

Using KeyUp

KeyUp will be able to solve this as it will detect when you have released one key.

Hence we would get:

```<code>Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        AddHandler WebBrowser1.Document.Body.KeyUp, AddressOf WebBrowser1_KeyUp
End Sub
</code>```

And then just get the Ctrl + G as follows:

```<code>Private Sub WebBrowser1_KeyUp(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
    If e.CtrlKeyPressed And e.KeyPressedCode = CType(Keys.G, Integer) Then
        'CTRL+G was pressed.
        Console.WriteLine("Here is the Ctrl + G")
    Else
        'Wrong combo
    End If
End Sub
</code>```

Body:
I want to trigger code were if i press ctrl + G on the keyboard, it will trigger my code! Thing is, it wont work. If i hit the letter u or g on its own, my else triggers grand! What am i doing wrong?

My question is different than others because im trying to get a keypress event off of a webbrowser component. So i have to make do with what i got and make a keypress event using document.body.keydown adding that into a eventhandler

My code:

Private Sub AdsDisplayer_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles AdsDisplayer.DocumentCompleted
    AddHandler AdsDisplayer.Document.Body.KeyDown, AddressOf AdsDisplayer_KeyDown
End Sub

Private Sub AdsDisplayer_KeyDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
    If e.CtrlKeyPressed And Chr(e.KeyPressedCode) = "G" Then
        'CTRL+G was pressed.
        MsgBox("CTRL + " & Chr(e.KeyPressedCode))
    Else
        'SomeKey was pressed without any modifier keys.
        MsgBox(Chr(e.KeyPressedCode))
    End If
End Sub

EDIT

What i tried from below comments and not working:

If (e.KeyPressedCode And Not Keys.Modifiers) = Keys.G AndAlso e.CtrlKeyPressed = Keys.ControlKey Then
    MsgBox("Ctrl + G")
End If

Body:
KeyDown vs KeyUp

The problem here comes from the timing of the event you use.
You use the KeyDown event and this means it is fired as soon as Ctrl is down.

Using KeyUp

KeyUp will be able to solve this as it will detect when you have released one key.

Hence we would get:

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        AddHandler WebBrowser1.Document.Body.KeyUp, AddressOf WebBrowser1_KeyUp
End Sub

And then just get the Ctrl + G as follows:

Private Sub WebBrowser1_KeyUp(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
    If e.CtrlKeyPressed And e.KeyPressedCode = CType(Keys.G, Integer) Then
        'CTRL+G was pressed.
        Console.WriteLine("Here is the Ctrl + G")
    Else
        'Wrong combo
    End If
End Sub


问:
Check the answer and verify from database whether it is correct or not in PHP
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

Here is the code

```<code><?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>
</code>```

答:
You have set same name for all radio buttons. You should group the radio buttons for each question. For that you can get the question id from the database and set the radio button name like  </p>

```<code>echo ' A) <input type="radio" name="ans'.$row["id"].'"
    value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
</code>```

Body:
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

Here is the code

<?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully

";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "
Question: " . $row["Question"] . "
";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '
';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '
';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '
';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '
';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>

Body:
You have set same name for all radio buttons. You should group the radio buttons for each question. For that you can get the question id from the database and set the radio button name like

echo ' A) <input type="radio" name="ans'.$row["id"].'"
    value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';


问:
Using JavaScript to edit HTML style in .cshtml
I am making a MVC Web Application and trying to edit the width of a progress bar to show an increase or decrease in the progress and am using a basic javascript function to do it but it is not working.

Can anyone tell me what am I doing wrong? Thanks.

@{
    ViewBag.Title = "About";
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

        45% Complete

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />

```

答:
Your code to define the style is wrong. See below (I've also added a background colour to make it easier to see the effect):

function increase()
    {
        document.getElementById("pb1").style.width = '80%';
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#pb1
{
  background-color:green;
}</code>```

@{
    ViewBag.Title = "About";
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

        45% Complete

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />```

Body:
Your code to define the style is wrong. See below (I've also added a background colour to make it easier to see the effect):

function increase()
    {
        document.getElementById("pb1").style.width = '80%';
    }

#pb1
{
  background-color:green;
}

@{
    ViewBag.Title = "About";
}

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

<div class="progress progress-striped active progress-sm">
    <div class="progress-bar progress-bar-success" name="blah" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%"  id="pb1">
        <span class="sr-only">45% Complete</span>
    </div>
</div>
<br/>
<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />


问:
Changing permanently html values using javascript?
Is it possible to change a html value permanently via javascript? I'm accessing a local file.

These are my codes:

```<code>function switchPic(){
  top.topPage.activeDef = top.topPage.document.getElementById('h1');
  top.topPage.activeDef.href = "pic2.html";

}
</code>```

答:
No, this is not possible.

Javascript in the browser is insulated from the local file system (sandboxed) for security reasons.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to change a html value permanently via javascript? I'm accessing a local file.

These are my codes:

function switchPic(){
  top.topPage.activeDef = top.topPage.document.getElementById('h1');
  top.topPage.activeDef.href = "pic2.html";

}


问:
Generic list and for-each loop
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

```<code>public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}
</code>```

I am not sure why is this error as i am using generic list ?

答:
the reason is because you are using raw types... do instead</p>

```<code>TestThrows<Throwable> testThrows = new TestThrows<>();
</code>```

Title: Generic list and for-each loop

Body:
I am using a  generic class TestThrows< T > with a containing function that returns a generic list . My problem is i am unable to compile this program and it is throwing following error :

Type mismatch: cannot convert from element type Object to Throwable

public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}

I am not sure why is this error as i am using generic list ?

Body:
the reason is because you are using raw types... do instead

TestThrows<Throwable> testThrows = new TestThrows<>();


问:
Rails Truncate and raw not working together
I'm using Rails 4 and come across with very strange problem. That raw and truncate not working properly together.

```<code>     <%= raw(job.description)%>  # working properly

     <%= raw(truncate(job.description,:length => 200))%>  # Not strip html tags

     <%= truncate((raw job.description),:length => 200)%>  # Not strip html tags
</code>```

What the problem is?

Any help please??

答:
You can make use of truncate with sanitize

```<code>truncate(sanitize(job.description, tags: []), length: 200)
</code>```

Body:
I'm using Rails 4 and come across with very strange problem. That raw and truncate not working properly together.

     <%= raw(job.description)%>  # working properly

     <%= raw(truncate(job.description,:length => 200))%>  # Not strip html tags

     <%= truncate((raw job.description),:length => 200)%>  # Not strip html tags

What the problem is?

Any help please??

Body:
You can make use of truncate with sanitize

truncate(sanitize(job.description, tags: []), length: 200)


问:
python compare string in mukltiple rows
I have excel sheet in that I have 2 columns.

1st column has string .This string need to be compared with 2nd column's same row.If it matches need to write 'match' in 3rd column of same row.

If it wont match I need to iterate over the all the rows in excel till the end.
If it found in between need to write 'MATCH' otherwise I need to write 'Not Match'

I am using openpyxl to do this.

答:
You would need to compare the columns with an if-statement and then write the output ('match'/'No match') to the third column. This could be done with the following example code:</p>

```<code>    for index1, cell_col1 in enumerate(ws.columns[0]): # iterates through column 1 with indexing
        for index2, cell_col2 in enumerate(ws.columns[1]): # iterates through column 2 with indexing
            if cell_col1.value == cell_col2.value: # if the values match
                ws.cell(row=index1 + 1, column=3).value = 'Match'
                break
            elif index2 == ws.max_row - 1: # if the second loop is at the end of the table (so no match)
                ws.cell(row=index1 + 1, column=3).value = 'No match'
</code>```

Title: python compare string in mukltiple rows

Body:
You would need to compare the columns with an if-statement and then write the output ('match'/'No match') to the third column. This could be done with the following example code:

    for index1, cell_col1 in enumerate(ws.columns[0]): # iterates through column 1 with indexing
        for index2, cell_col2 in enumerate(ws.columns[1]): # iterates through column 2 with indexing
            if cell_col1.value == cell_col2.value: # if the values match
                ws.cell(row=index1 + 1, column=3).value = 'Match'
                break
            elif index2 == ws.max_row - 1: # if the second loop is at the end of the table (so no match)
                ws.cell(row=index1 + 1, column=3).value = 'No match'


问:
WP Options API Custom Action After Form Submit
I'm sorry if this is an old question but I really can't find answer for this. I am new to wordpress plugin development. How can I do a somewhat like a callback before a form is submitted using WP Options API? In a native PHP, we can just say as

```<code>if (isset($_POST['submit'])) {
    $options = $_POST['zt_ftp_settings'];
    var_dump($options);
 }
</code>```

However, I am using the WP Options API. It saves the data correctly, I just want to do some more after saving the data.

Here is what I did,

```<code><form method="post" action="options.php">
<?php
settings_fields('zt_ftp_settings_options' );
do_settings_sections( 'zt_ftp_settings_options' );
$option = get_option('zt_ftp_settings');
?>
<h2>FTP Settings</h2>
<p>Please provide your ftp credentials.</p>
<table class="form-table">
    <tbody>
            <tr>
                <th scope="row">FTP Hostname</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_host_name]" type="text" id="zt_ftp_host_name" value="<?php echo $option['zt_ftp_host_name']?>" class="regular-text">
                </td>
            </tr>
            <tr>
                <th scope="row">FTP Username</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_user_name]" type="text" id="zt_ftp_user_name" value="<?php echo $option['zt_ftp_user_name']?>" class="regular-text">
                </td>
            </tr>
            <tr>
                <th scope="row">FTP Password</th>
                <td>
                    <input name="zt_ftp_settings[zt_ftp_password]" type="password" id="zt_ftp_password" value="<?php echo $option['zt_ftp_password']?>" class="regular-text">
                </td>
            </tr>
    </tbody>
</table>
<?php submit_button( 'Save Settings' ); ?>
</code>```

Thanks.

答:
Use WP AJAX functionality.

Use below JS,

```<code> $("#submit").click(function(){
    var url = window.location.href;

    jQuery.post(
        ajaxurl,
        {
            'action': 'delete_search',
            'tid':   tid,
        },
        function(response){
          location.reload();
        });
 });
</code>```

Replace your submit button ID and use your form values.

Use below code in function.php

```<code>function prefix_ajax_delete_search() {
    global $wpdb;
    $user_id = get_current_user_id();
    $wpdb->delete('sf_save_search', array('id' => $_POST['tid']) );
    wp_die();
}
add_action( 'wp_ajax_delete_search', 'prefix_ajax_delete_search' );
</code>```

As per your requirement change the function name and variables

Body:
I'm sorry if this is an old question but I really can't find answer for this. I am new to wordpress plugin development. How can I do a somewhat like a callback before a form is submitted using WP Options API? In a native PHP, we can just say as

if (isset($_POST['submit'])) {
    $options = $_POST['zt_ftp_settings'];
    var_dump($options);
 }

However, I am using the WP Options API. It saves the data correctly, I just want to do some more after saving the data.

Here is what I did,

<form method="post" action="options.php">
<?php
settings_fields('zt_ftp_settings_options' );
do_settings_sections( 'zt_ftp_settings_options' );
$option = get_option('zt_ftp_settings');
?>

FTP Settings

Please provide your ftp credentials.

                FTP Hostname

                    <input name="zt_ftp_settings[zt_ftp_host_name]" type="text" id="zt_ftp_host_name" value="<?php echo $option['zt_ftp_host_name']?>" class="regular-text">

                FTP Username

                    <input name="zt_ftp_settings[zt_ftp_user_name]" type="text" id="zt_ftp_user_name" value="<?php echo $option['zt_ftp_user_name']?>" class="regular-text">

                FTP Password

                    <input name="zt_ftp_settings[zt_ftp_password]" type="password" id="zt_ftp_password" value="<?php echo $option['zt_ftp_password']?>" class="regular-text">

<?php submit_button( 'Save Settings' ); ?>

Thanks.

Body:
Use WP AJAX functionality.

Use below JS,

 $("#submit").click(function(){
    var url = window.location.href;

    jQuery.post(
        ajaxurl,
        {
            'action': 'delete_search',
            'tid':   tid,
        },
        function(response){
          location.reload();
        });
 });

Replace your submit button ID and use your form values.

Use below code in function.php

function prefix_ajax_delete_search() {
    global $wpdb;
    $user_id = get_current_user_id();
    $wpdb->delete('sf_save_search', array('id' => $_POST['tid']) );
    wp_die();
}
add_action( 'wp_ajax_delete_search', 'prefix_ajax_delete_search' );

As per your requirement change the function name and variables


问:
File upload validation get trigger on upload button click but not on Ok Button
I am validating File uploader using Jquery Validation like this:

HTML

```<code><form class="getintouch_form" name="Form_Career" action="" id="frm">
  <input type="file" id="fileInput" name="UploadResume" placeholder="Upload Resume">
  <button class="submitbtn bluebutton" id="BtnSend" type="button">Send</button>
</form>
</code>```

JQuery

```<code>$.validator.addMethod(
  "UploadResume",
  function(value, element) {
    return /\.(doc|docx|pdf)$/i.test(value);
  },
  "Only docx,doc,pdf file formats allow"
);
$("#frm").validate({
  onfocusout: function(element) {
    $(element).valid();
  },
  rules: {
    UploadResume: {
      required: true,
      UploadResume: true
    }
  },

  messages: {
    UploadResume: {
      required: "Resume is mandatory field."
    }
  },
});
</code>```

Issue

Validation gets fired immediately after I click Upload button and not after I click ok button after selecting file. I want to trigger validation only after I select the file. I've attached Codepen Link as well.

CodePen : https://codepen.io/Ruhard/pen/RgPeQP

答:
Please try simple jquery function for validation and file type check.
Here i mention new jquery code for the same.</p>

```<code> function FileUploadValidation(){
  var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = $("#fileInput");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.val().toLowerCase())) {
            alert("Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.");
            return false;
        }
        return true;
}
$( "#BtnSend" ).click(function() {
        FileUploadValidation();
});
$('#fileInput').bind('change', function() {
       if(!FileUploadValidation())
          $('#fileInput').val();
});
</code>```

Body:
I am validating File uploader using Jquery Validation like this:

HTML

<form class="getintouch_form" name="Form_Career" action="" id="frm">
  <input type="file" id="fileInput" name="UploadResume" placeholder="Upload Resume">
  <button class="submitbtn bluebutton" id="BtnSend" type="button">Send</button>
</form>

JQuery

$.validator.addMethod(
  "UploadResume",
  function(value, element) {
    return /\.(doc|docx|pdf)$/i.test(value);
  },
  "Only docx,doc,pdf file formats allow"
);
$("#frm").validate({
  onfocusout: function(element) {
    $(element).valid();
  },
  rules: {
    UploadResume: {
      required: true,
      UploadResume: true
    }
  },

  messages: {
    UploadResume: {
      required: "Resume is mandatory field."
    }
  },
});

Issue

Validation gets fired immediately after I click Upload button and not after I click ok button after selecting file. I want to trigger validation only after I select the file. I've attached Codepen Link as well.

CodePen : https://codepen.io/Ruhard/pen/RgPeQP

Body:
Please try simple jquery function for validation and file type check.
Here i mention new jquery code for the same.

 function FileUploadValidation(){
  var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = $("#fileInput");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.val().toLowerCase())) {
            alert("Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.");
            return false;
        }
        return true;
}
$( "#BtnSend" ).click(function() {
        FileUploadValidation();
});
$('#fileInput').bind('change', function() {
       if(!FileUploadValidation())
          $('#fileInput').val();
});


问:
Compiler test cases or how to test a compiler
Compilers like all software, would also be prone to bugs, logical errors.

How does one validate the output generated by the compiler. Typically, my question is(are)

How to validate that the machine code generated is correct?

How to ensure that the machine code generated is according to the language specification.

Does it make sense to just pick an open source project (in C if one is also writing a compiler in C) to just compile it through the "compiler". In that case also, how do judge that the compiler is behaving as expected.

Are there any formal test cases (literature) provided by the language standards committee that a "language complying" compiler has to satisfy?

What are the sure "give aways" that the problem in a program compiled by a compiler is a compiler bug and not a program bug.

- Any examples where mainstream compilers get confused and compile the code wrong?

Links to any literature would be appreciated.

答: GCC has a quite large test suite (https://gcc.gnu.org/onlinedocs/gccint/Testsuites.html#Testsuites). It is available on the SCM : https://github.com/gcc-mirror/gcc/tree/master/gcc/testsuite</p>


问:
How to access function key to add focus to a control?
In my web application on my master page I have a search box [<option> </option> list] for searching pages.

something like this

I like to enable this search option on function key press [ f9 ]. How can I do that ?

Design

```<code><form class="form form-search">
                    <select id="select-templating" data-placeholder="Search " onchange="location = this.value;" class="width300">
                        <option value="">Search</option>
                        <option value="Home.aspx">Home</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AuthorizationList.aspx">Authorization List</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AccountClosing.aspx">Account Closing</option>
                        <option value="AccountTransaction.aspx">Account Transaction</option>
                        <option value="CustomerCreation.aspx">Customer Creation</option>
                        <option value="ShareDividendDeclaration.aspx">Share Dividend Declaration</option>
                    </select>
                </form>
</code>```

In the same solution, I used key f2 to redirect to home using jquery
function(which is working) :

```<code> $(function () {
        $(document).keyup(function (e) {
            var key = (e.keyCode ? e.keyCode : e.charCode);
            switch (key) {

                case 113:
                    window.location.replace("Home.aspx");
                    break;

                default:;
            }
        });
        function navigateUrl(jObj) {
            window.location.href = $(jObj).attr("href");
        }
    });
</code>```

but I don't know how to use f9 key for open search <option> control.. Help me please

答:
Using focus method. Example below.

$(document).keyup(function (e) {
    var key = (e.keyCode ? e.keyCode : e.charCode);
    switch (key) {

        case 120: {
          $('select').focus();
          break;
        }

        default:;
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>select:focus {
  border: 1px solid red;
}</code>```

<select multiple>
  <option>Opt1</option>
  <option>Opt2</option>
  <option>Opt3</option>
</select>```

Edit

You said you tried focus, so maybe try click instead of focus.

Body:
In my web application on my master page I have a search box [<option> </option> list] for searching pages.

something like this

I like to enable this search option on function key press [ f9 ]. How can I do that ?

Design

<form class="form form-search">
                    <select id="select-templating" data-placeholder="Search " onchange="location = this.value;" class="width300">
                        <option value="">Search</option>
                        <option value="Home.aspx">Home</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AuthorizationList.aspx">Authorization List</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AccountClosing.aspx">Account Closing</option>
                        <option value="AccountTransaction.aspx">Account Transaction</option>
                        <option value="CustomerCreation.aspx">Customer Creation</option>
                        <option value="ShareDividendDeclaration.aspx">Share Dividend Declaration</option>
                    </select>
                </form>

In the same solution, I used key f2 to redirect to home using jquery
function(which is working) :

 $(function () {
        $(document).keyup(function (e) {
            var key = (e.keyCode ? e.keyCode : e.charCode);
            switch (key) {

                case 113:
                    window.location.replace("Home.aspx");
                    break;

                default:;
            }
        });
        function navigateUrl(jObj) {
            window.location.href = $(jObj).attr("href");
        }
    });

but I don't know how to use f9 key for open search <option> control.. Help me please

Body:
Using focus method. Example below.

$(document).keyup(function (e) {
    var key = (e.keyCode ? e.keyCode : e.charCode);
    switch (key) {

        case 120: {
          $('select').focus();
          break;
        }

        default:;
    }
});

select:focus {
  border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
  <option>Opt1</option>
  <option>Opt2</option>
  <option>Opt3</option>
</select>

Edit

You said you tried focus, so maybe try click instead of focus.


问:
Order <form:error path="*"/> messages so their order isn't random
When I do a <form:errors path="*"/> my errors are always shown in a random order.
Now I was wondering how I could display them in a set order.

What I mean with random is:
fields: field1, field2, field3
output 1: field2, field1, field3
output 2: field 3, field 2, field 1
...

答:
This is not an exact fit to your question.
You can order your errors if you specify the desired path value instead of "*".
For example,</p>

```<code><form:errors path="field1"/>
<form:errors path="field2"/>
<form:errors path="field3"/></code>```

Body:
This is not an exact fit to your question.
You can order your errors if you specify the desired path value instead of "*".
For example,

<form:errors path="field1"/>
<form:errors path="field2"/>
<form:errors path="field3"/>


问:
print lines after finding a key word in perl
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

```<code>$string=~ /apple /;
</code>```

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

答:
If your data in scalar variable we can use several methods

Recommended method

```<code>($matching) =  $string=~ /([^\n]*apple.+)/s;
print "$matching\n";
</code>```

And there is another way to do it

```<code>$string=~ /[^\n]*apple.+/s;
print $&; #it will print the data which is match.
</code>```

If you reading the data from file, try the following

```<code>while (<$fh>)
{
  if(/apple/)
  {
     print <$fh>;
  }
}
</code>```

Or else try the following one liner

```<code>perl -ne 'print <> and exit if(/apple/);' file.txt
</code>```

Body:
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

$string=~ /apple /;

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

Body:
If your data in scalar variable we can use several methods

Recommended method

($matching) =  $string=~ /([^\n]*apple.+)/s;
print "$matching\n";

And there is another way to do it

$string=~ /[^\n]*apple.+/s;
print $&; #it will print the data which is match.

If you reading the data from file, try the following

while (<$fh>)
{
  if(/apple/)
  {
     print <$fh>;
  }
}

Or else try the following one liner

perl -ne 'print <> and exit if(/apple/);' file.txt


问:
Pointer arithmetic using cast to "wrong" type
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

```<code>#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}
</code>```

Here's a test driver:

```<code>#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}
</code>```

Both approaches produce the expected results:

```<code>0 0 0 0
1 1 1 1
2 2 2 2
</code>```

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

```<code>vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax
</code>```

答:
vertex_a indeed breaks the strict aliasing rule (none of your floats are valid xyzs, and in 50% of your example they're not even at the start of an xyz even if there's no padding).

vertex_b relies on, shall we say, creative interpretation of the standard. Though your cast to const char* is sound, performing arithmetic with it around the rest of the array is a little more dodgy. Historically I've concluded that this kind of thing has undefined behaviour, because "the object" in this context is the xyz, not the array. However, I'm leaning towards others' interpretation nowadays that this will always work, and wouldn't expect anything else in practice.

Body:
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}

Here's a test driver:

#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}

Both approaches produce the expected results:

0 0 0 0
1 1 1 1
2 2 2 2

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax


问:
ExpandableListView item background color weird behavior
I am trying to set background color when the user touch a child inside expandable list view. I managed to do this by using this code:

```<code>ArrayList<ChildView> childViewList;

ExpandableListView expandablelistview_options = (ExpandableListView) view.findViewById(R.id.expandablelistview_options);

expandablelistview_options.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
    int index = removeChildView(groupPosition);
    ArrayList<ConciergeOptionsPairs> children=data.Options.get(groupPosition).childrens;

    if (index != childPosition)
    {
        v.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.orange));
        v.invalidate();
        addChildView(new ChildView(groupPosition, childPosition, v, children.get(childPosition)));
    }

    return false;
}
});

private int removeChildView(int groupPosition)
    {
        int index = 0;
        int childpos = 0;
        boolean exists = false;
        for (ChildView c : childViewList)
        {
            if (c.groupPosition == groupPosition)
            {
                c.view.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.transparent));
                c.view.invalidate();
                childpos = c.childPosition;
                exists = true;
                break;
            }
            index++;
        }

        if (exists)
        {
            childViewList.remove(index);
            return childpos;
        }

        return -1;
    }

private void addChildView(ChildView child)
{
    childViewList.add(child);
}
</code>```

Everything works fine except from this weird behavior:

I have 2 group Views, If I expand the second group, choose the second child and then expand the first group, the background of the first child of the first group get colored and the background of the child of the second group get transparent.

When I expand the first group without choosing any child :

If I collapse the first group, the background of the child of the second group get colored again.

Here is my ExpandableListView adapter code:

```<code>public class ConciergeOptionsExpandableListAdapter extends BaseExpandableListAdapter
{
    private Context context;
    private ArrayList<ConciergeOptions> data;
    private HotelStay hotelStay;
    private int lastExpandedGroupPosition;

    public ConciergeOptionsExpandableListAdapter(Context context, ArrayList<ConciergeOptions> data) {
        this.context = context;
        this.data = data;
        hotelStay=HotelStay.getInstance(context);
    }

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

    @Override
    public Object getGroup(int groupPosition) {
        return this.data.get(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        ConciergeOptions options = (ConciergeOptions) getGroup(groupPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.concierge_options_item, null);
        }

        RelativeLayout container = (RelativeLayout) convertView.findViewById(R.id.container);
        TextView option_name = (TextView) convertView.findViewById(R.id.option_name);
        ImageView arrow = (ImageView) convertView.findViewById(R.id.arrow);

        option_name.setText(options.name);

        if(isExpanded){
            convertView.setBackgroundResource(R.color.bluebutton);
        }else{
            convertView.setBackgroundResource(R.color.transparent);
        }

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return (this.data.get(groupPosition).childrens.size());
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        ArrayList<ConciergeOptionsPairs> children=this.data.get(groupPosition).childrens;
        if(children!=null){
            return children.get(childPosititon);
        }
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.concierge_options_inner_items, null);
        }

        TextView option_type = (TextView) convertView.findViewById(R.id.option_type);
        TextView price = (TextView) convertView.findViewById(R.id.price);
        TextView decimal = (TextView) convertView.findViewById(R.id.decimal);
        TextView currency = (TextView) convertView.findViewById(R.id.currency);

        ConciergeOptionsPairs option_pair = (ConciergeOptionsPairs) getChild(groupPosition, childPosition);
        option_type.setText(option_pair.name);

        double t_price = Double.parseDouble(option_pair.value);
        double dec = t_price - (long) t_price;
        long decim = (long) dec;

        int decimal_int = (int) t_price;

        price.setText("+" + String.valueOf(decimal_int));
        decimal.setText("." + String.valueOf(decim));
        currency.setText("$");

        return convertView;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }
}
</code>```

Any idea how can I solve this problem?

答:
i consider ConciergeOptionsPairs as your child data so add one boolean variable isSelect in ConciergeOptionsPairs class then in your onChildClick

```<code>@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{

    ArrayList<ConciergeOptionsPairs> children=data.Options.get(groupPosition).childrens; //i consider this is your child view array, need to be same dataset which used as child array
    int count=0;
   for(ConciergeOptionsPairs objChild:children)
   {
      if(count==childPosition)
         objChild.isSelect=true;
      else
       objChild.isSelect=false;
    count++;

   }

   yourexpandableadpater.notifyDataSetChanged();

    return false;
}
});
</code>```

now in your adapter in getChildView

```<code>      @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this.context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.concierge_options_inner_items, null);
            }

            TextView option_type = (TextView) convertView.findViewById(R.id.option_type);
            TextView price = (TextView) convertView.findViewById(R.id.price);
            TextView decimal = (TextView) convertView.findViewById(R.id.decimal);
            TextView currency = (TextView) convertView.findViewById(R.id.currency);

            ConciergeOptionsPairs option_pair = (ConciergeOptionsPairs) getChild(groupPosition, childPosition);
            option_type.setText(option_pair.name);

            double t_price = Double.parseDouble(option_pair.value);
            double dec = t_price - (long) t_price;
            long decim = (long) dec;

            int decimal_int = (int) t_price;

            price.setText("+" + String.valueOf(decimal_int));
            decimal.setText("." + String.valueOf(decim));
            currency.setText("$");
            if(option_pair.isSelect)
convertView.setBackgroundColor(ContextCompat.getColor(context,R.color.orange));
    else
convertView.setBackgroundColor(ContextCompat.getColor(context,R.color.transparent));
            return convertView;
        }
</code>```

this is what i understand your code you can check with this

Body:
I am trying to set background color when the user touch a child inside expandable list view. I managed to do this by using this code:

ArrayList<ChildView> childViewList;

ExpandableListView expandablelistview_options = (ExpandableListView) view.findViewById(R.id.expandablelistview_options);

expandablelistview_options.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
    int index = removeChildView(groupPosition);
    ArrayList<ConciergeOptionsPairs> children=data.Options.get(groupPosition).childrens;

    if (index != childPosition)
    {
        v.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.orange));
        v.invalidate();
        addChildView(new ChildView(groupPosition, childPosition, v, children.get(childPosition)));
    }

    return false;
}
});

private int removeChildView(int groupPosition)
    {
        int index = 0;
        int childpos = 0;
        boolean exists = false;
        for (ChildView c : childViewList)
        {
            if (c.groupPosition == groupPosition)
            {
                c.view.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.transparent));
                c.view.invalidate();
                childpos = c.childPosition;
                exists = true;
                break;
            }
            index++;
        }

        if (exists)
        {
            childViewList.remove(index);
            return childpos;
        }

        return -1;
    }

private void addChildView(ChildView child)
{
    childViewList.add(child);
}

Everything works fine except from this weird behavior:

I have 2 group Views, If I expand the second group, choose the second child and then expand the first group, the background of the first child of the first group get colored and the background of the child of the second group get transparent.

When I expand the first group without choosing any child :

If I collapse the first group, the background of the child of the second group get colored again.

Here is my ExpandableListView adapter code:

public class ConciergeOptionsExpandableListAdapter extends BaseExpandableListAdapter
{
    private Context context;
    private ArrayList<ConciergeOptions> data;
    private HotelStay hotelStay;
    private int lastExpandedGroupPosition;

    public ConciergeOptionsExpandableListAdapter(Context context, ArrayList<ConciergeOptions> data) {
        this.context = context;
        this.data = data;
        hotelStay=HotelStay.getInstance(context);
    }

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

    @Override
    public Object getGroup(int groupPosition) {
        return this.data.get(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        ConciergeOptions options = (ConciergeOptions) getGroup(groupPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.concierge_options_item, null);
        }

        RelativeLayout container = (RelativeLayout) convertView.findViewById(R.id.container);
        TextView option_name = (TextView) convertView.findViewById(R.id.option_name);
        ImageView arrow = (ImageView) convertView.findViewById(R.id.arrow);

        option_name.setText(options.name);

        if(isExpanded){
            convertView.setBackgroundResource(R.color.bluebutton);
        }else{
            convertView.setBackgroundResource(R.color.transparent);
        }

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return (this.data.get(groupPosition).childrens.size());
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        ArrayList<ConciergeOptionsPairs> children=this.data.get(groupPosition).childrens;
        if(children!=null){
            return children.get(childPosititon);
        }
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.concierge_options_inner_items, null);
        }

        TextView option_type = (TextView) convertView.findViewById(R.id.option_type);
        TextView price = (TextView) convertView.findViewById(R.id.price);
        TextView decimal = (TextView) convertView.findViewById(R.id.decimal);
        TextView currency = (TextView) convertView.findViewById(R.id.currency);

        ConciergeOptionsPairs option_pair = (ConciergeOptionsPairs) getChild(groupPosition, childPosition);
        option_type.setText(option_pair.name);

        double t_price = Double.parseDouble(option_pair.value);
        double dec = t_price - (long) t_price;
        long decim = (long) dec;

        int decimal_int = (int) t_price;

        price.setText("+" + String.valueOf(decimal_int));
        decimal.setText("." + String.valueOf(decim));
        currency.setText("$");

        return convertView;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }
}

Any idea how can I solve this problem?

Body:
i consider ConciergeOptionsPairs as your child data so add one boolean variable isSelect in ConciergeOptionsPairs class then in your onChildClick

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{

    ArrayList<ConciergeOptionsPairs> children=data.Options.get(groupPosition).childrens; //i consider this is your child view array, need to be same dataset which used as child array
    int count=0;
   for(ConciergeOptionsPairs objChild:children)
   {
      if(count==childPosition)
         objChild.isSelect=true;
      else
       objChild.isSelect=false;
    count++;

   }

   yourexpandableadpater.notifyDataSetChanged();

    return false;
}
});

now in your adapter in getChildView

      @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this.context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.concierge_options_inner_items, null);
            }

            TextView option_type = (TextView) convertView.findViewById(R.id.option_type);
            TextView price = (TextView) convertView.findViewById(R.id.price);
            TextView decimal = (TextView) convertView.findViewById(R.id.decimal);
            TextView currency = (TextView) convertView.findViewById(R.id.currency);

            ConciergeOptionsPairs option_pair = (ConciergeOptionsPairs) getChild(groupPosition, childPosition);
            option_type.setText(option_pair.name);

            double t_price = Double.parseDouble(option_pair.value);
            double dec = t_price - (long) t_price;
            long decim = (long) dec;

            int decimal_int = (int) t_price;

            price.setText("+" + String.valueOf(decimal_int));
            decimal.setText("." + String.valueOf(decim));
            currency.setText("$");
            if(option_pair.isSelect)
convertView.setBackgroundColor(ContextCompat.getColor(context,R.color.orange));
    else
convertView.setBackgroundColor(ContextCompat.getColor(context,R.color.transparent));
            return convertView;
        }

this is what i understand your code you can check with this


问:
How to add days into the date in android
In my database I am getting start date like 2011-11-30(yyyy/mm/dd)format.and duration date like 40 days.How can i calculate the days and get new date format of mm/dd/yyyy.

Can anyone help me

Thanks

答:
It works for me.</p>

```<code>Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

String CurrentDate = mYear + "/" + mMonth + "/" + mDay;
String dateInString = dob; // Select date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 14);    //14 dats add
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
System.out.println(dateInString);
</code>```

Body:
It works for me.

Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

String CurrentDate = mYear + "/" + mMonth + "/" + mDay;
String dateInString = dob; // Select date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 14);    //14 dats add
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
System.out.println(dateInString);


问:
Getting the link URL tapped in WKWebView
I want to get the url of a tapped link in WKWebView. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom. I am using KVO like so:

```<code>override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }
</code>```

This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!

答:
You can use WKWebView delegate method. And don't forget to set the webview delegate to self: webview.navigationDelegate = self

```<code>func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {

    switch navigationAction.navigationType {
        case .LinkActivated:
        if navigationAction.targetFrame == nil {
            self.webView?.loadRequest(navigationAction.request)// It will load that link in same WKWebView
        }
        default:
            break
    }

    if let url = navigationAction.request.URL {
        print(url.absoluteString) // It will give the selected link URL

    }
    decisionHandler(.Allow)
}
</code>```

Body:
I want to get the url of a tapped link in WKWebView. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom. I am using KVO like so:

override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }

This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!

Body:
You can use WKWebView delegate method. And don't forget to set the webview delegate to self: webview.navigationDelegate = self

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {

    switch navigationAction.navigationType {
        case .LinkActivated:
        if navigationAction.targetFrame == nil {
            self.webView?.loadRequest(navigationAction.request)// It will load that link in same WKWebView
        }
        default:
            break
    }

    if let url = navigationAction.request.URL {
        print(url.absoluteString) // It will give the selected link URL

    }
    decisionHandler(.Allow)
}


问:
Recycle Application Mod_Mono 2.8
I have a CentOS 5.x server running Mono 2.8.1 and mod_mono 2.8 with apache2.

Every time I deploy a site from visual studio 2010 to my server by ftp, and navigate to the site, I get a 404 not found error page.

Sites in other subdomains (virtual hosts) are not affected.

Performing a restart of httpd using /etc/init.d/httpd restart fixes the problem, and I can view my ASP site again. Obviously restarting the entire httpd process is less than adequate.

My guess is that this is similar to application domains in IIS. Is there a way to 'recycle' and app domain in mod_mono? Can I set this to happen on deployment?

答: We have a process that attempts to download a hosted URL every minute, and if it returns 404, we kill -9 mod_mono.  That should be enough, you shouldn't need to touch Apache.</p>

Title: Recycle Application Mod_Mono 2.8


问:
Vue.js Component combined with Laravel Form Validation (i.e. passing an initial value for data)
After much Googling and finding the Vue.js forum down, I am ready to give up.

I'm creating a Postcode Lookup component, and everything was working well until I tried to combine it with Laravel's form validation - particularly when there's an error, and the form re-fills the old values.

Hopefully I cover everything here. I have a form input partial that I use which generates every form input. It also uses Laravel's old(...) value if present.

The issue is because there's a default value (in this case for postcode and address) of an empty string, this overrides the value attribute of Postcode input, and the content of the Address textarea.

In made up land, the ideal would be:

```<code>data : function() {
    return {
        postcode        : old('postcode'),
        address         : old('address'),
        addresses       : [],
        hasResponse     : false,
        selectedAddress : ''
    };
},
</code>```

So that's what I'm trying to replicate.

I can probably replace validation with Ajax validation, but my form partial changes the appearance of fields with an error slightly, so this would be messy

From my understanding:

I can't set an initial data value, as this will override the input value.

I can set a prop, but this is immutable

Any help I can find suggests 'using a computed property which determines its value from the prop' but if you literally do that, it doesn't update.

Here's what I have so far:

```<code><so-postcode-lookup initial-postcode="{{ old('postcode') }}" initial-address="{{ old('address') }}"></so-postcode-lookup>
</code>```

```<code>/**
 * Allow user to select an address from those found in the postcode database
 */
Vue.component('so-postcode-lookup', {
    name     : 'so-postcode-lookup',
    template : '#so-postcode-lookup-template',
    props    : ['initialPostcode', 'initialAddress'],
    data     : function() {
        return {
            postcode        : '',
            address         : '',
            addresses       : [],
            hasResponse     : false,
            selectedAddress : ''
        };
    },
    computed : {
        currentAddress : function() {
            if (this.address !== '') {
                return this.address;
            } else {
                return this.initialAddress;
            }
        },
        currentPostcode : function() {
            if (this.postcode !== '') {
                return this.postcode;
            } else {
                return this.initialPostcode;
            }
        },
        hasAddresses : function() {
            return this.addresses.length;
        },
        isValidPostcode : function() {
            return this.postcode !== '' && this.postcode.length > 4;
        },
        isInvalidPostcode : function() {
            return !this.isValidPostcode;
        }
    },
    methods : {
        fetchAddresses : function() {
            var resource = this.$resource(lang.ajax.apiPath + '/postcode-lookup{/postcode}');
            var $vm      = this;
            var element  = event.currentTarget;

            // Fetch addresses from API
            resource.get({ postcode : this.postcode }).then(function(response) {
                response = response.body;

                if (response.status == 'success') {
                    // Update addresses property, allowing select to be displayed
                    $vm.addresses = response.data;
                } else {
                    $vm.addresses = [];
                }

                this.hasResponse = true;
            });
        },
        setAddress : function() {
            this.address = this.selectedAddress;
        }
    }
});
</code>```

```<code><template id="so-postcode-lookup-template">
    <div class="row">
        @include('partials.input', [
            'label'                  => trans('register.form.postcode'),
            'sub_type'               => 'postcode',
            'input_id'               => 'postcode',
            'autocorrect'            => false,
            'input_attributes'       => 'v-model="currentPostcode"',
            'suffix_button'          => true,
            'suffix_button_reactive' => trans('register.form.postcode_button_reactive'),
            'suffix_text'            => trans('register.form.postcode_button'),
            'required'               => true,
            'columns'                => 'col-med-50',
            'wrapper'                => 'postcode-wrapper'
        ])

        <div class="col-med-50 form__item" v-show="hasResponse">
            <label for="address-selector" class="form__label" v-show="hasAddresses">{{ trans('forms.select_address') }}</label>
            <select id="address-selector" class="form__select" v-show="hasAddresses" v-model="selectedAddress" @change="setAddress">
                <template v-for="address in addresses">
                    <option :value="address.value">@{{ address.text }}</option>
                </template>
            </select>
            <so-alert type="error" allow-close="false" v-show="!hasAddresses">{{ trans('forms.no_addresses') }}</so-alert>
        </div>

        @include('partials.input', [
            'label'            => trans('register.form.address'),
            'input_id'         => 'address',
            'type'             => 'textarea',
            'input_attributes' => 'v-model="currentAddress"',
            'required'         => true
        ])
    </div>
</template>
</code>```

If I try this, and set the model of the inputs to currentPostcode and currentAddress respectively, I seem to get an infinite loop.

I think I'm overthinking this somehow.

答:
Im working in a easy way to do that using laravel 5.4 controller to send the data directly

In Laravel view:

```<code> <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ old('ciudad',  isset($documento->ciudad) ? $documento->ciudad : null) }}" >
</code>```

in vue.js 2.0

```<code> data: {

    documento: {
      ciudad: $('#ciudad').val(),
    },

},
</code>```

In Laravel Controller

```<code>  $documento = ReduJornada::where("id_documento",$id)->first();

  return view('documentos.redujornada')->with(compact('documento'));
</code>```

Body:
After much Googling and finding the Vue.js forum down, I am ready to give up.

I'm creating a Postcode Lookup component, and everything was working well until I tried to combine it with Laravel's form validation - particularly when there's an error, and the form re-fills the old values.

Hopefully I cover everything here. I have a form input partial that I use which generates every form input. It also uses Laravel's old(...) value if present.

The issue is because there's a default value (in this case for postcode and address) of an empty string, this overrides the value attribute of Postcode input, and the content of the Address textarea.

In made up land, the ideal would be:

data : function() {
    return {
        postcode        : old('postcode'),
        address         : old('address'),
        addresses       : [],
        hasResponse     : false,
        selectedAddress : ''
    };
},

So that's what I'm trying to replicate.

I can probably replace validation with Ajax validation, but my form partial changes the appearance of fields with an error slightly, so this would be messy

From my understanding:

I can't set an initial data value, as this will override the input value.

I can set a prop, but this is immutable

Any help I can find suggests 'using a computed property which determines its value from the prop' but if you literally do that, it doesn't update.

Here's what I have so far:

<so-postcode-lookup initial-postcode="{{ old('postcode') }}" initial-address="{{ old('address') }}"></so-postcode-lookup>

/**
 * Allow user to select an address from those found in the postcode database
 */
Vue.component('so-postcode-lookup', {
    name     : 'so-postcode-lookup',
    template : '#so-postcode-lookup-template',
    props    : ['initialPostcode', 'initialAddress'],
    data     : function() {
        return {
            postcode        : '',
            address         : '',
            addresses       : [],
            hasResponse     : false,
            selectedAddress : ''
        };
    },
    computed : {
        currentAddress : function() {
            if (this.address !== '') {
                return this.address;
            } else {
                return this.initialAddress;
            }
        },
        currentPostcode : function() {
            if (this.postcode !== '') {
                return this.postcode;
            } else {
                return this.initialPostcode;
            }
        },
        hasAddresses : function() {
            return this.addresses.length;
        },
        isValidPostcode : function() {
            return this.postcode !== '' && this.postcode.length > 4;
        },
        isInvalidPostcode : function() {
            return !this.isValidPostcode;
        }
    },
    methods : {
        fetchAddresses : function() {
            var resource = this.$resource(lang.ajax.apiPath + '/postcode-lookup{/postcode}');
            var $vm      = this;
            var element  = event.currentTarget;

            // Fetch addresses from API
            resource.get({ postcode : this.postcode }).then(function(response) {
                response = response.body;

                if (response.status == 'success') {
                    // Update addresses property, allowing select to be displayed
                    $vm.addresses = response.data;
                } else {
                    $vm.addresses = [];
                }

                this.hasResponse = true;
            });
        },
        setAddress : function() {
            this.address = this.selectedAddress;
        }
    }
});

<template id="so-postcode-lookup-template">

        @include('partials.input', [
            'label'                  => trans('register.form.postcode'),
            'sub_type'               => 'postcode',
            'input_id'               => 'postcode',
            'autocorrect'            => false,
            'input_attributes'       => 'v-model="currentPostcode"',
            'suffix_button'          => true,
            'suffix_button_reactive' => trans('register.form.postcode_button_reactive'),
            'suffix_text'            => trans('register.form.postcode_button'),
            'required'               => true,
            'columns'                => 'col-med-50',
            'wrapper'                => 'postcode-wrapper'
        ])

            {{ trans('forms.select_address') }}
            <select id="address-selector" class="form__select" v-show="hasAddresses" v-model="selectedAddress" @change="setAddress">
                <template v-for="address in addresses">
                    <option :value="address.value">@{{ address.text }}</option>
                </template>
            </select>
            <so-alert type="error" allow-close="false" v-show="!hasAddresses">{{ trans('forms.no_addresses') }}</so-alert>

        @include('partials.input', [
            'label'            => trans('register.form.address'),
            'input_id'         => 'address',
            'type'             => 'textarea',
            'input_attributes' => 'v-model="currentAddress"',
            'required'         => true
        ])

</template>

If I try this, and set the model of the inputs to currentPostcode and currentAddress respectively, I seem to get an infinite loop.

I think I'm overthinking this somehow.

Body:
Im working in a easy way to do that using laravel 5.4 controller to send the data directly

In Laravel view:

 <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ old('ciudad',  isset($documento->ciudad) ? $documento->ciudad : null) }}" >

in vue.js 2.0

 data: {

    documento: {
      ciudad: $('#ciudad').val(),
    },

},

In Laravel Controller

  $documento = ReduJornada::where("id_documento",$id)->first();

  return view('documentos.redujornada')->with(compact('documento'));


问:
Python create folders structure based on current date
i'm using the following var on my script to send output to one

```<code>output = "/opt/output"
</code>```

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

```<code>output = "/opt/output/year/month/day"
</code>```

i'm not sure if i'm using the correct way here i used the following approach

```<code>output = "/opt/output/" + today.strftime('%Y%m%d')
</code>```

any tips here

答:
I will suggest using os.path.join and os.path.sep:

```<code>import os
.
.
.
full_dir = os.path.join(base_dir, today.strftime('%Y{0}%m{0}%d').format(os.path.sep))
</code>```

Body:
i'm using the following var on my script to send output to one

output = "/opt/output"

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

output = "/opt/output/year/month/day"

i'm not sure if i'm using the correct way here i used the following approach

output = "/opt/output/" + today.strftime('%Y%m%d')

any tips here

Body:
I will suggest using os.path.join and os.path.sep:

import os
.
.
.
full_dir = os.path.join(base_dir, today.strftime('%Y{0}%m{0}%d').format(os.path.sep))