问:
Best way to implement visitor pattern in Kotlin
Are there any tricks or common approaches for implementing the visitor pattern in Kotlin? Anything that might be non-obvious to beginners, but leads to more concise or organized code.

EDIT for clarification: I have an AST with many (~30) types of nodes in it. Currently each class implements its own print() method, which I want to factor out into a separate Printer class. With the visitor pattern in place it'll be cleaner to add other AST-traversal classes, of which there will be several.

答:
A combination of companion objects and lambdas can be used to achieve dynamic visitation, like so:</p>

```<code>interface Visitable { fun visit()}

class FooOne(): Visitable {
    val title1 = "111"
    companion object { var visit: (FooOne)->Unit  = {} }
    override fun visit() { FooOne.visit(this) }
}

class FooTwo(): Visitable {
    val title2 = "222"
    companion object { var visit: (FooTwo)->Unit  = {} }
    override fun visit() { FooTwo.visit(this) }
}

/* assign visitor functionality based on types */
fun visitorStars() {
    FooOne.visit = {println("In FooOne: ***${it.title1}***") }
    FooTwo.visit = {println("In FooTwo: ***${it.title2}***") }
}

/* assign different visitor functionality */
fun visitorHashes() {
    FooOne.visit = { println("In FooOne: ###${it.title1}###") }
    FooTwo.visit = {println("In FooTwo: ###${it.title2}###") }
}

fun main(args: Array<String>) {
    val foos = listOf<Visitable>(FooOne(), FooTwo())
    visitorStars()
    foos.forEach {it.visit()}
    visitorHashes()
    foos.forEach {it.visit()}
}

>>>
In FooOne: ***111***
In FooTwo: ***222***
In FooOne: ###111###
In FooTwo: ###222###
</code>```

Body:
A combination of companion objects and lambdas can be used to achieve dynamic visitation, like so:

interface Visitable { fun visit()}

class FooOne(): Visitable {
    val title1 = "111"
    companion object { var visit: (FooOne)->Unit  = {} }
    override fun visit() { FooOne.visit(this) }
}

class FooTwo(): Visitable {
    val title2 = "222"
    companion object { var visit: (FooTwo)->Unit  = {} }
    override fun visit() { FooTwo.visit(this) }
}

/* assign visitor functionality based on types */
fun visitorStars() {
    FooOne.visit = {println("In FooOne: ***${it.title1}***") }
    FooTwo.visit = {println("In FooTwo: ***${it.title2}***") }
}

/* assign different visitor functionality */
fun visitorHashes() {
    FooOne.visit = { println("In FooOne: ###${it.title1}###") }
    FooTwo.visit = {println("In FooTwo: ###${it.title2}###") }
}

fun main(args: Array<String>) {
    val foos = listOf<Visitable>(FooOne(), FooTwo())
    visitorStars()
    foos.forEach {it.visit()}
    visitorHashes()
    foos.forEach {it.visit()}
}

>>>
In FooOne: ***111***
In FooTwo: ***222***
In FooOne: ###111###
In FooTwo: ###222###


来源: stackexchange

问:
Cloud Functions for Firebase database onWrite triggered twice
Hi I am developing a notification system, but I am having trouble deleting the processed notification data. The onWrite event listener is triggered twice resulting to two notifications.

Can you help me find a work around so that onWrite event listener should not be triggered twice? It is important to delete the processed data.

```<code>exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */

return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });

      //Deletes processed notification
      console.log("Removing notification");
      const getNotificationPromise = admin.database().ref(`/notification/message/${recipientUid}/${senderUid}`).once('value');
      return Promise.all([getNotificationPromise]).then(results => {
        const notificationSnapshot = results[0];
        toRemove.push(notificationSnapshot.ref.remove());

        console.log("Removing tokens.")
        return Promise.all(toRemove);
      });
      //return Promise.all(tokensToRemove);
    });
});

})
</code>```

答:
This is a common mistake.  You are writing back into the same database location (by removing the data) that was matched when the function first triggered.  This means that removal will be triggering the function again to handle that second change.  This is currently the expected behavior.

You will need to come up with a way to detect that the second write happened in response to the removal of data.  Also, you are currently doing too much work in your function.  There's no need to read the value of the database at '/notification/message/{recipientUid}/{senderUid}' - it is already being delivered to you in the event that's passed to the function.  Be sure to read the docs about database triggers.  You can know if the function was triggered a second time by examining the event data and returning early if it's null, which means it was removed.

Also, you don't need Promise.all() if you are dealing with a single promise.  Just use then() on that single promise to continue processing, or return that single promise from then().

You might want to look at some of the sample code that shows database triggers.

ContentLicense: CC BY-SA 3.0

Body:
Hi I am developing a notification system, but I am having trouble deleting the processed notification data. The onWrite event listener is triggered twice resulting to two notifications.

Can you help me find a work around so that onWrite event listener should not be triggered twice? It is important to delete the processed data.

exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */

return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });

      //Deletes processed notification
      console.log("Removing notification");
      const getNotificationPromise = admin.database().ref(`/notification/message/${recipientUid}/${senderUid}`).once('value');
      return Promise.all([getNotificationPromise]).then(results => {
        const notificationSnapshot = results[0];
        toRemove.push(notificationSnapshot.ref.remove());

        console.log("Removing tokens.")
        return Promise.all(toRemove);
      });
      //return Promise.all(tokensToRemove);
    });
});

})


问:
In Rust, is Option compiled to a runtime check or an instruction jump?
In Rust, Option is defined as:

```<code>pub enum Option<T> {
    None,
    Some(T),
}
</code>```

Used like so:

```<code>fn may_return_none() -> Option<i32> {
    if is_full_moon {
        None
    } else {
        Some(1)
    }
}

fn main() {
    let optional = may_return_none();
    match optional {
        None => println!("None"),
        Some(v) => println!("Some"),
    }
}
</code>```

I'm not familiar with Rust internals, but initially I assumed it might work similar to Nullable in .NET, so the compiled logic of my above Rust code would be like so:

// occupies `sizeof(T) + 1` memory space, possibly more depending on `Bool`'s alignment, so `Nullable<Int32>` consumes 5 bytes.
struct Nullable<T> {
    Bool hasValue;
    T value;
}

Nullable<Int32> MayReturnNone() {
    if( isFullMoon )
        // as a `struct`, the Nullable<Int32> instance is returned via the stack
        return Nullable<Int32>() { HasValue = false }
    else
        return Nullable<Int32>() { HasValue = true, Value = 1 }
}

