问:
C - Segmentation fault after freeing dynamically allocated array
I'm trying to create dynamically allocated array of clusters, where every cluster has its own dynamically allocated array of points.

```<code>typedef struct Point
{
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
}Point;

typedef struct Cluster
{
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
}Cluster;
</code>```

I am able to initialize clusters array and populate it with this function:

```<code>void fill_array(Cluster **arr, int how_many_clusters)
{
    *arr = (Cluster *)malloc(sizeof(Cluster) * how_many_clusters);

    for(int i = 0; i < how_many_clusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        (*arr)[i].points = (Point *)malloc(sizeof(Point));
        (*arr)[i].points[i] = point;
    }
}
</code>```

In main I want to create the array, fill it with function mentioned before and then free it.

```<code>int main ()
{
    Cluster *clusters;
    int clusters_count = 20;
    fill_array(&cluters, clusters_count);

    for(int i = clusters_count - 1; i >= 0; i--)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free(clusters);

    return 0;
}
</code>```

When I compile and run this program, it crashes at second iteration of freeing with segmentation fault. I have spent last 2 days digging through the internet, but didn't find anything about what I'm doing wrong.
Can anyone point out where is the mistake I can't see?

答:
There is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?. malloc returns void * compatible with any pointer. A cast can only serve to muddy the waters. Simply allocate your pointer points and then call sizeof on the dereferenced pointer, e.g.:

```<code>(*arr)[i].points = malloc (sizeof *(*arr)[i].points);
</code>```

While a correct statement for the allocation, it wholly fails to validate the allocation succeeds, instead, check the return from malloc is not NULL, e.g.

```<code>         if (!((*arr)[i].points = malloc (sizeof *(*arr)[i].points))) {
            perror ("malloc failed - points");
            exit (EXIT_FAILURE);
        }
</code>```

The same for the allocation of *arr, e.g.

```<code>    if (!(*arr = malloc (sizeof **arr * nclusters))) {
        perror ("malloc failed - nclusters");
        exit (EXIT_FAILURE);
    }
</code>```

(note: how_many_clusters was shortened to nclusters, we are not writing a novel)

Your primary problem is:

```<code>        (*arr)[i].points[i] = point;
</code>```

You only allocate memory for one Point struct, therefore points[i] makes no sense at all. You allocated sizeof(Point) -- how many of them do you think there are?

Since your goal is to copy point to the newly allocated block of memory at the address held by the pointer (*arr)[i].points, "How Do You Access (or Set) the value Referenced (e.g. Pointed-to) by a Pointer?" (Answer:, you dereference the pointer to obtain the value).

That's all you need do here. No additional [..] tacked on the end to dereference (*arr)[i].points, just dereference it with the unary '*', e.g.

```<code>        *(*arr)[i].points = point;  /* copy struct to allocated memory */
</code>```

Putting the pieces altogether, you can do something like the following:

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
} Point;

typedef struct {
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
} Cluster;

void fill_array (Cluster **arr, int nclusters)
{
    if (!(*arr = malloc (sizeof **arr * nclusters))) {
        perror ("malloc failed - nclusters");
        exit (EXIT_FAILURE);
    }
    for (int i = 0; i < nclusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        if (!((*arr)[i].points = malloc (sizeof *(*arr)[i].points))) {
            perror ("malloc failed - points");
            exit (EXIT_FAILURE);
        }
        *(*arr)[i].points = point;  /* copy struct to allocated memory */
    }
}

int main (void) {

    Cluster *clusters;
    int clusters_count = 20;

    fill_array (&clusters, clusters_count);

    for(int i = 0; i < clusters_count; i++)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free (clusters);

    return 0;
}
</code>```

(note: you do not have to free each clusters[i].points in reverse order. (it's not wrong, there is just no need to go out of your way to do it). Just free them as you work your way through the loop.)

Example Use/Validation

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

```<code>$ valgrind ./bin/fillclusters_alloc
==26217== Memcheck, a memory error detector
==26217== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==26217== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==26217== Command: ./bin/fillclusters_alloc
==26217==
==26217==
==26217== HEAP SUMMARY:
==26217==     in use at exit: 0 bytes in 0 blocks
==26217==   total heap usage: 21 allocs, 21 frees, 560 bytes allocated
==26217==
==26217== All heap blocks were freed -- no leaks are possible
==26217==
==26217== For counts of detected and suppressed errors, rerun with: -v
==26217== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions.

Body:
I'm trying to create dynamically allocated array of clusters, where every cluster has its own dynamically allocated array of points.

typedef struct Point
{
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
}Point;

typedef struct Cluster
{
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
}Cluster;

I am able to initialize clusters array and populate it with this function:

void fill_array(Cluster **arr, int how_many_clusters)
{
    *arr = (Cluster *)malloc(sizeof(Cluster) * how_many_clusters);

    for(int i = 0; i < how_many_clusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        (*arr)[i].points = (Point *)malloc(sizeof(Point));
        (*arr)[i].points[i] = point;
    }
}

In main I want to create the array, fill it with function mentioned before and then free it.

int main ()
{
    Cluster *clusters;
    int clusters_count = 20;
    fill_array(&cluters, clusters_count);

    for(int i = clusters_count - 1; i >= 0; i--)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free(clusters);

    return 0;
}

When I compile and run this program, it crashes at second iteration of freeing with segmentation fault. I have spent last 2 days digging through the internet, but didn't find anything about what I'm doing wrong.
Can anyone point out where is the mistake I can't see?

Body:
There is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?. malloc returns void * compatible with any pointer. A cast can only serve to muddy the waters. Simply allocate your pointer points and then call sizeof on the dereferenced pointer, e.g.:

(*arr)[i].points = malloc (sizeof *(*arr)[i].points);

While a correct statement for the allocation, it wholly fails to validate the allocation succeeds, instead, check the return from malloc is not NULL, e.g.

         if (!((*arr)[i].points = malloc (sizeof *(*arr)[i].points))) {
            perror ("malloc failed - points");
            exit (EXIT_FAILURE);
        }

The same for the allocation of *arr, e.g.

    if (!(*arr = malloc (sizeof **arr * nclusters))) {
        perror ("malloc failed - nclusters");
        exit (EXIT_FAILURE);
    }

(note: how_many_clusters was shortened to nclusters, we are not writing a novel)

Your primary problem is:

        (*arr)[i].points[i] = point;

You only allocate memory for one Point struct, therefore points[i] makes no sense at all. You allocated sizeof(Point) -- how many of them do you think there are?

Since your goal is to copy point to the newly allocated block of memory at the address held by the pointer (*arr)[i].points, "How Do You Access (or Set) the value Referenced (e.g. Pointed-to) by a Pointer?" (Answer:, you dereference the pointer to obtain the value).

That's all you need do here. No additional [..] tacked on the end to dereference (*arr)[i].points, just dereference it with the unary '*', e.g.

        *(*arr)[i].points = point;  /* copy struct to allocated memory */

