问:
How to capture subprocess output on both stderr and stdout in OCaml
I'm looking at the following OCaml code, which attempts to open a subprocess, feed it some input, and then collect all of the output it produces on either stdout or stderr.  But the fact that it first reads everything from stdout and then reads everything from stderr seems fishy -- if the subprocess happens to write a lot of stuff to stderr, it seems like the result will be a deadlock.

```<code>let rec output_lines (output : string list) (chan : out_channel) : unit =
  ignore (List.map (output_string chan) output); flush chan

let async_command
    (name : string)
    (arguments : string list)
  : (in_channel * out_channel * in_channel) =
  Unix.open_process_full
    (name ^ " " ^ (String.concat " " arguments))
    (Unix.environment ())

let sync_command
    (name : string)
    (arguments : string list)
    (input : string list) : (string list * string list) =
  let (o, i, e) = async_command name arguments in
  output_lines input i;
  let out, err = (input_lines o, input_lines e) in
  let status = Unix.close_process_full (o, i, e) in
  begin match status with
    | Unix.WEXITED   x -> if x != 0 then raise (Shell_error (unlines err))
    | Unix.WSIGNALED x -> if x = Sys.sigint then raise Sys.Break
    | Unix.WSTOPPED  x -> if x = Sys.sigint then raise Sys.Break
  end;
  (out, err)
</code>```

How should this be fixed?  (Better yet, what library should I use where this functionality is already implemented?)

答:
In general, you should use some sort of polling over a set of descriptors along with the non-blocking input to pipe information from the to the output. This will, of course, garbage the output, i.e., intermix it in an arbitrary order. The polling can be performed with the Unix.select function. A non-blocking io can be enabled by setting the O_NONBLOCK flag when a file is opened, or with the Unix.set_nonblock function.

With all these said, I would like to stress that writing non-blocking code is not a trivial exercise. Especially if it is done in raw, poll/read/write loop. Many modern languages/runtimes have libraries that decouple this cycle and provide a generic interface in the form of callbacks. OCaml was one of the pioneers in this direction, with its Lwt library. We also have the Async library, that is slightly bigger but shares the same design. I wouldn't advise one or another, as it is opinion based, but, as an anecdote, your namesake Benjamin Pierce was using Lwt for his Unison project :)

A complete example without Lwt (Async)

We can burrow an example from the Unix System Programming book

```<code>(* The multiplex function takes a descriptor open on the serial
   port and two arrays of descriptors of the same size, one containing
   pipes connected to the standard input of the user processes, the other
   containing pipes connected to their standard output. *)
open Unix;;

let rec really_read fd buff start length =
  if length <= 0 then () else
    match read fd buff start length with
    | 0 -> raise End_of_file
    | n -> really_read fd buff (start+n) (length-n);;

let buffer = String.create 258;;

let multiplex channel inputs outputs =
  let input_fds = channel :: Array.to_list inputs in
  try
    while true do
      let (ready_fds, _, _) = select input_fds [] [] (-1.0) in
      for i = 0 to Array.length inputs - 1 do
        if List.mem inputs.(i) ready_fds then begin
          let n = read inputs.(i) buffer 2 255 in
          buffer.[0] <- char_of_int i;
          buffer.[1] <- char_of_int n;
          ignore (write channel buffer 0 (n+2));
          ()
        end
      done;
      if List.mem channel ready_fds then begin
        really_read channel buffer 0 2;
        let i = int_of_char(buffer.[0])
        and n = int_of_char(buffer.[1]) in
        if n = 0 then close outputs.(i) else
        begin
          really_read channel buffer 0 n;
          ignore (write outputs.(i) buffer 0 n);
          ()
        end
      end
    done
  with End_of_file -> () ;;
</code>```

Note: You should use create_subprocess that returns the file descriptors, to implement non blocking IO.

Body:
I'm looking at the following OCaml code, which attempts to open a subprocess, feed it some input, and then collect all of the output it produces on either stdout or stderr.  But the fact that it first reads everything from stdout and then reads everything from stderr seems fishy -- if the subprocess happens to write a lot of stuff to stderr, it seems like the result will be a deadlock.

let rec output_lines (output : string list) (chan : out_channel) : unit =
  ignore (List.map (output_string chan) output); flush chan

let async_command
    (name : string)
    (arguments : string list)
  : (in_channel * out_channel * in_channel) =
  Unix.open_process_full
    (name ^ " " ^ (String.concat " " arguments))
    (Unix.environment ())

let sync_command
    (name : string)
    (arguments : string list)
    (input : string list) : (string list * string list) =
  let (o, i, e) = async_command name arguments in
  output_lines input i;
  let out, err = (input_lines o, input_lines e) in
  let status = Unix.close_process_full (o, i, e) in
  begin match status with
    | Unix.WEXITED   x -> if x != 0 then raise (Shell_error (unlines err))
    | Unix.WSIGNALED x -> if x = Sys.sigint then raise Sys.Break
    | Unix.WSTOPPED  x -> if x = Sys.sigint then raise Sys.Break
  end;
  (out, err)

How should this be fixed?  (Better yet, what library should I use where this functionality is already implemented?)

Body:
In general, you should use some sort of polling over a set of descriptors along with the non-blocking input to pipe information from the to the output. This will, of course, garbage the output, i.e., intermix it in an arbitrary order. The polling can be performed with the Unix.select function. A non-blocking io can be enabled by setting the O_NONBLOCK flag when a file is opened, or with the Unix.set_nonblock function.

With all these said, I would like to stress that writing non-blocking code is not a trivial exercise. Especially if it is done in raw, poll/read/write loop. Many modern languages/runtimes have libraries that decouple this cycle and provide a generic interface in the form of callbacks. OCaml was one of the pioneers in this direction, with its Lwt library. We also have the Async library, that is slightly bigger but shares the same design. I wouldn't advise one or another, as it is opinion based, but, as an anecdote, your namesake Benjamin Pierce was using Lwt for his Unison project :)

A complete example without Lwt (Async)

We can burrow an example from the Unix System Programming book

(* The multiplex function takes a descriptor open on the serial
   port and two arrays of descriptors of the same size, one containing
   pipes connected to the standard input of the user processes, the other
   containing pipes connected to their standard output. *)
open Unix;;

let rec really_read fd buff start length =
  if length <= 0 then () else
    match read fd buff start length with
    | 0 -> raise End_of_file
    | n -> really_read fd buff (start+n) (length-n);;

let buffer = String.create 258;;

let multiplex channel inputs outputs =
  let input_fds = channel :: Array.to_list inputs in
  try
    while true do
      let (ready_fds, _, _) = select input_fds [] [] (-1.0) in
      for i = 0 to Array.length inputs - 1 do
        if List.mem inputs.(i) ready_fds then begin
          let n = read inputs.(i) buffer 2 255 in
          buffer.[0] <- char_of_int i;
          buffer.[1] <- char_of_int n;
          ignore (write channel buffer 0 (n+2));
          ()
        end
      done;
      if List.mem channel ready_fds then begin
        really_read channel buffer 0 2;
        let i = int_of_char(buffer.[0])
        and n = int_of_char(buffer.[1]) in
        if n = 0 then close outputs.(i) else
        begin
          really_read channel buffer 0 n;
          ignore (write outputs.(i) buffer 0 n);
          ()
        end
      end
    done
  with End_of_file -> () ;;

Note: You should use create_subprocess that returns the file descriptors, to implement non blocking IO.


来源: stackexchange

问:
Show balance in PHP using API?
I'm trying to show SMS balance using an API in a PHP page.
What am I missing to simplify this? (The API is working fine directly):</p>

```<code>public function show_sms_credits() {

    if ( false === ( $my_query = get_transient( 'available_sms_credits' ) ) ) {

        $api_key    = get_option( 'wc_api_key', true );
        $api_token  = get_option( 'wc_api_token', true );

        if( empty ( $api_key ) || empty( $api_token ) ){
            return;
        }

        $url = 'http://mywebsite.com/api/';

        $response = wp_remote_get("{$this->url}GetBalance?User={$this->api_key}&Password={$this->api_token}");

        if( ! is_wp_error( $response ) && 200 == wp_remote_retrieve_response_code( $response ) ) {
            $body = json_decode( wp_remote_retrieve_body( $response ) );
            set_transient( 'available_sms_credits', $body->sms_credits, 12 * HOUR_IN_SECONDS );
        }
    }

    $sms_credits = get_transient( 'available_sms_credits' );

    }
}
<p> SMS Balance: <?php echo 'available_sms_credits': ?> </p>
</code>```

答:
Because you use this syntax

```<code>$url = 'http://mywebsite.com/api/';
</code>```

You should simply use

```<code>$response = wp_remote_get("{$url}GetBalance?User={$api_key}&Password={$api_token}");
</code>```

Because you've only assigned local variables, not assignments to the current object itself. If you needed to add the URL as a property against your object you'd have use $this like...

```<code>$this->url = 'http://mywebsite.com/api/';
</code>```

Also your're not doing anything with $sms_credits

ContentLicense: CC BY-SA 3.0

Title: Show balance in PHP using API?

Body:
I'm trying to show SMS balance using an API in a PHP page.
What am I missing to simplify this? (The API is working fine directly):

public function show_sms_credits() {

    if ( false === ( $my_query = get_transient( 'available_sms_credits' ) ) ) {

        $api_key    = get_option( 'wc_api_key', true );
        $api_token  = get_option( 'wc_api_token', true );

        if( empty ( $api_key ) || empty( $api_token ) ){
            return;
        }

        $url = 'http://mywebsite.com/api/';

        $response = wp_remote_get("{$this->url}GetBalance?User={$this->api_key}&Password={$this->api_token}");

        if( ! is_wp_error( $response ) && 200 == wp_remote_retrieve_response_code( $response ) ) {
            $body = json_decode( wp_remote_retrieve_body( $response ) );
            set_transient( 'available_sms_credits', $body->sms_credits, 12 * HOUR_IN_SECONDS );
        }
    }

    $sms_credits = get_transient( 'available_sms_credits' );

    }
}

 SMS Balance: <?php echo 'available_sms_credits': ?>