void Test() {
    Nullable<Int32> optional = may_return_none();
    if( !optional.HasValue ) println("None");
    else                     println("Some");
}
```

<p>However this isn't a zero-cost abstraction because of the space required for the <code>Bool hasValue</code> flag - and Rust makes a point of providing zero-cost abstractions.</p>

<p>I realise that <code>Option</code> could be implemented via a direct return-jump by the compiler, though it would need the exact jump-to values to be provided as arguments on the stack - as though you can push multiple return addresses:</p>

<p>(Psuedocode)</p>

```mayReturnNone(returnToIfNone, returnToIfHasValue) {

    if( isFullMoon ) {
        cleanup-current-stackframe
        jump-to returnToIfNone
    else {
        cleanup-current-stackframe
        push-stack 1
        jump-to returnToIfHasValue
    }

test() {

    mayReturnNone( instructionAddressOf( ifHasValue ), instructionAddressOf( ifNoValue ) )
ifHasValue:
    println("Some")
ifNoValue:
    println("None")
}
```

Is this how it's implemented? This approach also works for other enum types in Rust - but this specific application I've demonstrated is very brittle and breaks if you want to execute code in-between the call to mayReturnNone and the match statement, for example (as mayReturnNone will jump directly to the match, skipping intermediate instructions).

答:
It depends entirely on optimization. Consider this implementation (playground):

```<code>#![feature(asm)]

extern crate rand;

use rand::Rng;

#[inline(never)]
fn is_full_moon() -> bool {
    rand::thread_rng().gen()
}

fn may_return_none() -> Option<i32> {
    if is_full_moon() { None } else { Some(1) }
}

#[inline(never)]
fn usage() {
    let optional = may_return_none();
    match optional {
        None => unsafe { asm!("nop") },
        Some(v) => unsafe { asm!("nop; nop") },
    }
}

fn main() {
    usage();
}
</code>```

Here, I've used inline assembly instead of printing because it doesn't clutter up the resulting output as much. Here's the assembly for usage when compiled in release mode:

```<code>    .section    .text._ZN10playground5usage17hc2760d0a512fe6f1E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground5usage17hc2760d0a512fe6f1E,@function
_ZN10playground5usage17hc2760d0a512fe6f1E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    testb   %al, %al
    je  .LBB1_2
    #APP
    nop
    #NO_APP
    popq    %rax
    retq
.LBB1_2:
    #APP
    nop
    nop
    #NO_APP
    popq    %rax
    retq
.Lfunc_end1:
    .size   _ZN10playground5usage17hc2760d0a512fe6f1E, .Lfunc_end1-_ZN10playground5usage17hc2760d0a512fe6f1E
    .cfi_endproc
</code>```

The quick rundown is:

It calls the is_full_moon function (callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E).

The result of the random value is tested (testb   %al, %al)

One branch goes to the nop, the other goes to the nop; nop

Everything else has been optimized out. The function may_return_none basically never exists; no Option was ever created, the value of 1 was never materialized.

I'm sure that various people have different opinions, but I don't think I could have written this any more optimized.

Likewise, if we use the value in the Some (which I changed to 42 to find easier):

```<code>Some(v) => unsafe { asm!("nop; nop" : : "r"(v)) },
</code>```

Then the value is inlined in the branch that uses it:

```<code>    .section    .text._ZN10playground5usage17hc2760d0a512fe6f1E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground5usage17hc2760d0a512fe6f1E,@function
_ZN10playground5usage17hc2760d0a512fe6f1E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    testb   %al, %al
    je  .LBB1_2
    #APP
    nop
    #NO_APP
    popq    %rax
    retq
.LBB1_2:
    movl    $42, %eax  ;; Here it is
    #APP
    nop
    nop
    #NO_APP
    popq    %rax
    retq
.Lfunc_end1:
    .size   _ZN10playground5usage17hc2760d0a512fe6f1E, .Lfunc_end1-_ZN10playground5usage17hc2760d0a512fe6f1E
    .cfi_endproc
</code>```

However, nothing can "optimize" around a contractural obligation; if a function has to return an Option, it has to return an Option:

```<code>#[inline(never)]
pub fn may_return_none() -> Option<i32> {
    if is_full_moon() { None } else { Some(42) }
}
</code>```

This makes some Deep Magic assembly:

```<code>    .section    .text._ZN10playground15may_return_none17ha1178226d153ece2E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground15may_return_none17ha1178226d153ece2E,@function
_ZN10playground15may_return_none17ha1178226d153ece2E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    movabsq $180388626432, %rdx
    leaq    1(%rdx), %rcx
    testb   %al, %al
    cmovneq %rdx, %rcx
    movq    %rcx, %rax
    popq    %rcx
    retq
.Lfunc_end1:
    .size   _ZN10playground15may_return_none17ha1178226d153ece2E, .Lfunc_end1-_ZN10playground15may_return_none17ha1178226d153ece2E
    .cfi_endproc
</code>```

Let's hope I get this right...

Load the 64-bit value 0x2A00000000 to %rdx. 0x2A is 42. This is our Option being built; it's the None variant.

Load %rdx + 1 into %rcx. This is the Some variant.

We test the random value

Depending on the result of the test, move the invalid value to %rcx or not

Move %rcx to %rax - the return register

The main point here is that regardless of optimization, a function that says it's going to return data in a specific format has to do so. Only when it's inlined with other code is it valid to remove that abstraction.

Body:
In Rust, Option is defined as:

pub enum Option<T> {
    None,
    Some(T),
}

Used like so:

fn may_return_none() -> Option<i32> {
    if is_full_moon {
        None
    } else {
        Some(1)
    }
}

fn main() {
    let optional = may_return_none();
    match optional {
        None => println!("None"),
        Some(v) => println!("Some"),
    }
}

I'm not familiar with Rust internals, but initially I assumed it might work similar to Nullable in .NET, so the compiled logic of my above Rust code would be like so:

// occupies `sizeof(T) + 1` memory space, possibly more depending on `Bool`'s alignment, so `Nullable<Int32>` consumes 5 bytes.
struct Nullable<T> {
    Bool hasValue;
    T value;
}

Nullable<Int32> MayReturnNone() {
    if( isFullMoon )
        // as a `struct`, the Nullable<Int32> instance is returned via the stack
        return Nullable<Int32>() { HasValue = false }
    else
        return Nullable<Int32>() { HasValue = true, Value = 1 }
}

void Test() {
    Nullable<Int32> optional = may_return_none();
    if( !optional.HasValue ) println("None");
    else                     println("Some");
}

However this isn't a zero-cost abstraction because of the space required for the Bool hasValue flag - and Rust makes a point of providing zero-cost abstractions.

I realise that Option could be implemented via a direct return-jump by the compiler, though it would need the exact jump-to values to be provided as arguments on the stack - as though you can push multiple return addresses:

(Psuedocode)

mayReturnNone(returnToIfNone, returnToIfHasValue) {

    if( isFullMoon ) {
        cleanup-current-stackframe
        jump-to returnToIfNone
    else {
        cleanup-current-stackframe
        push-stack 1
        jump-to returnToIfHasValue
    }

test() {

    mayReturnNone( instructionAddressOf( ifHasValue ), instructionAddressOf( ifNoValue ) )
ifHasValue:
    println("Some")
ifNoValue:
    println("None")
}

Is this how it's implemented? This approach also works for other enum types in Rust - but this specific application I've demonstrated is very brittle and breaks if you want to execute code in-between the call to mayReturnNone and the match statement, for example (as mayReturnNone will jump directly to the match, skipping intermediate instructions).

Body:
It depends entirely on optimization. Consider this implementation (playground):

#![feature(asm)]

extern crate rand;

use rand::Rng;

#[inline(never)]
fn is_full_moon() -> bool {
    rand::thread_rng().gen()
}

fn may_return_none() -> Option<i32> {
    if is_full_moon() { None } else { Some(1) }
}

#[inline(never)]
fn usage() {
    let optional = may_return_none();
    match optional {
        None => unsafe { asm!("nop") },
        Some(v) => unsafe { asm!("nop; nop") },
    }
}

fn main() {
    usage();
}

Here, I've used inline assembly instead of printing because it doesn't clutter up the resulting output as much. Here's the assembly for usage when compiled in release mode:

    .section    .text._ZN10playground5usage17hc2760d0a512fe6f1E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground5usage17hc2760d0a512fe6f1E,@function
_ZN10playground5usage17hc2760d0a512fe6f1E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    testb   %al, %al
    je  .LBB1_2
    #APP
    nop
    #NO_APP
    popq    %rax
    retq
.LBB1_2:
    #APP
    nop
    nop
    #NO_APP
    popq    %rax
    retq
.Lfunc_end1:
    .size   _ZN10playground5usage17hc2760d0a512fe6f1E, .Lfunc_end1-_ZN10playground5usage17hc2760d0a512fe6f1E
    .cfi_endproc

The quick rundown is:

It calls the is_full_moon function (callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E).

The result of the random value is tested (testb   %al, %al)

One branch goes to the nop, the other goes to the nop; nop

Everything else has been optimized out. The function may_return_none basically never exists; no Option was ever created, the value of 1 was never materialized.

I'm sure that various people have different opinions, but I don't think I could have written this any more optimized.

Likewise, if we use the value in the Some (which I changed to 42 to find easier):

Some(v) => unsafe { asm!("nop; nop" : : "r"(v)) },

Then the value is inlined in the branch that uses it:

    .section    .text._ZN10playground5usage17hc2760d0a512fe6f1E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground5usage17hc2760d0a512fe6f1E,@function
_ZN10playground5usage17hc2760d0a512fe6f1E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    testb   %al, %al
    je  .LBB1_2
    #APP
    nop
    #NO_APP
    popq    %rax
    retq
.LBB1_2:
    movl    $42, %eax  ;; Here it is
    #APP
    nop
    nop
    #NO_APP
    popq    %rax
    retq
.Lfunc_end1:
    .size   _ZN10playground5usage17hc2760d0a512fe6f1E, .Lfunc_end1-_ZN10playground5usage17hc2760d0a512fe6f1E
    .cfi_endproc

However, nothing can "optimize" around a contractural obligation; if a function has to return an Option, it has to return an Option:

#[inline(never)]
pub fn may_return_none() -> Option<i32> {
    if is_full_moon() { None } else { Some(42) }
}

This makes some Deep Magic assembly:

    .section    .text._ZN10playground15may_return_none17ha1178226d153ece2E,"ax",@progbits
    .p2align    4, 0x90
    .type   _ZN10playground15may_return_none17ha1178226d153ece2E,@function
_ZN10playground15may_return_none17ha1178226d153ece2E:
    .cfi_startproc
    pushq   %rax
.Ltmp6:
    .cfi_def_cfa_offset 16
    callq   _ZN10playground12is_full_moon17h78e56c4ffd6b7730E
    movabsq $180388626432, %rdx
    leaq    1(%rdx), %rcx
    testb   %al, %al
    cmovneq %rdx, %rcx
    movq    %rcx, %rax
    popq    %rcx
    retq
.Lfunc_end1:
    .size   _ZN10playground15may_return_none17ha1178226d153ece2E, .Lfunc_end1-_ZN10playground15may_return_none17ha1178226d153ece2E
    .cfi_endproc

Let's hope I get this right...

Load the 64-bit value 0x2A00000000 to %rdx. 0x2A is 42. This is our Option being built; it's the None variant.

Load %rdx + 1 into %rcx. This is the Some variant.

We test the random value

Depending on the result of the test, move the invalid value to %rcx or not

Move %rcx to %rax - the return register

The main point here is that regardless of optimization, a function that says it's going to return data in a specific format has to do so. Only when it's inlined with other code is it valid to remove that abstraction.


问:
Nginx Reverse proxy force https
We have a server setup for reverse proxy using nginx. This server will redirect visitors to the corresponding server in which path they are accessed. Now, I want to set up the nginx.conf to force redirect them to https. The problem is I am getting a "too many redirection" error. I tried using a rewrite and adding "proxy_set_header X-Forwarded-Proto https;" but none of it works. Is there a way we can achieve this?  We have set up a ssl cert on cloudflare so we won't need to add it on the config.

Below is the config setting of the current nginx.

```<code>   server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

   if ($http_x_forwarded_proto = "http") {
      rewrite  ^/(.*)$  https://development-link/$1 permanent;
   }

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb1;
            proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb2;
            proxy_set_header    X-Forwarded-Proto https;
    }
</code>```

答:
Use a separate block.</p>

```<code># Redirect HTTP to HTTPS
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    return 301   https://$host$request_uri;
}