Putting the pieces altogether, you can do something like the following:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
} Point;

typedef struct {
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
} Cluster;

void fill_array (Cluster **arr, int nclusters)
{
    if (!(*arr = malloc (sizeof **arr * nclusters))) {
        perror ("malloc failed - nclusters");
        exit (EXIT_FAILURE);
    }
    for (int i = 0; i < nclusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        if (!((*arr)[i].points = malloc (sizeof *(*arr)[i].points))) {
            perror ("malloc failed - points");
            exit (EXIT_FAILURE);
        }
        *(*arr)[i].points = point;  /* copy struct to allocated memory */
    }
}

int main (void) {

    Cluster *clusters;
    int clusters_count = 20;

    fill_array (&clusters, clusters_count);

    for(int i = 0; i < clusters_count; i++)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free (clusters);

    return 0;
}

(note: you do not have to free each clusters[i].points in reverse order. (it's not wrong, there is just no need to go out of your way to do it). Just free them as you work your way through the loop.)

Example Use/Validation

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/fillclusters_alloc
==26217== Memcheck, a memory error detector
==26217== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==26217== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==26217== Command: ./bin/fillclusters_alloc
==26217==
==26217==
==26217== HEAP SUMMARY:
==26217==     in use at exit: 0 bytes in 0 blocks
==26217==   total heap usage: 21 allocs, 21 frees, 560 bytes allocated
==26217==
==26217== All heap blocks were freed -- no leaks are possible
==26217==
==26217== For counts of detected and suppressed errors, rerun with: -v
==26217== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions.


来源: stackexchange

问:
Php error in code while updating the data in sql
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

```<code> <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

The HTML code is:

```<code>  <html>
    <head>
        <title>Edit Data</title>
    </head>

    <body>
        <a href="index.php">Home</a>
        <br/><br/>

        <form name="form1" method="post" action="update.php">
            <table border="0">
                <tr>
                    <td>Name</td>
                    <td><input type="text" name="name" value="<?php echo $name;?>"></td>
                </tr>
                <tr>
                    <td>address</td>
                    <td><input type="text" name="address" value="<?php echo $address;?>"></td>
                </tr>

                <tr>
                   <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                    <td><input type="submit" name="update" value="Update"></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
</code>```

答:
Please replace below line

```<code><td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
</code>```

by

```<code><td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
</code>```

You missed "" in value attribute.

Edit:
After correction your HTML will be correct and then please check $id=$_GET['update']; its not defined I think you need to correct it as $id=$_POST['id'];

ContentLicense: CC BY-SA 3.0

Body:
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

 <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

The HTML code is:

        <title>Edit Data</title>

        Home

        <form name="form1" method="post" action="update.php">

                    Name
                    <input type="text" name="name" value="<?php echo $name;?>">

                    address
                    <input type="text" name="address" value="<?php echo $address;?>">

                   <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                    <input type="submit" name="update" value="Update">

        </form>

Body:
Please replace below line

<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>

by

<td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>

You missed "" in value attribute.

Edit:
After correction your HTML will be correct and then please check $id=$_GET['update']; its not defined I think you need to correct it as $id=$_POST['id'];


问:
How should I name my CSS classes?
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

```<code>.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
</code>```

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

答:
It's just naming, so it's up to you what you like. Either of your examples would work fine. Just pick one and stick to it.

The three first selectors addresses single elements, the fourth addresses a single element with two classes, the fifth addresses an element inside another, and the sixth does the same but with the inner ellement having two classes.

I would probably put class="Vote" on the surronding element, and out class="count" on the count element inside it to address it. I use pascal case for surrounding elements and lowercase for child elements inside them, so I would use:

```<code>.Vote .count
</code>```

ContentLicense: CC BY-SA 2.5

Title: How should I name my CSS classes?

Body:
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

Body:
It's just naming, so it's up to you what you like. Either of your examples would work fine. Just pick one and stick to it.

The three first selectors addresses single elements, the fourth addresses a single element with two classes, the fifth addresses an element inside another, and the sixth does the same but with the inner ellement having two classes.

I would probably put class="Vote" on the surronding element, and out class="count" on the count element inside it to address it. I use pascal case for surrounding elements and lowercase for child elements inside them, so I would use:

.Vote .count


问:
ValueError: not enough values to unpack (expected 2, got 1) -Ask Expert project using tkinter
I know that this question has been asked before, which is why I've checked the internet before posting this question. I tried all sorts of solutions, including if len(line.split())<2: continue, but none of it worked. So if any of you know some solution that I may have not tried yet please let me know. Thank You in advance.

Here is my python code. By the way I am using Python 3.6.0.

```<code>    from tkinter import Tk, simpledialog, messagebox

def read_from_file():

    with open('capital_data.txt') as file:
        for line in file:
            line=line.rstrip('\n')
            country, city = line.split('/')
            the_world[country]=city

def write_to_file(country_name, city_name):
    with open('capital_data.txt','a') as file:
        file.write('\n' + country_name + '/' + city_name)

print('Ask The Expert-Capital Cities Of The World')
root=Tk()
root.withdraw()
the_world={}

read_from_file()

while True:
    query_country = simpledialog.askstring('Country', 'Type the name of the country: ')

    if query_country in the_world:
        result = the_world[query_country]

        messagebox.showinfo('Answer',
                            'The capital city of ' + query_country + ' is ' + result + '!')
    else:
        new_city = simpledialog.askstring('Teach me',
                                          'I don\'t know!' +
                                          'What is the capital city of ' + query_country + '?')
        the_world[query_country] = new_city
        write_to_file(query_country, new_city)
</code>```

答:
One of the lines in capital_data.txt does not contain a /. As a result, the line: country, city = line.split('/') is not able to provide you two values. Either your data is not correct as expected by your code, or you should adjust your code to deal with a varying number of elements generated by that line.

One approach could be something like row_data = line.split('/') and then you operate on that based on how many elements are returned.

Another approach is a try/except statement to handle erroneous rows:

```<code>try:
    country, city = line.split('/')
except ValueError:
    # code to handle the error
</code>```

Body:
I know that this question has been asked before, which is why I've checked the internet before posting this question. I tried all sorts of solutions, including if len(line.split())<2: continue, but none of it worked. So if any of you know some solution that I may have not tried yet please let me know. Thank You in advance.

Here is my python code. By the way I am using Python 3.6.0.

    from tkinter import Tk, simpledialog, messagebox

def read_from_file():

    with open('capital_data.txt') as file:
        for line in file:
            line=line.rstrip('\n')
            country, city = line.split('/')
            the_world[country]=city

def write_to_file(country_name, city_name):
    with open('capital_data.txt','a') as file:
        file.write('\n' + country_name + '/' + city_name)

print('Ask The Expert-Capital Cities Of The World')
root=Tk()
root.withdraw()
the_world={}

read_from_file()

while True:
    query_country = simpledialog.askstring('Country', 'Type the name of the country: ')

    if query_country in the_world:
        result = the_world[query_country]

        messagebox.showinfo('Answer',
                            'The capital city of ' + query_country + ' is ' + result + '!')
    else:
        new_city = simpledialog.askstring('Teach me',
                                          'I don\'t know!' +
                                          'What is the capital city of ' + query_country + '?')
        the_world[query_country] = new_city
        write_to_file(query_country, new_city)

Body:
One of the lines in capital_data.txt does not contain a /. As a result, the line: country, city = line.split('/') is not able to provide you two values. Either your data is not correct as expected by your code, or you should adjust your code to deal with a varying number of elements generated by that line.

One approach could be something like row_data = line.split('/') and then you operate on that based on how many elements are returned.

Another approach is a try/except statement to handle erroneous rows:

try:
    country, city = line.split('/')
except ValueError:
    # code to handle the error


问:
Fibonacci Modified:How to fix this algorithm?
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

```<code>public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}
</code>```

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

答:
Non-recursive|Memoized
You should not use recursion since it will not be good in performance.
Use memoization instead.

```<code>def FibonacciModified(n):
    fib = [0]*n
    fib[0],fib[1]=0,1
    for idx in range(2,n):
        fib[idx] = fib[idx-1]**2 + fib[idx-2]**2
    return fib

if __name__ == '__main__':
    fib = FibonacciModified(8)
    for x in fib:
        print x
</code>```

Output:

```<code>0
1
1
2
5
29
866
750797
</code>```

The above will calculate every number in the series once[not more than that].
While in recursion an element in the series will be calculated multiple times irrespective of the fact that the number was calculated before.

http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/

Body:
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

Body:
Non-recursive|Memoized
You should not use recursion since it will not be good in performance.
Use memoization instead.

def FibonacciModified(n):
    fib = [0]*n
    fib[0],fib[1]=0,1
    for idx in range(2,n):
        fib[idx] = fib[idx-1]**2 + fib[idx-2]**2
    return fib

if __name__ == '__main__':
    fib = FibonacciModified(8)
    for x in fib:
        print x

Output:

0
1
1
2
5
29
866
750797

The above will calculate every number in the series once[not more than that].
While in recursion an element in the series will be calculated multiple times irrespective of the fact that the number was calculated before.

http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/


问:
React native-fbsdk unknown issue?
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}
</code>```

And here is my android/app/build.gradle

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
</code>```

How can I solve this issue? Any help on this?

答:
Seems like your issue was caused by new release facebook-sdk-4.29.0 You need to limit this dependency by 4.28.0 version. The optimal solution would be to add to your {project_root}/android/build.gradle

```<code>def versionOverrides = [
  "com.facebook.android:facebook-android-sdk": "4.28.0",
]

allprojects {
  /* your original repository dependencies here... */
  configurations.all {

    resolutionStrategy.eachDependency { DependencyResolveDetails details ->

      def overrideVersion = versionOverrides[details.requested.group + ":" + details.requested.name]

      if (overrideVersion != null && details.requested.version != overrideVersion) {
        println("********************************************************")
        println("Overriding dependency ${details.requested.group}:${details.requested.name} version ${details.requested.version} --> $overrideVersion")
        details.useVersion overrideVersion
        println("********************************************************")
      }
    }
  }
}
</code>```

Title: React native-fbsdk unknown issue?

Body:
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

And here is my android/app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

How can I solve this issue? Any help on this?

Body:
Seems like your issue was caused by new release facebook-sdk-4.29.0 You need to limit this dependency by 4.28.0 version. The optimal solution would be to add to your {project_root}/android/build.gradle

def versionOverrides = [
  "com.facebook.android:facebook-android-sdk": "4.28.0",
]

allprojects {
  /* your original repository dependencies here... */
  configurations.all {

    resolutionStrategy.eachDependency { DependencyResolveDetails details ->

      def overrideVersion = versionOverrides[details.requested.group + ":" + details.requested.name]

      if (overrideVersion != null && details.requested.version != overrideVersion) {
        println("********************************************************")
        println("Overriding dependency ${details.requested.group}:${details.requested.name} version ${details.requested.version} --> $overrideVersion")
        details.useVersion overrideVersion
        println("********************************************************")
      }
    }
  }
}


答:
I vote for (1) to always use lower case for your CSS. That way you don't have to remember where you capitalize stuff. So that eliminates (2) and (3).

(5) is really two different elements so can't apply to a single element.

(4) and (6) are invalid for a single element. (4) assumes you are applying two classes to the same element such as class='vote count-post'. (6) is a combination of (4) and (5).

Title: How should I name my CSS classes?


问:
Fast element access for multi-dimensional representation of contiguous array
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

```<code>template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};
</code>```

So if I initialize this class and attempted to access an element, it would look something like this:

```<code>my_array = MultiArray<4>();
element = my_array(2,5,4,1);
</code>```

How might I go about doing this using templates? Is this even possible?

答:
It seems to me that you could use Boost.MultiArray, boost::multi_array_ref to be more specific. boost::multi_array_ref does exactly what you want: it wraps continuous data array into an object that may be treated as a multidimensional array. You may also use boost::multi_array_ref::array_view for slicing purposes.

I cannot provide you with any benchmark results, but from my experience, I can say that boost::multi_array_ref works pretty fast.

Body:
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};

So if I initialize this class and attempted to access an element, it would look something like this:

my_array = MultiArray<4>();
element = my_array(2,5,4,1);

How might I go about doing this using templates? Is this even possible?


问:
Add query string to all pages after user logged in wordpress
I need to add query string to all pages including homepage.after user logged in. as example after user logged in homepage url need to look like domain.com?aff=1234567 and other links also modify with custom query string such as page domain.com?p=1&aff=1234567

anyone has idea how to do this or how can i use wp_redirect for this

答:
add following code to functions.php,

```<code>add_action('wp_head', 'your_function');
function your_function(){
    if ( is_user_logged_in() ) {
        $genre_url = add_query_arg('aff', '1234567', get_permalink());
    }
}
</code>```

Hope this will help you.
for more information,

is_user_logged_in()

How can I include a query string with get_permalink

wp_head action hook

get_permalink()

Body:
add following code to functions.php,

add_action('wp_head', 'your_function');
function your_function(){
    if ( is_user_logged_in() ) {
        $genre_url = add_query_arg('aff', '1234567', get_permalink());
    }
}

Hope this will help you.
for more information,

is_user_logged_in()

How can I include a query string with get_permalink

wp_head action hook

get_permalink()


问:
How are data types interpreted, calculated, and/or stored?
In python, suppose the code is:</p>

```<code>import.math