Body:
Because you use this syntax

$url = 'http://mywebsite.com/api/';

You should simply use

$response = wp_remote_get("{$url}GetBalance?User={$api_key}&Password={$api_token}");

Because you've only assigned local variables, not assignments to the current object itself. If you needed to add the URL as a property against your object you'd have use $this like...

$this->url = 'http://mywebsite.com/api/';

Also your're not doing anything with $sms_credits


问:
C# Can I display images in a list box?
C# In a nut shell can I display images in a list box? I have a list of users and I want to display a green tick next to some of the names, is this possible?

Thanks

答: In WPF it's quite simple, but if you're using winforms, you can't do it with the System.Windows.Forms.ListBox control.  You can do it with the ListView control, or third party controls.

OwnerDisplayName: Steve

LastEditorDisplayName: Steve

Title: C# Can I display images in a list box?

OwnerDisplayName: Michael Meadows

ContentLicense: CC BY-SA 2.5


问:
Design function so variables get assigned values without large if/else block
There must be a better way to do this:

```<code>def map_leds(self, i):
        if i[0] == 1:
            self.ledg_1_1.setVisible(True)
            self.ledr_1_1.setVisible(False)
        else:
            self.ledg_1_1.setVisible(False)
            self.ledr_1_1.setVisible(True)

###############################################

        if int(i[1]) == 1:
            self.ledg_1_2.setVisible(True)
            self.ledr_1_2.setVisible(False)
        else:
            self.ledg_1_2.setVisible(False)
            self.ledr_1_2.setVisible(True)

###############################################

        if int(i[2]) == 1:
            self.ledg_1_3.setVisible(True)
            self.ledr_1_3.setVisible(False)
        else:
            self.ledg_1_3.setVisible(False)
            self.ledr_1_3.setVisible(True)

###############################################

        if int(i[3]) == 1:
            self.ledg_2_1.setVisible(True)
            self.ledr_2_1.setVisible(False)
        else:
            self.ledg_2_1.setVisible(False)
            self.ledr_2_1.setVisible(True)

###############################################

        if int(i[4]) == 1:
            self.ledg_2_2.setVisible(True)
            self.ledr_2_2.setVisible(False)
        else:
            self.ledg_2_2.setVisible(False)
            self.ledr_2_2.setVisible(True)

###############################################

        if int(i[5]) == 1:
            self.ledg_2_3.setVisible(True)
            self.ledr_2_3.setVisible(False)
        else:
            self.ledg_2_3.setVisible(False)
            self.ledr_2_3.setVisible(True)

###############################################

        if int(i[6]) == 1:
            self.ledg_3_1.setVisible(True)
            self.ledr_3_1.setVisible(False)
        else:
            self.ledg_3_1.setVisible(False)
            self.ledr_3_1.setVisible(True)

###############################################

        if int(i[7]) == 1:
            self.ledg_3_2.setVisible(True)
            self.ledr_3_2.setVisible(False)
        else:
            self.ledg_3_2.setVisible(False)
            self.ledr_3_2.setVisible(True)

###############################################

if int(i[8]) == 1:
            self.ledg_3_3.setVisible(True)
            self.ledr_3_3.setVisible(False)
        else:
            self.ledg_3_3.setVisible(False)
            self.ledr_3_3.setVisible(True)
</code>```

I have 9 LEDS, and I my function map_leds is fed an list of len 9 populated with 0s and 1s. If the first value is 1, the first LED should be green (this is a GUI, so an LED is actually a picture and I have to switch between both pictures, hence the "setVisible" function). If the first value is 0, then the LED (that should be displayed) is the red one. And so on for all the other values.

There must be a better way to actually do all this than have a huge if-else statement block, right?

答:
The pattern I'm noticing is that the default is the red led on and green led off for all cases if i is not equal to 1. The leds are toggled if i equals 1.

```<code>LOOKUP_TABLE = {
    0: (1, 1),
    1: (1, 2),
    2: (1, 3),
    3: (2, 1),
    4: (2, 2),
    5: (2, 3),
    6: (3, 1),
    7: (3, 2),
    8: (3, 3),
}

LED_NAMING = "led{color}_{row}_{column}"

COLORS = {
    'green': 'g',
    'red': 'r'
}

def led_name(row=None, column=None, color=None, naming=LED_NAMING):
    """Get a led's name."""
    return naming.format(
        row=row,
        column=column,
        color=COLORS[color],
    )

def toggle(self, i, lookup=None):
    """Toggle the `i`th pair of leds."""

    lookup = lookup or LOOKUP_TABLE
    for led_index, led_switch in enumerate(i):
        row, column = lookup[led_index]

        green_led_name = led_name(row, column, 'green')
        red_led_name = led_name(row, column, 'red')

        green_led = getattr(self, green_led_name)
        red_led = getattr(self, red_led_name)

        if int(led_switch) == 1:
            green_led.setVisible(True)
            red_led.setVisible(False)
        else:
            green_led.setVisible(False)
            red_led.setVisible(True)
</code>```

Here's a demonstration the code works:

```<code>class LED(object):
    def setVisible(self, value):
        self._visible = value

    @property
    def visible(self):
        return self._visible

class LEDMatrix(object):
    def __init__(self):
        for row, column in LOOKUP_TABLE.values():
            for color in COLORS:
                setattr(self, led_name(row, column, color), LED())
</code>```

How you would use that:

```<code>>>> LEDMatrix.toggle = toggle # Inject our method in example class.
>>> ledmatrix = LEDMatrix()
>>> dir(ledmatrix) # We remove magic methods from display for clarity.
[
 'ledg_1_1',
 'ledg_1_2',
 'ledg_1_3',
 'ledg_2_1',
 'ledg_2_2',
 'ledg_2_3',
 'ledg_3_1',
 'ledg_3_2',
 'ledg_3_3',
 'ledr_1_1',
 'ledr_1_2',
 'ledr_1_3',
 'ledr_2_1',
 'ledr_2_2',
 'ledr_2_3',
 'ledr_3_1',
 'ledr_3_2',
 'ledr_3_3',
 'toggle'
]
>>> ledmatrix.ledg_1_1.visible # AttributeError
>>> ledmatrix.toggle([0, 1, 0, 1, 1, 1, 0, 1, 1])
>>> ledmatrix.ledg_1_1.visible # False
>>> ledmatrix.toggle([1, 1, 0, 1, 1, 1, 0, 1, 1])
>>> ledmatrix.ledg_1_1.visible # True
</code>```

Body:
There must be a better way to do this:

def map_leds(self, i):
        if i[0] == 1:
            self.ledg_1_1.setVisible(True)
            self.ledr_1_1.setVisible(False)
        else:
            self.ledg_1_1.setVisible(False)
            self.ledr_1_1.setVisible(True)

###############################################

        if int(i[1]) == 1:
            self.ledg_1_2.setVisible(True)
            self.ledr_1_2.setVisible(False)
        else:
            self.ledg_1_2.setVisible(False)
            self.ledr_1_2.setVisible(True)

###############################################

        if int(i[2]) == 1:
            self.ledg_1_3.setVisible(True)
            self.ledr_1_3.setVisible(False)
        else:
            self.ledg_1_3.setVisible(False)
            self.ledr_1_3.setVisible(True)

###############################################

        if int(i[3]) == 1:
            self.ledg_2_1.setVisible(True)
            self.ledr_2_1.setVisible(False)
        else:
            self.ledg_2_1.setVisible(False)
            self.ledr_2_1.setVisible(True)

###############################################

        if int(i[4]) == 1:
            self.ledg_2_2.setVisible(True)
            self.ledr_2_2.setVisible(False)
        else:
            self.ledg_2_2.setVisible(False)
            self.ledr_2_2.setVisible(True)

###############################################

        if int(i[5]) == 1:
            self.ledg_2_3.setVisible(True)
            self.ledr_2_3.setVisible(False)
        else:
            self.ledg_2_3.setVisible(False)
            self.ledr_2_3.setVisible(True)

###############################################

        if int(i[6]) == 1:
            self.ledg_3_1.setVisible(True)
            self.ledr_3_1.setVisible(False)
        else:
            self.ledg_3_1.setVisible(False)
            self.ledr_3_1.setVisible(True)

###############################################

        if int(i[7]) == 1:
            self.ledg_3_2.setVisible(True)
            self.ledr_3_2.setVisible(False)
        else:
            self.ledg_3_2.setVisible(False)
            self.ledr_3_2.setVisible(True)

###############################################

if int(i[8]) == 1:
            self.ledg_3_3.setVisible(True)
            self.ledr_3_3.setVisible(False)
        else:
            self.ledg_3_3.setVisible(False)
            self.ledr_3_3.setVisible(True)

I have 9 LEDS, and I my function map_leds is fed an list of len 9 populated with 0s and 1s. If the first value is 1, the first LED should be green (this is a GUI, so an LED is actually a picture and I have to switch between both pictures, hence the "setVisible" function). If the first value is 0, then the LED (that should be displayed) is the red one. And so on for all the other values.

There must be a better way to actually do all this than have a huge if-else statement block, right?

Body:
The pattern I'm noticing is that the default is the red led on and green led off for all cases if i is not equal to 1. The leds are toggled if i equals 1.

LOOKUP_TABLE = {
    0: (1, 1),
    1: (1, 2),
    2: (1, 3),
    3: (2, 1),
    4: (2, 2),
    5: (2, 3),
    6: (3, 1),
    7: (3, 2),
    8: (3, 3),
}