# HTTPS
server {
    listen       443 default_server;
    listen       [::]:443 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://development-elb1;
        proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://development-elb2;
        proxy_set_header    X-Forwarded-Proto https;
    }
}
</code>```

Title: Nginx Reverse proxy force https

Body:
We have a server setup for reverse proxy using nginx. This server will redirect visitors to the corresponding server in which path they are accessed. Now, I want to set up the nginx.conf to force redirect them to https. The problem is I am getting a "too many redirection" error. I tried using a rewrite and adding "proxy_set_header X-Forwarded-Proto https;" but none of it works. Is there a way we can achieve this?  We have set up a ssl cert on cloudflare so we won't need to add it on the config.

Below is the config setting of the current nginx.

   server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

   if ($http_x_forwarded_proto = "http") {
      rewrite  ^/(.*)$  https://development-link/$1 permanent;
   }

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb1;
            proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb2;
            proxy_set_header    X-Forwarded-Proto https;
    }

Body:
Use a separate block.

# Redirect HTTP to HTTPS
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    return 301   https://$host$request_uri;
}

# HTTPS
server {
    listen       443 default_server;
    listen       [::]:443 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://development-elb1;
        proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://development-elb2;
        proxy_set_header    X-Forwarded-Proto https;
    }
}


问:
Why does sklearn preprocessing LabelEncoder inverse_transform apply from only one column?
I have a random forest model built with sklearn. The model is built in one file, and I have a second file where I use joblib to load the model and apply it to new data. The data has categorical fields that are converted via sklearn's preprocessing LabelEncoder.fit_transform. Once the prediction is made, I am attempting to reverse this conversion with LabelEncoder.inverse_transform.

Here is the code:

```<code> #transform the categorical rf inputs
 df["method"] = le.fit_transform(df["method"])
 df["vendor"] = le.fit_transform(df["vendor"])
 df["type"] = le.fit_transform(df["type"])
 df["name"] = le.fit_transform(df["name"])
 dups["address"] = le.fit_transform(df["address"])

 #designate inputs for rf model
 inputs = ["amt","vendor","type","name","address","method"]

 #load rf model and run it on new data
 from sklearn.externals import joblib
 rf = joblib.load('rf.pkl')
 predict = rf.predict(df[inputs])

 #reverse LabelEncoder fit_transform
 df["method"] = le.inverse_transform(df["method"])
 df["vendor"] = le.inverse_transform(df["vendor"])
 df["type"] = le.inverse_transform(df["type"])
 df["name"] = le.inverse_transform(df["name"])
 df["address"] = le.inverse_transform(df["address"])

 #convert target to numeric to make it play nice with SQL Server
 predict = pd.to_numeric(predict)

 #add target field to df
 df["prediction"] = predict

 #write results to SQL Server table
 import sqlalchemy
 engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@UserDSN")
 df.to_sql('TABLE_NAME', engine, schema='SCHEMANAME', if_exists='replace', index=False)
</code>```

Without the inverse_transform piece, the results are as expected: numeric codes in place of categorical values. With the inverse_transform piece, the results are odd: the categorical values corresponding to the "address" field are returned for all categorical fields.

So if 1600 Pennsylvania Avenue is encoded as the number 1, all categorical values encoded as the number 1 (regardless of field) now return 1600 Pennsylvania Avenue. Why is inverse_transform picking one column from which to reverse all fit_transform codes?

答:
This is the expected behaviour.

When you call le.fit_transform(), the internal parameters (classes learned) of the LabelEncoder are re-initialised. The le object is fitted onto the values of the column you supplied.

In the above code, you are using the same object to transform all columns, and the last column you supplied is the address. Hence the le forgets all info about previous calls to fit()  (or fit_transform() in this case), and again learns the new data. So when you call inverse_transform() on it, it only returns values related to address. Hope I'm clear.

To encode all columns, you need to initialize different objects, one for each column. Something like below:

```<code> df["method"] = le_method.fit_transform(df["method"])
 df["vendor"] = le_vendor.fit_transform(df["vendor"])
 df["type"] = le_type.fit_transform(df["type"])
 df["name"] = le_name.fit_transform(df["name"])
 df["address"] = le_address.fit_transform(df["address"])
</code>```

and then call inverse_transform() on the appropriate encoder.

Body:
I have a random forest model built with sklearn. The model is built in one file, and I have a second file where I use joblib to load the model and apply it to new data. The data has categorical fields that are converted via sklearn's preprocessing LabelEncoder.fit_transform. Once the prediction is made, I am attempting to reverse this conversion with LabelEncoder.inverse_transform.

Here is the code:

 #transform the categorical rf inputs
 df["method"] = le.fit_transform(df["method"])
 df["vendor"] = le.fit_transform(df["vendor"])
 df["type"] = le.fit_transform(df["type"])
 df["name"] = le.fit_transform(df["name"])
 dups["address"] = le.fit_transform(df["address"])

 #designate inputs for rf model
 inputs = ["amt","vendor","type","name","address","method"]

 #load rf model and run it on new data
 from sklearn.externals import joblib
 rf = joblib.load('rf.pkl')
 predict = rf.predict(df[inputs])

 #reverse LabelEncoder fit_transform
 df["method"] = le.inverse_transform(df["method"])
 df["vendor"] = le.inverse_transform(df["vendor"])
 df["type"] = le.inverse_transform(df["type"])
 df["name"] = le.inverse_transform(df["name"])
 df["address"] = le.inverse_transform(df["address"])

 #convert target to numeric to make it play nice with SQL Server
 predict = pd.to_numeric(predict)

 #add target field to df
 df["prediction"] = predict

 #write results to SQL Server table
 import sqlalchemy
 engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@UserDSN")
 df.to_sql('TABLE_NAME', engine, schema='SCHEMANAME', if_exists='replace', index=False)

Without the inverse_transform piece, the results are as expected: numeric codes in place of categorical values. With the inverse_transform piece, the results are odd: the categorical values corresponding to the "address" field are returned for all categorical fields.

So if 1600 Pennsylvania Avenue is encoded as the number 1, all categorical values encoded as the number 1 (regardless of field) now return 1600 Pennsylvania Avenue. Why is inverse_transform picking one column from which to reverse all fit_transform codes?

Body:
This is the expected behaviour.

When you call le.fit_transform(), the internal parameters (classes learned) of the LabelEncoder are re-initialised. The le object is fitted onto the values of the column you supplied.

In the above code, you are using the same object to transform all columns, and the last column you supplied is the address. Hence the le forgets all info about previous calls to fit()  (or fit_transform() in this case), and again learns the new data. So when you call inverse_transform() on it, it only returns values related to address. Hope I'm clear.

To encode all columns, you need to initialize different objects, one for each column. Something like below:

 df["method"] = le_method.fit_transform(df["method"])
 df["vendor"] = le_vendor.fit_transform(df["vendor"])
 df["type"] = le_type.fit_transform(df["type"])
 df["name"] = le_name.fit_transform(df["name"])
 df["address"] = le_address.fit_transform(df["address"])

and then call inverse_transform() on the appropriate encoder.


问:
Comparing tm Type in C++
I have a vector<tm> times(x); object of assorted tm structs, each different than the other.  I would like to check every item in the vector and determine which time is the biggest/lowest.

For example, out of the tm items with times as follows:

```<code>01:00:00
00:01:00
00:00:01
</code>```

The first would be the largest time, and the last, which is closest to 00:00:00 is the smallest.  Is there any special way to go about finding the largest/smallest struct in the vector, or will I need to design a long looping program to compare each tm struct's hours, minutes and seconds respectively from scratch?

答: Use mktime(tm) and compare the returned values.  The returned values are in epoch time which means larger values are more recent in time.</p>

Title: Comparing tm Type in C++

Body:
I have a vector<tm> times(x); object of assorted tm structs, each different than the other.  I would like to check every item in the vector and determine which time is the biggest/lowest.

For example, out of the tm items with times as follows:

01:00:00
00:01:00
00:00:01

The first would be the largest time, and the last, which is closest to 00:00:00 is the smallest.  Is there any special way to go about finding the largest/smallest struct in the vector, or will I need to design a long looping program to compare each tm struct's hours, minutes and seconds respectively from scratch?


问:
What is the VM folder when using Linux as OS and kvm as driver in kubernetes?
The kubernetes docs provides for each OS and each driver the name VM when mounting a volume of type hostPath.

Nevertheless, it is missing that case:

OS: linux

Driver: kvm

Host folder: /home

VM folder: ???

This is the targeted deployment I would like to use in order to avoid to recreate the image after each change of the code.

This is only for the development env. In the production env, the code will be directly in the image.

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
  labels:
    app: php-hostpath
spec:
  containers:
  - name: php-hostpath
    image: php:7.0-apache
    ports:
    - containerPort: 80
    volumeMounts:
      - name: vol-php-hostpath
        mountPath: /var/www/html
  volumes:
  - name: vol-php-hostpath
    hostPath:
      path: /hosthome/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/
</code>```

