问:
minishell created in c not working as expected, pipes related
im making an UNIX minishell in c, in my OS signature. I only have to improve the shell itself, we have a premade parser for implement yacc and a scanner for implement lex among other files.
The file to modify is msh.c, the main executable file.

Well, the problem begins when I try to implement the pipe secuences. This is what I made:

```<code>int executePipeLine (char*** argvv, int bg, char** filev, int n){
    int i;
    int in = 0;
    pid_t pid;
    int fd[2];

for (i = 0 ; i < n-1 ; i++){

    pipe(fd);
    pid_t pid = fork();

    if (pid == 0){ //child

        if (in != STDIN_FILENO){
            dup2(in, STDIN_FILENO);
            close(in);

        }

        if (fd[1] != STDOUT_FILENO){
            dup2(fd[1], STDOUT_FILENO);
            close(fd[1]);
        }

        execvp(argvv[i][0], argvv[0]);
    }

    else { //parent

        close(fd[1]);
        in = fd[0];
    }

}

if(in != STDIN_FILENO){
    dup2(in, STDIN_FILENO);
    close(in);
}

pid_t lastpid = fork();
if(lastpid == 0){ //child

execvp(argvv[i][0], argvv[0]);

}

if(lastpid == -1){

    perror("no se pudo crear el hijo\n");
    exit(-1);

}
else { //parent

    /* not bg*/
    if(!bg ) {
    int status;
    while (wait(&status) != lastpid); /* wait the child. */
    }

    else {
    /*bg mode*/
        printf("pid del proceso last: %d\n", lastpid);

    }

    return 0;
}

}//end  executePipeLine
</code>```

This seems to work fine. In the main , where we have an extern function called obtain_order(); that returns the number of commands + 1 and save it to ret. If ret is 1 we continue with the prompt, if is 0 means EOF (Control + D keybinding) to end the shell, and if is >1 execute the commands.

Here you have it:

```<code>int main(void)
{
    char ***argvv;
    int command_counter;
    int num_commands;
    int args_counter;
    char *filev[3];
    int bg;
    int ret;
    int reset = 0;
    setbuf(stdout, NULL);           /* Unbuffered */
    setbuf(stdin, NULL);

while (1)
{
    fprintf(stderr, "%s", "msh> "); /* Prompt */

    ret = obtain_order(&argvv, filev, &bg);

    printf("ret: %d\n", ret);
    if (ret == 0) break;        /* EOF */
    if (ret == -1) continue;    /* Syntax error */
    num_commands = ret - 1;     /* Line */
    if (num_commands == 0) continue;    /* Empty line */

    if(num_commands > 1){

        executePipeLine(argvv, bg, filev, num_commands);

    }
    else if (num_commands == 1){
        executeCommand(argvv, bg, filev);

    }

} //fin while

return 0;

} //end main
</code>```

All works fine with a simple command. The problem is when I try to execute a pipe line. It show a good result, but i dont know we, after that ret always is 0 in the next iteration, so every time I try to execute a pipe line, it works but close the shell process, and have to execute it again instead of continue with the promt.

You know what is the problem here?

I hope you understand me, my english is not perfec. Thanks

答:
In the parent process (i.e. your mini-shell) you are duping the standard input:

```<code>...
else { //parent
    close(fd[1]);
    in = fd[0];
}

...

if(in != STDIN_FILENO){
    dup2(in, STDIN_FILENO);
    close(in);
}
</code>```

When your pipeline terminates, children are dead, pipes are no longer readable => stdin is considered as closed. When you later call obtain_order in your main loop, it returns 0 (EOF) and your program exits.

Body:
im making an UNIX minishell in c, in my OS signature. I only have to improve the shell itself, we have a premade parser for implement yacc and a scanner for implement lex among other files.
The file to modify is msh.c, the main executable file.

Well, the problem begins when I try to implement the pipe secuences. This is what I made:

int executePipeLine (char*** argvv, int bg, char** filev, int n){
    int i;
    int in = 0;
    pid_t pid;
    int fd[2];

for (i = 0 ; i < n-1 ; i++){

    pipe(fd);
    pid_t pid = fork();

    if (pid == 0){ //child

        if (in != STDIN_FILENO){
            dup2(in, STDIN_FILENO);
            close(in);

        }

        if (fd[1] != STDOUT_FILENO){
            dup2(fd[1], STDOUT_FILENO);
            close(fd[1]);
        }

        execvp(argvv[i][0], argvv[0]);
    }

    else { //parent

        close(fd[1]);
        in = fd[0];
    }

}

if(in != STDIN_FILENO){
    dup2(in, STDIN_FILENO);
    close(in);
}

pid_t lastpid = fork();
if(lastpid == 0){ //child

execvp(argvv[i][0], argvv[0]);

}

if(lastpid == -1){

    perror("no se pudo crear el hijo\n");
    exit(-1);

}
else { //parent

    /* not bg*/
    if(!bg ) {
    int status;
    while (wait(&status) != lastpid); /* wait the child. */
    }

    else {
    /*bg mode*/
        printf("pid del proceso last: %d\n", lastpid);

    }

    return 0;
}

}//end  executePipeLine

This seems to work fine. In the main , where we have an extern function called obtain_order(); that returns the number of commands + 1 and save it to ret. If ret is 1 we continue with the prompt, if is 0 means EOF (Control + D keybinding) to end the shell, and if is >1 execute the commands.

Here you have it:

int main(void)
{
    char ***argvv;
    int command_counter;
    int num_commands;
    int args_counter;
    char *filev[3];
    int bg;
    int ret;
    int reset = 0;
    setbuf(stdout, NULL);           /* Unbuffered */
    setbuf(stdin, NULL);

while (1)
{
    fprintf(stderr, "%s", "msh> "); /* Prompt */

    ret = obtain_order(&argvv, filev, &bg);

    printf("ret: %d\n", ret);
    if (ret == 0) break;        /* EOF */
    if (ret == -1) continue;    /* Syntax error */
    num_commands = ret - 1;     /* Line */
    if (num_commands == 0) continue;    /* Empty line */

    if(num_commands > 1){

        executePipeLine(argvv, bg, filev, num_commands);

    }
    else if (num_commands == 1){
        executeCommand(argvv, bg, filev);

    }

} //fin while

return 0;

} //end main

All works fine with a simple command. The problem is when I try to execute a pipe line. It show a good result, but i dont know we, after that ret always is 0 in the next iteration, so every time I try to execute a pipe line, it works but close the shell process, and have to execute it again instead of continue with the promt.

You know what is the problem here?

I hope you understand me, my english is not perfec. Thanks

Body:
In the parent process (i.e. your mini-shell) you are duping the standard input:

...
else { //parent
    close(fd[1]);
    in = fd[0];
}

...

if(in != STDIN_FILENO){
    dup2(in, STDIN_FILENO);
    close(in);
}

When your pipeline terminates, children are dead, pipes are no longer readable => stdin is considered as closed. When you later call obtain_order in your main loop, it returns 0 (EOF) and your program exits.


来源: stackexchange

问:
PHP refactor if else
I have this if else structure and I want to refactor the else out since I want to clean up the code a bit. Only I am not sure how I can refactor the else out.

```<code>if ($validator->fails()) {
   return Redirect::back()
       ->with('error_code', 5)
       ->withErrors($validator->errors())
       ->withInput();
} else {
    // do something if validator does not fail
    return Redirect::back();
}
</code>```

Anyone has any idea how I can refactor the else out?

Many thanks in advance!

答:
If you want to minimize it as much as possible you can also remove the brackets of the if-statement. In PHP and in many other languages, if there is single line execution in a statement, you can remove the brackets.

So the minified version would be:

```<code>if ($validator->fails())
    return Redirect::back()
       ->with('error_code', 5)
       ->withErrors($validator->errors())
       ->withInput();

return Redirect::back();
</code>```

You could also rewrite it using Ternary Operator in the following manner:

```<code>return $validator->fails() ? Redirect::back()->with('error_code', 5)->withErrors($validator->errors())->withInput() : Redirect::back();
</code>```

Lastly I would like to point out that the best way to write code is not necessarily to write it as minified as possible. My example with the Ternary Operator above is a good example, does it really make it more readable to minify it like that? No.

Refactoring this type of statements should be done to make it easier to see and read what the statement actually do. Its not necessarily a bad thing to have an else {} the way you have in your original example.

ContentLicense: CC BY-SA 3.0

Title: PHP refactor if else

Body:
I have this if else structure and I want to refactor the else out since I want to clean up the code a bit. Only I am not sure how I can refactor the else out.

if ($validator->fails()) {
   return Redirect::back()
       ->with('error_code', 5)
       ->withErrors($validator->errors())
       ->withInput();
} else {
    // do something if validator does not fail
    return Redirect::back();
}

Anyone has any idea how I can refactor the else out?

Many thanks in advance!

Body:
If you want to minimize it as much as possible you can also remove the brackets of the if-statement. In PHP and in many other languages, if there is single line execution in a statement, you can remove the brackets.

So the minified version would be:

if ($validator->fails())
    return Redirect::back()
       ->with('error_code', 5)
       ->withErrors($validator->errors())
       ->withInput();

return Redirect::back();

You could also rewrite it using Ternary Operator in the following manner:

return $validator->fails() ? Redirect::back()->with('error_code', 5)->withErrors($validator->errors())->withInput() : Redirect::back();