LED_NAMING = "led{color}_{row}_{column}"

COLORS = {
    'green': 'g',
    'red': 'r'
}

def led_name(row=None, column=None, color=None, naming=LED_NAMING):
    """Get a led's name."""
    return naming.format(
        row=row,
        column=column,
        color=COLORS[color],
    )

def toggle(self, i, lookup=None):
    """Toggle the `i`th pair of leds."""

    lookup = lookup or LOOKUP_TABLE
    for led_index, led_switch in enumerate(i):
        row, column = lookup[led_index]

        green_led_name = led_name(row, column, 'green')
        red_led_name = led_name(row, column, 'red')

        green_led = getattr(self, green_led_name)
        red_led = getattr(self, red_led_name)

        if int(led_switch) == 1:
            green_led.setVisible(True)
            red_led.setVisible(False)
        else:
            green_led.setVisible(False)
            red_led.setVisible(True)

Here's a demonstration the code works:

class LED(object):
    def setVisible(self, value):
        self._visible = value

    @property
    def visible(self):
        return self._visible

class LEDMatrix(object):
    def __init__(self):
        for row, column in LOOKUP_TABLE.values():
            for color in COLORS:
                setattr(self, led_name(row, column, color), LED())

How you would use that:

>>> LEDMatrix.toggle = toggle # Inject our method in example class.
>>> ledmatrix = LEDMatrix()
>>> dir(ledmatrix) # We remove magic methods from display for clarity.
[
 'ledg_1_1',
 'ledg_1_2',
 'ledg_1_3',
 'ledg_2_1',
 'ledg_2_2',
 'ledg_2_3',
 'ledg_3_1',
 'ledg_3_2',
 'ledg_3_3',
 'ledr_1_1',
 'ledr_1_2',
 'ledr_1_3',
 'ledr_2_1',
 'ledr_2_2',
 'ledr_2_3',
 'ledr_3_1',
 'ledr_3_2',
 'ledr_3_3',
 'toggle'
]
>>> ledmatrix.ledg_1_1.visible # AttributeError
>>> ledmatrix.toggle([0, 1, 0, 1, 1, 1, 0, 1, 1])
>>> ledmatrix.ledg_1_1.visible # False
>>> ledmatrix.toggle([1, 1, 0, 1, 1, 1, 0, 1, 1])
>>> ledmatrix.ledg_1_1.visible # True


问:
Should I redefine or reassign a variable in a loop?
Supposing I need to iterate over something and set a variable in every cycle, like this:

```<code>for (int i=0; i < list.size(); i++) {
    final Object cur = list.get(i);
}
</code>```

this redefines the variable everytime, so I'm concerned that that might pollute the memory.

The alternate option is to define the variable once and then reassign it every iteration, like this:

```<code>Object cur
for (int i=0; i < list.size(); i++) {
    cur = list.get(i);
}
</code>```

would this be better in terms of memory? Would it make any difference? What if cur is a primitive type instead of an Object?

Don't tell me to use foreach, I need the counter, this is just a simplified example

答:
Performance of program is depend on how much time your code is taking to produce the output, and Statement/Loops/Conditions which take more time to execute it is natural that peace of code will consume more memory then other code which take less time to generate the output.

As per your code concern, 1st loop statement where you assigning final Object on every iteration is takes more time as compare to second loop statement where it assign to same object every time.

What I tried in my local linux(Ubuntu)  box, 1st statement take 18 milliseconds while 2nd statement takes only 15 seconds, so I guess 2nd statement will be more appropriate.

Code which I tried locally:

```<code>import java.util.ArrayList;
import java.util.List;

public class Solution8 {

    public static void main(String[] args) {
        List<String> lis = new ArrayList<String>();

        for (int i = 0; i <= Math.pow(10, 5); i++) {
            lis.add(i + "");
        }
        long startTime = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            final Object cur1 = lis.get(i);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("1st : "+(endTime-startTime)); // 18 milliseconds
        Object cur;
        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            cur = lis.get(i);
        }
        long endTime2 = System.currentTimeMillis();

        System.out.println("2nd : "+(endTime2-startTime2)); // 15 milliseconds
    }

}
</code>```

Hope this will help.

Body:
Supposing I need to iterate over something and set a variable in every cycle, like this:

for (int i=0; i < list.size(); i++) {
    final Object cur = list.get(i);
}

this redefines the variable everytime, so I'm concerned that that might pollute the memory.

The alternate option is to define the variable once and then reassign it every iteration, like this:

Object cur
for (int i=0; i < list.size(); i++) {
    cur = list.get(i);
}

would this be better in terms of memory? Would it make any difference? What if cur is a primitive type instead of an Object?

Don't tell me to use foreach, I need the counter, this is just a simplified example

Body:
Performance of program is depend on how much time your code is taking to produce the output, and Statement/Loops/Conditions which take more time to execute it is natural that peace of code will consume more memory then other code which take less time to generate the output.

As per your code concern, 1st loop statement where you assigning final Object on every iteration is takes more time as compare to second loop statement where it assign to same object every time.

What I tried in my local linux(Ubuntu)  box, 1st statement take 18 milliseconds while 2nd statement takes only 15 seconds, so I guess 2nd statement will be more appropriate.

Code which I tried locally:

import java.util.ArrayList;
import java.util.List;

public class Solution8 {

    public static void main(String[] args) {
        List<String> lis = new ArrayList<String>();

        for (int i = 0; i <= Math.pow(10, 5); i++) {
            lis.add(i + "");
        }
        long startTime = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            final Object cur1 = lis.get(i);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("1st : "+(endTime-startTime)); // 18 milliseconds
        Object cur;
        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i <= Math.pow(10, 5); i++) {
            cur = lis.get(i);
        }
        long endTime2 = System.currentTimeMillis();

        System.out.println("2nd : "+(endTime2-startTime2)); // 15 milliseconds
    }

}

Hope this will help.


问:
Wordpress: cloaking links
I am cloaking my affiliate link in wordpress and I don't want my user to see it in the status bar or something so is there a way for me to go to a page like www.mysite.com/my-redirect.php?p=foo without me having to create a page or post? or is there a better way?

My redirect.php file will do the redirection after the user lands to this file.

I am using the latest version.

答:
What I normally do is use the Urban Giraffe Redirection plugin to create a redirection in my blog to the affiliate link. i.e. say you're going to the link "http://blah.someproduct.clickbank.net", you can use Redirection to create a mapping for "/go/blah" to that link. Pretty easy stuff. Plus you can track how many times the link was clicked in the blog.

http://urbangiraffe.com/plugins/redirection/

Title: Wordpress: cloaking links


问:
Relational database: Hierarchy of alternating models, where do foreign keys belong?
I need to make a recommendation questionnaire, where answering a bunch of questions would lead to some unique result; decisions along the way should affect the end result.

It's fine to make it very basic - so I have two models - Questions and Answers. Each question has two answers, and each of the answers leads to one other question - so graphing out the hieararchy ends up like sort of like a binary tree:

```<code>          Question 1
         /         \
    Answer 1      Answer 2
      /              \
 Question 2        Question 3
  /       \         /       \
Ans3     Ans4     Ans5     Ans6
...
</code>```

So in plain english I'd say that each question has many answers, and each answer has one parent question and has one child question.

For a typical has many relationship, with the little experience I have I would probably just put the foreign key on the many end and not worry about the one end; so here Answer would get a question_id which doesn't have to be unique.

For has_one relationship, either end of relationship seems fine - but I already have a question_id on the answer; so maybe putting "parent" answer's answer_id on the question is appropriate, but that seems mighty confusing lexically - looking up something like Question.answer I would not intuitively understand it's the response that led to this question...

Alternatively, I could have two question_ids on in the Answer model - but then would have to differentiate between which one is "parent question" and which one is "follow-up question"...

Another consideration is that when I fetch the "next question" from the database (based on the answer), I also want to get the possible answers to display. Although optimizing the performance is not a requirement, it would be nice to "do it right" (or at least not completely wrong).

What's the best approach?

答:
With a bit of help from my friends, found the right term for what I'm trying to save - it's a decision tree!

https://en.wikipedia.org/wiki/Decision_tree

Then on this answer to a similar question https://stackoverflow.com/a/5278239/1592915 suggests using approach of a basically a man-to-many relationship between questions, where answers table is the intermediary.

Body:
I need to make a recommendation questionnaire, where answering a bunch of questions would lead to some unique result; decisions along the way should affect the end result.

It's fine to make it very basic - so I have two models - Questions and Answers. Each question has two answers, and each of the answers leads to one other question - so graphing out the hieararchy ends up like sort of like a binary tree:

          Question 1
         /         \
    Answer 1      Answer 2
      /              \
 Question 2        Question 3
  /       \         /       \
Ans3     Ans4     Ans5     Ans6
...

So in plain english I'd say that each question has many answers, and each answer has one parent question and has one child question.

For a typical has many relationship, with the little experience I have I would probably just put the foreign key on the many end and not worry about the one end; so here Answer would get a question_id which doesn't have to be unique.

For has_one relationship, either end of relationship seems fine - but I already have a question_id on the answer; so maybe putting "parent" answer's answer_id on the question is appropriate, but that seems mighty confusing lexically - looking up something like Question.answer I would not intuitively understand it's the response that led to this question...

Alternatively, I could have two question_ids on in the Answer model - but then would have to differentiate between which one is "parent question" and which one is "follow-up question"...

Another consideration is that when I fetch the "next question" from the database (based on the answer), I also want to get the possible answers to display. Although optimizing the performance is not a requirement, it would be nice to "do it right" (or at least not completely wrong).

What's the best approach?