a = math.sqrt(2.0)

if a * a == 2.0:
    x = 2
else:
    x = 1
</code>```

答:
This is a variant of "Floating Point Numbers are Approximations -- Not Exact".

Mathematically speaking, you are correct that sqrt(2) * sqrt(2) == 2.  But sqrt(2) can not be exactly represented as a native datatype (read: floating point number).  (Heck, the sqrt(2) is actually guaranteed to be an infinite decimal!). It can get really close, but not exact:

```<code>>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(2) * math.sqrt(2)
2.0000000000000004
</code>```

Note the result is, in fact, not exactly 2.

If you want the x = 2 branch to execute, you will need to use an epsilon value of "is the result close enough?":

```<code>epsilon = 1e-6    # 0.000001
if abs(2.0 - a*a) < epsilon:
    x = 2
else:
    x = 1
</code>```

Body:
In python, suppose the code is:

import.math

a = math.sqrt(2.0)

if a * a == 2.0:
    x = 2
else:
    x = 1

Body:
This is a variant of "Floating Point Numbers are Approximations -- Not Exact".

Mathematically speaking, you are correct that sqrt(2) * sqrt(2) == 2.  But sqrt(2) can not be exactly represented as a native datatype (read: floating point number).  (Heck, the sqrt(2) is actually guaranteed to be an infinite decimal!). It can get really close, but not exact:

>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(2) * math.sqrt(2)
2.0000000000000004

Note the result is, in fact, not exactly 2.

If you want the x = 2 branch to execute, you will need to use an epsilon value of "is the result close enough?":

epsilon = 1e-6    # 0.000001
if abs(2.0 - a*a) < epsilon:
    x = 2
else:
    x = 1


问:
Create multiple folders with files inside
I am trying to create a simple CLI that will create a folder structure and some files. The structure would look something like this:

```<code>app-name
├── app.py
├── models.py
├── static
│   ├── css
│   ├── img
│   └── js
├── templates
└── views.py
</code>```

I have taken a look at the mkdirp library, but I realized I would have to chain the mkdirp() function for each folder I am trying to make and then use the fs module to create the individual files.

What I have tried so far is to chain the mkdirp() functions back-to-back for each folder that I am trying to create.

```<code>const path = require('path');
const mkdirp = require('mkdirp-promise');