Lastly I would like to point out that the best way to write code is not necessarily to write it as minified as possible. My example with the Ternary Operator above is a good example, does it really make it more readable to minify it like that? No.

Refactoring this type of statements should be done to make it easier to see and read what the statement actually do. Its not necessarily a bad thing to have an else {} the way you have in your original example.


问:
How to Save View Controller Data Every Time New Tab Bar Item is Selected?
I have set up a Tab Bar that controls some view controllers in my app. In my view controller CheckViewController, I have user entry-based data that I would like to save every time I am switching from CheckViewController to another view controller. The code I have currently only saves data the first time I switch from CheckViewController to another view controller using the tab bar. I would like to save data every single time CheckViewController is opened and switched to another view controller.

I am currently using:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.tabBarController.delegate = self;

    //code

}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    if (![viewController isEqual:self]) {

        if ([self.tabBarController.selectedViewController isEqual:self] ) {

            //save data

        }

    }

    return YES;

}
</code>```

Suggestions are appreciated. Thanks!

答:
for saving small data,you can use NSUserDefault.
here is an example for saving and reading data.

Save:

```<code>[[NSUserDefaults standardUserDefaults] setObject:aData forKey:aKey];
[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

Read:

```<code>[[NSUserDefaults standardUserDefaults] objectForKey:aKey];
</code>```

Body:
I have set up a Tab Bar that controls some view controllers in my app. In my view controller CheckViewController, I have user entry-based data that I would like to save every time I am switching from CheckViewController to another view controller. The code I have currently only saves data the first time I switch from CheckViewController to another view controller using the tab bar. I would like to save data every single time CheckViewController is opened and switched to another view controller.

I am currently using:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tabBarController.delegate = self;

    //code

}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    if (![viewController isEqual:self]) {

        if ([self.tabBarController.selectedViewController isEqual:self] ) {

            //save data

        }

    }

    return YES;

}

Suggestions are appreciated. Thanks!

Body:
for saving small data,you can use NSUserDefault.
here is an example for saving and reading data.

Save:

[[NSUserDefaults standardUserDefaults] setObject:aData forKey:aKey];
[[NSUserDefaults standardUserDefaults] synchronize];

Read:

[[NSUserDefaults standardUserDefaults] objectForKey:aKey];


问:
Creating an array with large initial size in powershell
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

```<code>$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}
</code>```

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

答:
Use New-Object in this case:

PS> $arr = New-Object int[] 10000; $arr.length
10000
```
<p>Or, in PSv5+, using the static <code>new()</code> method on the type:</p>
<pre class="lang-sh prettyprint-override"><code>PS> $arr = [int[]]::new(10000); $arr.length
10000
</code>```

These commands create a strongly typed array, using base type [int] in this example.
If the use case allows it, this is preferable for reasons of performance and type safety.

If you need to create an "untyped" array the same way that PowerShell does ([System.Object[]]), substitute object for int; e.g., [object[]]::new(10000); the elements of such an array will default to $null.

TessellatingHeckler's helpful answer, however, shows a much more concise alternative that even allows you initialize all elements to a specific value.

Arrays have a fixed size; if you need an array-like data structure that you can preallocate and grow dynamically, see Bluecakes' helpful [System.Collections.ArrayList]-based answer.

[System.Collections.ArrayList] is the resizable analog to [System.Object[]], and its generic equivalent - which like the [int[]] example above - allows you to use a specific type for performance and robustness (if feasible), is [System.Collections.Generic.List[<type>]], e.g.:

PS> $lst = [System.Collections.Generic.List[int]]::New(10000); $lst.Capacity
10000
```
<p>Note that - as with <code>[System.Collections.ArrayList]</code> - specifying an <em>initial capacity</em> (<code>10000</code>, here) does not allocate the internally used array with that size <em>right away</em> - the capacity value is simply stored (and exposed as property <code>.Capacity</code>), and an internal array with that capacity (internal size that leaves room for growth) is allocated <em>on demand</em>, when the first element is added to the list.</p>
<p><code>[System.Collections.Generic.List[<type>]]</code>'s <code>.Add()</code> method commendably does <em>not</em> produce output, whereas <code>[System.Collections.ArrayList]</code>'s does (it returns the index of the element that was just added).</p>
<pre class="lang-sh prettyprint-override"><code># The non-generic ArrayList's .Add() produces (usually undesired) output.
PS> $al = [System.Collections.ArrayList]::new(); $al.Add('first elem')
0  # .Add() outputs the index of the newly added item

# Simplest way to suppress this output:
PS> $null = $al.Add('first elem')
# NO output.

# The generic List[T]'s .Add() does NOT produce output.
PS> $gl = [System.Collections.Generic.List[string]]::new(); $gl.Add('first elem')
# NO output from .Add()
</code>```

Body:
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

Body:
Use New-Object in this case:

PS> $arr = New-Object int[] 10000; $arr.length
10000

Or, in PSv5+, using the static new() method on the type:

PS> $arr = [int[]]::new(10000); $arr.length
10000

These commands create a strongly typed array, using base type [int] in this example.
If the use case allows it, this is preferable for reasons of performance and type safety.

If you need to create an "untyped" array the same way that PowerShell does ([System.Object[]]), substitute object for int; e.g., [object[]]::new(10000); the elements of such an array will default to $null.

TessellatingHeckler's helpful answer, however, shows a much more concise alternative that even allows you initialize all elements to a specific value.

Arrays have a fixed size; if you need an array-like data structure that you can preallocate and grow dynamically, see Bluecakes' helpful [System.Collections.ArrayList]-based answer.

[System.Collections.ArrayList] is the resizable analog to [System.Object[]], and its generic equivalent - which like the [int[]] example above - allows you to use a specific type for performance and robustness (if feasible), is [System.Collections.Generic.List[<type>]], e.g.:

PS> $lst = [System.Collections.Generic.List[int]]::New(10000); $lst.Capacity
10000

Note that - as with [System.Collections.ArrayList] - specifying an initial capacity (10000, here) does not allocate the internally used array with that size right away - the capacity value is simply stored (and exposed as property .Capacity), and an internal array with that capacity (internal size that leaves room for growth) is allocated on demand, when the first element is added to the list.

[System.Collections.Generic.List[<type>]]'s .Add() method commendably does not produce output, whereas [System.Collections.ArrayList]'s does (it returns the index of the element that was just added).

# The non-generic ArrayList's .Add() produces (usually undesired) output.
PS> $al = [System.Collections.ArrayList]::new(); $al.Add('first elem')
0  # .Add() outputs the index of the newly added item

# Simplest way to suppress this output:
PS> $null = $al.Add('first elem')
# NO output.

# The generic List[T]'s .Add() does NOT produce output.
PS> $gl = [System.Collections.Generic.List[string]]::new(); $gl.Add('first elem')
# NO output from .Add()

ContentLicense: CC BY-SA 4.0


问:
C# string with decimal into formatted int
I'm looking to try to change a string like 10.00% into an int like 1000.

I've been trying different things but I keep getting FormatException errors.

Here's what I've done to work around it:

```<code>string text = "10.00%";
string s = text.TrimEnd(new char[] {'%'});
float f = float.Parse (s);
int i = (int)f;
i = i*100;
</code>```

Is there a better way?

Per comment - for 10.10% and 12.345% I would want the results of 1010 and 12345

However, for my uses, I would never parse 12.345% as it wouldn't exist in my string value, instead it would be 12.34%

always 2 decimals

答:
For accuracy with the math I would keep it as a float but here's a tad simpler solution

```<code>string t = "10.00%";
float f = float.Parse(t.Split('%')[0]);
int i = (int)(f * 100);
</code>```

What I would do is

```<code>string t = "10.00%";
float f = float.Parse(t.Split('%')[0]);
f = f * 100;
</code>```

Body:
I'm looking to try to change a string like 10.00% into an int like 1000.

I've been trying different things but I keep getting FormatException errors.

Here's what I've done to work around it:

string text = "10.00%";
string s = text.TrimEnd(new char[] {'%'});
float f = float.Parse (s);
int i = (int)f;
i = i*100;

Is there a better way?

Per comment - for 10.10% and 12.345% I would want the results of 1010 and 12345

However, for my uses, I would never parse 12.345% as it wouldn't exist in my string value, instead it would be 12.34%

always 2 decimals

Body:
For accuracy with the math I would keep it as a float but here's a tad simpler solution

string t = "10.00%";
float f = float.Parse(t.Split('%')[0]);
int i = (int)(f * 100);

What I would do is

string t = "10.00%";
float f = float.Parse(t.Split('%')[0]);
f = f * 100;


问:
Bash count lines and pipe into less info
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

```<code>queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29
</code>```

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

```<code>domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)
</code>```

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

答:
```<code>$ awk '/^domain[0-9]+\.TLD/{if(p)print p,c;p=$0;c=0;next}{c++}END{print p,c}' file
domain1.TLD 2
domain2.TLD 4
domain3.TLD 1
</code>```

Explained:

```<code>/^domain[0-9]+\.TLD/ {  # domain*TLD records:
    if(p) print p, c    # print p revious domain and c ount
    p=$0                # reset vars
    c=0
    next                # next record
}
{ c++ }                 # count other records
END { print p, c }      # print the last domain*TLD
</code>```

Body:
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

Body:
$ awk '/^domain[0-9]+\.TLD/{if(p)print p,c;p=$0;c=0;next}{c++}END{print p,c}' file
domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

Explained:

/^domain[0-9]+\.TLD/ {  # domain*TLD records:
    if(p) print p, c    # print p revious domain and c ount
    p=$0                # reset vars
    c=0
    next                # next record
}
{ c++ }                 # count other records
END { print p, c }      # print the last domain*TLD


问:
Calculating distance from GPS coordinates
I have an app with a start and a stop button. When the user hits start, it turns on GPS. When the user hits stop, it turns off GPS. I want to calculate the distance the user traveled from start to stop.

This is the code I have so far but it's not working.

I'm printing GPS coordinates for Point 1 and Point 2 rounded to 4 decimal places. It's entering the if-statement in Update() even though it's printing the same GPS coordinates for Point 1 and Point 2.

Another issue is that it says I've traveled ~1200 km as soon as I hit the start button even though I haven't moved.

```<code>public double long1 = 0;
public double lat1 = 0;

public double long2 = 0;
public double lat2 = 0;

void Start ()
{
    distance_label = distanceObject.GetComponent<Text> ();

    // *** DELETE WHEN DONE - text labels for testing
    testP1 = p1Object.GetComponent<Text> ();
    testP2 = p2Object.GetComponent<Text> ();
    testMsg = test.GetComponent<Text> ();

    distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
}

void Update ()
{

    GetCurrentLocation ();

    double latRounded1 = Math.Round (lat1, 4);
    double longRounded1 = Math.Round (long1, 4);
    double latRounded2 = Math.Round (lat2, 4);
    double longRounded2 = Math.Round (long2, 4);

    testP1.text = "<Point 1 Coordinates> Lat: " + latRounded1 + ", Long: " + longRounded1;
    testP2.text = "<Point 2 Coordinates> Lat: " + latRounded2 + ", Long: " + longRounded2;

    // Compare GPS coordinates rounded to 4 decimal places
    if (latRounded1 != latRounded2 || longRounded1 != longRounded2) {
        testMsg.text = "Lat/Long don't match.";
        distanceWalked += CalculateDistance (longRounded1, latRounded1, longRounded2, latRounded2);
        distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
        long1 = long2;
        lat1 = lat2;
    }
}

/// <summary>
/// Makes a call to start GPS service when Start button is clicked.
/// </summary>
public void StartButtonClicked ()
{
    Debug.Log ("Start button clicked...");
    StartCoroutine (StartLocationService ());
}

/// <summary>
/// Stops GPS service when Stop button is clicked.
/// </summary>

public void StopButtonClicked ()
{
    Debug.Log ("Stop button clicked...");
    Input.location.Stop ();
    distance_label.text = "Stopped.";
}

public void ResetButtonClicked()
{
    Debug.Log("Reset button clicked...");
    distanceWalked = 0;
    Input.location.Stop ();

    Debug.Log ("distanceWalked after reset: " + distanceWalked);
}

public void GetCurrentLocation()
{
    if (Input.location.status == LocationServiceStatus.Running) {
        long2 = Input.location.lastData.longitude;
        lat2 = Input.location.lastData.latitude;
    }
}

/// <summary>
/// Starts the location service.
/// </summary>

IEnumerator StartLocationService ()
{
    // First, check if user has location service enabled
    if (!Input.location.isEnabledByUser)
        //yield break;
        distance_label.text = "Not initialized";

    // Start service before querying location
    Input.location.Start (0.5f);    // accuracy = 0.5m

    // Wait until service initializes
    int maxWait = 20;
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
        yield return new WaitForSeconds (1);
        maxWait--;
    }

    // Service didn't initialize in 20 seconds
    if (maxWait < 1) {
        distance_label.text = "Timed out";
        yield break;
    }

    // Connection has failed
    if (Input.location.status == LocationServiceStatus.Failed) {
        distance_label.text = "Unable to determine device location";
        yield break;
    } else {
        long1 = long2 = Input.location.lastData.longitude;
        lat1 = lat2 = Input.location.lastData.latitude;

        // Access granted and location value could be retrieved
        // distance_label.text = "Location: " + Input.location.lastData.latitude + " " +
        // Input.location.lastData.longitude + " " +
        // Input.location.lastData.altitude;

    }

    // Stop service if there is no need to query location updates continuously
    //Input.location.Stop ();
}

/// <summary>
/// Calculate distance traveled given two points.
/// </summary>
/// <param name="longitude1"> Longitude coordinate of point 1</param>
/// <param name="latitude1"> Latitude coordinate of point 1</param>
/// <param name="longitude2"> Longitude coordinate of point 2</param>
/// <param name="latitude2"> Latitude coordinate of point 2</param>
public double CalculateDistance (double longitude1, double latitude1, double longitude2, double latitude2)
{
    double radiansOverDegrees = (Math.PI / 180.0);
    double EARTH_MEAN_RADIUS = 6371;    // in km

    double radiansLong1 = longitude1 * radiansOverDegrees;
    double radiansLat1 = latitude1 * radiansOverDegrees;

    double radiansLong2 = longitude2 * radiansOverDegrees;
    double radiansLat2 = latitude2 * radiansOverDegrees;

    double dLong = radiansLong2 - radiansLong1;
    double dLat = radiansLat2 - radiansLat1;

    double dist1 = Math.Pow (Math.Sin (dLat / 2.0), 2.0) +
        Math.Cos (radiansLat1) * Math.Cos (radiansLat2) *
        Math.Pow (Math.Sin (dLong / 2.0), 2.0);

    double dist2 = EARTH_MEAN_RADIUS * 2.0 * Math.Atan2 (Math.Sqrt (dist1), Math.Sqrt (1.0 - dist1));

    return dist2;
}
</code>```

答:
Use SphericalUtil which in com.google.maps.android package.    </p>

```<code>public static double getDistance(LatLng origin, LatLng destination) {
            return SphericalUtil.computeDistanceBetween(origin, destination);
        }
</code>```

Body:
I have an app with a start and a stop button. When the user hits start, it turns on GPS. When the user hits stop, it turns off GPS. I want to calculate the distance the user traveled from start to stop.

This is the code I have so far but it's not working.

I'm printing GPS coordinates for Point 1 and Point 2 rounded to 4 decimal places. It's entering the if-statement in Update() even though it's printing the same GPS coordinates for Point 1 and Point 2.

Another issue is that it says I've traveled ~1200 km as soon as I hit the start button even though I haven't moved.

public double long1 = 0;
public double lat1 = 0;

public double long2 = 0;
public double lat2 = 0;

void Start ()
{
    distance_label = distanceObject.GetComponent<Text> ();

    // *** DELETE WHEN DONE - text labels for testing
    testP1 = p1Object.GetComponent<Text> ();
    testP2 = p2Object.GetComponent<Text> ();
    testMsg = test.GetComponent<Text> ();

    distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
}

void Update ()
{

    GetCurrentLocation ();

    double latRounded1 = Math.Round (lat1, 4);
    double longRounded1 = Math.Round (long1, 4);
    double latRounded2 = Math.Round (lat2, 4);
    double longRounded2 = Math.Round (long2, 4);

    testP1.text = "<Point 1 Coordinates> Lat: " + latRounded1 + ", Long: " + longRounded1;
    testP2.text = "<Point 2 Coordinates> Lat: " + latRounded2 + ", Long: " + longRounded2;

    // Compare GPS coordinates rounded to 4 decimal places
    if (latRounded1 != latRounded2 || longRounded1 != longRounded2) {
        testMsg.text = "Lat/Long don't match.";
        distanceWalked += CalculateDistance (longRounded1, latRounded1, longRounded2, latRounded2);
        distance_label.text = "You and your blobs have walked " + distanceWalked + " km.";
        long1 = long2;
        lat1 = lat2;
    }
}

///
/// Makes a call to start GPS service when Start button is clicked.
///
public void StartButtonClicked ()
{
    Debug.Log ("Start button clicked...");
    StartCoroutine (StartLocationService ());
}

///
/// Stops GPS service when Stop button is clicked.
///

public void StopButtonClicked ()
{
    Debug.Log ("Stop button clicked...");
    Input.location.Stop ();
    distance_label.text = "Stopped.";
}

public void ResetButtonClicked()
{
    Debug.Log("Reset button clicked...");
    distanceWalked = 0;
    Input.location.Stop ();

    Debug.Log ("distanceWalked after reset: " + distanceWalked);
}

public void GetCurrentLocation()
{
    if (Input.location.status == LocationServiceStatus.Running) {
        long2 = Input.location.lastData.longitude;
        lat2 = Input.location.lastData.latitude;
    }
}

///
/// Starts the location service.
///

IEnumerator StartLocationService ()
{
    // First, check if user has location service enabled
    if (!Input.location.isEnabledByUser)
        //yield break;
        distance_label.text = "Not initialized";

    // Start service before querying location
    Input.location.Start (0.5f);    // accuracy = 0.5m

    // Wait until service initializes
    int maxWait = 20;
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
        yield return new WaitForSeconds (1);
        maxWait--;
    }

    // Service didn't initialize in 20 seconds
    if (maxWait < 1) {
        distance_label.text = "Timed out";
        yield break;
    }

    // Connection has failed
    if (Input.location.status == LocationServiceStatus.Failed) {
        distance_label.text = "Unable to determine device location";
        yield break;
    } else {
        long1 = long2 = Input.location.lastData.longitude;
        lat1 = lat2 = Input.location.lastData.latitude;

        // Access granted and location value could be retrieved
        // distance_label.text = "Location: " + Input.location.lastData.latitude + " " +
        // Input.location.lastData.longitude + " " +
        // Input.location.lastData.altitude;

    }

    // Stop service if there is no need to query location updates continuously
    //Input.location.Stop ();
}