问:
Change the text in a field with a VBA function
I'm currently working on a database in Access which has a table (Pro_Cons) who compares the pros and cons of different product-types. This table has 3 columns; Type (Product_type), Pros (Pro) and Cons.
For each of product-type I created a form which includes the pro- and the cons-field of the according type out of this table.
For adding new text to this fields I'm creating a VBA-function which is triggered by a button-click.

Because nothing worked as supposed to, I created the following function, which should only replace the Pro -field of the product type1 to change1.

Access doesnt throw an error, but nothing changes in the table.

Has someone an idea whats happening here?

```<code>Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset

Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If .RecordCount > 0 Then

    .MoveFirst

    .Edit

    !Pro.Value = strNew

    .Update

   End If
End With
End Sub
</code>```

答:
I think your literal should be changed to reference a form control:

```<code>strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"
</code>```

Changes to:

```<code>strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='" & Me!strProduct_type &
"'";
</code>```

Body:
I'm currently working on a database in Access which has a table (Pro_Cons) who compares the pros and cons of different product-types. This table has 3 columns; Type (Product_type), Pros (Pro) and Cons.
For each of product-type I created a form which includes the pro- and the cons-field of the according type out of this table.
For adding new text to this fields I'm creating a VBA-function which is triggered by a button-click.

Because nothing worked as supposed to, I created the following function, which should only replace the Pro -field of the product type1 to change1.

Access doesnt throw an error, but nothing changes in the table.

Has someone an idea whats happening here?

Sub Change_Pos_Inf()

Dim db As DAO.Database
Dim rst As DAO.Recordset

Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String

Set db = CurrentDb()

strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"

Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst

   If .RecordCount > 0 Then

    .MoveFirst

    .Edit

    !Pro.Value = strNew

    .Update

   End If
End With
End Sub

Body:
I think your literal should be changed to reference a form control:

strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"

Changes to:

strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='" & Me!strProduct_type &
"'";


问:
Configure service endpoint for angular 4/5 application
Have angular4 application and web api data service for this application. Have 100 customers of this application and data service. They have this data service and angular application on their IIS. So every of 100 angular application use ANOTHER endpoint address. So angular application in every customer need configuration for setting endpoint address - which have to be set in customer. None constant endpoint can be written into any file of angular application. How to solve this for angular 4/5 application?</p>

答:
One solution that I've seen for this problem is to create a file called configuration.json (or whichever name you wish) in the assets folder of your project, and change all of the endpoints when you're deploying on site.

In your code, you should create an angular service that reads the json from the file and exposes it as an object to the parts of your application that require the data service endpoints. This will involve using HttpClient to do a GET request on the configuration.json file.

Additionally, you can use a resolver, which uses the service, to resolve the environment data before navigating to each route.

This article describes the solution well enough: https://www.intertech.com/Blog/deploying-angular-4-apps-with-environment-specific-info/

The main point is that you can change the endpoints in the file and your application will resolve them at runtime.


问:
R interactive plot?
How can a user interactively change one aspect (e.g., orientation or length of a line) on a 2D plot?</p>

答:
The rpanel package has worked for me.   </p>

```<code>library(rpanel)

lvm.draw <- function(panel) {
  x=0:20
  plot(x, panel$int + (panel$slo*x), ylim=panel$data, ylab="y", main="Adam's Super Duper Interactive Graph", typ="l", lwd=3, col="red")
  grid()
  panel
}

ylimdat<-c(-50,50)
panel <- rp.control(title = "Adam's Panel", data=ylimdat, slo=0.5, int=1.0, size=c(300, 160))
rp.slider(panel, var=slo, from=-5, to=5, action=lvm.draw, title="Slope", pos=c(5, 5, 290, 70), showvalue=TRUE)
rp.slider(panel, var=int, from=-50, to=50, action=lvm.draw, title="Intercept", pos=c(5, 70, 290, 90), showvalue=TRUE)
</code>```

Title: R interactive plot?

Body:
The rpanel package has worked for me.

library(rpanel)

lvm.draw <- function(panel) {
  x=0:20
  plot(x, panel$int + (panel$slo*x), ylim=panel$data, ylab="y", main="Adam's Super Duper Interactive Graph", typ="l", lwd=3, col="red")
  grid()
  panel
}

ylimdat<-c(-50,50)
panel <- rp.control(title = "Adam's Panel", data=ylimdat, slo=0.5, int=1.0, size=c(300, 160))
rp.slider(panel, var=slo, from=-5, to=5, action=lvm.draw, title="Slope", pos=c(5, 5, 290, 70), showvalue=TRUE)
rp.slider(panel, var=int, from=-50, to=50, action=lvm.draw, title="Intercept", pos=c(5, 70, 290, 90), showvalue=TRUE)


问:
Runtime error 438 when assigning 1 of 2 worksheet variables
I am losing my mind here, I appreciate help understanding what is going on.

I'm writing a macro to prompt the user to open a datafile and then to open a report to populate the data to. The macro is launched via ActiveX button from a 3rd xlsm workbook (just like all of my other macros).

I am doing this with 2 separate FileDialog Objects. Once I have both workbooks opened and assigned to variables, I pass them ByVal to a sub that is supposed to do the work. The first step in the sub is to assign the worksheet variables for both workbooks. The first worksheet variable assigns properly, but the 2nd worksheet variable keeps giving me the "RTE 438 - Object doesn't support this property or method".

I am writing this macro based off a previous one I wrote that had a similar flow of opening 2 workbooks (but with one FileDialog object), passing them to a sub, then operating on them.

I know that my workbooks are not the issue, as my old macro works when I load my current report/data workbooks. I've also tried opening 2 test workbooks in my current macro and it still fails with the same message as before. Something is going on in the code but I really have no clue at this point, I've been on this for 2 days now. My current macro up to this point is basically a copy/paste of the older one that somehow works.

Random things I've tried:

Copy macro into new .bas file, delete old one

Combine the 2 FileDialog objects into 1 (mimicking old macro)

restart excel

rename variables

setting first filedialog object=nothing before running 2nd filedialog object

Here's my code on the sheet tied to button.click()

```<code>    Dim data_Path As String, report_Path As String
    Dim getData As FileDialog
    Dim getReport As FileDialog
    Dim Data_wb As Workbook
    Dim Report_wb As Workbook

    'Prompt User open data file
    Set getData = Application.FileDialog(msoFileDialogOpen)
    With getData
        .Title = "Select the new data file."
        .Filters.Clear
        .Filters.Add "Files", "*.xlsx; *.csv", 1
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count = 0 Then
            Exit Sub
        Else
            data_Path = .SelectedItems(1)
        End If
    End With

'Set data workbook variable
    Set Data_wb = Workbooks.Open(data_Path)

   'Prompt user to open Report
    Set getReport = Application.FileDialog(msoFileDialogOpen)
    With getReport
        .Title = "Select the destination report."
        .Filters.Clear
        .Filters.Add "Files", "*.xlsx; *.csv", 1
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count = 0 Then
            Exit Sub
        Else
            report_Path = .SelectedItems(1)
        End If
    End With

    Set Report_wb = Workbooks.Open(report_Path)

    Call report_update(Data_wb, Report_wb)
</code>```

Here is the code for report_update sub:

```<code>Dim datash As Worksheet
Dim reportsh As Worksheet
Dim mydatawb As Workbook
Dim myreportwb As Workbook

sub report_update(ByVal mydatawb as Workbook, ByVal myreportwb as Workbook)
set datash = mydatawb.Worksheets(1)
set reportsh = myreportwb.Worksheets(1)
</code>```

Set datash works fine, but Set reportsh throws the run-time error.

What am I missing here? Thanks!

答: I moved my Set worksheet objects to before my sub call and passed the worksheet references in rather than the workbook. That seems to have fixed it, I just don't understand why as I've never had to do that before.</p>

Body:
I am losing my mind here, I appreciate help understanding what is going on.

I'm writing a macro to prompt the user to open a datafile and then to open a report to populate the data to. The macro is launched via ActiveX button from a 3rd xlsm workbook (just like all of my other macros).

I am doing this with 2 separate FileDialog Objects. Once I have both workbooks opened and assigned to variables, I pass them ByVal to a sub that is supposed to do the work. The first step in the sub is to assign the worksheet variables for both workbooks. The first worksheet variable assigns properly, but the 2nd worksheet variable keeps giving me the "RTE 438 - Object doesn't support this property or method".

I am writing this macro based off a previous one I wrote that had a similar flow of opening 2 workbooks (but with one FileDialog object), passing them to a sub, then operating on them.

I know that my workbooks are not the issue, as my old macro works when I load my current report/data workbooks. I've also tried opening 2 test workbooks in my current macro and it still fails with the same message as before. Something is going on in the code but I really have no clue at this point, I've been on this for 2 days now. My current macro up to this point is basically a copy/paste of the older one that somehow works.

Random things I've tried:

Copy macro into new .bas file, delete old one

Combine the 2 FileDialog objects into 1 (mimicking old macro)

restart excel

rename variables

setting first filedialog object=nothing before running 2nd filedialog object

Here's my code on the sheet tied to button.click()

    Dim data_Path As String, report_Path As String
    Dim getData As FileDialog
    Dim getReport As FileDialog
    Dim Data_wb As Workbook
    Dim Report_wb As Workbook

    'Prompt User open data file
    Set getData = Application.FileDialog(msoFileDialogOpen)
    With getData
        .Title = "Select the new data file."
        .Filters.Clear
        .Filters.Add "Files", "*.xlsx; *.csv", 1
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count = 0 Then
            Exit Sub
        Else
            data_Path = .SelectedItems(1)
        End If
    End With