mkdirp(path.join(__dirname, 'app-name', 'static', 'css'))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'js')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'img')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'templates')))
    .then(console.log)
    .catch(console.error);
</code>```

This approach doesn't seem to be very efficient, especially with different types of arguments that could be passed to the CLI.

I have thought about creating a folder that has the entire folder structure in it as well as the contents of the Python files, then just copy those files. But I am unsure if this is doable.

What would be a good approach to creating this folder and file hierarchy?

答:
This does exactly what you want based on your input (this might not be the best approach if the structure is provided by the user):

```<code>const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

function createDirectory(dirPath) {

  return promisify(fs.mkdir)(dirPath);

}

function createFile(filePath, content) {

  return promisify(fs.writeFile)(filePath, content, 'utf-8');

}

function scaffoldProject(projectName) {

  createDirectory(path.join(__dirname, projectName))
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'templates'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'css'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'img'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'js'));

  })
  .then(() => {

    // Last argument is the app.py's content
    return createFile(path.join(__dirname, projectName, 'app.py'), '');

  })
  .then(() => {

    // Last argument is the models.py's content
    return createFile(path.join(__dirname, projectName, 'models.py'), '');

  })
  .then(() => {

    // Last argument is the views.py's content
    return createFile(path.join(__dirname, projectName, 'views.py'), '');

  })
  .then(() => {

    console.log(`Project ${projectName} was successfully scaffolded at ${path.join(__dirname, projectName)}`);

  })
  .catch(error => {

    console.log(error);

  });

}