///
/// Calculate distance traveled given two points.
///
/// <param name="longitude1"> Longitude coordinate of point 1</param>
/// <param name="latitude1"> Latitude coordinate of point 1</param>
/// <param name="longitude2"> Longitude coordinate of point 2</param>
/// <param name="latitude2"> Latitude coordinate of point 2</param>
public double CalculateDistance (double longitude1, double latitude1, double longitude2, double latitude2)
{
    double radiansOverDegrees = (Math.PI / 180.0);
    double EARTH_MEAN_RADIUS = 6371;    // in km

    double radiansLong1 = longitude1 * radiansOverDegrees;
    double radiansLat1 = latitude1 * radiansOverDegrees;

    double radiansLong2 = longitude2 * radiansOverDegrees;
    double radiansLat2 = latitude2 * radiansOverDegrees;

    double dLong = radiansLong2 - radiansLong1;
    double dLat = radiansLat2 - radiansLat1;

    double dist1 = Math.Pow (Math.Sin (dLat / 2.0), 2.0) +
        Math.Cos (radiansLat1) * Math.Cos (radiansLat2) *
        Math.Pow (Math.Sin (dLong / 2.0), 2.0);

    double dist2 = EARTH_MEAN_RADIUS * 2.0 * Math.Atan2 (Math.Sqrt (dist1), Math.Sqrt (1.0 - dist1));

    return dist2;
}

Body:
Use SphericalUtil which in com.google.maps.android package.

public static double getDistance(LatLng origin, LatLng destination) {
            return SphericalUtil.computeDistanceBetween(origin, destination);
        }


问:
Select network interface to be used for getting IP information using WMI
I'm creating a script that finds and displays IP configuration information. I have managed to create the variables to get the information and to display it:

```<code>$ip = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").IPAddress[0]

$subnet = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").IPSubnet[0]

$gateway = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").DefaultIPGateway

$dns = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").DNSServerSearchOrder

write-host
write-host

write-host "IP address is: $ip"

write-host "Subnet Mask is: $subnet"

write-host "Default Gateway is: $gateway"

write-host "DNS is: $dns"
</code>```

I'm filtering the interface by index number, which for my case the number is 12 for the right interface. I want to prompt the user with a list of network interfaces. Get-NetAdapter command should not be used because it doesn't work on PowerShell v2. The user must be able to see current interfaces including descriptions and be able to select one netowrk adapter interface. The selected interface must be put into a variable i.e. $interface. The variable must output the corresponding adapter index number.  After that, I am able to place the variable in the filter command like: -Filter "index = '$interfaceindexnumber'" which should normally display IP information for the selected interface.

Feel free to use a different filter if you believe index number is not the right solution for this case. Please, make sure to use commands that work with PowerShell v2.

Thank You!

答:
```<code>Get-WmiObject -Class win32_networkadapterconfiguration | Select Index, @{n="IP"; e={$_.ipaddress[0]}}, @{n="Subnet"; e={$_.IPSubnet[0]}}, Description | Format-Table -AutoSize
[int]$ifindex = Read-Host "Select Network Adapter by Index Number"

$adapters = Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '$ifindex'"

foreach ($adapter in $adapters){
$ip = $adapter.IPAddress[0]
$subnet = $adapter.IPSubnet[0]
$gateway = $adapter.DefaultIPGateway
$dns = $adapter.DNSServerSearchOrder
}

$ip
$subnet
$gateway
$dns
</code>```

Body:
I'm creating a script that finds and displays IP configuration information. I have managed to create the variables to get the information and to display it:

$ip = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").IPAddress[0]

$subnet = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").IPSubnet[0]

$gateway = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").DefaultIPGateway

$dns = (Get-WmiObject -Class win32_networkadapterconfiguration -Filter "index = '12'").DNSServerSearchOrder

write-host
write-host

write-host "IP address is: $ip"

write-host "Subnet Mask is: $subnet"

write-host "Default Gateway is: $gateway"

write-host "DNS is: $dns"

I'm filtering the interface by index number, which for my case the number is 12 for the right interface. I want to prompt the user with a list of network interfaces. Get-NetAdapter command should not be used because it doesn't work on PowerShell v2. The user must be able to see current interfaces including descriptions and be able to select one netowrk adapter interface. The selected interface must be put into a variable i.e. $interface. The variable must output the corresponding adapter index number.  After that, I am able to place the variable in the filter command like: -Filter "index = '$interfaceindexnumber'" which should normally display IP information for the selected interface.

Feel free to use a different filter if you believe index number is not the right solution for this case. Please, make sure to use commands that work with PowerShell v2.

Thank You!


问:
Rails Mailer - Can't access instance variable from Mailer View
I have a rails mailer that currently sends an email successfully anytime a user replies to another user's comment.  (the email goes to the person who was replied to).  I'm trying to add some dynamic content in the email body like the username of the person who replied and that user's comment itself.  I'm not sure how to grab that particular comment within the new_reply.html.erb view so that it shows correctly in my email that is being sent...my code is as follows:

views/comment_mailer/new_reply.html.erb (email content)

```<code><!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <table width="100%">

        <h2 style="color: #428bca">You have a new reply.</h2>
            <p>Someone replied with the following comment...</p>

      <p><%= comment.body %></p>

            <p>To reply back, login to the app...</p>

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

views/comments/_comment.html.erb (the actual comment view in the app)

```<code><div class="well">
  <p class="text-muted">Added on
    <%= l(comment.created_at, format: '%B, %d %Y %H:%M:%S') %></p>

  <blockquote>
    <p><%= comment.body %></p>
        <p><%= link_to 'reply', new_comment_path(comment.id) %></p>
  </blockquote>
</div>
</code>```

mailers/comment_mailer.rb (my comment mailer)

```<code>class CommentMailer < ApplicationMailer
    default from: "notifications@app.com"

    def new_reply(parent_comment)
    owner = parent_comment.owner
        mail(to: owner.email, subject: 'New reply to one of your comments')
    end
end
</code>```

controllers/model_comments_controller.rb (controller for these comments)

```<code>def create
    @taskrelationship = commentable_type.constantize.find(commentable_id)
    @project = @taskrelationship.taskproject
    @new_comment = Comment.build_from(@taskrelationship, current_user.id, body)
    if @new_comment.save

      # create the notification
      (@taskrelationship.taskproject.followers.uniq - [current_user]).each do |user|
        Notification.create(recipient: user, actor: current_user, action: "posted", notifiable: @new_comment)
      end

      make_child_comment
    end
    render 'projects/show_project_task_comments', layout: false
  end

private

def make_child_comment
  return if comment_id.blank?

  parent_comment = Comment.find comment_id
  @new_comment.move_to_child_of(parent_comment)
  CommentMailer.new_reply(parent_comment).deliver
end
</code>```

答:
In the new_reply method in the mailer declare an instance variable @comment that references the comment you'll like to use.

Then in the template, just use @comment to reference it.

Body:
I have a rails mailer that currently sends an email successfully anytime a user replies to another user's comment.  (the email goes to the person who was replied to).  I'm trying to add some dynamic content in the email body like the username of the person who replied and that user's comment itself.  I'm not sure how to grab that particular comment within the new_reply.html.erb view so that it shows correctly in my email that is being sent...my code is as follows:

views/comment_mailer/new_reply.html.erb (email content)

<!DOCTYPE html>

    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />

You have a new reply.

Someone replied with the following comment...

<%= comment.body %>

To reply back, login to the app...

views/comments/_comment.html.erb (the actual comment view in the app)

Added on
    <%= l(comment.created_at, format: '%B, %d %Y %H:%M:%S') %>

<%= comment.body %>

<%= link_to 'reply', new_comment_path(comment.id) %>

mailers/comment_mailer.rb (my comment mailer)

class CommentMailer < ApplicationMailer
    default from: "notifications@app.com"

    def new_reply(parent_comment)
    owner = parent_comment.owner
        mail(to: owner.email, subject: 'New reply to one of your comments')
    end
end

controllers/model_comments_controller.rb (controller for these comments)

def create
    @taskrelationship = commentable_type.constantize.find(commentable_id)
    @project = @taskrelationship.taskproject
    @new_comment = Comment.build_from(@taskrelationship, current_user.id, body)
    if @new_comment.save

      # create the notification
      (@taskrelationship.taskproject.followers.uniq - [current_user]).each do |user|
        Notification.create(recipient: user, actor: current_user, action: "posted", notifiable: @new_comment)
      end

      make_child_comment
    end
    render 'projects/show_project_task_comments', layout: false
  end

private

def make_child_comment
  return if comment_id.blank?

  parent_comment = Comment.find comment_id
  @new_comment.move_to_child_of(parent_comment)
  CommentMailer.new_reply(parent_comment).deliver
end


问:
Specify css for specific div
In the process of making a single page website, the css for my form is interfering with the rest of my page. Can the div be specified without going one by one through the css and specifying the div. Any help appreciated.</p>

答:
The form you are trying to use includes some very generic CSS - it styles the  and  elements, for starters, as well as all <input> elements.  If you want to limit the impact of the CSS from the form on the rest of your site, you will need to make it more specific.  For example, if you change

```<code>header {
  position: relative;
  margin: 100px 0 25px 0;
  font-size: 2.3em;
  text-align: center;
  letter-spacing: 7px;
}
</code>```

to

```<code>#form header {
  position: relative;
  margin: 100px 0 25px 0;
  font-size: 2.3em;
  text-align: center;
  letter-spacing: 7px;
}
</code>```

it will only be applied to  elements that are inside of an element with the id="form" attribute (in this case, that's the ID on the form you are trying to use). You may have to add this more specific selector to several of the CSS selectors from the form that are impacting other parts of your page.

Title: Specify css for specific div

Body:
The form you are trying to use includes some very generic CSS - it styles the <body> and <header> elements, for starters, as well as all <input> elements.  If you want to limit the impact of the CSS from the form on the rest of your site, you will need to make it more specific.  For example, if you change

header {
  position: relative;
  margin: 100px 0 25px 0;
  font-size: 2.3em;
  text-align: center;
  letter-spacing: 7px;
}

to

#form header {
  position: relative;
  margin: 100px 0 25px 0;
  font-size: 2.3em;
  text-align: center;
  letter-spacing: 7px;
}

it will only be applied to <header> elements that are inside of an element with the id="form" attribute (in this case, that's the ID on the form you are trying to use). You may have to add this more specific selector to several of the CSS selectors from the form that are impacting other parts of your page.


问:
how to see raw request body in yesod?
For debugging, I'd like to see raw request bodies that are being sent
to my yesod application.

I know how to use runRequestBody https://www.stackage.org/haddock/lts-7.0/yesod-core-1.4.24/Yesod-Core-Handler.html#v:runRequestBody

Now there is rawRequestBody. I am using

```<code>rawRequestBody Data.Conduit.$$ Data.Conduit.List.consume
</code>```

inside defaultLayout but the result is always empty.

The actual representation is a Conduit, so I suspect that it is already drained at this point. Then when do I get to see this in a state where it holds data? Assume this is possible, then how can I read it without removing its contents?

答:
Try this </p>

```<code>import qualified Data.Conduit.Text as CT
import qualified Data.Conduit.List as CL