'Set data workbook variable
    Set Data_wb = Workbooks.Open(data_Path)

   'Prompt user to open Report
    Set getReport = Application.FileDialog(msoFileDialogOpen)
    With getReport
        .Title = "Select the destination report."
        .Filters.Clear
        .Filters.Add "Files", "*.xlsx; *.csv", 1
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count = 0 Then
            Exit Sub
        Else
            report_Path = .SelectedItems(1)
        End If
    End With

    Set Report_wb = Workbooks.Open(report_Path)

    Call report_update(Data_wb, Report_wb)

Here is the code for report_update sub:

Dim datash As Worksheet
Dim reportsh As Worksheet
Dim mydatawb As Workbook
Dim myreportwb As Workbook

sub report_update(ByVal mydatawb as Workbook, ByVal myreportwb as Workbook)
set datash = mydatawb.Worksheets(1)
set reportsh = myreportwb.Worksheets(1)

Set datash works fine, but Set reportsh throws the run-time error.

What am I missing here? Thanks!


问:
How to get my location?
I am new with maps in android i have this code :

```<code>enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
    GoogleMap.OnMyLocationClickListener,
    OnMapReadyCallback {

private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    Intent intent1 = getIntent();
    lat = intent1.getStringArrayExtra("latitute");
    lon  = intent1.getStringArrayExtra("longitude");
    id = intent1.getStringArrayExtra("id");
    emails  = intent1.getStringArrayExtra("emails");
    latitude=intent1.getDoubleExtra("MyLat",0);
    lonitude=intent1.getDoubleExtra("MyLon",0);
    req_button =(Button)findViewById(R.id.R_id);
    this.mHandler = new Handler();

    this.mHandler.postDelayed(m_Runnable,5000);

}

private final Runnable m_Runnable = new Runnable()
{
    public void run()

    {

        Search_for_Accepted_Job();
        Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();

        MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
    }

};

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng [] sydeny = new LatLng[lat.length];
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    // Add a marker in Sydney and move the camera
    for (int i=0 ; i< lat.length;i++) {
        sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));

    }
    for (int i=0 ; i< sydeny.length;i++) {
        mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
      //  mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
    }
   LatLng sydeny1 = new LatLng(latitude,lonitude);
    mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/

   mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationButtonClickListener(this);
    mMap.setOnMyLocationClickListener(this);

}

public void Request(View view) {

    Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
  for (int i=0; i< lat.length;i++)
    {

            send_request(id[i]);

    }
    req_button.setEnabled(false);
}

@Override
public boolean onMyLocationButtonClick() {
    Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
    return false;
}

@Override
public void onMyLocationClick(@NonNull Location location) {
    Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    lonitude=location.getLatitude();
    lonitude=location.getLongitude();
}
</code>```

So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
      (GoogleMap.OnMyLocationButtonClickListener
        GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named

```<code> public void onMyLocationClick(@NonNull Location location) {
    Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
</code>```

my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .

答:
To correctly use location in your app, you need to handle asking user permission to turn on location in settings (in case it is turned off) and then follow the steps in the documentation:
https://developer.android.com/training/location/retrieve-current.html

To answer your question exactly, did you try location.getLatitude() and location.getLongitude()?

Title: How to get my location?

Body:
I am new with maps in android i have this code :

enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
    GoogleMap.OnMyLocationClickListener,
    OnMapReadyCallback {

private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    Intent intent1 = getIntent();
    lat = intent1.getStringArrayExtra("latitute");
    lon  = intent1.getStringArrayExtra("longitude");
    id = intent1.getStringArrayExtra("id");
    emails  = intent1.getStringArrayExtra("emails");
    latitude=intent1.getDoubleExtra("MyLat",0);
    lonitude=intent1.getDoubleExtra("MyLon",0);
    req_button =(Button)findViewById(R.id.R_id);
    this.mHandler = new Handler();

    this.mHandler.postDelayed(m_Runnable,5000);

}

private final Runnable m_Runnable = new Runnable()
{
    public void run()

    {

        Search_for_Accepted_Job();
        Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();

        MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
    }

};

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    LatLng [] sydeny = new LatLng[lat.length];
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    // Add a marker in Sydney and move the camera
    for (int i=0 ; i< lat.length;i++) {
        sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));

    }
    for (int i=0 ; i< sydeny.length;i++) {
        mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
      //  mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
    }
   LatLng sydeny1 = new LatLng(latitude,lonitude);
    mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/

   mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationButtonClickListener(this);
    mMap.setOnMyLocationClickListener(this);

}

public void Request(View view) {

    Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
  for (int i=0; i< lat.length;i++)
    {

            send_request(id[i]);

    }
    req_button.setEnabled(false);
}

@Override
public boolean onMyLocationButtonClick() {
    Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
    return false;
}

@Override
public void onMyLocationClick(@NonNull Location location) {
    Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    lonitude=location.getLatitude();
    lonitude=location.getLongitude();
}