// Replace 'test-project' with user input
scaffoldProject('test-project');
</code>```

This uses the fs module and turns it's callback API into a Promise API (promisifies). You call createDirectory or createFile and chain then using .then() to control the flow. The .catch() catches any errors thrown in the chain.

Body:
I am trying to create a simple CLI that will create a folder structure and some files. The structure would look something like this:

app-name
├── app.py
├── models.py
├── static
│   ├── css
│   ├── img
│   └── js
├── templates
└── views.py

I have taken a look at the mkdirp library, but I realized I would have to chain the mkdirp() function for each folder I am trying to make and then use the fs module to create the individual files.

What I have tried so far is to chain the mkdirp() functions back-to-back for each folder that I am trying to create.

const path = require('path');
const mkdirp = require('mkdirp-promise');

mkdirp(path.join(__dirname, 'app-name', 'static', 'css'))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'js')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'static', 'img')))
    .then(mkdirp(path.join(__dirname, 'app-name', 'templates')))
    .then(console.log)
    .catch(console.error);

This approach doesn't seem to be very efficient, especially with different types of arguments that could be passed to the CLI.

I have thought about creating a folder that has the entire folder structure in it as well as the contents of the Python files, then just copy those files. But I am unsure if this is doable.

What would be a good approach to creating this folder and file hierarchy?

Body:
This does exactly what you want based on your input (this might not be the best approach if the structure is provided by the user):

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

function createDirectory(dirPath) {

  return promisify(fs.mkdir)(dirPath);

}

function createFile(filePath, content) {

  return promisify(fs.writeFile)(filePath, content, 'utf-8');

}

function scaffoldProject(projectName) {

  createDirectory(path.join(__dirname, projectName))
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'templates'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'css'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'img'));

  })
  .then(() => {

    return createDirectory(path.join(__dirname, projectName, 'static', 'js'));

  })
  .then(() => {

    // Last argument is the app.py's content
    return createFile(path.join(__dirname, projectName, 'app.py'), '');

  })
  .then(() => {

    // Last argument is the models.py's content
    return createFile(path.join(__dirname, projectName, 'models.py'), '');

  })
  .then(() => {

    // Last argument is the views.py's content
    return createFile(path.join(__dirname, projectName, 'views.py'), '');

  })
  .then(() => {

    console.log(`Project ${projectName} was successfully scaffolded at ${path.join(__dirname, projectName)}`);

  })
  .catch(error => {

    console.log(error);

  });

}

// Replace 'test-project' with user input
scaffoldProject('test-project');

This uses the fs module and turns it's callback API into a Promise API (promisifies). You call createDirectory or createFile and chain then using .then() to control the flow. The .catch() catches any errors thrown in the chain.


Title: Replace duplicate results with blank

Body:
I am looking to omit duplicate lines of data from my results list.

declare @Table1 TABLE(
    ID int not null,
    OrderNo varchar(5) not null)

declare @Table2 TABLE(
    OrderID int not null,
    Invoice varchar(7) not null)

declare @Table3 TABLE(
    OrderID int not null,
    Payment varchar(7) not null)

insert into @Table1 values (1,'14598'),(2,'14599'),(3,'14600'),(4,'14601')
insert into @Table2 values (1,'35.01'),(1,'396.90'),(1,'79.00'),(2,'786.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')
insert into @Table3 values (1,'20.50'),(1,'180.00'),(2,'786.20'),(2,'15.20'),(2,'186.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')

select t1.ID, t2.Invoice, t3.Payment from @Table1 t1
join @Table2 t2 on t2.OrderID = t1.ID
join @Table3 t3 on t3.OrderID = t1.ID

Table data:

Table1
ID |  OrderNo
-------------
1  |  14598
2  |  14599
3  |  14600
4  |  14601

Table2
OrderID |  Invoice
------------------
1       |   35.01
1       |  396.90
1       |   79.00
2       |  786.20
3       |   40.00
3       |   93.60
3       |   43.60
4       |   15.08

Table3
OrderID | Payment
-----------------
1       |   20.50
1       |  180.00
2       |  786.20
2       |   15.20
2       |  186.20
3       |   40.00
3       |   93.60
3       |   43.60
4       |   15.08

When I try joining all three of these tables together, I get the following:

ID | Invoice | Payment
----------------------
1  | 35.01   | 20.50
1  | 35.01   |180.00
1  | 396.90  | 20.50
1  | 396.90  |180.00
1  | 79.00   | 20.50
1  | 79.00   |180.00
2  | 786.20  |786.20
2  | 786.20  | 15.20
2  | 786.20  |186.20
3  | 40.00   | 40.00
3  | 40.00   | 93.60
3  | 40.00   | 43.60
3  | 93.60   | 40.00
3  | 93.60   | 93.60
3  | 93.60   | 43.60
3  | 43.60   | 40.00
3  | 43.60   | 93.60
3  | 43.60   | 43.60
4  | 15.08   | 15.08

Now as you can see, order 2 only has a single invoice in Table2, however has 3 payments in Table3.  I do want to display 3 lines, with each of the Payments on a separate line, however I don't want it to repeat the single Invoice on each subsequent line.

Subsequently with order 1, there are 3 invoices in Table2, however only 2 payments in Table3.  Currently it is showing everything from Table3 for each entry in Table2, resulting in 6 lines instead of 3.

I only want to report on each amount once, with subsequent lines (if generated due to more than the number of results being in another table) showing blanks.  Selecting DISTINCT doesn't accomplish this.  Is there any way of achieving what I am after here?

ID | Invoice | Payment
----------------------
1  | 35.01   | 20.50
1  | 396.90  | 180.00
1  | 79.00   |
2  | 786.20  | 786.20
2  |         | 15.20
2  |         | 186.20

Body:
        declare @Table1 TABLE(
            ID int not null,
            OrderNo varchar(5) not null)

        declare @Table2 TABLE(
            OrderID int not null,
            Invoice varchar(7) not null)

        declare @Table3 TABLE(
            OrderID int not null,
            Payment varchar(7) not null)

        insert into @Table1 values (1,'14598'),(2,'14599'),(3,'14600'),(4,'14601')
        insert into @Table2 values (1,'35.01'),(1,'396.90'),(1,'79.00'),(2,'786.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')
        insert into @Table3 values (1,'20.50'),(1,'180.00'),(2,'786.20'),(2,'15.20'),(2,'186.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')

        select isnull(t2.OrderID,t3.OrderID) AS ID,t2.Invoice,
        t3.Payment
        from
         @Table1 t1
        join (select *,Row_number()over(partition by OrderID  order by (select 1))rn from @Table2) t2 on t2.OrderID = t1.ID
        full join
       (select *,Row_number()over(partition by OrderID  order by (select 1))rn2 from @Table3) t3
              on t3.OrderID = t2.OrderID and t2.rn=t3.rn2 ;

    ----------------------
    ID  Invoice Payment
    -----------------------
    1   35.01   20.50
    1   396.90  180.00
    1   79.00   NULL
    2   786.20  786.20
    2   NULL    15.20
    2   NULL    186.20
    3   40.00   40.00
    3   93.60   93.60
    3   43.60   43.60
    4   15.08   15.08


问:
nav bar won't display horizontally when fully expanded in the browser
I am trying to get my nav bar to display horizontally in a line at the top of my web page below my h1 tag. I tried all sorts of different methods to get it to line up horizontally but it won't change. My nav bar continues to display vertically centered. I want it to be a thin bar up at the top below the h1. As of right now, it displays with each li stacked on top of the other instead of side by side. Any help or ideas are appreciated.

#wrapper{
        background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {
        background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;
        }

main {
        margin-left: 180px;
        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 100%;
    }
li a {
   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}
nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }
 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid ;
    text-align: right;
    display:inline-block;
}
nav a{
        text-decoration: none;
        border: 1px solid;
        width: 100%
        }
nav a:link{color:cyan;}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<header>
<h1>Polar Bar</h1>
<nav>
<ul>
<li>Home</li>
<li>Menu</li>
<li>About Us</li>
<li>Contact</li>
<li>Social</li>
</ul>
</nav></code>```

答:
I don't understand your question. what did you want?.But Is this you want?

#wrapper{   background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;}

main {margin-left: 180px;

        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 98% !important;

}

li a {

   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}

nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }

 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid;
    text-align: right;
    display: inline-block;
}
nav > ul > li {
    float: left;
    display: inline-block;
}
nav a{text-decoration: none;
        border: 1px solid;
      }

nav a:link{color:cyan;
}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<header>
<h1>Polar Bar</h1>
<nav>
<ul>
<li>Home</li>
<li>Menu</li>
<li>About Us</li>
<li>Contact</li>
<li>Social</li>
</ul>
</nav>
  </header>