rawRequestBody $$ CT.decode CT.utf8 =$ CL.consume
</code>```

Title: how to see raw request body in yesod?

Body:
For debugging, I'd like to see raw request bodies that are being sent
to my yesod application.

I know how to use runRequestBody https://www.stackage.org/haddock/lts-7.0/yesod-core-1.4.24/Yesod-Core-Handler.html#v:runRequestBody

Now there is rawRequestBody. I am using

rawRequestBody Data.Conduit.$$ Data.Conduit.List.consume

inside defaultLayout but the result is always empty.

The actual representation is a Conduit, so I suspect that it is already drained at this point. Then when do I get to see this in a state where it holds data? Assume this is possible, then how can I read it without removing its contents?

Body:
Try this

import qualified Data.Conduit.Text as CT
import qualified Data.Conduit.List as CL

rawRequestBody $$ CT.decode CT.utf8 =$ CL.consume


问:
Podio Authentication: how to use the scope parameter
Here is the relevant part of the documentation. I want to make sure an authenticated user has access to a 'space' on Podio before I redirect them but nothing is working so far...

I have tried adding this to the URL

```<code>&scope=space_3293195:read
&scope=3293195:read
&scope=thename:read
</code>```

but it's not working. Any suggestions?

答:
Sorry, but scope's feature is currently in Beta only and therefore not available for all Podio users.

We still have some work to do on the granular authentication project
  before we are able to release to public. Would love your feedback
  about how would you use scopes as this will help us come closer to a
  public release!

Body:
Here is the relevant part of the documentation. I want to make sure an authenticated user has access to a 'space' on Podio before I redirect them but nothing is working so far...

I have tried adding this to the URL

&scope=space_3293195:read
&scope=3293195:read
&scope=thename:read

but it's not working. Any suggestions?


问:
React Native Dev Menu on Android Nexus 5 Device
I have a basic react-native app which I am running on a real Nexus 5 and I cannot find a way to enable the developer menu which is present for iOS and emulated devices.

https://facebook.github.io/react-native/docs/debugging.html

https://facebook.github.io/react-native/docs/running-on-device.html

Method 1: Using adb reverse (recommended)

  You can use this method if
  your device is running Android 5.0 (Lollipop), it has USB debugging
  enabled, and it is connected via USB to your development machine.

Run the following in a command prompt:

$ adb reverse tcp:8081 tcp:8081 You can now use Reload JS from the
  React Native in-app Developer menu without any additional
  configuration.

When I run react-native run-android I see this line in the terminal

Running adb -s 06adb216 reverse tcp:8081 tcp:8081

But I see NO React Native in-app Developer menu

I am running:

```<code>Windows 10
react-native-cli: 2.0.1
react-native: 0.42.0
</code>```

My index.android.js file looks like this:

```<code>import { AppRegistry } from 'react-native';
import Welcome from './src/modules/onboarding/components/welcome';

AppRegistry.registerComponent('mobileapp', () => Welcome);
</code>```

答:
To work with android device or simulator without directly accessing hardware or click event, you can pass input to the device by adb
By adb shell input keyevent, either an event_code or a string will be sent to the device.

More information is given at Android Debug Bridge or ADB shell input

To open menu control, please use adb shell input keyevent 82 command.

Please let me know if you need more information on this.

Regards,
Durga

Body:
I have a basic react-native app which I am running on a real Nexus 5 and I cannot find a way to enable the developer menu which is present for iOS and emulated devices.

https://facebook.github.io/react-native/docs/debugging.html

https://facebook.github.io/react-native/docs/running-on-device.html

Method 1: Using adb reverse (recommended)

  You can use this method if
  your device is running Android 5.0 (Lollipop), it has USB debugging
  enabled, and it is connected via USB to your development machine.

Run the following in a command prompt:

$ adb reverse tcp:8081 tcp:8081 You can now use Reload JS from the
  React Native in-app Developer menu without any additional
  configuration.

When I run react-native run-android I see this line in the terminal

Running adb -s 06adb216 reverse tcp:8081 tcp:8081

But I see NO React Native in-app Developer menu

I am running:

Windows 10
react-native-cli: 2.0.1
react-native: 0.42.0

My index.android.js file looks like this:

import { AppRegistry } from 'react-native';
import Welcome from './src/modules/onboarding/components/welcome';

AppRegistry.registerComponent('mobileapp', () => Welcome);


问:
Cannot send email in localhost
why i can't send email in localhost but when i try in hosting it can send email
this my code
**

```<code>define('ROOT', 'localhost/OMG1/');
$kode = md5(uniqid(rand()));
$to = $_GET['f11'];
        $headers = "From: rizka.nugroho@omg-indonesia.com\r\n";
        $headers .= "Reply-to: $to\r\n";
        $pesan    = "Klik link berikut untuk verifikasi dan mengaktifkan akun : ";
        $pesan    .= ROOT."active.php?email=".$_GET['f11']."&kode=$kode&username=".$_GET['f5'];var_dump($pesan);
$a = @mail($to, "Aktivasi Akun Anda", $pesan, $headers);var_dump($a);
if($a)
        {
            echo "Email send";
        }
        else
        {
            echo "failed to send mail";
        }