So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
      (GoogleMap.OnMyLocationButtonClickListener
        GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named

 public void onMyLocationClick(@NonNull Location location) {
    Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();

my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .


问:
How to save parent entity without inserting child in one to one relationship by shared primary key in hibernate?

I am using one to one relation by shared primary key in hibernate,
  whenever I call the save method to insert parent entity without inserying child entity I get below
  exception

```<code>org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.example.sms.domain.Child.parent]
</code>```

Code of child class entity with mapping of parent class entity is
  given below

```<code>@Entity
@Table(name = "t_child")
public class Child {

@Id
    @Column(name="user_id", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private Long id;

@OneToOne(optional = false,fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Parent parent;
</code>```

And in parent class entity i have mapped child class entity like below

```<code>@OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
    private Child child;
</code>```

Is there any way to save only parent entity without inserting child entity?

答:
The entity relationship diagram is not showing us a one-to-one relationship. But let us assume it is.

If I understood you well the child entity is dependent on the parent entity and it does not have its own identity. So you don't need to define an ID attribute for it; so the mapping for the Child entity should look like the following:

```<code>@Entity
@Table(name = "t_child")
public class Child {

    @Id
    @OneToOne(optional = false,fetch = FetchType.LAZY)
    @JoinColumn(name="parent_id")
    private Parent parent;
    // ...

}
</code>```

and the Parententity should look like the following:

```<code>@Entity
@Table(name = "t_parent")
public class Parent {

    @Id
    @GeneratedValue(generator="gen")
    private Long id;

    @OneToOne(mappedBy="parent")
    private Child child;

    // ...
}
</code>```

That should be the mapping. Now, if you want to save parent without child do as follows:

```<code>Parent parent = new Parent();
// set attribute values
entityManager.persist(parent);
</code>```

But if you want to save child, you should know that you first must have to save parent because the child is dependent on the parent, which means the parent must exist.

Body:
I am using one to one relation by shared primary key in hibernate,
  whenever I call the save method to insert parent entity without inserying child entity I get below
  exception

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.example.sms.domain.Child.parent]

Code of child class entity with mapping of parent class entity is
  given below

@Entity
@Table(name = "t_child")
public class Child {

@Id
    @Column(name="user_id", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private Long id;

@OneToOne(optional = false,fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Parent parent;

And in parent class entity i have mapped child class entity like below

@OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
    private Child child;

Is there any way to save only parent entity without inserting child entity?

Body:
The entity relationship diagram is not showing us a one-to-one relationship. But let us assume it is.

If I understood you well the child entity is dependent on the parent entity and it does not have its own identity. So you don't need to define an ID attribute for it; so the mapping for the Child entity should look like the following:

@Entity
@Table(name = "t_child")
public class Child {

    @Id
    @OneToOne(optional = false,fetch = FetchType.LAZY)
    @JoinColumn(name="parent_id")
    private Parent parent;
    // ...

}

and the Parententity should look like the following:

@Entity
@Table(name = "t_parent")
public class Parent {

    @Id
    @GeneratedValue(generator="gen")
    private Long id;

    @OneToOne(mappedBy="parent")
    private Child child;

    // ...
}

That should be the mapping. Now, if you want to save parent without child do as follows:

Parent parent = new Parent();
// set attribute values
entityManager.persist(parent);

But if you want to save child, you should know that you first must have to save parent because the child is dependent on the parent, which means the parent must exist.


问:
How to put jars from all subprojects into one directory in gradle 4.0?
I have a multi project project build as follows and when I do gradle clean build it creates jars under build/libs/ of each sub directory like below

```<code>root
   /projectA
       /build/libs/projectA.jar
   /projectB
       /build/libs/projectB.jar
</code>```

Now I want to have all these subprojects jars (project A & B) in one place (say root/build/libs) so it would like this

```<code>root
   /build
       /libs
           /projectA.jar
           /projectB.jar
   /projectA
       /build/libs/projectA.jar
   /projectB
       /build/libs/projectB.jar
</code>```

How do I do this ? Any code example? I am using gradle 4.0

答:
This works, albeit its rough, because hardcoding subprojects is not ideal.</p>

```<code>task copyJars(type: Copy) {
    def jars = [
        '/projectA/build/libs/.',
        '/projectB/build/libs/.']
    from jars
    include '*.jar'
    into 'build/libs'
}
</code>```

Body:
I have a multi project project build as follows and when I do gradle clean build it creates jars under build/libs/ of each sub directory like below

root
   /projectA
       /build/libs/projectA.jar
   /projectB
       /build/libs/projectB.jar

Now I want to have all these subprojects jars (project A & B) in one place (say root/build/libs) so it would like this

root
   /build
       /libs
           /projectA.jar
           /projectB.jar
   /projectA
       /build/libs/projectA.jar
   /projectB
       /build/libs/projectB.jar

How do I do this ? Any code example? I am using gradle 4.0

Body:
This works, albeit its rough, because hardcoding subprojects is not ideal.

task copyJars(type: Copy) {
    def jars = [
        '/projectA/build/libs/.',
        '/projectB/build/libs/.']
    from jars
    include '*.jar'
    into 'build/libs'
}


问:
Getting the values of textboxes in Javascript
I have this html code:

```<code><table border="" cellpadding="3" cellspacing="0" id="mytable">

<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
</code>```

How do I get the values of "song" and "artist"? I have tried:

```<code>var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
</code>```

but I keep getting "undefined" even when there is text inside the textbox

答:
Download jquery

```<code>jQuery("input[name='song']").val()
</code>```

To try and resolve the argument below. This can be down with plain javascript as above but for simplicity and cross browser standardisation I would recommend jQuery. It is a widely used and generally highly recommended library.

Body:
I have this html code:

Song:	 <input type="text" name="song" maxlength="64" size="48" />

Artist:	 <input type="text" name="artist" maxlength="16" size="48" />

How do I get the values of "song" and "artist"? I have tried:

var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);

but I keep getting "undefined" even when there is text inside the textbox

Body:
Download jquery

jQuery("input[name='song']").val()

To try and resolve the argument below. This can be down with plain javascript as above but for simplicity and cross browser standardisation I would recommend jQuery. It is a widely used and generally highly recommended library.


问:
How to get unique/distinct values in included in render json
I'd like the instituciones values to be unique/distinct when rendering profesionales.

The model is as shown:

```<code>class Profesional < ApplicationRecord
has_many :instituciones, through: :horarios
</code>```

and profesionales_controller.rb goes:

```<code>render json: @profesionales.to_json(include: {
        instituciones:  { only: [:id] }
})
</code>```

But I get some instituciones repeated. Is there a way to apply uniq or distinct?

答:
In this case, I think you might really want the JSON which would be served via an Institucion endpoint.

If not, then you might look to a more flexible means of generating the JSON where you can call something like profesional.instrituciones.uniq.each. jbuilder and rabl are good options for more flexible JSON templates.

Body:
I'd like the instituciones values to be unique/distinct when rendering profesionales.

The model is as shown:

class Profesional < ApplicationRecord
has_many :instituciones, through: :horarios

and profesionales_controller.rb goes:

render json: @profesionales.to_json(include: {
        instituciones:  { only: [:id] }
})

But I get some instituciones repeated. Is there a way to apply uniq or distinct?


问:
Communication link failure : while inserting into Linked Server (Azure) from SQL Server 2012
I'm trying to copy data from one table on SQL Server 2012 into another table on remote server (Azure)

Azure is added as linked server on SQL Server 2012

I'm  creating XML statements for inserts and then executing those statements on remote server as mentioned below.

```<code>DECLARE @xml XML

SET @xml = (
        SELECT 'insert into Table_on_Azure values ('  + convert(varchar(300),isnull(ID, 'NULL')) + ','  + convert(varchar(300),isnull(ST_ID, 'NULL')) + ',' ..... etc etc ...');'
        FROM local_table
        FOR XML path('')
        )

DECLARE @sql AS VARCHAR(max)

SET @sql = 'set nocount on;' + cast(@xml AS VARCHAR(max)) + 'set nocount off;' --Converts XML back to a long string
EXEC ('select * from remote_table_2') AT Linked_Azure_Server -- To confirm that the Linked Server is working fine and yes I do get results from this.

EXEC ('use myRemoteDB;' + @sql ) AT Linked_Azure_Server
</code>```

The reason why I'm doing this is : "The local table has around 1 million records and it was taking me more than 3 hours to push the data onto Linked Server. Then I found this answer Linked Server Insert-Select Performance in which it was suggested to create XML insert statements and execute on remote server.

But When I'm doing this I'm getting below error

```<code>OLE DB provider "SQLNCLI11" for linked server "Linked_Azure_Server" returned message "Communication link failure".
TCP Provider: The specified network name is no longer available.
</code>```

I'm sure the link to Linked_Server is fine. To cross check I wrote this statement EXEC ('select * from remote_table_2') AT Linked_Azure_Server just before inserting records and I do get results from this.

I've checked other answers to similar questions related to Communication Link Failure but no one is really helpful.

答:
I've experienced this before as well, and it dead-stopped my productivity for hours. The key for me was the db url. Which needed the word "secure" in it, as follows:

[db_name].database.secure.windows.net

I was shocked that there was no documentation on this, and the url isn't listed anywhere. For reference, I got to the bottom of it by chance when I stumbled upon this article.

Body:
I'm trying to copy data from one table on SQL Server 2012 into another table on remote server (Azure)

Azure is added as linked server on SQL Server 2012

I'm  creating XML statements for inserts and then executing those statements on remote server as mentioned below.

DECLARE @xml XML

SET @xml = (
        SELECT 'insert into Table_on_Azure values ('  + convert(varchar(300),isnull(ID, 'NULL')) + ','  + convert(varchar(300),isnull(ST_ID, 'NULL')) + ',' ..... etc etc ...');'
        FROM local_table
        FOR XML path('')
        )

DECLARE @sql AS VARCHAR(max)

SET @sql = 'set nocount on;' + cast(@xml AS VARCHAR(max)) + 'set nocount off;' --Converts XML back to a long string
EXEC ('select * from remote_table_2') AT Linked_Azure_Server -- To confirm that the Linked Server is working fine and yes I do get results from this.

EXEC ('use myRemoteDB;' + @sql ) AT Linked_Azure_Server

The reason why I'm doing this is : "The local table has around 1 million records and it was taking me more than 3 hours to push the data onto Linked Server. Then I found this answer Linked Server Insert-Select Performance in which it was suggested to create XML insert statements and execute on remote server.

But When I'm doing this I'm getting below error

OLE DB provider "SQLNCLI11" for linked server "Linked_Azure_Server" returned message "Communication link failure".
TCP Provider: The specified network name is no longer available.

I'm sure the link to Linked_Server is fine. To cross check I wrote this statement EXEC ('select * from remote_table_2') AT Linked_Azure_Server just before inserting records and I do get results from this.

I've checked other answers to similar questions related to Communication Link Failure but no one is really helpful.


问:
IndexingError: Unalignable boolean Series key provided after dropna and filtering
I want to remove rows that are blank for a certain column and then filter on that column:

If I do it like this:

```<code>df['location'].dropna(inplace=True)
dfloc = df[df['location'] == myvar]
</code>```

Then I get this error:

```<code>IndexingError: Unalignable boolean Series key provided
</code>```

So I have to use dropna like this instead to avoid the error:

```<code>df.dropna(subset = ['location'],inplace=True)
dfloc = df[df['location'] == myvar]
</code>```

Does anyone know why the first method yields an error while the second does not?

Here is an sample of my DataFrame:

```<code>      uid                date          location
1  1114-104119      2017-11-14 10:41:19     Chicago
2  1114-104056      2017-11-14 10:40:56     NaN
3  1114-104055      2017-11-14 10:40:55     LA
4  1114-103223      2017-11-14 10:32:23     NaN
5  1114-103050      2017-11-14 10:30:50     NYC
</code>```

答:
The first method, what is happening is that you are creating a copy or a slice of the original dataframe and dropping rows from that series, you are not really affecting the original dataframe.  Now, when you try to use that mangled series to slice your original dataframe the indexes of the series doesn't match that of the original dataframe. Hence, the error

IndexingError: Unalignable boolean Series key provided

Here is proof.

```<code>df = pd.DataFrame({'Location':[1,np.nan,3,np.nan],'A':np.random.randint(0,10,4)})
df
   A  Location
0  7       1.0
1  6       NaN
2  1       3.0
3  8       NaN

df['Location'].dropna(inplace=True)
print(df['Location'])
0    1.0
2    3.0
Name: Location, dtype: float64
</code>```

However, if you print df again you get the full dataframe, you have not modified this dataframe.

```<code>print(df)

   A  Location
0  7       1.0
1  6       NaN
2  1       3.0
3  8       NaN
</code>```

In the second method you are preforming a drop on the oringal dataframe based on a subset selection.  Therefore, that method works and you can use that series to do boolean indexing of your dataframe.

Body:
I want to remove rows that are blank for a certain column and then filter on that column:

If I do it like this:

df['location'].dropna(inplace=True)
dfloc = df[df['location'] == myvar]

Then I get this error:

IndexingError: Unalignable boolean Series key provided

So I have to use dropna like this instead to avoid the error:

df.dropna(subset = ['location'],inplace=True)
dfloc = df[df['location'] == myvar]

Does anyone know why the first method yields an error while the second does not?

Here is an sample of my DataFrame:

      uid                date          location
1  1114-104119      2017-11-14 10:41:19     Chicago
2  1114-104056      2017-11-14 10:40:56     NaN
3  1114-104055      2017-11-14 10:40:55     LA
4  1114-103223      2017-11-14 10:32:23     NaN
5  1114-103050      2017-11-14 10:30:50     NYC

Body:
The first method, what is happening is that you are creating a copy or a slice of the original dataframe and dropping rows from that series, you are not really affecting the original dataframe.  Now, when you try to use that mangled series to slice your original dataframe the indexes of the series doesn't match that of the original dataframe. Hence, the error

IndexingError: Unalignable boolean Series key provided

Here is proof.

df = pd.DataFrame({'Location':[1,np.nan,3,np.nan],'A':np.random.randint(0,10,4)})
df
   A  Location
0  7       1.0
1  6       NaN
2  1       3.0
3  8       NaN

df['Location'].dropna(inplace=True)
print(df['Location'])
0    1.0
2    3.0
Name: Location, dtype: float64

However, if you print df again you get the full dataframe, you have not modified this dataframe.

print(df)

   A  Location
0  7       1.0
1  6       NaN
2  1       3.0
3  8       NaN

In the second method you are preforming a drop on the oringal dataframe based on a subset selection.  Therefore, that method works and you can use that series to do boolean indexing of your dataframe.


问:
Oracle distinct listagg with count
I need to display a comma-separated description per table row but I need the list to be distinct and have counts for some of the descriptions available.

```<code>every_description     needs_count
---------------------------------
Bred                          yes
From Vendor                   yes
Grouped                        no
Removed                       yes
Separated                      no
Weaned                        yes
</code>```

So in a day, the description could be something like Bred, Grouped, Weaned and I have this working now using LISTAGG and removing the duplicates using the solution mentioned here but I need to add counts for some of the descriptions like 5 Bred, Grouped, 2 Weaned.

Here's my current query where I'm stuck:

```<code>WITH cages AS (
        SELECT 1234 AS id FROM DUAL
  UNION SELECT 5678 AS id FROM DUAL
  UNION SELECT 9012 AS id FROM DUAL
  UNION SELECT 3456 AS id FROM DUAL
), cage_comments AS (
        SELECT 1234 AS cage_id, 'Bred' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 5678 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 9012 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Bred' AS description, TO_DATE('11/02/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
), calendar AS (
  SELECT dt
  FROM (
    SELECT TRUNC(LAST_DAY(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY')) - ROWNUM + 1) dt
    FROM DUAL CONNECT BY ROWNUM <= 31
  )
  WHERE dt >= TRUNC(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY'), 'MM')
  ORDER BY dt ASC
)

SELECT
  cal.dt,
  (
    SELECT
      CASE
        WHEN COUNT(cc.cage_id) > 0 THEN RTRIM(
          REGEXP_REPLACE(
            (LISTAGG(cc.description, ',') WITHIN GROUP (ORDER BY cc.description)),
            '([^,]*)(,\1)+($|,)',
            '\1\3'
          ),
          ','
        )
        ELSE NULL
      END
    FROM cages c
    LEFT JOIN cage_comments cc ON cc.cage_id = c.id
    WHERE cc.event_date = cal.dt
  ) AS description
FROM calendar cal
ORDER BY cal.dt
</code>```

In short - I'm just having difficulties adding the COUNT for some of the descriptions for that day. In the case above I would like to say 1 Bred for November 2, 2017 and 1 Bred, Grouped, 2 Weaned for November 14, 2017.

答:
Currently you are aggregating all the descriptions (without DISTINCT) and then you remove the duplicate descriptions with a regular expression replace. This is very inefficient - it would be better to select distinct and then apply LISTAGG.

This becomes even more important if you need to add the count. Take the result of your join and GROUP BY description. (In particular, this will take care of DISTINCT). In the SELECT for this aggregate step, include the count. Then join the result to the additional table at the top of your question, and re-write the argument to LISTAGG to include a CASE expression, equal to the count (and a space) when the needs_count value is 'yes'.

Title: Oracle distinct listagg with count

Body:
I need to display a comma-separated description per table row but I need the list to be distinct and have counts for some of the descriptions available.

every_description     needs_count
---------------------------------
Bred                          yes
From Vendor                   yes
Grouped                        no
Removed                       yes
Separated                      no
Weaned                        yes

So in a day, the description could be something like Bred, Grouped, Weaned and I have this working now using LISTAGG and removing the duplicates using the solution mentioned here but I need to add counts for some of the descriptions like 5 Bred, Grouped, 2 Weaned.

Here's my current query where I'm stuck:

WITH cages AS (
        SELECT 1234 AS id FROM DUAL
  UNION SELECT 5678 AS id FROM DUAL
  UNION SELECT 9012 AS id FROM DUAL
  UNION SELECT 3456 AS id FROM DUAL
), cage_comments AS (
        SELECT 1234 AS cage_id, 'Bred' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 5678 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 9012 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Bred' AS description, TO_DATE('11/02/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
), calendar AS (
  SELECT dt
  FROM (
    SELECT TRUNC(LAST_DAY(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY')) - ROWNUM + 1) dt
    FROM DUAL CONNECT BY ROWNUM <= 31
  )
  WHERE dt >= TRUNC(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY'), 'MM')
  ORDER BY dt ASC
)

SELECT
  cal.dt,
  (
    SELECT
      CASE
        WHEN COUNT(cc.cage_id) > 0 THEN RTRIM(
          REGEXP_REPLACE(
            (LISTAGG(cc.description, ',') WITHIN GROUP (ORDER BY cc.description)),
            '([^,]*)(,\1)+($|,)',
            '\1\3'
          ),
          ','
        )
        ELSE NULL
      END
    FROM cages c
    LEFT JOIN cage_comments cc ON cc.cage_id = c.id
    WHERE cc.event_date = cal.dt
  ) AS description
FROM calendar cal
ORDER BY cal.dt

In short - I'm just having difficulties adding the COUNT for some of the descriptions for that day. In the case above I would like to say 1 Bred for November 2, 2017 and 1 Bred, Grouped, 2 Weaned for November 14, 2017.


问:
Can't create ListViewLinearLayout
I have the following in my XAML...

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
             xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.XamarinForms.DataControls"
             xmlns:listView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls"
             xmlns:this="clr-namespace:Namespace123"
             x:Class="MyClass"
             BackgroundColor="#F7F7F7">
</code>```

And...

```<code> <telerikDataControls:RadListView.LayoutDefinition>
          <listView:ListViewLinearLayout>
            <listView:ListViewLinearLayout.ItemLength>
              <OnPlatform x:TypeArguments="x:Double"
                          iOS="48"
                          Android="48"
                          WinPhone="48" />
            </listView:ListViewLinearLayout.ItemLength>
            <listView:ListViewLinearLayout.VerticalItemSpacing>
              <OnPlatform x:TypeArguments="x:Double"
                          iOS="10"
                          Android="10"
                          WinPhone="2" />
            </listView:ListViewLinearLayout.VerticalItemSpacing>
          </listView:ListViewLinearLayout>
        </telerikDataControls:RadListView.LayoutDefinition>
...
</code>```

And I get the following exception...

Exception is: XamlParseException - Position 50:12. Type
  listView:ListViewLinearLayout not found in xmlns
  clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls

I've cleaned the solution and deleted obj/bin folders. Why can't it find the type?

This runs fine in the code behind..

```<code>var list = new RadListView();

list.LayoutDefinition = new ListViewLinearLayout();
</code>```

答: Today when I ran the app for the first time, it worked.</p>

Title: Can't create ListViewLinearLayout

Body:
I have the following in my XAML...

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
             xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.XamarinForms.DataControls"
             xmlns:listView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls"
             xmlns:this="clr-namespace:Namespace123"
             x:Class="MyClass"
             BackgroundColor="#F7F7F7">

And...

 <telerikDataControls:RadListView.LayoutDefinition>
          <listView:ListViewLinearLayout>
            <listView:ListViewLinearLayout.ItemLength>
              <OnPlatform x:TypeArguments="x:Double"
                          iOS="48"
                          Android="48"
                          WinPhone="48" />
            </listView:ListViewLinearLayout.ItemLength>
            <listView:ListViewLinearLayout.VerticalItemSpacing>
              <OnPlatform x:TypeArguments="x:Double"
                          iOS="10"
                          Android="10"
                          WinPhone="2" />
            </listView:ListViewLinearLayout.VerticalItemSpacing>
          </listView:ListViewLinearLayout>
        </telerikDataControls:RadListView.LayoutDefinition>
...

And I get the following exception...

Exception is: XamlParseException - Position 50:12. Type
  listView:ListViewLinearLayout not found in xmlns
  clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls

I've cleaned the solution and deleted obj/bin folders. Why can't it find the type?

This runs fine in the code behind..

var list = new RadListView();

list.LayoutDefinition = new ListViewLinearLayout();


问:
Permissions for sending SMS
I was wondering what did I do wrong? I know with sdk version 24+ I need to get some extra runtime permissions, but I tried a lot of them and nothing worked so far.. So here is the code, I added the last part with permission request but its still not working, app opens but when I click on button app crashes.. Anyone knows what is wrong?

CODE FROM MAIN_ACTIVITY:

```<code>public class MainActivity extends Activity {

ImageView imageView;
Button button;
boolean running;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.imageView);

    button = (Button) findViewById(R.id.button);

    running = false;

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            if(!running){
            ((AnimationDrawable) imageView.getDrawable()).start();
            running = true;}

            SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);

            int GET_MY_PERMISSION = 1;
            if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_SMS)
                    != PackageManager.PERMISSION_GRANTED){
                if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.SEND_SMS)){

                }
                else{

                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.SEND_SMS},GET_MY_PERMISSION);
                }
            }

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

}