</div></code>```

Body:
I am trying to get my nav bar to display horizontally in a line at the top of my web page below my h1 tag. I tried all sorts of different methods to get it to line up horizontally but it won't change. My nav bar continues to display vertically centered. I want it to be a thin bar up at the top below the h1. As of right now, it displays with each li stacked on top of the other instead of side by side. Any help or ideas are appreciated.

#wrapper{
        background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {
        background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;
        }

main {
        margin-left: 180px;
        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 100%;
    }
li a {
   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}
nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }
 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid ;
    text-align: right;
    display:inline-block;
}
nav a{
        text-decoration: none;
        border: 1px solid;
        width: 100%
        }
nav a:link{color:cyan;}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}

Polar Bar

Home

Menu

About Us

Contact

Social

Body:
I don't understand your question. what did you want?.But Is this you want?

#wrapper{   background-color: #FFFFFF;
        color: #000066;
        min-width: 700px;
        max-width: 1024px;
        margin-right: auto;
        margin-left: auto;
        padding-top: 0px;
        }

h1 {background-color: darkcyan;
        color: #74ebd5;
        background-position: center;
        background-repeat: no-repeat;
        text-align: center;
        font-size: 3em;
        line-height: 80%;
        padding: 30px;
        text-shadow: #CCCCCC;
        margin-bottom: 0;}

main {margin-left: 180px;

        padding-bottom: 100px;
        }

ul {
    list-style-type: none;
    margin: 0;
    padding: 10px;
    overflow: hidden;
    background-color: #333;
    width: 98% !important;

}

li a {

   display: block;
    color: white;
    text-align: center;
    padding: 14px 20px;
    text-decoration: none;
}

nav{    display:inline-block;
        width: 100%;
        font-weight: bold;
        background-color: grey;
        }

 nav ul {
    list-style: none;
    width: 100%;
    border: 1px solid;
    text-align: right;
    display: inline-block;
}
nav > ul > li {
    float: left;
    display: inline-block;
}
nav a{text-decoration: none;
        border: 1px solid;
      }

nav a:link{color:cyan;
}
nav a:visited{color:#6699FF;}
nav a:hover{color: gold;}

<div id="wrapper">
<header>
<h1>Polar Bar</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="menu.html">Menu</a></li>
<li><a href="aboutus.html">About Us</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="social.html">Social</a></li>
</ul>
</nav>
  </header>
</div>


问:
how to implment click-once submit button in asp.net mvc 2?
I need to implement a click-once button for my asp.net mvc 2 application. I have just a very simple submit form, and when the user clicks on the submit button, I need to change its image to a "please wait..." type of graphics and disables the click event for further submits until the server comes back.

Is there an example or code snippet for this? I used to be able to do it in the asp.net webforms, but that technique does not apply here.

thanks!

答:
To disable the submit button when you submit the form you can use the onSubmit function for the form and call a javascript function that will disable the button.

For example:

```<code><% using (Html.BeginForm("Create", "Organisation", FormMethod.Post, new { autocomplete = "off", onsubmit = "disableSubmitButton()" }))
   { %>
       //Your code

      <input id="buttonName" type="submit" value="Create"/>
  <% } %>
</code>```

and then in your javascript section:

```<code>function disableSubmitButton() {

    document.getElementById("buttonName").disabled = true;

};
</code>```

Hope this helps.

Body:
To disable the submit button when you submit the form you can use the onSubmit function for the form and call a javascript function that will disable the button.

For example:

<% using (Html.BeginForm("Create", "Organisation", FormMethod.Post, new { autocomplete = "off", onsubmit = "disableSubmitButton()" }))
   { %>
       //Your code

      <input id="buttonName" type="submit" value="Create"/>
  <% } %>

and then in your javascript section:

function disableSubmitButton() {

    document.getElementById("buttonName").disabled = true;

};

Hope this helps.


问:
selinux, Avc issue after giving permission
I am getting avc denial issue after giving permission. Error message:

avc: denied { transition } for pid=189 comm="init"
  path="/system/bin/androlircd" dev="mmcblk0p9" ino=145
  scontext=u:r:init:s0 tcontext=u:object_r:lircd_exec:s0 tclass=process

I have given transition permission in init.te as :

```<code>type_transition init lircd_exec:process lircd;
allow init lircd_exec:file execute;
allow init lircd:process transition;
</code>```

after giving permission also the issue is happening.
Is there any way to solve this. please help.

my androlircd service is as :

```<code>service androlircd /system/bin/androlircd
class core
user root
group root system system
seclabel u:object_r:lircd_exec:s0
oneshot
</code>```

答:
I just got it corrected.
I need to assign selinux labels for the device node that was created,in device.te file. Label for the androlircd service in service.te and edited the service as

```<code>service androlircd /system/bin/androlircd
class main
oneshot
</code>```

Policies were written as required.

ContentLicense: CC BY-SA 4.0

Body:
I am getting avc denial issue after giving permission. Error message:

avc: denied { transition } for pid=189 comm="init"
  path="/system/bin/androlircd" dev="mmcblk0p9" ino=145
  scontext=u:r:init:s0 tcontext=u:object_r:lircd_exec:s0 tclass=process

I have given transition permission in init.te as :

type_transition init lircd_exec:process lircd;
allow init lircd_exec:file execute;
allow init lircd:process transition;

after giving permission also the issue is happening.
Is there any way to solve this. please help.

my androlircd service is as :

service androlircd /system/bin/androlircd
class core
user root
group root system system
seclabel u:object_r:lircd_exec:s0
oneshot

Body:
I just got it corrected.
I need to assign selinux labels for the device node that was created,in device.te file. Label for the androlircd service in service.te and edited the service as

service androlircd /system/bin/androlircd
class main
oneshot

Policies were written as required.


问:
Cloud Firestore: listen for new documents in a collection and load them
I am making a messaging app using Firebase and Cloud Firestore. I have a collection called "messages" that contains documents for each message. My main goal is to listen to that collection for new documents and load them without reloading all the documents in the collection.

EDIT: In a nutshell, I want the client to load messages saved by other clients.

答:
That depends on what defines when a document is "new" for you.

If "new" means "created after now()", then you need to have a created timestamp in your document and query to start at now(). That's pretty similar to what David explained here for the Firebase Realtime Database: How to only get new data without existing data from a Firebase?

If "new" means "documents this user hasn't loaded before", you will need to track the latest document they've seen, and start a query at that document. Kato explained a similar model for the Firebase Realtime here: Firebase child_added without loading all data first


问:
How to get multi table and paste to multi dropdowListFor on view
I'm newbie ASP.NET MVC.

I have many table such as (Country, State and city).
I want to put value in these DropDownListFor in one view.
Could you help me please.

Sorry for my bad question and bad English skill.

答:
Use viewmodel using all properties from all table

```<code>public class dataViewModel
{
public string country { get; set; }
public string state{ get; set; }
//all other properties from other class
}
</code>```

refer the viewmodel in the View.

Body:
Use viewmodel using all properties from all table

public class dataViewModel
{
public string country { get; set; }
public string state{ get; set; }
//all other properties from other class
}

refer the viewmodel in the View.


问:
Getting Java IO exception when using jenkins cli , jdk 8.144 , jenkins v2.93
This is the error.

root@myserver#java -jar
  /opt/tomcat/webapps/ROOT/WEB-INF/jenkins-cli.jar -s

  http://localhost:8181 -auth ****:**** help

```<code>java.io.IOException: Bogus chunk size
at sun.net.www.http.ChunkedInputStream.processRaw(ChunkedInputStream.java:319)
at sun.net.www.http.ChunkedInputStream.readAheadBlocking(ChunkedInputStream.java:572)
at sun.net.www.http.ChunkedInputStream.readAhead(ChunkedInputStream.java:609)
at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:696)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3375)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3368)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3356)
at hudson.cli.CLI$1ClientSideImpl.<init>(CLI.java:658)
at hudson.cli.CLI.plainHttpConnection(CLI.java:684)
at hudson.cli.CLI._main(CLI.java:612)
at hudson.cli.CLI.main(CLI.java:426)
</code>```

答:
On further troubleshooting  I found the issue to be linked to reverse-proxy .

“The HTTP(S) connection mode of the CLI in Jenkins 2.54 and newer does not work correctly behind an Apache HTTP reverse proxy server using mod_proxy. Workarounds include using a different reverse proxy such as Nginx or HAProxy, or using the SSH connection mode where possible.”
I used ssh instead .

https://issues.jenkins-ci.org/browse/JENKINS-47279

Body:
This is the error.

root@myserver#java -jar
  /opt/tomcat/webapps/ROOT/WEB-INF/jenkins-cli.jar -s

  http://localhost:8181 -auth ****:**** help

java.io.IOException: Bogus chunk size
at sun.net.www.http.ChunkedInputStream.processRaw(ChunkedInputStream.java:319)
at sun.net.www.http.ChunkedInputStream.readAheadBlocking(ChunkedInputStream.java:572)
at sun.net.www.http.ChunkedInputStream.readAhead(ChunkedInputStream.java:609)
at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:696)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3375)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3368)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3356)
at hudson.cli.CLI$1ClientSideImpl.<init>(CLI.java:658)
at hudson.cli.CLI.plainHttpConnection(CLI.java:684)
at hudson.cli.CLI._main(CLI.java:612)
at hudson.cli.CLI.main(CLI.java:426)


问:
ReCall iframe after setInterval

I wish popup box (iframe colorbox) keep available even after setInterval running. But in fact, only the first iframe actually can pop up, the next after 2 seconds, bring me to my requested page. (sorry for bad english)

```<code>        <script type="text/javascript">
          $(document).ready(function(){

            $("#iframe").colorbox({iframe:true, width:"400px", height:"600px"});

            var refreshId = setInterval(function() {
             $('#chatting').load("<?php echo current_url() ?> #chatting") ;
             $("#iframe").colorbox({iframe:true, width:"400px", height:"600px"});
            }, 2000);

          });
        </script>

           <div id="chatting">
                <li class="chat-list">
                    <div class="chat-body">
                        <a id="iframe"href="intern/public_chat/test.php">XXX</a>
                    </div>
                </li>
            </div>