</code>```

**
please help solved my problem

答:
You need to configure your email settings on XAMPP. A quick search on stack overflow shows that someone already asked a question like this and received and answer...

How to configure XAMPP to send mail from localhost?

Please try and use the search function first next time.

Title: Cannot send email in localhost

Body:
why i can't send email in localhost but when i try in hosting it can send email
this my code
**

define('ROOT', 'localhost/OMG1/');
$kode = md5(uniqid(rand()));
$to = $_GET['f11'];
        $headers = "From: rizka.nugroho@omg-indonesia.com\r\n";
        $headers .= "Reply-to: $to\r\n";
        $pesan    = "Klik link berikut untuk verifikasi dan mengaktifkan akun : ";
        $pesan    .= ROOT."active.php?email=".$_GET['f11']."&kode=$kode&username=".$_GET['f5'];var_dump($pesan);
$a = @mail($to, "Aktivasi Akun Anda", $pesan, $headers);var_dump($a);
if($a)
        {
            echo "Email send";
        }
        else
        {
            echo "failed to send mail";
        }

**
please help solved my problem


问:
Can OCUnit rely on code in background threads? (in order to test asynchronous requests)
I've been trying to automate tests on asynchronous requests but I haven't been able to run anything in a different thread while the test function was waiting.
Here is the test function:

```<code>- (void) testBoxManagerConnexionStatus
{
    ControlSender* cs = [ControlSender get];
    requestShouldSucceed = YES;
    [cs startCheckingReachabilityWithDelegate:self];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:TIMEOUT_INTERVAL+1.0]];

    STAssertTrue(downloadComplete, @"Download should be over by now");
}
</code>```

My test class implements the callback methods this way:

```<code>- (void)controlSender:(ControlSender *)controlSender sentSuccessfullyCode:(FreeboxControl)code
{
    if (requestShouldFail) {
        STAssertTrue(NO, @"Request should have failed");
    }
    downloadComplete = YES;

}
- (void)controlSender:(ControlSender *)controlSender couldntSendCode:(FreeboxControl)code details:(NSHTTPURLResponse*)details
{
    if (requestShouldSucceed) {
        STAssertTrue(NO, @"Request should have succeded");
    }
    downloadComplete = YES;
}
</code>```

But whenever my usual code try to run something in a different thread nothing happens. For example the NSURLConnection never call its delegate methods when allocated:

```<code>m_connexion = [[NSURLConnection alloc] initWithRequest:m_networkRequest delegate:self];
</code>```

Neither the -connectionDidFinishLoading: nor the -connection:didFailWithError:

Same thing for calls like this one:

```<code>[self performSelectorInBackground:@selector(BG_startCheckingReachabilityWithDelegate:) withObject:delegate];
</code>```

Nothings gets called in background when running the test.
The same code works fine outside of the test though.
Is there any way to test asynchronous url request with OCUnit?

Thanks for the help.

答:
You can try running requests like this in a background thread, but you don't want to.  For your sanity, you don't want your tests dependent on external services.  What if the remote service is down?  Your test fails.  What if the remote service returns an error?  Your test fails?  What if you want to what your code does when the remote service responds with an error to a valid request?  You can't (consistently).  Even if your tests pass they'll run slowly, depending on how long the remote service takes to respond.

Your life will be easier if you stub out the dependency on any remote services for the purpose of your tests.  See this answer (and the associated question) for more detailed reasoning.

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to automate tests on asynchronous requests but I haven't been able to run anything in a different thread while the test function was waiting.
Here is the test function:

- (void) testBoxManagerConnexionStatus
{
    ControlSender* cs = [ControlSender get];
    requestShouldSucceed = YES;
    [cs startCheckingReachabilityWithDelegate:self];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:TIMEOUT_INTERVAL+1.0]];

    STAssertTrue(downloadComplete, @"Download should be over by now");
}

My test class implements the callback methods this way:

- (void)controlSender:(ControlSender *)controlSender sentSuccessfullyCode:(FreeboxControl)code
{
    if (requestShouldFail) {
        STAssertTrue(NO, @"Request should have failed");
    }
    downloadComplete = YES;

}
- (void)controlSender:(ControlSender *)controlSender couldntSendCode:(FreeboxControl)code details:(NSHTTPURLResponse*)details
{
    if (requestShouldSucceed) {
        STAssertTrue(NO, @"Request should have succeded");
    }
    downloadComplete = YES;
}

But whenever my usual code try to run something in a different thread nothing happens. For example the NSURLConnection never call its delegate methods when allocated:

m_connexion = [[NSURLConnection alloc] initWithRequest:m_networkRequest delegate:self];

Neither the -connectionDidFinishLoading: nor the -connection:didFailWithError:

Same thing for calls like this one:

[self performSelectorInBackground:@selector(BG_startCheckingReachabilityWithDelegate:) withObject:delegate];

Nothings gets called in background when running the test.
The same code works fine outside of the test though.
Is there any way to test asynchronous url request with OCUnit?

Thanks for the help.


问:
Playframework 2.5.0 : Unable to serve server-side generated zip file
My Playframework 2.5.0 application has to serve temporary created zip file.
I create and fulfill the zip file in the /tmp directory, without any problem (I can open it in this place and extract the contained files).

But the file sent to the client seems to be truncated and can't be opened.

```<code>String tempPath = "/tmp/" + label + ".zip";

File zipFile = new File(tempPath);
zipFile.deleteOnExit();
ZipOutputStream zos = null;