Thanks...

答:
Based on this doc, Host folder sharing is not implemented in the KVM driver yet. This is the driver I am using actually.

To overcome this, there are 2 solutions:

Use the virtualbox driver so that you can mount your hostPath volume by changing the path on you localhost /home/THE_USR/... to /hosthome/THE_USR/...

Mount your volume to the minikube VM based on the command $ minikube mount /home/THE_USR/.... The command will return you the path of your mounted volume on the minikube VM. Example is given down.

Example

(a) mounting a volume on the minikube VM

the minikube mount command returned that path /mount-9p

```<code>$ minikube mount -v 3 /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube
Mounting /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube into /mount-9p on the minikubeVM
This daemon process needs to stay alive for the mount to still be accessible...
2017/03/31 06:42:27 connected
2017/03/31 06:42:27 >>> 192.168.42.241:34012 Tversion tag 65535 msize 8192 version '9P2000.L'
2017/03/31 06:42:27 <<< 192.168.42.241:34012 Rversion tag 65535 msize 8192 version '9P2000'
</code>```

(b) Specification of the path on the deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: /mount-9p
</code>```

(c) Checking if mounting the volume worked well

```<code>amine@amine-Inspiron-N5110:~/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube$ kubectl exec -ti php-hostpath-3498998593-6mxsn bash
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php
echo "This is my first docker project";
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html#
</code>```

NB: this kind of volume mounting is only development environment. If I were in production environment, the code will not be mounted: it will be in the image.

Hope it helps others.

Body:
The kubernetes docs provides for each OS and each driver the name VM when mounting a volume of type hostPath.

Nevertheless, it is missing that case:

OS: linux

Driver: kvm

Host folder: /home

VM folder: ???

This is the targeted deployment I would like to use in order to avoid to recreate the image after each change of the code.

This is only for the development env. In the production env, the code will be directly in the image.

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
  labels:
    app: php-hostpath
spec:
  containers:
  - name: php-hostpath
    image: php:7.0-apache
    ports:
    - containerPort: 80
    volumeMounts:
      - name: vol-php-hostpath
        mountPath: /var/www/html
  volumes:
  - name: vol-php-hostpath
    hostPath:
      path: /hosthome/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/

Thanks...

Body:
Based on this doc, Host folder sharing is not implemented in the KVM driver yet. This is the driver I am using actually.

To overcome this, there are 2 solutions:

Use the virtualbox driver so that you can mount your hostPath volume by changing the path on you localhost /home/THE_USR/... to /hosthome/THE_USR/...

Mount your volume to the minikube VM based on the command $ minikube mount /home/THE_USR/.... The command will return you the path of your mounted volume on the minikube VM. Example is given down.

Example

(a) mounting a volume on the minikube VM

the minikube mount command returned that path /mount-9p

$ minikube mount -v 3 /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube
Mounting /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube into /mount-9p on the minikubeVM
This daemon process needs to stay alive for the mount to still be accessible...
2017/03/31 06:42:27 connected
2017/03/31 06:42:27 >>> 192.168.42.241:34012 Tversion tag 65535 msize 8192 version '9P2000.L'
2017/03/31 06:42:27 <<< 192.168.42.241:34012 Rversion tag 65535 msize 8192 version '9P2000'

(b) Specification of the path on the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: /mount-9p

(c) Checking if mounting the volume worked well

amine@amine-Inspiron-N5110:~/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube$ kubectl exec -ti php-hostpath-3498998593-6mxsn bash
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php
echo "This is my first docker project";
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html#

NB: this kind of volume mounting is only development environment. If I were in production environment, the code will not be mounted: it will be in the image.

Hope it helps others.


问:
Rails - Hiding option for Activities
So I would like to implement a hiding option for my app where the user can click on the hide icon and it would hide the respective activity from the home view. The plan is to implement that and then another button that "unhides" the activities once clicked. I have already set up the boolean value, named "hidden" for the table already but I am having trouble getting the Javascript working as I would like to.

Here is the code for the home.html.erb view for activity:

```<code><!--home.html.erb-->

<!--<h1>Time Tracker</h1>
<li><%= link_to 'Login', login_new_path %></li> -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <title>Bootstrap 101 Template</title>
  <link rel='stylesheet' type='text/css' href='../stylesheets/bootstrap.min.css'/>
  <script src='../javascripts/bootstrap.min.js'></script>
  <!-- Bootstrap -->
  <!--<link href="css/bootstrap.min.css" rel="stylesheet"> -->

  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <![endif]-->
</head>
<body>
<!--
<style>
.navbar {
  background-color:#2F4F4F
}
</style>
-->
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">TimeTracker</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Activities<span class="sr-only">(current)</span></a></li>
      </ul>
      </li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Signed in as Admin</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Settings <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Profile</a></li>
            <!--
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            -->
            <li role="separator" class="divider"></li>
            <li><a href="#">Account Settings</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">

<span>Change This</span>
<div id="activity_container">
  <input type="text" class="rename"/> <!--***NEW to edit -->
  <input type="button" value="rename"/> <!--***NEW to edit -->
  <ul class="list-group-sortable" id="Activities" >
    <h1 align = "center">Activities</h1>
    <% @activities.each do |activity| %>
        <li class="list-group-item" id="item" style="list-style: none;">
          <input type="text" class="edit" /> <!-- New 3/28 -->
          <input type="button" value="rename" class="showButton"/> <!--***NEW to edit -->
          <%= activity.a_name %>
          <%= link_to activity, method: :delete, data: { confirm: "Are you sure?" } do %>
              <i class="fa fa-trash-o" aria-hidden="true" title="Delete"></i>
          <% end %>
          <i onclick="editClick()" class="fa fa-pencil fa-fw" aria-hidden="true" title="Edit" id="editActivity"></i>
          <button id="hideActivity" style="border:none; padding:0">
            <i class="fa fa-eye" aria-hidden="true" title="Hide" id="item"></i>
          </button>
        </li>
    <% end %>
  </ul>
</div>

<ul class="pager">

  <li class="previous"><a href="#"><span aria-hidden="true">←</span>Previous </a></li>
  <li class="next"><a href="#"> Next<span aria-hidden="true">→</span></a></li>
</ul>

<!-- *****************NEW*********************** -->
<%= form_for @activity do |a| %>
    <%= a.text_field :a_name, id: 'a_name_field', placeholder: 'Activity Name'%>
    <%= a.submit 'Create', id: 'submitButton', class: 'btn btn-primary'%>
<% end %>

<!-- ***************************************** -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
    $(document).ready(function(){
        $("#unfilled").click(function(){
            if($("#unfilled").attr("src") == "<%=asset_path('unfilledbubble.png')%>"){
                $("#unfilled").attr("src", "<%=asset_path('filledbubble.png')%>");
            }else{
                $("#unfilled").attr("src", "<%=asset_path('unfilledbubble.png')%>");
            }
        });
    });
</script>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <!-- NEW 3/23 -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sortable/0.9.13/jquery-sortable-min.js"></script>

<script src="jquery.sortable.js"></script>
<script>
    function myFunction() {
        var x = document.getElementById("mySelect");
        x.remove(x.selectedIndex);
    }
    $( function() {
        $('#Activities').sortable({
            containment: '#activity_container',
            cursorAt: {left:event.offsetX, top:event.offsetY}, //to keep item near cursor NOT WORKING
            update: function (event, ui) { //to save order NOT WORKING
                var data = $(this).sortable('serialize');
                // POST to server using $.post or $.ajax
                $.ajax({
                    data: data,
                    type: 'POST',
                    url: 'localhost:3000/activities'
                });
            }
        });
        $('#Activities').disableSelection();
    });

    var chosenValue;
    var chosenIndex;
    var newValue;

    //New 3/29 hide activity
    var index;
    //    $( 'li' ).click(function() {
    //
    //        index = $('li').index(this);
    //        $('li').eq(index).hide();
    //        $('span').text("That was li index #" + index);
    //    });
    $('#hideActivity').click(function() {
        index = $('li').index(this);
        $('li').eq(index).hide("slow"); //deletes everything //$(this).hide('li') deletes logo //$(this).closest('li').hide() only deletes first one
//
        $('span').text("That was div index #" + index);
    });
</script>