</code>```

I need every reload time (2 seconds as setinterval), updated value keep can using iframe colorbox.

But only it's always bring me to my requested page but not in pop up box.

答:
look at your anchor tag

i just improve and it's work
id="iframe" href="intern/public_chat/test.php">

Title: ReCall iframe after setInterval

Body:
I wish popup box (iframe colorbox) keep available even after setInterval running. But in fact, only the first iframe actually can pop up, the next after 2 seconds, bring me to my requested page. (sorry for bad english)

                        XXX

I need every reload time (2 seconds as setinterval), updated value keep can using iframe colorbox.

But only it's always bring me to my requested page but not in pop up box.

Body:
look at your anchor tag
<a id="iframe" href="intern/public_chat/test.php</a>

i just improve and it's work
<a id="iframe" href="intern/public_chat/test.php"> </a>


问:
How to read two columns using python
How to read two columns the first of which contains letters and the second of the values.

```<code>C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979
</code>```

I often used this script below (it works for two or more columns), but not for this time !!

```<code>with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]
</code>```

Thanks for your help.

答:
Pandas is the way to go if you want to play around data from csv file.
  It saves you from unnecessary iterations and makes data manipulation
  easy

.

You can load file into a pandas data frame

```<code>df = pd.read_csv('file.csv')
</code>```

Then select the required columns

```<code>df_temp = df.iloc[:,0:2]
</code>```

To get pair of row values you can then use a tolist() function

```<code>df.values.tolist()
</code>```

Output

```<code>[['C1', -0.157117], ['C2', -0.143805], ['C3', -0.140561], ['S4', 0.059175], ['H5', 0.12894], ['H6', 0.12900699999999998], ['H7', 0.142421], ['H8', 0.139979]]
</code>```

Title: How to read two columns using python

Body:
How to read two columns the first of which contains letters and the second of the values.

C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979

I often used this script below (it works for two or more columns), but not for this time !!

with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]

Thanks for your help.

Body:
Pandas is the way to go if you want to play around data from csv file.
  It saves you from unnecessary iterations and makes data manipulation
  easy

.

You can load file into a pandas data frame

df = pd.read_csv('file.csv')

Then select the required columns

df_temp = df.iloc[:,0:2]

To get pair of row values you can then use a tolist() function

df.values.tolist()

Output

[['C1', -0.157117], ['C2', -0.143805], ['C3', -0.140561], ['S4', 0.059175], ['H5', 0.12894], ['H6', 0.12900699999999998], ['H7', 0.142421], ['H8', 0.139979]]


问:
Nosql does not support to ACID property then why some companies using NoSql databases
Nosql does not support to ACID property then why some companies using NoSql databases  Like Facebook uses Cassandra and Amazon uses dynamodb</p>

答:
Use Cosmos DB and be happy as it supports all most everything you need for data :

Here is the FAQ: https://learn.microsoft.com/en-us/azure/cosmos-db/faq


问:
MVVM Progress Bar EventTrigger
This is my sample code to animate progress bar during page loaded.

My question is, how can i start progress bar when button click?

```<code><ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
     <ProgressBar.Triggers>
          <EventTrigger RoutedEvent="FrameworkElement.Loaded">
               <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Value"
                                        From="0" To="{Binding Bar1}"
                                        Duration="{Binding Duration1}"/>
                     </Storyboard>
                </BeginStoryboard>
          </EventTrigger>
     </ProgressBar.Triggers>
</ProgressBar>
</code>```

答:
One of the way to do this is with DataTrigger:

```<code><Button x:Name="BtnToClick" Height="30" Width="100" Content="Click" />

<ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
        RenderTransformOrigin="0.5,0.5"
        Margin="0,0" Background="Transparent"
        BorderThickness="0" Foreground="DarkCyan">
<ProgressBar.RenderTransform>
  <TransformGroup>
    <ScaleTransform/>
    <SkewTransform/>
    <RotateTransform Angle="-90"/>
    <TranslateTransform/>
   </TransformGroup>
  </ProgressBar.RenderTransform>
  <ProgressBar.Style>
    <Style TargetType="ProgressBar">
       <Style.Triggers>
          <DataTrigger Binding="{Binding IsPressed ,ElementName=BtnToClick}" Value="True">
           <DataTrigger.EnterActions>
              <BeginStoryboard>
                 <Storyboard>
                   <DoubleAnimation Storyboard.TargetProperty="Value"
                                    From="0" To="100"
                                    Duration="0:0:0:1"/>
                  </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
           </DataTrigger>
       </Style.Triggers>
      </Style>
    </ProgressBar.Style>
 </ProgressBar>