try {
    zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    for (/* loops through files to zip */) {
        InputStream is = methodToGetTheDocument();
        ZipEntry zipEntry = new ZipEntry(document.getLabel());
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[2048];
        int count = is.read(bytes);
        while (count > -1) {
            zos.write(bytes, 0, count);
            count = is.read(bytes);
        }
        is.close();
        zos.closeEntry();
    }
    return ok(zipFile);
} catch (Exception e) {
    return badRequest("Bad request");
} finally {
    try {
        zos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

I return a classical Result object... What is the problem ?

答: You have to "close" the zip file using zos.close() before you return ok(zipFile)

Body:
My Playframework 2.5.0 application has to serve temporary created zip file.
I create and fulfill the zip file in the /tmp directory, without any problem (I can open it in this place and extract the contained files).

But the file sent to the client seems to be truncated and can't be opened.

String tempPath = "/tmp/" + label + ".zip";

File zipFile = new File(tempPath);
zipFile.deleteOnExit();
ZipOutputStream zos = null;

try {
    zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    for (/* loops through files to zip */) {
        InputStream is = methodToGetTheDocument();
        ZipEntry zipEntry = new ZipEntry(document.getLabel());
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[2048];
        int count = is.read(bytes);
        while (count > -1) {
            zos.write(bytes, 0, count);
            count = is.read(bytes);
        }
        is.close();
        zos.closeEntry();
    }
    return ok(zipFile);
} catch (Exception e) {
    return badRequest("Bad request");
} finally {
    try {
        zos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I return a classical Result object... What is the problem ?


问:
Format Dynamically added textBox in Excel
I am adding TextBoxes dynamically in a userform and want to make them a date format to ensure correct date entry.  I am unable to find any examples.

Here is my code for the userform activation:

```<code>Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)

fltDays = TextBox3.Value If TextBox3.Value = 0 Then Exit Sub

For i = 1 To fltDays

n = i - 1

Dim TextBox As Control

Set theLbl = FloatDayFrm.Controls.add("Forms.Label.1", "lbl_" & i, True)
    With theLbl
      .Caption = "Day " & i
      .Left = 20
      .Width = 60
      .Top = n * 24 + 100
      .Font.Size = 10
    End With

Set TextBox = FloatDayFrm.Controls.add("Forms.TextBox.1", "TextBox_" & n, True)
    With TextBox
        .Top = 100 + (n * 24)
        .Left = 90
        .Height = 18
        .Width = 50
        .Name = "txtBox" & i
        .Font.Size = 10
        .TabIndex = n + 4
        .TabStop = True
    End With Next i

FloatDayFrm.Height = 150 + fltDays * 24 With btnOK .Top = 102 + fltDays * 24 .TabStop = True .TabIndex = n + 5 End With

With btnCancel .Top = 102 + fltDays * 24 '.TabStop = True .TabIndex = n + 6 End With

End Sub
</code>```

This is my code for the Command button:

```<code>Private Sub btnOK_Click()

n = TextBox3.Value

For j = 1 To n

Set varFloatDay = FloatDayFrm.Controls("txtBox" & j)

Select Case varFloatDay
    Case ""
        MsgBox "Day " & j & " can't be blank", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is > TextBox2.Value
         MsgBox "Date is after end date", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is < TextBox1.Value
         MsgBox "Date is BEFORE end date", vbOKOnly, "Incorrect Value"
        Exit Sub
End Select

Next j

End Sub
</code>```

Any help would be appreciated.

答:
You have to convert text to date format. You can use multiple approach.

Add a label beside textbox to display the format user has to specify the date. Parse the text specified by user as per the format. Do validation and conversion as shown in code below.

Use a calendar control instead of textbox as user input.

Have separate textboxes or cells for year, month and day. Do validation and conversion as shown in code below.

If you are sure date is in the specified format as per regional setting. Do validation and conversion as shown in code below.

Try below

```<code>Private Sub TestDate()
    Dim yr As Integer
    Dim mnth As Integer
    Dim day As Integer
    Dim dt As Date
    Dim strDate As String

    '''''3rd approach''''''
    yr = ActiveSheet.Range("A1")
    mnth = ActiveSheet.Range("B1")
    day = ActiveSheet.Range("C1")
    If IsNumeric(yr) And IsNumeric(mnth) And IsNumeric(day) Then
        If yr < 0 Or mnth < 0 Or day < 0 Then
            MsgBox "Year, Month and Day must be greater than 0."
            Exit Sub
        End If
    Else
        MsgBox "Year, Month and Day must be an integer."
        Exit Sub
    End If
    'convert to Date
    dt = DateSerial(yr, mnth, day)

    '''''4th approach''''''
    'Display a date according to your system's short date format
    'i.e. regional settings in control panel
    strDate = Format(ActiveSheet.Range("D1"), "Short Date")
    If Not IsDate(strDate) Then
        MsgBox "Incorrect Date Format"
        Exit Sub
    End If
    dt = CDate(strDate)
End Sub
</code>```

Body:
I am adding TextBoxes dynamically in a userform and want to make them a date format to ensure correct date entry.  I am unable to find any examples.

Here is my code for the userform activation:

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)

fltDays = TextBox3.Value If TextBox3.Value = 0 Then Exit Sub

For i = 1 To fltDays

n = i - 1

Dim TextBox As Control

Set theLbl = FloatDayFrm.Controls.add("Forms.Label.1", "lbl_" & i, True)
    With theLbl
      .Caption = "Day " & i
      .Left = 20
      .Width = 60
      .Top = n * 24 + 100
      .Font.Size = 10
    End With

Set TextBox = FloatDayFrm.Controls.add("Forms.TextBox.1", "TextBox_" & n, True)
    With TextBox
        .Top = 100 + (n * 24)
        .Left = 90
        .Height = 18
        .Width = 50
        .Name = "txtBox" & i
        .Font.Size = 10
        .TabIndex = n + 4
        .TabStop = True
    End With Next i

FloatDayFrm.Height = 150 + fltDays * 24 With btnOK .Top = 102 + fltDays * 24 .TabStop = True .TabIndex = n + 5 End With

With btnCancel .Top = 102 + fltDays * 24 '.TabStop = True .TabIndex = n + 6 End With

End Sub

This is my code for the Command button:

Private Sub btnOK_Click()

n = TextBox3.Value

For j = 1 To n

Set varFloatDay = FloatDayFrm.Controls("txtBox" & j)

Select Case varFloatDay
    Case ""
        MsgBox "Day " & j & " can't be blank", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is > TextBox2.Value
         MsgBox "Date is after end date", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is < TextBox1.Value
         MsgBox "Date is BEFORE end date", vbOKOnly, "Incorrect Value"
        Exit Sub
End Select

Next j

End Sub

Any help would be appreciated.

Body:
You have to convert text to date format. You can use multiple approach.

Add a label beside textbox to display the format user has to specify the date. Parse the text specified by user as per the format. Do validation and conversion as shown in code below.

Use a calendar control instead of textbox as user input.

Have separate textboxes or cells for year, month and day. Do validation and conversion as shown in code below.

If you are sure date is in the specified format as per regional setting. Do validation and conversion as shown in code below.

Try below

Private Sub TestDate()
    Dim yr As Integer
    Dim mnth As Integer
    Dim day As Integer
    Dim dt As Date
    Dim strDate As String

    '''''3rd approach''''''
    yr = ActiveSheet.Range("A1")
    mnth = ActiveSheet.Range("B1")
    day = ActiveSheet.Range("C1")
    If IsNumeric(yr) And IsNumeric(mnth) And IsNumeric(day) Then
        If yr < 0 Or mnth < 0 Or day < 0 Then
            MsgBox "Year, Month and Day must be greater than 0."
            Exit Sub
        End If
    Else
        MsgBox "Year, Month and Day must be an integer."
        Exit Sub
    End If
    'convert to Date
    dt = DateSerial(yr, mnth, day)

    '''''4th approach''''''
    'Display a date according to your system's short date format
    'i.e. regional settings in control panel
    strDate = Format(ActiveSheet.Range("D1"), "Short Date")
    If Not IsDate(strDate) Then
        MsgBox "Incorrect Date Format"
        Exit Sub
    End If
    dt = CDate(strDate)
End Sub


问:
How can I find the first occurrence in a string that is not numeric in java
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:</p>

```<code>public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}
</code>```

答:
The easiest way is splitting the numbers and operators using regex and Java 8 (for use lambda expression), for example:

```<code>String input =  "698+33-47*2";

String[] operators = input.split("\\d"); // ----------------------> split the operators
List<String> listOperators = Arrays.stream(operators)
                                   .filter(o -> !o.isEmpty()) // -> checks the current position is not empty
                                   .collect(Collectors.toList());
System.out.println("operators: " + listOperators.toString());

String[] numbers = input.split("[*+-/]"); // ---------------------> split the numbers
List<String> listNumbers = Arrays.stream(numbers)
                                 .collect(Collectors.toList());
System.out.println("numbers: " + listNumbers.toString());
</code>```

Output:

operators: [+, -, *]

numbers: [698, 33, 47, 2]

Body:
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:

public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}

Body:
The easiest way is splitting the numbers and operators using regex and Java 8 (for use lambda expression), for example:

String input =  "698+33-47*2";

String[] operators = input.split("\\d"); // ----------------------> split the operators
List<String> listOperators = Arrays.stream(operators)
                                   .filter(o -> !o.isEmpty()) // -> checks the current position is not empty
                                   .collect(Collectors.toList());
System.out.println("operators: " + listOperators.toString());

String[] numbers = input.split("[*+-/]"); // ---------------------> split the numbers
List<String> listNumbers = Arrays.stream(numbers)
                                 .collect(Collectors.toList());
System.out.println("numbers: " + listNumbers.toString());

Output:

operators: [+, -, *]

numbers: [698, 33, 47, 2]


问:
Create and Execute an aws lambda function through cloud formation
I am creating my lambda function like following through cloud formation template.
My question is , after creating this lambda resource , I want to pass it few variables as an input and execute it immediately. Is there a way I can do it through cloud formation template?

```<code>AWSTemplateFormatVersion: '2010-09-09'
Description: Create a lambda function for chef rds read replica
Parameters:
  Environment:
    Description: Environment that will be built
    Type: String
    Default: q1
    AllowedValues:
    - q1
Mappings:
  ChefEnvironmentMap:
    q1:
      IAMRole: CHEFAWS-RDS
      Subnets:
      - subnet-***
      SecurityGroups:
      - sg-***
      NetCoreEnvironment: qa
Resources:
  ChefRDSReadOnlyReplica:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: cheftestbucket
        S3Key: lambda/cheflambda.zip
      Description: "Chef rds"
      Environment:
        Variables:
          http_proxy: 'http://**'
          https_proxy: 'http://**'
          no_proxy: '169.254.169.254,127.0.0.1,localaddress,.localdomain.com'
      Handler: createreadreplica.lambda_handler
      MemorySize: 128
      Role: arn:aws:iam::*****:role/CHEFAWS-RDS
      Runtime: python2.7
      Timeout: 60
      VpcConfig:
        SecurityGroupIds: !FindInMap [ChefEnvironmentMap, !Ref Environment, SecurityGroups]
        SubnetIds: !FindInMap [ChefEnvironmentMap, !Ref Environment, Subnets]
</code>```

答:
I followed the approach to create a custom resource to execute the lambda fuction. I launched the custom resource through the cft as well, like this.

```<code>  Lambdaresource:
    DependsOn: ChefRDSReadOnlyReplica
    Properties:
      sourceregion: "us-east-1"
      target_region: "us-west-2"
      db_instance_id: "chef-tod-pg-rds"
      dbsubnet_groupname: "******"
      kms_keyid: "******"
      ServiceToken: !GetAtt ChefRDSReadOnlyReplica.Arn
    Type: AWS::CloudFormation::CustomResource
</code>```

However, this lead to more complexity . As cloud formation of custom resource doesnt get notified after it triggers the lambda function. So it remains in “Creating Resource”  State. To handle this , I had to create a new function in my lambda Python code that returned the success/failure. As mentioned here: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html

Body:
I am creating my lambda function like following through cloud formation template.
My question is , after creating this lambda resource , I want to pass it few variables as an input and execute it immediately. Is there a way I can do it through cloud formation template?

AWSTemplateFormatVersion: '2010-09-09'
Description: Create a lambda function for chef rds read replica
Parameters:
  Environment:
    Description: Environment that will be built
    Type: String
    Default: q1
    AllowedValues:
    - q1
Mappings:
  ChefEnvironmentMap:
    q1:
      IAMRole: CHEFAWS-RDS
      Subnets:
      - subnet-***
      SecurityGroups:
      - sg-***
      NetCoreEnvironment: qa
Resources:
  ChefRDSReadOnlyReplica:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: cheftestbucket
        S3Key: lambda/cheflambda.zip
      Description: "Chef rds"
      Environment:
        Variables:
          http_proxy: 'http://**'
          https_proxy: 'http://**'
          no_proxy: '169.254.169.254,127.0.0.1,localaddress,.localdomain.com'
      Handler: createreadreplica.lambda_handler
      MemorySize: 128
      Role: arn:aws:iam::*****:role/CHEFAWS-RDS
      Runtime: python2.7
      Timeout: 60
      VpcConfig:
        SecurityGroupIds: !FindInMap [ChefEnvironmentMap, !Ref Environment, SecurityGroups]
        SubnetIds: !FindInMap [ChefEnvironmentMap, !Ref Environment, Subnets]

Body:
I followed the approach to create a custom resource to execute the lambda fuction. I launched the custom resource through the cft as well, like this.

  Lambdaresource:
    DependsOn: ChefRDSReadOnlyReplica
    Properties:
      sourceregion: "us-east-1"
      target_region: "us-west-2"
      db_instance_id: "chef-tod-pg-rds"
      dbsubnet_groupname: "******"
      kms_keyid: "******"
      ServiceToken: !GetAtt ChefRDSReadOnlyReplica.Arn
    Type: AWS::CloudFormation::CustomResource

However, this lead to more complexity . As cloud formation of custom resource doesnt get notified after it triggers the lambda function. So it remains in “Creating Resource”  State. To handle this , I had to create a new function in my lambda Python code that returned the success/failure. As mentioned here: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html


问:
Combine Row Cell for Repeater Record
I'm trying to combine the row cells when the campaign code and vehicle no are repeated as shown in below image. The result listed below is with gridview 20 page size

Problem

When the grid view page size is set with 2 for example, the row cell no longer combined. The result show each separated record.

If campaign code is sorted ascending/descending, the last record row cells will always not combine even though the campaign code and vehicle no are matched. Below image shown campaign code sorted in ascending. So when the campaign code is sorted descending, all the CMP002 are combined, while the last record of CMP001 will not be combined as shown in below image anymore.

Code Behind

```<code> Private Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound

    For rowIndex As Integer = GV.Rows.Count - 2 To 0 Step -1

        Dim gvRow As GridViewRow = GV.Rows(rowIndex)
        Dim gvPreviousRow As GridViewRow = GV.Rows(rowIndex + 1)
        Dim sCurrCampaignCode As String = GV.DataKeys(rowIndex).Values("CAMPAIGN_CODE")
        Dim sCurrVehicleNo As String = GV.DataKeys(rowIndex).Values("VEHICLE_NO")
        Dim sPreviousCampaignCode As String = GV.DataKeys(rowIndex + 1).Values("CAMPAIG_CODE")
        Dim sPreviousVehicleNo As String = GV.DataKeys(rowIndex + 1).Values("VEHICLE_NO")

        If sCurrCampaignCode = sPreviousCampaignCode AndAlso sCurrVehicleNo = sPreviousVehicleNo Then

            If sCurrCampaignCode = sPreviousCampaignCode Then

                    If gvPreviousRow.Cells(1).RowSpan < 2 Then
                        gvRow.Cells(1).RowSpan = 2
                        gvRow.Cells(2).RowSpan = 2
                        gvRow.Cells(3).RowSpan = 2
                    Else
                        gvRow.Cells(1).RowSpan = gvPreviousRow.Cells(1).RowSpan + 1
                        gvRow.Cells(2).RowSpan = gvPreviousRow.Cells(2).RowSpan + 1
                        gvRow.Cells(3).RowSpan = gvPreviousRow.Cells(3).RowSpan + 1
                    End If

                    gvPreviousRow.Cells(1).Visible = False
                    gvPreviousRow.Cells(2).Visible = False
                    gvPreviousRow.Cells(3).Visible = False
            End If

        End If

    Next

End Sub
</code>```

答: I just found a solution. Code have to be moved from RowDataBound to OnDataBound instead</p>

Title: Combine Row Cell for Repeater Record

Body:
I'm trying to combine the row cells when the campaign code and vehicle no are repeated as shown in below image. The result listed below is with gridview 20 page size

Problem

When the grid view page size is set with 2 for example, the row cell no longer combined. The result show each separated record.

If campaign code is sorted ascending/descending, the last record row cells will always not combine even though the campaign code and vehicle no are matched. Below image shown campaign code sorted in ascending. So when the campaign code is sorted descending, all the CMP002 are combined, while the last record of CMP001 will not be combined as shown in below image anymore.

Code Behind

 Private Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound

    For rowIndex As Integer = GV.Rows.Count - 2 To 0 Step -1

        Dim gvRow As GridViewRow = GV.Rows(rowIndex)
        Dim gvPreviousRow As GridViewRow = GV.Rows(rowIndex + 1)
        Dim sCurrCampaignCode As String = GV.DataKeys(rowIndex).Values("CAMPAIGN_CODE")
        Dim sCurrVehicleNo As String = GV.DataKeys(rowIndex).Values("VEHICLE_NO")
        Dim sPreviousCampaignCode As String = GV.DataKeys(rowIndex + 1).Values("CAMPAIG_CODE")
        Dim sPreviousVehicleNo As String = GV.DataKeys(rowIndex + 1).Values("VEHICLE_NO")

        If sCurrCampaignCode = sPreviousCampaignCode AndAlso sCurrVehicleNo = sPreviousVehicleNo Then

            If sCurrCampaignCode = sPreviousCampaignCode Then

                    If gvPreviousRow.Cells(1).RowSpan < 2 Then
                        gvRow.Cells(1).RowSpan = 2
                        gvRow.Cells(2).RowSpan = 2
                        gvRow.Cells(3).RowSpan = 2
                    Else
                        gvRow.Cells(1).RowSpan = gvPreviousRow.Cells(1).RowSpan + 1
                        gvRow.Cells(2).RowSpan = gvPreviousRow.Cells(2).RowSpan + 1
                        gvRow.Cells(3).RowSpan = gvPreviousRow.Cells(3).RowSpan + 1
                    End If

                    gvPreviousRow.Cells(1).Visible = False
                    gvPreviousRow.Cells(2).Visible = False
                    gvPreviousRow.Cells(3).Visible = False
            End If

        End If

    Next

End Sub


问:
SWIG C++ bindings with callback
I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The data capture threads evidently start up and start hogging the CPU, but no debug lines from the callback come through. What would be better way to populate data buffers and easily access them from python ?

```<code>class KinectListener
{
     public:
        virtual ~KinectListener(){};
        virtual void KinectDisconnected(Kinect *K) {};
        virtual void DepthReceived(Kinect *K) {};
        virtual void ColorReceived(Kinect *K) {};
        virtual void AudioReceived(Kinect *K) {};
};
</code>```

Here is the listener class with the virtual methods, can the Python wrapped version of this class be used to inherit listeners for the c++ class ? I added a minimal listener in C++ and now the remaining work is to access the arrays efficiently with typemaps. Currently I am using this naive typemap

```<code>%typemap(out) unsigned short [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PyInt_FromLong((long)$1[i]);
    PyList_SetItem($result,i,o);
  }
}
</code>```

Better options ?

答:
By coincidence, I happen to be looking into callbacks with SWIG at the moment.

The SWIG 2.0 documentation says this:

SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language. ... However, existing C functions can be used as arguments provided you install them as constants. One way to do this is to use the %constant directive like this ...

I'm planning to write a C callback with hand-written JNI to call into Java. If there's another way, I would also love to hear it.

Title: SWIG C++ bindings with callback

Body:
I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The data capture threads evidently start up and start hogging the CPU, but no debug lines from the callback come through. What would be better way to populate data buffers and easily access them from python ?

class KinectListener
{
     public:
        virtual ~KinectListener(){};
        virtual void KinectDisconnected(Kinect *K) {};
        virtual void DepthReceived(Kinect *K) {};
        virtual void ColorReceived(Kinect *K) {};
        virtual void AudioReceived(Kinect *K) {};
};

Here is the listener class with the virtual methods, can the Python wrapped version of this class be used to inherit listeners for the c++ class ? I added a minimal listener in C++ and now the remaining work is to access the arrays efficiently with typemaps. Currently I am using this naive typemap

%typemap(out) unsigned short [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PyInt_FromLong((long)$1[i]);
    PyList_SetItem($result,i,o);
  }
}

Better options ?


问:
Can't write data to database
I am trying to write a simple application with PHP to write and receive data from a database. I am able to retrieve data already in the database through my PHP script, but I can not write anything to it. When I try, I do not get any errors - just the title of my script and a blank screen.

My code is as follows:

My HTML

```<code><form action="insert_book.php" method="post">

    <fieldset>
        <p><label for="ISBN">ISBN</label>
            <input type="text" id="ISBN" name="ISBN" maxlength="13" size="13" /></p>

        <p><label for="Author">Author</label>
            <input type="text" id="Author" name="Author" maxlength="30" size="30" /></p>

        <p><label for="Title">Title</label>
            <input type="text" id="Title" name="Title" maxlength="60" size="30" /></p>

        <p><label for="Price">Price</label>
            $ <input type="text" id="Price" name="Price" maxlength="7" size="7" /></p>
    </fieldset>
    <p><input type="submit" value="Add New Book" /></p>

</form>
</code>```

PHP

```<code><?php

if(!isset($_POST['ISBN']) || !isset($_POST['Author'])
 || !isset($_POST['Title']) || !isset($_POST['Price'])) {
    echo "<p>You have not entered all the details.<br/>
    Go back and try again.</p>";
    exit;
}

// create short variable names
$isbn=$_POST['ISBN'];
$author=$_POST['Author'];
$title=$_POST['Title'];
$price=$_POST['Price'];
$price = doubleval($price);

@$db = new mysqli('localhost', 'jay', '******', 'Books');

if (msqli_connect_errno()) {
    echo '<p>Error: Could not connect to database.<br/>
    Please try again.</p>';
    exit;
}

$query = "INSERT INTO Books VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('sssd', $isbn, $author, $title, $price);
$stmt->execute();

if ($stmt->affected_rows > 0) {
    echo '<p>Submission successful.</p>';
} else {
    echo '<p>An Aweful error occured.<br/>
    Nothing was added.</p>';
}

$db->close();

?>
</code>```

Please let me know if you can see any issues.
Thanks!

答:
You have an error in this line:

```<code>if (msqli_connect_errno()) {
</code>```

It should be

```<code>if (mysqli_connect_errno()) {
</code>```

You missed a y.

Title: Can't write data to database

Body:
I am trying to write a simple application with PHP to write and receive data from a database. I am able to retrieve data already in the database through my PHP script, but I can not write anything to it. When I try, I do not get any errors - just the title of my script and a blank screen.

My code is as follows:

My HTML

<form action="insert_book.php" method="post">

    <fieldset>

ISBN
            <input type="text" id="ISBN" name="ISBN" maxlength="13" size="13" />

Author
            <input type="text" id="Author" name="Author" maxlength="30" size="30" />

Title
            <input type="text" id="Title" name="Title" maxlength="60" size="30" />

Price
            $ <input type="text" id="Price" name="Price" maxlength="7" size="7" />

    </fieldset>

<input type="submit" value="Add New Book" />

</form>

PHP

<?php

if(!isset($_POST['ISBN']) || !isset($_POST['Author'])
 || !isset($_POST['Title']) || !isset($_POST['Price'])) {
    echo "
You have not entered all the details.

    Go back and try again.
";
    exit;
}

// create short variable names
$isbn=$_POST['ISBN'];
$author=$_POST['Author'];
$title=$_POST['Title'];
$price=$_POST['Price'];
$price = doubleval($price);

@$db = new mysqli('localhost', 'jay', '******', 'Books');

if (msqli_connect_errno()) {
    echo '
Error: Could not connect to database.

    Please try again.
';
    exit;
}

$query = "INSERT INTO Books VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('sssd', $isbn, $author, $title, $price);
$stmt->execute();

if ($stmt->affected_rows > 0) {
    echo '
Submission successful.
';
} else {
    echo '
An Aweful error occured.

    Nothing was added.
';
}

$db->close();

?>

Please let me know if you can see any issues.
Thanks!

Body:
You have an error in this line:

if (msqli_connect_errno()) {

It should be

if (mysqli_connect_errno()) {

You missed a y.