</body>
</html>
</code>```

Near the bottom, is commented out Javascript code:

```<code>//    $( 'li' ).click(function() {
//
//        index = $('li').index(this);
//        $('li').eq(index).hide();
//        $('span').text("That was li index #" + index);
//    });
</code>```

When the above code is uncommented and the proceeding Javascript code for the "hideActivity" is commented out, the hiding works but it does so when the user simply clicks on the list item with the activity name instead of just the hide icon. I want to allow the user to sort their activities in whichever order they wish so that is why this code is not exactly what I want.

With that code commented out, the "hideActivity" function is what I tried to use for the icon but when I go to the page and click on the hide icon, the resulting text in the span tag states that the index is -1, which means that it could not find an index.

I suspect that the "index = $('li').index(this);", particularly the keyword "this", is the main problem but I do not know why it works for the commented code but not this one.

Any help or advice would be appreciated, thanks.

答:
There are a couple of issues:

You shouldn't use an id value more than once on a page so you want to change

```<code><button id="hideActivity"
</code>```

to

```<code><button class="hideActivity"
</code>```

You set your handler as:

```<code>$( 'li' ).click(
</code>```

This will handle a click anywhere inside any li element on your page, not necessarily inside the hide button. Some li elements aren't even part of your list. You should scope it more narrowly as

```<code>    $('#Activities li .hideActivity').click( ....
</code>```

So your code should probably look something like:

```<code>$( '#Activities li .hideActivity' ).click(function() {
    var index = $('#Activities li .hideActivity').index(this);
    $(this).closest('li').hide();
    $('span').text("That was .hideActivity index #" + index);
});
</code>```

Note the var keyword before the index. You don't want to give the variable global scope.

Title: Rails - Hiding option for Activities

Body:
So I would like to implement a hiding option for my app where the user can click on the hide icon and it would hide the respective activity from the home view. The plan is to implement that and then another button that "unhides" the activities once clicked. I have already set up the boolean value, named "hidden" for the table already but I am having trouble getting the Javascript working as I would like to.

Here is the code for the home.html.erb view for activity:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Bootstrap 101 Template</title>
  <link rel='stylesheet' type='text/css' href='../stylesheets/bootstrap.min.css'/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      TimeTracker

Activities(current)

Signed in as Admin

          Settings

Profile

Account Settings

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">

Change This

  <input type="text" class="rename"/>
  <input type="button" value="rename"/>

Activities

    <% @activities.each do |activity| %>

          <input type="text" class="edit" />
          <input type="button" value="rename" class="showButton"/>
          <%= activity.a_name %>
          <%= link_to activity, method: :delete, data: { confirm: "Are you sure?" } do %>

          <% end %>

          <button id="hideActivity" style="border:none; padding:0">

          </button>

    <% end %>

←Previous

 Next→

<%= form_for @activity do |a| %>
    <%= a.text_field :a_name, id: 'a_name_field', placeholder: 'Activity Name'%>
    <%= a.submit 'Create', id: 'submitButton', class: 'btn btn-primary'%>
<% end %>

Near the bottom, is commented out Javascript code:

//    $( 'li' ).click(function() {
//
//        index = $('li').index(this);
//        $('li').eq(index).hide();
//        $('span').text("That was li index #" + index);
//    });

When the above code is uncommented and the proceeding Javascript code for the "hideActivity" is commented out, the hiding works but it does so when the user simply clicks on the list item with the activity name instead of just the hide icon. I want to allow the user to sort their activities in whichever order they wish so that is why this code is not exactly what I want.

With that code commented out, the "hideActivity" function is what I tried to use for the icon but when I go to the page and click on the hide icon, the resulting text in the span tag states that the index is -1, which means that it could not find an index.

I suspect that the "index = $('li').index(this);", particularly the keyword "this", is the main problem but I do not know why it works for the commented code but not this one.

Any help or advice would be appreciated, thanks.

Body:
There are a couple of issues:

You shouldn't use an id value more than once on a page so you want to change

<button id="hideActivity"

to

<button class="hideActivity"

You set your handler as:

$( 'li' ).click(

This will handle a click anywhere inside any li element on your page, not necessarily inside the hide button. Some li elements aren't even part of your list. You should scope it more narrowly as

    $('#Activities li .hideActivity').click( ....

So your code should probably look something like:

$( '#Activities li .hideActivity' ).click(function() {
    var index = $('#Activities li .hideActivity').index(this);
    $(this).closest('li').hide();
    $('span').text("That was .hideActivity index #" + index);
});

Note the var keyword before the index. You don't want to give the variable global scope.


问:
View Back end Connections to Access DB from Excel
I Have a database that many people across my workplace have excel files with linked tables etc.

There are times where it is critical I have exclusive access to the DB and it is not feasible to track down hundreds of possible excel files with links that do not properly break and revamp them; especially when people are makign new files all the time.

I found the following code that allows me to see whether someone is connected o the front end of the database:

```<code>Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i, j As Long

Set cn = CurrentProject.Connection

' The user roster is exposed as a provider-specific schema rowset
' in the Jet 4.0 OLE DB provider.  You have to use a GUID to
' reference the schema, as provider-specific schemas are not
' listed in ADO's type library for schema rowsets

Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}")

'Output the list of all users in the current database.

Debug.Print rs.Fields(0).Name, "", rs.Fields(1).Name, _
"", rs.Fields(2).Name, rs.Fields(3).Name

While Not rs.EOF
    Debug.Print rs.Fields(0), rs.Fields(1), _
    rs.Fields(2), rs.Fields(3)
    rs.MoveNext
Wend

End Sub
</code>```

is there any code that will do the same thing as this to give me back end connections? As in who has an open excel file that is linked and locking the DB to Read- Only?

答:
1) You can open a connection to any database. You've used "CurrentProject.Connection", but you can use:

```<code>set cn=Server.CreateObject("ADODB.Connection")
cn.Provider="Microsoft.Jet.OLEDB.4.0"
cn.Open "c:/webdata/northwind.mdb"
</code>```

2) If method (1) is not suitable, you can use ODBC to query WMI and get a list of everyone connected to any particular file.

Body:
I Have a database that many people across my workplace have excel files with linked tables etc.

There are times where it is critical I have exclusive access to the DB and it is not feasible to track down hundreds of possible excel files with links that do not properly break and revamp them; especially when people are makign new files all the time.

I found the following code that allows me to see whether someone is connected o the front end of the database:

Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i, j As Long

Set cn = CurrentProject.Connection

' The user roster is exposed as a provider-specific schema rowset
' in the Jet 4.0 OLE DB provider.  You have to use a GUID to
' reference the schema, as provider-specific schemas are not
' listed in ADO's type library for schema rowsets

Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}")

'Output the list of all users in the current database.

Debug.Print rs.Fields(0).Name, "", rs.Fields(1).Name, _
"", rs.Fields(2).Name, rs.Fields(3).Name

While Not rs.EOF
    Debug.Print rs.Fields(0), rs.Fields(1), _
    rs.Fields(2), rs.Fields(3)
    rs.MoveNext
Wend

End Sub

is there any code that will do the same thing as this to give me back end connections? As in who has an open excel file that is linked and locking the DB to Read- Only?

Body:
1) You can open a connection to any database. You've used "CurrentProject.Connection", but you can use:

set cn=Server.CreateObject("ADODB.Connection")
cn.Provider="Microsoft.Jet.OLEDB.4.0"
cn.Open "c:/webdata/northwind.mdb"

2) If method (1) is not suitable, you can use ODBC to query WMI and get a list of everyone connected to any particular file.


问:
What should be returned from a REST endpoint that takes a list of ids, where some are invalid?
I've seen questions like this one that were asking about how to handle constructing API's that take multiple ids for a resource and return a list. But my question is if one or more of these ids don't actually match an instance of that resource, what should the response look like?

For example,

data:

```<code>{id: 1, value: "one"}
{id: 2, value: "two"}
{id: 3, value: "three"}
</code>```

request:

```<code>.../data/id=1,5,2,6
OR
.../data?ids[]=1&ids[]=5&ids[]=2&ids[]=6
</code>```

Now, should the endpoint return

(1)

```<code>[
    {id: 1, value: "one"},
    null,
    {id: 2, value: "two"},
    null
]
</code>```

OR

(2)

```<code>[
    {id: 1, value: "one"},
    {id: 2, value: "two"}
]
</code>```

In REST standards, is it important that the order of the resources requested be preserved and/or the size of the list, or should it just return the resources that were found?

I am leaning towards (2) because if you are using the order of list of ids you sent with the request as a direct mapping to the object in the response (3), that seems kinda flaky because it can be an unordered list (and not that useful, because the id should already be in each object).

(3)

```<code>1,5,2,6
becomes
[
 id=1 =>    {id: 1, value: "one"},
 id=5 =>    null,
 id=2 =>    {id: 2, value: "two"},
 id=6 =>    null
]
</code>```

答:
On failure:
You can return list of failed Id's alongwith suitable HttpStatusCode for failure.

On Success:
You can return expected data and 200Ok HttpStatusCode.

So that api-consumer can easily detect success and failure.

Example: I have list of 7 students:[1,2,3,4,5,x,y] and I don't know how many of them are passed exam. Then I will send these Ids to api to check there status. Then

Suppose x and y are invalid Id's, then my api will return [x,y] and statuscode: 400BadRequest.

And If x,y is absent my api will return statuscode:200Ok

Body:
I've seen questions like this one that were asking about how to handle constructing API's that take multiple ids for a resource and return a list. But my question is if one or more of these ids don't actually match an instance of that resource, what should the response look like?

For example,

data:

{id: 1, value: "one"}
{id: 2, value: "two"}
{id: 3, value: "three"}

request:

.../data/id=1,5,2,6
OR
.../data?ids[]=1&ids[]=5&ids[]=2&ids[]=6

Now, should the endpoint return

(1)

[
    {id: 1, value: "one"},
    null,
    {id: 2, value: "two"},
    null
]

OR

(2)

[
    {id: 1, value: "one"},
    {id: 2, value: "two"}
]

In REST standards, is it important that the order of the resources requested be preserved and/or the size of the list, or should it just return the resources that were found?

I am leaning towards (2) because if you are using the order of list of ids you sent with the request as a direct mapping to the object in the response (3), that seems kinda flaky because it can be an unordered list (and not that useful, because the id should already be in each object).

(3)

1,5,2,6
becomes
[
 id=1 =>    {id: 1, value: "one"},
 id=5 =>    null,
 id=2 =>    {id: 2, value: "two"},
 id=6 =>    null
]


问:
How do I dispatch contextmenu on click
I'm using ng2-contextmenu which has a plunker here. I want to fire the same context menu on click as I'm getting when right-clicking.

I tried adding (click)="rethrowContextMenu($event)" to the element and defined that as:

```<code>rethrowContextMenu(e:MouseEvent):void{
    let evt = new MouseEvent('contextmenu',{bubbles:true});
    e.target.dispatchEvent(evt);
}
</code>```

But it doesn't seem to trigger the context menu. Where am I going wrong?

My Plunker

答:
If you take a look at source code you can notice global click handler:

```<code>@HostListener('document:click', [])
public onClick(): void {
    this.hide();
}
</code>```

it means whenever you open dialog this handler will close it immediatelly. So you need to stop propagation your click event:

```<code>rethrowContextMenu(e:MouseEvent):void{
   let evt = new MouseEvent('contextmenu',{bubbles:true});
   e.target.dispatchEvent(evt);
   e.stopPropagation();
}
</code>```

And you also need to pass clientX and clientY if you want to get right dialog position:

```<code>let evt = new MouseEvent('contextmenu', {
  bubbles:true,
  clientX: e.clientX,
  clientY: e.clientY
});
</code>```

Modified Plunker

Title: How do I dispatch contextmenu on click

Body:
I'm using ng2-contextmenu which has a plunker here. I want to fire the same context menu on click as I'm getting when right-clicking.

I tried adding (click)="rethrowContextMenu($event)" to the element and defined that as:

rethrowContextMenu(e:MouseEvent):void{
    let evt = new MouseEvent('contextmenu',{bubbles:true});
    e.target.dispatchEvent(evt);
}

But it doesn't seem to trigger the context menu. Where am I going wrong?

My Plunker

Body:
If you take a look at source code you can notice global click handler:

@HostListener('document:click', [])
public onClick(): void {
    this.hide();
}

it means whenever you open dialog this handler will close it immediatelly. So you need to stop propagation your click event:

rethrowContextMenu(e:MouseEvent):void{
   let evt = new MouseEvent('contextmenu',{bubbles:true});
   e.target.dispatchEvent(evt);
   e.stopPropagation();
}

And you also need to pass clientX and clientY if you want to get right dialog position:

let evt = new MouseEvent('contextmenu', {
  bubbles:true,
  clientX: e.clientX,
  clientY: e.clientY
});

Modified Plunker


问:
My URL returns Json in Browser But not works in Postman
I have a test URL which returns a Json Result as following

```<code>{"result":[{"Users":{"id":"1","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"2","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"3","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"4","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"5","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"6","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"7","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"8","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"9","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"10","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"11","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"12","user_name":"raj","user_password":"rajesh123"}}],"error_code":1}
</code>```

My Problem is When i run this URL On Chrome Browser It returns the Correct response as mentioned above.But incase of Postman it returns errors with the following message

This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support

PS: In localhost it  [http://localhost/test/get_user.php] works fine in both Browser and PostMan.

答: Finally, I found that the problem is from Server Side.I have used the free hosting called Infinity Free in that they won't allow scraping. Now I am migrated to 000WebHost</p>

Body:
I have a test URL which returns a Json Result as following

{"result":[{"Users":{"id":"1","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"2","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"3","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"4","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"5","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"6","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"7","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"8","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"9","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"10","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"11","user_name":"raj","user_password":"rajesh123"}},{"Users":{"id":"12","user_name":"raj","user_password":"rajesh123"}}],"error_code":1}

My Problem is When i run this URL On Chrome Browser It returns the Correct response as mentioned above.But incase of Postman it returns errors with the following message

This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support

PS: In localhost it  [http://localhost/test/get_user.php] works fine in both Browser and PostMan.


问:
Supress the intersection of two dataframe
I understand it is basic in python but I didn't find a proper way to do the following thing...

I have 2 dataframe made of dates.
The first one contain 300 dates arround, the second contain 20 dates arround.

I want to create a new dataframe made of the 300 dates without the 20 contained in the second dataframe.

```<code>[in] Dates1
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-03
7    2017-03-02
8    2017-03-01
9    2017-02-28
10   2017-02-27
etc...

[in] Dates2
[out]
 1    2017-03-03
 2    2017-03-01

expectedResult
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-02
7    2017-02-28
8    2017-02-27
</code>```

Thank you very much!

答:
You can first merge and go heavy

result = df1.append(df2)
 data = result.drop_duplicates()

Body:
I understand it is basic in python but I didn't find a proper way to do the following thing...

I have 2 dataframe made of dates.
The first one contain 300 dates arround, the second contain 20 dates arround.

I want to create a new dataframe made of the 300 dates without the 20 contained in the second dataframe.

[in] Dates1
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-03
7    2017-03-02
8    2017-03-01
9    2017-02-28
10   2017-02-27
etc...

[in] Dates2
[out]
 1    2017-03-03
 2    2017-03-01

expectedResult
[out]
1    2017-03-10
2    2017-03-09
3    2017-03-08
4    2017-03-07
5    2017-03-06
6    2017-03-02
7    2017-02-28
8    2017-02-27

Thank you very much!


问:
Is there a way to expand a deterministic regular expression in javascript?
I want to know if there is a way to see if part of a regular expression is deterministic or not. For example, the regular expression 0{3} is deterministic a.k.a there is only one string that matches it: "000". So for example if we had the regular expression \d0{3} along with the string "1", is there a way to get the string "1000" from that? It seems technically possible since once you have the first digit, you know that the rest of the digits are all 0s and there can only be 3 of them. I don't know if I am missing something or not though.

答:
A sufficient condition for a regular expression to be deterministic is that it does not contain:

The | operator.

Any quantifiers (+,*,?,{n,m}) other than fixed repetition ({n}).

Any character class matching more than one character (\w, [a-z])

These conditions are not necessary because of zero-width assertions. For example, the expression (?!x)(x|y) only matches y. So this simple approach will not cover all cases, though it may suffice for your application.

At least for the case of true regular expressions without backreferences, it should be possible to determine whether they are singular. Simply use the standard construction to turn the expression into a nondeterministic finite automaton, then a deterministic finite automaton, then minimize it. The minimal DFA is singular if and only if there is exactly one accepting state, the accepting state has no edges coming from it, and every nonaccepting state has one edge coming from it.

To handle lookahead assertions, you might need to turn the expression into an alternating finite automaton, then use an approach similar to Thompson's construction to get the NFA, then proceed from there. Note that the worst-case here could have doubly exponential blowup. You can take \b and ^ and similar and translate them to one-character lookbehind assertions, then do some fiddly stuff to get those to work.


问:
CNTK: Define a custom loss function (Sørensen-Dice coefficient)
I'd like to use Wiki: Sørensen–Dice coefficient as a loss function in CNTK/Python. How can I define a custom loss function.</p>

答:
import numpy as np
import cntk as C

def dice_coefficient(x, y):
    # https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
    intersection = C.reduce_sum(C.element_times(x, y))

    return 2 * intersection / (C.reduce_sum(x) + C.reduce_sum(y))

shape = (1, 2, 2)

x1 = np.ones(shape)
y1 = np.reshape([0, 1, 0, 1], shape)

x = C.sanitize_input(x1)
y = C.sanitize_input(y1)

dice_coefficient(x, y).eval({x: x1, y: y1})
```

array([ 0.66666669], dtype=float32)

Body:
import numpy as np
import cntk as C

def dice_coefficient(x, y):
    # https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
    intersection = C.reduce_sum(C.element_times(x, y))

    return 2 * intersection / (C.reduce_sum(x) + C.reduce_sum(y))

shape = (1, 2, 2)

x1 = np.ones(shape)
y1 = np.reshape([0, 1, 0, 1], shape)

x = C.sanitize_input(x1)
y = C.sanitize_input(y1)

dice_coefficient(x, y).eval({x: x1, y: y1})

array([ 0.66666669], dtype=float32)


问:
Making sure the ships do not overlap
I have been stuck on this task for a long time now, so I thought it was about time to ask for some help. I am making a game of battle ship and I am currently writing a function where the ships are randomly placed on the 10 x 10 grid. I have this completed, but my problem is when they overlap.

I cannot figure out a way to get coordinates where they don't overlap with a previously randomly placed ship. In my current code I am trying to figure out a way to make it so that if a coordinate overlaps it will loop the ship over again until it has the right amount of cells that do not overlap with any other ship. I am writing in a 3 file format, so I will include the needed code from each file.

In the function, the up down left or right is random, so in the battle ship I have direction = 0 so that I am only working with up

Here is the header file

```<code>typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
}Game_Board;

Game_Board initalize_game_board(Game_Board *player);

//Game_Board manually_place_ships_on_board(Game_Board *player);
Game_Board randomlly_place_ships_on_board(Game_Board *player);
</code>```

Main

```<code>Game_Board person, computer;
    int who_goes_first = 0;

    person.symbol = '~';
    person.row = 10;
    person.col = 10;
    computer.symbol = '-';
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);

    printf("Player 1\n");
    initalize_game_board(&person);
    printf("\nPlayer 2\n");
    initalize_game_board(&computer);
    who_goes_first = select_who_starts_first();
    //manually_place_ships_on_board(&person);
    randomlly_place_ships_on_board(&computer);
</code>```

The function. I am only including the first 2 ship for redundancy reasons

```<code>int direction = 0, i = 0, cell_row = 0, cell_col = 0;

    //Carrier
    printf("CARRIER\n");
    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'c';
    if (direction == 0) // up
    {
        cell_row = rand() % 10;
        if (cell_row <= 4)
        {
            cell_row += 4;
        }
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 6;
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 4)
        {
            cell_col += 4;
        }
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            cell_col -= 1;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 6;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

    //Battle Ship
    printf("BATTLE SHIP\n");

    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'b';
    if (direction == 0) // up
    {

        cell_row = rand() % 10;

        if (cell_row <= 3)
        {
            cell_row += 3;
        }

        cell_col = rand() % 10;

        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 7;
        cell_col = rand() % 10;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 3)
        {
            cell_col += 3;
        }
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
            cell_col -= 1;
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 7;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }
</code>```

I have tried a combination of do while, while and for loops to try and get the ship to reset, but I can just not figure out a way to make this work

I could really use some guidance or a step in the right direction in order to fix this task. Thanks so much in advance!

答:
The reason why you are getting overlap is because when you place your second ship, at no point do you check to see if the randomly generated cell (in terms of row and column) is actually vacant.
That is, when you call rand() for your battle ship you never check to see if the column or row you get (and the neighboring ones, depending on the direction of the ship) are actually vacant or whether they are already in use by your carrier.

A simply approach would be to implement a function that checks whether the randomly generated cell is adequate or not. A possible signature would be something like:

```<code>int isAvailableCell(int cell, int direction,  int ship_length);
</code>```

This function takes the cell that was randomly generated, the direction of your ship and the length of your ship and it would check whether all "ship_length" cells (that is, the number of cells that the ship needs to fit in) starting from "cell" in "direction" are available. This merely involves checking whether your 2D vector has a non zero element in those cells (because you populate them when placing a ship).

If the cell is not adequate, then you need to call rand() again. Obviously, this is a brute force approach that is extremely inefficient because you might end up generating an inadequate cell multiple times but I would assume that at this point, you are not worrying about performance.

Also, A lot of the code is redundant, you can encapsulate placing a ship in a function. It will make your life much easier and your code look cleaner.
Hope this helps and good luck!

Title: Making sure the ships do not overlap

Body:
I have been stuck on this task for a long time now, so I thought it was about time to ask for some help. I am making a game of battle ship and I am currently writing a function where the ships are randomly placed on the 10 x 10 grid. I have this completed, but my problem is when they overlap.

I cannot figure out a way to get coordinates where they don't overlap with a previously randomly placed ship. In my current code I am trying to figure out a way to make it so that if a coordinate overlaps it will loop the ship over again until it has the right amount of cells that do not overlap with any other ship. I am writing in a 3 file format, so I will include the needed code from each file.

In the function, the up down left or right is random, so in the battle ship I have direction = 0 so that I am only working with up

Here is the header file

typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
}Game_Board;

Game_Board initalize_game_board(Game_Board *player);

//Game_Board manually_place_ships_on_board(Game_Board *player);
Game_Board randomlly_place_ships_on_board(Game_Board *player);

Main

Game_Board person, computer;
    int who_goes_first = 0;

    person.symbol = '~';
    person.row = 10;
    person.col = 10;
    computer.symbol = '-';
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);

    printf("Player 1\n");
    initalize_game_board(&person);
    printf("\nPlayer 2\n");
    initalize_game_board(&computer);
    who_goes_first = select_who_starts_first();
    //manually_place_ships_on_board(&person);
    randomlly_place_ships_on_board(&computer);

The function. I am only including the first 2 ship for redundancy reasons

int direction = 0, i = 0, cell_row = 0, cell_col = 0;

    //Carrier
    printf("CARRIER\n");
    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'c';
    if (direction == 0) // up
    {
        cell_row = rand() % 10;
        if (cell_row <= 4)
        {
            cell_row += 4;
        }
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 6;
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 4)
        {
            cell_col += 4;
        }
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            cell_col -= 1;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 6;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

    //Battle Ship
    printf("BATTLE SHIP\n");

    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'b';
    if (direction == 0) // up
    {

        cell_row = rand() % 10;

        if (cell_row <= 3)
        {
            cell_row += 3;
        }

        cell_col = rand() % 10;

        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 7;
        cell_col = rand() % 10;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 3)
        {
            cell_col += 3;
        }
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
            cell_col -= 1;
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 7;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

I have tried a combination of do while, while and for loops to try and get the ship to reset, but I can just not figure out a way to make this work

I could really use some guidance or a step in the right direction in order to fix this task. Thanks so much in advance!

Body:
The reason why you are getting overlap is because when you place your second ship, at no point do you check to see if the randomly generated cell (in terms of row and column) is actually vacant.
That is, when you call rand() for your battle ship you never check to see if the column or row you get (and the neighboring ones, depending on the direction of the ship) are actually vacant or whether they are already in use by your carrier.

A simply approach would be to implement a function that checks whether the randomly generated cell is adequate or not. A possible signature would be something like:

int isAvailableCell(int cell, int direction,  int ship_length);

This function takes the cell that was randomly generated, the direction of your ship and the length of your ship and it would check whether all "ship_length" cells (that is, the number of cells that the ship needs to fit in) starting from "cell" in "direction" are available. This merely involves checking whether your 2D vector has a non zero element in those cells (because you populate them when placing a ship).

If the cell is not adequate, then you need to call rand() again. Obviously, this is a brute force approach that is extremely inefficient because you might end up generating an inadequate cell multiple times but I would assume that at this point, you are not worrying about performance.

Also, A lot of the code is redundant, you can encapsulate placing a ship in a function. It will make your life much easier and your code look cleaner.
Hope this helps and good luck!


问:
c# code to create a new windows form every click of button
I need help on creating a new form when I click a button.

For example, I have a form named create_form then has a button named Create. What I want is to create a form every time I click the Create button, and the forms created will be independent from each other.

I don't want to create a lot of form in Visual Studio like "Form1, Form2, Form3, Form4..etc.." and call each one every time the button is clicked. Then I'd have to be able to create another form in Visual Studio for each time I wanted to click the button, even if I click it 20 times or more. All I want is to create one windows form (Form3 for example) then every time I click the Create button it will just call it and create a new instance of that form. If I click 20 times then there should be 20 forms created and independent from each other.

答:
Assuming you already have a form named Form3, here is what your button click event will look like:

```<code>//use this so you have an easy reference to each of your forms
private myForms As new List<Form3>();

protected void Create_Click(object sender, EventArgs e)
{
     var form = new Form3();
     myForms.Add(form);
     form.Show();
}
</code>```

Body:
Assuming you already have a form named Form3, here is what your button click event will look like:

//use this so you have an easy reference to each of your forms
private myForms As new List<Form3>();

protected void Create_Click(object sender, EventArgs e)
{
     var form = new Form3();
     myForms.Add(form);
     form.Show();
}


问:
How to insert ISO-8859-1 charset values in DB using php
I'm inserting contents into table as bulk upload format (.csv).

In my CSV some columns include special characters but server can't insert special characters included rows into db and stops execution.

How can I insert these values?

I'm trying:

```<code>$field1= addslashes(trim($data[0]));
</code>```

and I'm using mysqli_real_escape_string, it's working but it omits all special characters from the fields...

```<code>$field2= mysqli_real_escape_string(trim($data[1]));
</code>```

答:
Do not call any conversion routines.  Simply declare that the .csv file is encoded latin1.  Do that with this clause in the LOAD DATA statement:

```<code>CHARACTER SET latin1
</code>```

You have not said what charset the column/table is.  Please provide SHOW CREATE TABLE.  The column can be either latin1 or utf8.

Also, use mysqli_set_charset to establish which charset your client code is using.  (It does not need to be the same as the column/table.)

You say "omits special characters".  Do you mean that data is stored into the table(s), but with strings truncated at the special characters?  See "Truncated text" in Trouble with utf8 characters; what I see is not what I stored .

You say "stops execution".  That seems unlikely; please provide more details, such as the SQL that caused the termination, whether other commands come be run after it, whether you needed to start (not "restart") mysqld again.

You say "special characters"; let's see some examples.  You used escaping to get $field variables, but what did you then do with those variables?

Body:
I'm inserting contents into table as bulk upload format (.csv).

In my CSV some columns include special characters but server can't insert special characters included rows into db and stops execution.

How can I insert these values?

I'm trying:

$field1= addslashes(trim($data[0]));

and I'm using mysqli_real_escape_string, it's working but it omits all special characters from the fields...

$field2= mysqli_real_escape_string(trim($data[1]));

Body:
Do not call any conversion routines.  Simply declare that the .csv file is encoded latin1.  Do that with this clause in the LOAD DATA statement:

CHARACTER SET latin1

You have not said what charset the column/table is.  Please provide SHOW CREATE TABLE.  The column can be either latin1 or utf8.

Also, use mysqli_set_charset to establish which charset your client code is using.  (It does not need to be the same as the column/table.)

You say "omits special characters".  Do you mean that data is stored into the table(s), but with strings truncated at the special characters?  See "Truncated text" in Trouble with utf8 characters; what I see is not what I stored .

You say "stops execution".  That seems unlikely; please provide more details, such as the SQL that caused the termination, whether other commands come be run after it, whether you needed to start (not "restart") mysqld again.

You say "special characters"; let's see some examples.  You used escaping to get $field variables, but what did you then do with those variables?


问:
How to get ObservableCollection item by ListView SelectedIndex
I created a ListView and set a ObservableCollection to ItemsSource.

Then, I can use a int to binding SelectedIndex, it's work well.

But I don't know how to get item's detail when I selected.

I want to get ObservableCollection, then binding it to show on a TextBlock.

My TextBlock and ListView are difference UserControl. ViewModel in MainWindow.

So I want to know how to get ObservableCollection item by ListView SelectedIndex?

Or others method to resolve it?

Thx.

ViewModel in MainWinodw:

```<code>public class TestVM : INotifyPropertyChanged
{
    private int _index;
    public int Index
    {
        get
        {
            return _index;
        }
        set
        {
            _index = value;
            RaisePropertyChanged("Index");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(String propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<User> _items;
    public ObservableCollection<User> Items
    {
        get
        {
            return _items;
        }
        private set
        {
            _items = value;
            RaisePropertyChanged("Items");
        }
    }

    ObservableCollection<User> _collection;
    public ObservableCollection<User> Collection
    {
        get
        {
            return _collection;
        }
        private set
        {
            _collection = value;
            RaisePropertyChanged("Collection");
        }
    }

    ListCollectionView _groupView;
    public ListCollectionView GroupView
    {
        get
        {
            return _groupView;
        }
        private set
        {
            _groupView = value;
            RaisePropertyChanged("GroupView");
        }
    }

    public TestVM()
    {
        Collection = new ObservableCollection<User>();
        Collection.Add(new User() { Name = "John Doe1", Age = 10, group = "Group 1" });
        Collection.Add(new User() { Name = "Jane Doe2", Age = 20, group = "Group 1" });

        Collection.Add(new User() { Name = "Sammy Doe", Age = 30, group = "Group 2" });
        Collection.Add(new User() { Name = "Sammy Doe1", Age = 40, group = "Group 2" });
        Collection.Add(new User() { Name = "Sammy Doe2", Age = 50, group = "Group 2" });

        Collection.Add(new User() { Name = "Sammy Doe3", Age = 60, group = "Group 3" });
        Collection.Add(new User() { Name = "Sammy Doe4", Age = 70, group = "Group 3" });

        GroupView = new ListCollectionView(Collection);
        GroupView.GroupDescriptions.Add(new PropertyGroupDescription("group"));
    }
}

public class User
{
    public string Name { set; get; }
    public int Age { set; get; }

    public string group { get; set; }
}
</code>```

ListView in UserControl1:

```<code><ListView Margin="10" Name="lv" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}">
        <ListView.View>
            <GridView>
                <local:GridViewColumnExt Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
                <local:GridViewColumnExt x:Name="colAge" Header="Age" Width="50">
                    <local:GridViewColumnExt.CellTemplate>
                        <DataTemplate>
                            <Button Content="{Binding Age}"></Button>
                        </DataTemplate>
                    </local:GridViewColumnExt.CellTemplate>
                </local:GridViewColumnExt>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</code>```

TextBlock in UserControl2 (Just want to show item detail) :

```<code><WrapPanel>
    <TextBlock Text="SelectdIndex: "/>
    <TextBlock Text="{Binding Index}" />
</WrapPanel>
</code>```

MainWindow.xmal

```<code><Grid>
        <Grid.DataContext>
            <local:TestVM/>
        </Grid.DataContext>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <local:StepList Grid.Column="0"></local:StepList>
        <local:ItemDetail Grid.Column="1"></local:ItemDetail>
    </Grid>
</code>```

答:
If you want the details of the selected item in ListView to show up in the Textbox you have to set the binding in the Textbox.

e.g.

```<code>Text="{Binding SelectedItem.EnterThePropertyToShowhere, ElementName=EnterTheNameOfyourListViewhere, UpdateSourceTrigger="PropertyChanged"}"
</code>```

Edit 3: Ok forgett what I said. Try:

Add to your Listview

```<code>SelectedItem="{Bindig SelectedUser , UpdateSourceTrigger="PropertyChanged"}"
</code>```

Add to your ViewModel a property SelectedUser with propertychange Notification

```<code>public User SelectedUser{
     get { return _selectedUser; }
     set
     {
        if (value == _selectedUser) return;
        _selectedUser= value;
        RaisePropertyChanged("SelectedUser");
     }
  }
</code>```

Add to your Textbox:

```<code> Text="{Binding SelectedUser.PropertyWhichShouldShow, UpdateSourceTrigger="PropertyChanged"}"
</code>```

Body:
I created a ListView and set a ObservableCollection to ItemsSource.

Then, I can use a int to binding SelectedIndex, it's work well.

But I don't know how to get item's detail when I selected.

I want to get ObservableCollection, then binding it to show on a TextBlock.

My TextBlock and ListView are difference UserControl. ViewModel in MainWindow.

So I want to know how to get ObservableCollection item by ListView SelectedIndex?

Or others method to resolve it?

Thx.

ViewModel in MainWinodw:

public class TestVM : INotifyPropertyChanged
{
    private int _index;
    public int Index
    {
        get
        {
            return _index;
        }
        set
        {
            _index = value;
            RaisePropertyChanged("Index");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(String propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<User> _items;
    public ObservableCollection<User> Items
    {
        get
        {
            return _items;
        }
        private set
        {
            _items = value;
            RaisePropertyChanged("Items");
        }
    }

    ObservableCollection<User> _collection;
    public ObservableCollection<User> Collection
    {
        get
        {
            return _collection;
        }
        private set
        {
            _collection = value;
            RaisePropertyChanged("Collection");
        }
    }

    ListCollectionView _groupView;
    public ListCollectionView GroupView
    {
        get
        {
            return _groupView;
        }
        private set
        {
            _groupView = value;
            RaisePropertyChanged("GroupView");
        }
    }

    public TestVM()
    {
        Collection = new ObservableCollection<User>();
        Collection.Add(new User() { Name = "John Doe1", Age = 10, group = "Group 1" });
        Collection.Add(new User() { Name = "Jane Doe2", Age = 20, group = "Group 1" });

        Collection.Add(new User() { Name = "Sammy Doe", Age = 30, group = "Group 2" });
        Collection.Add(new User() { Name = "Sammy Doe1", Age = 40, group = "Group 2" });
        Collection.Add(new User() { Name = "Sammy Doe2", Age = 50, group = "Group 2" });

        Collection.Add(new User() { Name = "Sammy Doe3", Age = 60, group = "Group 3" });
        Collection.Add(new User() { Name = "Sammy Doe4", Age = 70, group = "Group 3" });

        GroupView = new ListCollectionView(Collection);
        GroupView.GroupDescriptions.Add(new PropertyGroupDescription("group"));
    }
}

public class User
{
    public string Name { set; get; }
    public int Age { set; get; }

    public string group { get; set; }
}

ListView in UserControl1:

<ListView Margin="10" Name="lv" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}">
        <ListView.View>
            <GridView>
                <local:GridViewColumnExt Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
                <local:GridViewColumnExt x:Name="colAge" Header="Age" Width="50">
                    <local:GridViewColumnExt.CellTemplate>
                        <DataTemplate>
                            <Button Content="{Binding Age}"></Button>
                        </DataTemplate>
                    </local:GridViewColumnExt.CellTemplate>
                </local:GridViewColumnExt>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>

TextBlock in UserControl2 (Just want to show item detail) :

<WrapPanel>
    <TextBlock Text="SelectdIndex: "/>
    <TextBlock Text="{Binding Index}" />
</WrapPanel>

MainWindow.xmal

<Grid>
        <Grid.DataContext>
            <local:TestVM/>
        </Grid.DataContext>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <local:StepList Grid.Column="0"></local:StepList>
        <local:ItemDetail Grid.Column="1"></local:ItemDetail>
    </Grid>

Body:
If you want the details of the selected item in ListView to show up in the Textbox you have to set the binding in the Textbox.

e.g.

Text="{Binding SelectedItem.EnterThePropertyToShowhere, ElementName=EnterTheNameOfyourListViewhere, UpdateSourceTrigger="PropertyChanged"}"

Edit 3: Ok forgett what I said. Try:

Add to your Listview

SelectedItem="{Bindig SelectedUser , UpdateSourceTrigger="PropertyChanged"}"

Add to your ViewModel a property SelectedUser with propertychange Notification

public User SelectedUser{
     get { return _selectedUser; }
     set
     {
        if (value == _selectedUser) return;
        _selectedUser= value;
        RaisePropertyChanged("SelectedUser");
     }
  }

Add to your Textbox:

 Text="{Binding SelectedUser.PropertyWhichShouldShow, UpdateSourceTrigger="PropertyChanged"}"