</code>```

Title: MVVM Progress Bar EventTrigger

Body:
This is my sample code to animate progress bar during page loaded.

My question is, how can i start progress bar when button click?

<ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
            RenderTransformOrigin="0.5,0.5"
            Margin="-113,0" Background="Transparent"
            BorderThickness="0" Foreground="DarkCyan">
     <ProgressBar.RenderTransform>
          <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-90"/>
              <TranslateTransform/>
          </TransformGroup>
     </ProgressBar.RenderTransform>
     <ProgressBar.Triggers>
          <EventTrigger RoutedEvent="FrameworkElement.Loaded">
               <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Value"
                                        From="0" To="{Binding Bar1}"
                                        Duration="{Binding Duration1}"/>
                     </Storyboard>
                </BeginStoryboard>
          </EventTrigger>
     </ProgressBar.Triggers>
</ProgressBar>

Body:
One of the way to do this is with DataTrigger:

<Button x:Name="BtnToClick" Height="30" Width="100" Content="Click" />

<ProgressBar Height="50" Minimum="0" Maximum="100" Value="0"
        RenderTransformOrigin="0.5,0.5"
        Margin="0,0" Background="Transparent"
        BorderThickness="0" Foreground="DarkCyan">
<ProgressBar.RenderTransform>
  <TransformGroup>
    <ScaleTransform/>
    <SkewTransform/>
    <RotateTransform Angle="-90"/>
    <TranslateTransform/>
   </TransformGroup>
  </ProgressBar.RenderTransform>
  <ProgressBar.Style>
    <Style TargetType="ProgressBar">
       <Style.Triggers>
          <DataTrigger Binding="{Binding IsPressed ,ElementName=BtnToClick}" Value="True">
           <DataTrigger.EnterActions>
              <BeginStoryboard>
                 <Storyboard>
                   <DoubleAnimation Storyboard.TargetProperty="Value"
                                    From="0" To="100"
                                    Duration="0:0:0:1"/>
                  </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
           </DataTrigger>
       </Style.Triggers>
      </Style>
    </ProgressBar.Style>
 </ProgressBar>


问:
javascript find and replace just whole words in a textarea
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

```<code>XI
XXI
XXXI
</code>```

and I get

```<code>11
X11
XX11
</code>```

but I want

```<code>11
XXI
XXXI
</code>```

The code I'm using is:

```<code>function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}
</code>```

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

答:
I took your spec and made it "work", by:

Defining the correct regular expression \b[XIV]+\b (matches a whole roman number)

Use your object as a mapping function and a fallback if it fails, mapObj[roman] || roman

What the script doesn't do:

Catch illegal roman numbers, i.e. it allows XIIX

Implement a proper algorithm for the match, like XV, idealistically should parse to 10 + 5 = 15

function fromRoman(roman) {
  var mapObj = {
    XI:"11",
    V:"5"
  };
  return mapObj[roman] || roman;
}

function convertFromRoman() {
  var str = document.getElementById("textArea").value;
  var output = str.replace(/\b[XIV]+\b/g, fromRoman);
  document.getElementById("output").value = output;
}

convertFromRoman();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Input:</p>

<textarea id="textArea" style="width:100%; height:50px" onkeyup="convertFromRoman()">
XI
XXI
XXXI
</textarea>

<p/>

<p>Output:</p>

<textarea id="output" style="width:100%; height:50px">
</textarea></code>```

Body:
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

XI
XXI
XXXI

and I get

11
X11
XX11

but I want

11
XXI
XXXI

The code I'm using is:

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

Body:
I took your spec and made it "work", by:

Defining the correct regular expression \b[XIV]+\b (matches a whole roman number)

Use your object as a mapping function and a fallback if it fails, mapObj[roman] || roman

What the script doesn't do:

Catch illegal roman numbers, i.e. it allows XIIX

Implement a proper algorithm for the match, like XV, idealistically should parse to 10 + 5 = 15

function fromRoman(roman) {
  var mapObj = {
    XI:"11",
    V:"5"
  };
  return mapObj[roman] || roman;
}

function convertFromRoman() {
  var str = document.getElementById("textArea").value;
  var output = str.replace(/\b[XIV]+\b/g, fromRoman);
  document.getElementById("output").value = output;
}

convertFromRoman();

<p>Input:</p>

<textarea id="textArea" style="width:100%; height:50px" onkeyup="convertFromRoman()">
XI
XXI
XXXI
</textarea>

<p/>

<p>Output:</p>

<textarea id="output" style="width:100%; height:50px">
</textarea>


问:
Bad Data Binding Oracle Trigger
I have two tables called Projects and Opportunity. I want my triggers to fire when the status of Opportunity becomes 'P'. Then I want to increase project_code by 100 and grab some data from opportunity column and insert into Project table.
I have my trigger written below and that gives me a bad data binding error. How do I fix that error?
Thanks in advance.

```<code>create or replace trigger proj_creator
   after insert or update on opportunity
   for each row
begin
   if :new.status = :p
   then
      insert into projects
         (project_code
         ,project_name
         ,client_id
         ,project_start_date
         ,project_end_date
         ,project_status
         ,pm_emp_id)
      values
         (:old.project_code auto_increment + 100
         ,:old.opp_name
         ,:old.client_id
         ,current_date
         ,add_months(date '2017-10-10', 48)
         ,'I'
         ,44444);
   end if;
end;
</code>```

答:
Your string comparison looks wrong

```<code>IF :new.status =: P
THEN
</code>```

Should probably be

```<code>IF :new.status = 'P'
THEN
</code>```

Does your opportunity table contain a PROJECT_CODE column? Is it case sensitive? If so put the exact case in " quotes "

I've never seen someone write :old.column_name AUTO_INCREMENT +x as part of an insert statement. What are you expecting this set of words to do? (It looks like a column definition has been badly copied)

Title: Bad Data Binding Oracle Trigger

Body:
I have two tables called Projects and Opportunity. I want my triggers to fire when the status of Opportunity becomes 'P'. Then I want to increase project_code by 100 and grab some data from opportunity column and insert into Project table.
I have my trigger written below and that gives me a bad data binding error. How do I fix that error?
Thanks in advance.

create or replace trigger proj_creator
   after insert or update on opportunity
   for each row
begin
   if :new.status = :p
   then
      insert into projects
         (project_code
         ,project_name
         ,client_id
         ,project_start_date
         ,project_end_date
         ,project_status
         ,pm_emp_id)
      values
         (:old.project_code auto_increment + 100
         ,:old.opp_name
         ,:old.client_id
         ,current_date
         ,add_months(date '2017-10-10', 48)
         ,'I'
         ,44444);
   end if;
end;

Body:
Your string comparison looks wrong

IF :new.status =: P
THEN

Should probably be

IF :new.status = 'P'
THEN

Does your opportunity table contain a PROJECT_CODE column? Is it case sensitive? If so put the exact case in " quotes "

I've never seen someone write :old.column_name AUTO_INCREMENT +x as part of an insert statement. What are you expecting this set of words to do? (It looks like a column definition has been badly copied)