I ALSO HAVE THIS IN MY MANIFEST :

```<code><uses-permission android:name="android.permission.SEND_SMS"/>
</code>```

What am I missing?

答:
Have you added your [onRequestPermissionResult()](https://developer.android.com/reference/android/support/v4/app/ActivityCompat.OnRequestPermissionsResultCallback.html#onRequestPermissionsResult(int, java.lang.String[], int[]))?

it looks like its calling back to nothing.

Are you sure you are calling requestPermissions? if shouldShouldRequestPermissionRationale is false, then nothing happens.

Title: Permissions for sending SMS

Body:
I was wondering what did I do wrong? I know with sdk version 24+ I need to get some extra runtime permissions, but I tried a lot of them and nothing worked so far.. So here is the code, I added the last part with permission request but its still not working, app opens but when I click on button app crashes.. Anyone knows what is wrong?

CODE FROM MAIN_ACTIVITY:

public class MainActivity extends Activity {

ImageView imageView;
Button button;
boolean running;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    imageView = (ImageView) findViewById(R.id.imageView);

    button = (Button) findViewById(R.id.button);

    running = false;

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            if(!running){
            ((AnimationDrawable) imageView.getDrawable()).start();
            running = true;}

            SmsManager.getDefault().sendTextMessage("+3564245237",null,"1", null, null);

            int GET_MY_PERMISSION = 1;
            if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_SMS)
                    != PackageManager.PERMISSION_GRANTED){
                if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.SEND_SMS)){

                }
                else{

                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.SEND_SMS},GET_MY_PERMISSION);
                }
            }

        }
    }
    );
}

}

I ALSO HAVE THIS IN MY MANIFEST :

<uses-permission android:name="android.permission.SEND_SMS"/>

What am I missing?


问:
Hiding div with Javascript based on value of php variable
I currently have a select box in my laravel blade:

```<code><div style="text-align:center;">
   <div>
    <span style="color:#fff;"><strong>Sort by:</strong></span>
    <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" onchange="filterText()" >
      <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
      <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="" >Popularity</option>
      <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="">Recently Ordered </option>
     </select>
   </div>
</code>```

And I want to use JS to show/hide my .groupcontainer div based on the value of a PHP variable. I have a function that creates PHP variables $topsellers and $reorder. So I want to map my option popularity to $topsellers and the option Recently Ordered to $reorder

I have some JS that I was playing with but I don't know how to do this properly, however, it gives an idea:

```<code><script type="text/javascript">
$('#filterText').on('change', function () {
if (this.value == '') {
  $(".groupcontainer").show();
} else {
  $(".groupcontainer").hide();
}
});
</script>
</code>```

But basically, I want to say :

if value popularity is selected and $topsellers == true, show the groupcontainer div, and if value recently ordered is selected and $reorder is true, only show those groupcontainer divs.

I hope that makes sense. I feel like the pieces are there but I need help connecting them with logic and syntax.

UPDATE (new attempted solution):

JS:

```<code><script type="text/javascript">

$('#filterText').on('change', function () {

var topsellers = "<?php echo $pgroups->topseller; ?>";
var reorder    = "<?php echo $pgroups->reorder; ?>";

 var currentVal = $(this).val();

 if (currentVal == 'popularity' && topsellers == "true" || currentVal == 'recently_ordered' && reorder == "true") {
   $(".groupcontainer").show();
 } else {
   $(".groupcontainer").hide();
 }
});
</script>
</code>```

HTML/Select box:

```<code>    <div style="text-align:center;">
                                <div>
                                    <span style="color:#fff;"><strong>Sort by:</strong></span>
                                    <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" onchange="filterText()" >
                                        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="popularity" >Popularity</option>
                                      <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
                                    </select>
                                </div>
                            </div>
</code>```

答:
You could add hidden inputs for those values like :

```<code><input class="topsellers" value="{{$topsellers}}" />
<input class="reorder" value="{{$reorder}}" />
</code>```

Or you could put the variables to the Js variables like :

```<code>var topsellers = "<?php echo $topsellers; ?>";
var reorder    = "<?php echo $reorder; ?>";
</code>```

Then use those value in the condition in your JS code, something like :

```<code>$(function(){
    var topsellers = "<?php echo $topsellers; ?>";
    var reorder    = "<?php echo $reorder; ?>";

    $('#filterText').on('change', function() {
      var currentVal = $(this).val();

      if (currentVal == 'popularity' && topsellers == "1" || currentVal == 'recently_ordered' && reorder == "1") {
        $(".groupcontainer").show();
      } else {
        $(".groupcontainer").hide();
      }
    });
});
</code>```

Hope this helps.

Body:
I currently have a select box in my laravel blade:

    Sort by:
    <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" onchange="filterText()" >
      <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
      <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="" >Popularity</option>
      <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="">Recently Ordered </option>
     </select>

And I want to use JS to show/hide my .groupcontainer div based on the value of a PHP variable. I have a function that creates PHP variables $topsellers and $reorder. So I want to map my option popularity to $topsellers and the option Recently Ordered to $reorder

I have some JS that I was playing with but I don't know how to do this properly, however, it gives an idea:

But basically, I want to say :

if value popularity is selected and $topsellers == true, show the groupcontainer div, and if value recently ordered is selected and $reorder is true, only show those groupcontainer divs.

I hope that makes sense. I feel like the pieces are there but I need help connecting them with logic and syntax.

UPDATE (new attempted solution):

JS:

HTML/Select box:

                                    Sort by:
                                    <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" onchange="filterText()" >
                                        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="popularity" >Popularity</option>
                                      <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
                                    </select>

Body:
You could add hidden inputs for those values like :

<input class="topsellers" value="{{$topsellers}}" />
<input class="reorder" value="{{$reorder}}" />

Or you could put the variables to the Js variables like :

var topsellers = "<?php echo $topsellers; ?>";
var reorder    = "<?php echo $reorder; ?>";

Then use those value in the condition in your JS code, something like :

$(function(){
    var topsellers = "<?php echo $topsellers; ?>";
    var reorder    = "<?php echo $reorder; ?>";

    $('#filterText').on('change', function() {
      var currentVal = $(this).val();

      if (currentVal == 'popularity' && topsellers == "1" || currentVal == 'recently_ordered' && reorder == "1") {
        $(".groupcontainer").show();
      } else {
        $(".groupcontainer").hide();
      }
    });
});

Hope this helps.


问:
How to alter an array in JS file through a method call from HTML in Angular?
I'm using Angular.js and trying to clear an array which is first instantiated and held on my module:

```<code> angular.module(myApp)
  .controller('myCtrl', function ($rootScope){
    var vm = this;

    vm.myArr = ["Clear", "Me"]

    vm.clearer = function(arr) {
       arr = [];
    };

    vm.copier = function(arrToOverwrite, arrToCopy) {
        arrToOverWrite = angular.copy(arrToCopy);
   };
</code>```

And I call this method from my HTML file:

```<code>    (controller myCtrl is aliased as ctrl)
    <input type="button" ng-click="ctrl.clearer(ctrl.myArr)" value="clear">
</code>```

However, in the JS, it is underlining the arr, saying the value is never used. And, say I have something that always displays the value of myArr in the HTML, it is unaffected by the changes. I thought since JS is pass by reference, if myArr is passed as the reference in the clearer method, if it gets updated there, that it would then be updated with that value everywhere?

How would I go about this? I need to use the clearer method in other places on other arrays that may be held "in memory" here in the JS file at other times.

答:
When you call the function you assign the arr param with a reference to ctrl.myArr. With the expression arr = [] you assign arr to reference an empty array, but ctrl.myArr still points to the original array.

In this case you need to mutate the array directly, by changing the length to 0, for example:

var array = [1, 2, 3];

var clearer = function(arr) {
  arr.length = 0;
};

clearer(array);

console.log(array);```
</div>
</div>
</p>

<p>If you need to remove certain items, or add new items, you can use Array#splice or <code>angular.copy()</code> to overwrite the array with another:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [1, 2, 3, 4, 5, 6, 7];
var replacement = [9, 10, 11];

function copier(arrToOverwrite, arrToCopy) {
  arrToOverwrite.splice(0, arrToOverwrite.length, ...arrToCopy); // or angular.copy(arrToCopy, arrToOverwrite)
};

copier(array, replacement);

console.log(array);</code>```

Body:
I'm using Angular.js and trying to clear an array which is first instantiated and held on my module:

 angular.module(myApp)
  .controller('myCtrl', function ($rootScope){
    var vm = this;

    vm.myArr = ["Clear", "Me"]

    vm.clearer = function(arr) {
       arr = [];
    };

    vm.copier = function(arrToOverwrite, arrToCopy) {
        arrToOverWrite = angular.copy(arrToCopy);
   };

And I call this method from my HTML file:

    (controller myCtrl is aliased as ctrl)
    <input type="button" ng-click="ctrl.clearer(ctrl.myArr)" value="clear">

However, in the JS, it is underlining the arr, saying the value is never used. And, say I have something that always displays the value of myArr in the HTML, it is unaffected by the changes. I thought since JS is pass by reference, if myArr is passed as the reference in the clearer method, if it gets updated there, that it would then be updated with that value everywhere?

How would I go about this? I need to use the clearer method in other places on other arrays that may be held "in memory" here in the JS file at other times.

Body:
When you call the function you assign the arr param with a reference to ctrl.myArr. With the expression arr = [] you assign arr to reference an empty array, but ctrl.myArr still points to the original array.

In this case you need to mutate the array directly, by changing the length to 0, for example:

var array = [1, 2, 3];

var clearer = function(arr) {
  arr.length = 0;
};

clearer(array);

console.log(array);

If you need to remove certain items, or add new items, you can use Array#splice or angular.copy() to overwrite the array with another:

var array = [1, 2, 3, 4, 5, 6, 7];
var replacement = [9, 10, 11];

function copier(arrToOverwrite, arrToCopy) {
  arrToOverwrite.splice(0, arrToOverwrite.length, ...arrToCopy); // or angular.copy(arrToCopy, arrToOverwrite)
};

copier(array, replacement);

console.log(array);


答:
Since PHP is a backend language you have to expose the variable in javascript context which is at the browser level.  To do so what you would end up doing is something like this:

```<code><script type="text/javascript">
var somePHPVariable = "<?php echo $SOMEVAR; ?>";
...
</script>
</code>```

That now gives you the PHP variable at the javascript level so you can do operations on it just like you would with any other javascript variable.  Just keep in mind that PHP renders / computes before javascript does, so your php variables will always be set first.  The alternative to this would be to "ask php" via rest / ajax request what the value is and then continue calculation based on the result.

Title: Hiding div with Javascript based on value of php variable

Body:
Since PHP is a backend language you have to expose the variable in javascript context which is at the browser level.  To do so what you would end up doing is something like this:

<script type="text/javascript">
var somePHPVariable = "<?php echo $SOMEVAR; ?>";
...
</script>

That now gives you the PHP variable at the javascript level so you can do operations on it just like you would with any other javascript variable.  Just keep in mind that PHP renders / computes before javascript does, so your php variables will always be set first.  The alternative to this would be to "ask php" via rest / ajax request what the value is and then continue calculation based on the result.