问:
Continually sending GPS data to the Android emulator
I am writing an app for Android that will measure speed as the Android device is moving, using the GPS receiver. I know I can telnet into the Android emulator and send Geo coordinates using the "geo fix" command. What I want to know though, is there a way to continually send geo fix data to simulate a car moving down a street? Otherwise, how else can I test my application?</p>

答:
Hi in my first GPS based project I faced the same problem so I write a java code that will send GPS Fix to my android emulator below is the snippet</p>

```<code>import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Main {

    static final int PAUSE = 4000; // ms
    static final float START_LONGITUDE = 51, START_LATITUDE = -1.3f;
    static final int NO_SAMPLE = 100;
    static final float DELTA_LONGITUDE = 0.000005f, DELTA_LADITUDE = 0.000005f;

    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 5554); // usually 5554

            PrintStream out = new PrintStream(socket.getOutputStream());
            float longitude = START_LONGITUDE, latitude = START_LATITUDE;
            String str;

            for (int i = 0; i < NO_SAMPLE; i++) {
                str = "geo fix " + latitude + " " + longitude + "\n";
                out.print(str);
                System.out.print(str);

                Thread.sleep(PAUSE);

                longitude += DELTA_LONGITUDE;
                latitude += DELTA_LADITUDE;
            }
        } catch (UnknownHostException e) {
            System.exit(-1);
        } catch (IOException e) {
            System.exit(-1);
        } catch (InterruptedException e) {
            System.exit(-1);
        }

    }
}
</code>```

Body:
Hi in my first GPS based project I faced the same problem so I write a java code that will send GPS Fix to my android emulator below is the snippet

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Main {

    static final int PAUSE = 4000; // ms
    static final float START_LONGITUDE = 51, START_LATITUDE = -1.3f;
    static final int NO_SAMPLE = 100;
    static final float DELTA_LONGITUDE = 0.000005f, DELTA_LADITUDE = 0.000005f;

    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 5554); // usually 5554

            PrintStream out = new PrintStream(socket.getOutputStream());
            float longitude = START_LONGITUDE, latitude = START_LATITUDE;
            String str;

            for (int i = 0; i < NO_SAMPLE; i++) {
                str = "geo fix " + latitude + " " + longitude + "\n";
                out.print(str);
                System.out.print(str);

                Thread.sleep(PAUSE);

                longitude += DELTA_LONGITUDE;
                latitude += DELTA_LADITUDE;
            }
        } catch (UnknownHostException e) {
            System.exit(-1);
        } catch (IOException e) {
            System.exit(-1);
        } catch (InterruptedException e) {
            System.exit(-1);
        }

    }
}


来源: stackexchange

问:
How to calculate price and quantity with tax in javascript
My price: 20

Quantity: 2

Tax: 10%

How to calculate this?

I dont know the formula to do this calculation.

答:
```<code>var price = 20;
var tax = 0.1;
var qty = 2;
//amount includes the tax
var amountWithTax = (qty * price) / (1 - 0.1);
console.log(amountWithTax);
//amount you get after you pay the tax
var amountAfterDeductTax = amountWithTax - (amountWithTax * tax) ;
console.log(amountAfterDeductTax)
</code>```

ContentLicense: CC BY-SA 4.0


问:
Source multiple r scripts from github
I usually use some personal functions during my r sessions, as:

```<code>s1<-"https://github.com/juanchiem/R-sources-Juan/blob/master/rend_aj.R?raw=TRUE" # rend_aj.R
s2<-"https://github.com/juanchiem/R-sources/blob/master/theme_juan.R?raw=TRUE" # theme_juan.R
s3<-"https://github.com/juanchiem/R-sources-Juan/blob/master/assumptions.R?raw=TRUE" # lm_assumptions.R

devtools::source_url(s1)
devtools::source_url(s2)
devtools::source_url(s3)
</code>```

I wonder if Is it possible to create a function to source these 3 files from github directly by their file names (detailed after #)
Thanks!

答:
We could write up a custom function(see note below) to achieve the goal:

```<code>custom_source <- function(repo_name,repo_branch,name,
                          ...){

  url_to_use <- paste0("https://github.com/",repo_name,
                        "/blob/",repo_branch,"/",name,".R",
                       "?raw=TRUE"
                       )
  devtools::source_url(url_to_use,...)
}
</code>```

Calling the function(you could include this in the same function above but I prefer calling it individually)

```<code>invisible(Map(function(x) custom_source("juanchiem/R-sources-Juan",
               "master",x), c("rend_aj","theme_juan", "lm_assumptions")))
</code>```

Result(truncated):

```<code>  SHA-1 hash of file is 586d156021371098ec51c35c4c056d7c98a94d3d
SHA-1 hash of file is 5c84c1e8e7bd4fe9bf6cd26c4f5e955c20cf851b
SHA-1 hash of file is 63790352a1dc712611bbd26a67cd33d2d1ce5b2c
</code>```

NOTE:

This will only download .R files. Can modify as needed.

invisible is used to suppress printing to console. However, adding echo=FALSE or verbose=FALSE should have suppressed the output but it doesn't.

Title: Source multiple r scripts from github

Body:
I usually use some personal functions during my r sessions, as:

s1<-"https://github.com/juanchiem/R-sources-Juan/blob/master/rend_aj.R?raw=TRUE" # rend_aj.R
s2<-"https://github.com/juanchiem/R-sources/blob/master/theme_juan.R?raw=TRUE" # theme_juan.R
s3<-"https://github.com/juanchiem/R-sources-Juan/blob/master/assumptions.R?raw=TRUE" # lm_assumptions.R

devtools::source_url(s1)
devtools::source_url(s2)
devtools::source_url(s3)

I wonder if Is it possible to create a function to source these 3 files from github directly by their file names (detailed after #)
Thanks!

Body:
We could write up a custom function(see note below) to achieve the goal:

custom_source <- function(repo_name,repo_branch,name,
                          ...){

  url_to_use <- paste0("https://github.com/",repo_name,
                        "/blob/",repo_branch,"/",name,".R",
                       "?raw=TRUE"
                       )
  devtools::source_url(url_to_use,...)
}

Calling the function(you could include this in the same function above but I prefer calling it individually)

invisible(Map(function(x) custom_source("juanchiem/R-sources-Juan",
               "master",x), c("rend_aj","theme_juan", "lm_assumptions")))

Result(truncated):

  SHA-1 hash of file is 586d156021371098ec51c35c4c056d7c98a94d3d
SHA-1 hash of file is 5c84c1e8e7bd4fe9bf6cd26c4f5e955c20cf851b
SHA-1 hash of file is 63790352a1dc712611bbd26a67cd33d2d1ce5b2c

NOTE:

This will only download .R files. Can modify as needed.

invisible is used to suppress printing to console. However, adding echo=FALSE or verbose=FALSE should have suppressed the output but it doesn't.


问:
Creating a Webhook for NetSuite
My client is using NetSuite and wants to integrate with Commonsku - Commonsku says they can do this via a Webhook. How do I create a webhook in NetSuite? Is this even possible?  Thank you.

Meg

答: Perform an HTTP call to Commonsku via User Event, whenever there's a relevant change to one of your NetSuite records. Example: If the item weight changes, then use the N/https to post the updated values to the Commonsku API endpoint.</p>

Title: Creating a Webhook for NetSuite


问:
jquery ajax in wordpress metabox
i build a word press page builder meta box,
my meta box work properly, but i think that is mistake, or i have better ways to do that better, my problem is append() jquery function. that is very complicated and Sapagty code. and i know i should't php codes in jquery append(), i want to do that with jquery Ajax. but i don't know what i should to do, can you show me a true or better way!

```<code>$page_builder = array(
array(
    'id'      => 'module',
    'type'    => 'tab',
    'title'   => __( 'tab', 'tx' ),
    'fields'  => array(
        array(
            'id'      => 'module_title',
            'type'    => 'text',
            'title'   => __( 'Module Title', 'tx' ),
        ),
        array(
            'id'      => 'module_numbers',
            'type'    => 'text',
            'title'   => __( 'Max Number of Post', 'tx' ),
        ),
        array(
            'id'      => 'module_offset',
            'type'    => 'text',
            'title'   => __( 'Posts Offset', 'tx' ),
        ),
        array(
            'id'      => 'module_category',
            'type'    => 'category',
            'title'   => __( 'Filter by Category', 'tx' ),
        ),
    ),
),
);

function call_metabox() {

global $page_builder;

$terms = get_terms( 'category', 'get=all' );

?>

<script>
    jQuery(document).ready( function() {

        var count    = 1;
        var button   = jQuery('.add-module');
        var panels   = jQuery('.panels');
        var geturi   = '<?php echo get_template_directory_uri(); ?>';
        var category = '<?php foreach ( $terms as $term ){ echo '<option value="'. $term->slug .'">'. $term->name .'</option>'; } ?>';

        button.live( 'click', function() {

            panels.append(
            '<li>'+
            '<div><?php _e( 'sample', 'tx' ); ?></div>'+
            '<div>'+geturi+'/img.png'+'</div>'+
            '<div><select name="<?php echo $page_builder[0]['fields'][0]['id']; ?>" id="">'+category+'</select></div>'+
            '<div>'+'<input type="text" name="module_title['+ count +'][title]" id="module_title['+ count +'][title]" value="" />'+'</div>'+
            '</li>'
            );

            count++;

        });

    });
</script>

<input type="button" id="add-module" class="add-module" value="<?php _e( 'Add New Module', 'tx' ) ?>">

<ul class="panels">

</ul>

< ?php
}
</code>```

thank you.

答:
you can put the js code in a .js file and then insert the script with wp_enqueue_script:

//this will register the script
wp_register_script(
    'my_script_id',
    plugins_url( '/assets/js/scritp.js', PLUGIN_URL ),
    [ 'JQuery' ], // define dependencies
    null,
    true
);

// this will pass data from php to js script
// it will output 'var object = { attribute: 'value' }' before script insertion
wp_localize_script(
    'my_script_id',
    'object',
    [
        'attribute'                       =>  'value'
    ]
);

// this will enqueue the script insertion
wp_enqueue_script( 'my_script_id' );

// this will insert the script
add_action( 'wp_enqueue_scripts', 'my_script_id' );
```

ContentLicense: CC BY-SA 3.0

Title: jquery ajax in wordpress metabox

Body:
i build a word press page builder meta box,
my meta box work properly, but i think that is mistake, or i have better ways to do that better, my problem is append() jquery function. that is very complicated and Sapagty code. and i know i should't php codes in jquery append(), i want to do that with jquery Ajax. but i don't know what i should to do, can you show me a true or better way!

$page_builder = array(
array(
    'id'      => 'module',
    'type'    => 'tab',
    'title'   => __( 'tab', 'tx' ),
    'fields'  => array(
        array(
            'id'      => 'module_title',
            'type'    => 'text',
            'title'   => __( 'Module Title', 'tx' ),
        ),
        array(
            'id'      => 'module_numbers',
            'type'    => 'text',
            'title'   => __( 'Max Number of Post', 'tx' ),
        ),
        array(
            'id'      => 'module_offset',
            'type'    => 'text',
            'title'   => __( 'Posts Offset', 'tx' ),
        ),
        array(
            'id'      => 'module_category',
            'type'    => 'category',
            'title'   => __( 'Filter by Category', 'tx' ),
        ),
    ),
),
);

function call_metabox() {

global $page_builder;

$terms = get_terms( 'category', 'get=all' );

?>

<input type="button" id="add-module" class="add-module" value="<?php _e( 'Add New Module', 'tx' ) ?>">

< ?php
}

thank you.


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答:
Template engines add overhead.

You should only use a template engine if you need to have others create/edit templates and you do not want them to be able to use PHP.

If you are the sole maintainer, defiantly go with plain PHP. If your team can be trusted (they are all devs), stick with plain PHP. If you have designers that don't know PHP or, more importantly, letting them use PHP is dangerous, then use Smarty or another template engine.

That being said, you are wondering if you should learn Smarty. You'll need to learn Smarty if creating templates with Smarty. You don't really need to learn Smarty if you are just implementing the Smarty template engine.


问:
Retrieve .textContent including pseudo elements
Given

firstsecond

```

<p>and</p>

<pre class="lang-css prettyprint-override"><code>span + span::before {
  content: ', ';
}
</code>```

I'd like to retrieve the rendered string 'first, second' in JavaScript but .textContent ignores the content of the pseudo-element as it's not part of the DOM. Is there a way to get the actual rendered text?

Example: https://jsfiddle.net/silverwind/nyr5kohj/2/

答:
Got it working using getComputedStyle. It does not support ::after but that shouldn't be too hard to add.

let text = '';
for (const child of children(document.querySelector('div'))) {
  if (child.nodeType === 1) {
    const before = window.getComputedStyle(child, '::before').getPropertyValue('content');
    if (before && before !== 'none') {
      text += before.replace(/^['"]/, '').replace(/['"]$/, '');
    }
  } else if (child.nodeType === 3) {
    text += child.textContent;
  }
}

alert(text);

function children(node) {
  const ret = [];
  for (let i = 0; i < node.childNodes.length; i++) {
    const child = node.childNodes[i];
    ret.push(child, ...children(child));
  }
  return ret;
}
```

Body:
Given

firstsecond

and

span + span::before {
  content: ', ';
}

I'd like to retrieve the rendered string 'first, second' in JavaScript but .textContent ignores the content of the pseudo-element as it's not part of the DOM. Is there a way to get the actual rendered text?

Example: https://jsfiddle.net/silverwind/nyr5kohj/2/


问:
column formatting options in psql/postgresql
As in oracle sqlplus, we have options of column formatting (like: column c3 heading City         Format a20).

I need to do this kind of data formatting with psql. However, after googling - I couldn't find anything for psql. Do we have anything/replacement for this in psql?

答:
You probably should try psql -x like psql -x -d "your_dbname" -c "your_query;" or \x if you are already in psql shell. This will print every column separately in a new line.

Also try reading official psql documentation, where all the formatting possibilities are explained -- https://www.postgresql.org/docs/9.6/app-psql.html (according to your postgres version).

Example 1:

```<code>$ psql -d dbname -c "SELECT *
                     FROM pg_stat_activity
                     WHERE datname = 'dbname'
                     AND application_name = 'psql'
                     AND client_port = -1;"
</code>```

Output (hard readable, if monitor/terminal window is not too wide):

```<code>   datid    | datname |  pid  | usesysid | usename  | application_name | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type | wait_event | state  | backend_xid | backend_xmin |                                                   query
------------+---------+-------+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+------------+--------+-------------+--------------+------------------------------------------------------------------------------------------------------------
 1322253912 | dbname   | 75924 |       10 | postgres | psql             |             |                 |          -1 | 2020-02-17 14:55:51.716436+02 | 2020-02-17 14:55:51.724092+02 | 2020-02-17 14:55:51.724092+02 | 2020-02-17 14:55:51.724095+02 |                 |            | active |             |     96305140 | SELECT * FROM pg_stat_activity WHERE datname = 'dbname' AND application_name = 'psql' AND client_port = -1;
(1 row)
</code>```

Example 2:

```<code>$ psql -x -d dbname -c "SELECT *
                        FROM pg_stat_activity
                        WHERE datname = 'dbname'
                        AND application_name = 'psql'
                        AND client_port = -1;"
</code>```

Output (much more readable):

```<code>-[ RECORD 1 ]----+-----------------------------------------------------------------------------------------------------------
datid            | 1322253912
datname          | dbname
pid              | 75952
usesysid         | 10
usename          | postgres
application_name | psql
client_addr      |
client_hostname  |
client_port      | -1
backend_start    | 2020-02-17 14:56:37.88717+02
xact_start       | 2020-02-17 14:56:37.894672+02
query_start      | 2020-02-17 14:56:37.894672+02
state_change     | 2020-02-17 14:56:37.894676+02
wait_event_type  |
wait_event       |
state            | active
backend_xid      |
backend_xmin     | 96305140
query            | SELECT * FROM pg_stat_activity WHERE datname = 'dbname' AND application_name = 'psql' AND client_port = -1;
</code>```

Body:
You probably should try psql -x like psql -x -d "your_dbname" -c "your_query;" or \x if you are already in psql shell. This will print every column separately in a new line.

Also try reading official psql documentation, where all the formatting possibilities are explained -- https://www.postgresql.org/docs/9.6/app-psql.html (according to your postgres version).

Example 1:

$ psql -d dbname -c "SELECT *
                     FROM pg_stat_activity
                     WHERE datname = 'dbname'
                     AND application_name = 'psql'
                     AND client_port = -1;"

Output (hard readable, if monitor/terminal window is not too wide):

   datid    | datname |  pid  | usesysid | usename  | application_name | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type | wait_event | state  | backend_xid | backend_xmin |                                                   query
------------+---------+-------+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+------------+--------+-------------+--------------+------------------------------------------------------------------------------------------------------------
 1322253912 | dbname   | 75924 |       10 | postgres | psql             |             |                 |          -1 | 2020-02-17 14:55:51.716436+02 | 2020-02-17 14:55:51.724092+02 | 2020-02-17 14:55:51.724092+02 | 2020-02-17 14:55:51.724095+02 |                 |            | active |             |     96305140 | SELECT * FROM pg_stat_activity WHERE datname = 'dbname' AND application_name = 'psql' AND client_port = -1;
(1 row)

Example 2:

$ psql -x -d dbname -c "SELECT *
                        FROM pg_stat_activity
                        WHERE datname = 'dbname'
                        AND application_name = 'psql'
                        AND client_port = -1;"

Output (much more readable):

-[ RECORD 1 ]----+-----------------------------------------------------------------------------------------------------------
datid            | 1322253912
datname          | dbname
pid              | 75952
usesysid         | 10
usename          | postgres
application_name | psql
client_addr      |
client_hostname  |
client_port      | -1
backend_start    | 2020-02-17 14:56:37.88717+02
xact_start       | 2020-02-17 14:56:37.894672+02
query_start      | 2020-02-17 14:56:37.894672+02
state_change     | 2020-02-17 14:56:37.894676+02
wait_event_type  |
wait_event       |
state            | active
backend_xid      |
backend_xmin     | 96305140
query            | SELECT * FROM pg_stat_activity WHERE datname = 'dbname' AND application_name = 'psql' AND client_port = -1;


问:
psql: warning: extra command-line argument "from" ignored
I am trying to execute a non-interactive postgres command.

```<code>PGPASSWORD=$PGPASS psql -h 127.0.0.1 -U postgresql -d $PGDB --command "select count(*) from services"
</code>```

Which has been giving me this response.

psql: warning: extra command-line argument "from" ignored

psql: warning: extra command-line argument "services;" ignored

psql: warning: extra command-line argument "mydbname" ignored

psql: FATAL:  database "count(*)" does not exist

I've read that this could be because the terminal / bash is trying to break up each argument to --command / -c as it's own argument.

I've also tried this:

```<code>PSQLARGS=(-h 127.0.0.1 -U postgresql -c )
PSQLARGS+=("select count(*) from services;")
PSQLARGS+=(${PGDB})
PGPASSWORD=$PGPASS psql "${PSQLARGS[@]}"
</code>```

Some way of forcing the terminal to know it's one argument, this also didn't work.

答:
This is a pretty cheap and common error.
Putting everything in quotes should do the trick.

Try this:

```<code>PGPASSWORD="$PGPASS" psql -h '127.0.0.1' -U 'postgresql' -d "$PGDB" --command "select count(*) from services"
</code>```

Let us know if it works for you.

Body:
I am trying to execute a non-interactive postgres command.

PGPASSWORD=$PGPASS psql -h 127.0.0.1 -U postgresql -d $PGDB --command "select count(*) from services"

Which has been giving me this response.

psql: warning: extra command-line argument "from" ignored

psql: warning: extra command-line argument "services;" ignored

psql: warning: extra command-line argument "mydbname" ignored

psql: FATAL:  database "count(*)" does not exist

I've read that this could be because the terminal / bash is trying to break up each argument to --command / -c as it's own argument.

I've also tried this:

PSQLARGS=(-h 127.0.0.1 -U postgresql -c )
PSQLARGS+=("select count(*) from services;")
PSQLARGS+=(${PGDB})
PGPASSWORD=$PGPASS psql "${PSQLARGS[@]}"

Some way of forcing the terminal to know it's one argument, this also didn't work.

Body:
This is a pretty cheap and common error.
Putting everything in quotes should do the trick.

Try this:

PGPASSWORD="$PGPASS" psql -h '127.0.0.1' -U 'postgresql' -d "$PGDB" --command "select count(*) from services"

Let us know if it works for you.


问:
When recording video, how to set transformation (portrait, landscape, etc.) for video?
Should I use AVCaptureConnection's videoOrientation property, or set the transform property of the videoWriterInput, or something else?</p>

答: Seems like AVCaptureConnection's videoOrientation property sets the orientation as it's recording, while the transform property of the videoWriterInput will set a flag for the playback transform.</p>


问:
How to compute distance between my original and supplied point in Java
```<code>public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}
</code>```

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}
```

Would this be fine?

Body:
public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}

Would this be fine?

Body: Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2))


问:
Access the variables of a component
I'd like to access a component variable. This variable is modified by an html input.

Here is my current code

Parent :

```<code><template>
   <component>Child</component>
</template>

<script>
export default {
    data () {
        return {
          dataChild : '',
    }
</script>
</code>```

Child :

```<code><template>
    <input type="text" name="data" v-model="data" class="form-control">
</template>

<script>
  export default {
    data () {
      return {
          data: ''
      }
    }
  }
</script>
</code>```

I've looked all over the internet but nothing works on my side or I'm doing wrong :(

Thanks in advance

答:
The standard way to send data from child component to parent in vue is to emit that inside child and listen for event inside parent. Like this:

Child:

```<code>export default {
  data: () => ({ dataChild: 'TEST' }),
  methods: {
    send () {
      this.$emit('data', this.dataChild)
    }
  },
  mounted () { this.send() }
}
</code>```

Parent:

```<code><div>
  <child @data="get"></child>
</div>

export default {
  data: () => ({ data: '' }),
  methods: {
    get(value) {
      this.data = value
    }
  }
}
</code>```

Title: Access the variables of a component

Body:
I'd like to access a component variable. This variable is modified by an html input.

Here is my current code

Parent :

<template>
   <component>Child</component>
</template>

Child :

<template>
    <input type="text" name="data" v-model="data" class="form-control">
</template>

I've looked all over the internet but nothing works on my side or I'm doing wrong :(

Thanks in advance

Body:
The standard way to send data from child component to parent in vue is to emit that inside child and listen for event inside parent. Like this:

Child:

export default {
  data: () => ({ dataChild: 'TEST' }),
  methods: {
    send () {
      this.$emit('data', this.dataChild)
    }
  },
  mounted () { this.send() }
}

Parent:

<div>
  <child @data="get"></child>
</div>

export default {
  data: () => ({ data: '' }),
  methods: {
    get(value) {
      this.data = value
    }
  }
}


问:
Fixing UnboundLocalError: local variable 'name' referenced before assignment in python
Reading a text file with names and birthdays in a function printBook(), returning name, birthday and referencing it later on in another function I get:

UnboundLocalError: local variable 'name' referenced before assignment

Code:

```<code>with open("scratch.txt") as file:

    def printBook():
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

    def givenMonthPrintsElse(monthGiven):
        obj = printBook()
        if monthGiven == obj[1]:
            print("Name:", obj[0], "Day:", obj[2])

    printBook()
    givenMonthPrintsElse("Feb")
</code>```

答:
You're declaring the name variable inside the for loop and accessing outside (in the return statement).

The easiest way to solve this is by declaring the variables before the for loop, so the printBook function would be something like:

```<code>def printBook():
    name, month, date = None, None, None
    for line in file:
        name, month, date = line.split(",")
        print("Name:", name, "    Month:", month, "    Date:", date)
    return name, month, date
</code>```

PS: As @Chris pointed out, the problem isn't just because you're accessing the variables outside the loop (python accepts it), but because when the loop doesn't run, your variables aren't declared.

Body:
Reading a text file with names and birthdays in a function printBook(), returning name, birthday and referencing it later on in another function I get:

UnboundLocalError: local variable 'name' referenced before assignment

Code:

with open("scratch.txt") as file:

    def printBook():
        for line in file:
            name, month, date = line.split(",")
            print("Name:", name, "    Month:", month, "    Date:", date)
        return name, month, date

    def givenMonthPrintsElse(monthGiven):
        obj = printBook()
        if monthGiven == obj[1]:
            print("Name:", obj[0], "Day:", obj[2])

    printBook()
    givenMonthPrintsElse("Feb")

Body:
You're declaring the name variable inside the for loop and accessing outside (in the return statement).

The easiest way to solve this is by declaring the variables before the for loop, so the printBook function would be something like:

def printBook():
    name, month, date = None, None, None
    for line in file:
        name, month, date = line.split(",")
        print("Name:", name, "    Month:", month, "    Date:", date)
    return name, month, date

PS: As @Chris pointed out, the problem isn't just because you're accessing the variables outside the loop (python accepts it), but because when the loop doesn't run, your variables aren't declared.


问:
How to fix a "NameError: name 'color' is not defined"?
here is my code :

```<code>size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)
</code>```

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

答:
The fact you defined color in the class's namespace (making it a class attribute) doesn't make it available in methods bodies. Names in a method (actually a function) body are resolved at function execution time, not at function definition time, and at this point the color varibale defined in the class body has already be turned into a class attributes - they are not part of the function's non-local namespace.

Now the "proper" solution depends on what you want to achieve.

If all of your particle instance should share the same "color" value, just keep the class attribute and remove the instance one in your initializer - class attributes can be accessed directly from the instances, so self.color will automagically resolve to type(self).color. Note that this won't prevent you to assign per-instance color values - the class attribute is only accessed thru the instance if the instance has no attribute by that name, so setting your_particle.color = something_else (or self.color = ... - just the same) later in your code will still create an instance attribute and shadow the class-level one - but this is usually considered bad practice as it doesn't make the intent clear.

If you want per-instance colors, the best solution is to get rid of the class level attribute and only set the color in the initializer ie

```<code>class Particle:

    # better to make this an implementation attribute
    _ID = 0

    @classmethod
    def _next_id(cls):
        cls._ID += 1
        return cls._ID

    def __init__(self, rect):
        self.ID = self._next_id()
        self.color = (255, 0, 0)
</code>```

or (if you want to be able to specify the color at instantiation time):

```<code>    def __init__(self, rect, color=(255, 0, 0)):
        self.ID = self._next_id()
        self.color = color
</code>```

Body:
here is my code :

size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

Body:
The fact you defined color in the class's namespace (making it a class attribute) doesn't make it available in methods bodies. Names in a method (actually a function) body are resolved at function execution time, not at function definition time, and at this point the color varibale defined in the class body has already be turned into a class attributes - they are not part of the function's non-local namespace.

Now the "proper" solution depends on what you want to achieve.

If all of your particle instance should share the same "color" value, just keep the class attribute and remove the instance one in your initializer - class attributes can be accessed directly from the instances, so self.color will automagically resolve to type(self).color. Note that this won't prevent you to assign per-instance color values - the class attribute is only accessed thru the instance if the instance has no attribute by that name, so setting your_particle.color = something_else (or self.color = ... - just the same) later in your code will still create an instance attribute and shadow the class-level one - but this is usually considered bad practice as it doesn't make the intent clear.

If you want per-instance colors, the best solution is to get rid of the class level attribute and only set the color in the initializer ie

class Particle:

    # better to make this an implementation attribute
    _ID = 0

    @classmethod
    def _next_id(cls):
        cls._ID += 1
        return cls._ID

    def __init__(self, rect):
        self.ID = self._next_id()
        self.color = (255, 0, 0)

or (if you want to be able to specify the color at instantiation time):

    def __init__(self, rect, color=(255, 0, 0)):
        self.ID = self._next_id()
        self.color = color


问:
Codeigniter Sessions Checking from a header view file
I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.

What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.

Can someone please show me how it can be done?

Ex. I don't want to do the following in every controller:

```<code>//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}
</code>```

Instead, I want something to like the following:

```<code>//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}
</code>```

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

答:
Firstly, theres no reason you can't just write something like this in your view:

```<code><? echo ($this->session->userdata('loggedin')) ? "Logged In": "Not Logged In"; ?>
</code>```

Then your controllers don't need any of that code.

However if the check is more complex or something, then theres a few places you can do it.

1) In the constructor of a custom controller: create a new file application/core/MY_Controller.php, and override the constructor with something like:

```<code>class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata("loggedin")) {
            // do something
        }
    }
}
</code>```

then make all your controllers extend MY_Controller.

2) Or in a post_controller_constructor hook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)

You can use native sessions with this:
http://codeigniter.com/wiki/Native_session/

Body:
I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.

What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.

Can someone please show me how it can be done?

Ex. I don't want to do the following in every controller:

//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}

Instead, I want something to like the following:

//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

Body:
Firstly, theres no reason you can't just write something like this in your view:

<? echo ($this->session->userdata('loggedin')) ? "Logged In": "Not Logged In"; ?>

Then your controllers don't need any of that code.

However if the check is more complex or something, then theres a few places you can do it.

1) In the constructor of a custom controller: create a new file application/core/MY_Controller.php, and override the constructor with something like:

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata("loggedin")) {
            // do something
        }
    }
}

then make all your controllers extend MY_Controller.

2) Or in a post_controller_constructor hook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)

You can use native sessions with this:
http://codeigniter.com/wiki/Native_session/


问:
Select rows where elements of two arrays don't match a pattern
I try to write a query where I select rows based one a LIKE pattern that has to match none of the entries of an array. What I have is the current one

```<code>SELECT * FROM mytable WHERE
NOT (EXISTS (SELECT * from unnest(a) WHERE  unnest LIKE '%XYZ%' )))
</code>```

Actually what I want is pairs - so it is more like

```<code>SELECT * FROM mytable WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%xyz%abc%' )) OR
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%abc%xyz%' ))
)
</code>```

This works for me but looks rather unwieldy. Is there prettier/more efficient solution to this? What I am find the most irksome is the SELECT as part of the WHERE clause to unroll arrays.

some points:

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists)

Both arrays have exactly the same number of elements (they are actually derived from another query)

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Edit:

Clarification: a row contains A as {rxyz,foo, bar} and B as {other, abc, this} should not be returned as it contains the rxyz in one array and abc in the other

Example:

```<code>SELECT * FROM(
 SELECT *
    FROM   (select 1 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 2 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{other,rabc,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 3 as ID, '{else,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row2

    ) mytable
WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||'-|-'||B LIKE '%xyz%-|-%abc%' OR B||'-|-'||A LIKE '%xyz%-|-%abc%' )))
</code>```

returns only row3. In my use case I can guaranty that -|- is not part of either list making it possible to separate these.

答:
You can unnest both into a single derived table:</p>

```<code>select *
from mytable
where not exists (select *
                  from unnest(a,b) as x(a,b)
                  where x.a like '%xyz%'
                     or x.b like '%xyz%'
                     or x.a like '%abc%'
                     or x.b like '%abc%')
</code>```

Body:
I try to write a query where I select rows based one a LIKE pattern that has to match none of the entries of an array. What I have is the current one

SELECT * FROM mytable WHERE
NOT (EXISTS (SELECT * from unnest(a) WHERE  unnest LIKE '%XYZ%' )))

Actually what I want is pairs - so it is more like

SELECT * FROM mytable WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%xyz%abc%' )) OR
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||B LIKE '%abc%xyz%' ))
)

This works for me but looks rather unwieldy. Is there prettier/more efficient solution to this? What I am find the most irksome is the SELECT as part of the WHERE clause to unroll arrays.

some points:

In my case xyz and abc will not appear together as substrings in a single array entry (e.g. nothing like xyzblaabcexists)

Both arrays have exactly the same number of elements (they are actually derived from another query)

no null elements (but even if that would still work as then I don't have a pair of abc and xyz)

Edit:

Clarification: a row contains A as {rxyz,foo, bar} and B as {other, abc, this} should not be returned as it contains the rxyz in one array and abc in the other

Example:

SELECT * FROM(
 SELECT *
    FROM   (select 1 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 2 as ID, '{rxyz,foo,bar}'::varchar[] as a, '{other,rabc,this}'::varchar[] as b) row1  UNION
 SELECT *
    FROM   (select 3 as ID, '{else,foo,bar}'::varchar[] as a, '{abc,other,this}'::varchar[] as b) row2

    ) mytable
WHERE
NOT (
  (EXISTS (select * from unnest(a) as A, unnest(b) as B  WHERE  A||'-|-'||B LIKE '%xyz%-|-%abc%' OR B||'-|-'||A LIKE '%xyz%-|-%abc%' )))

returns only row3. In my use case I can guaranty that -|- is not part of either list making it possible to separate these.

Body:
You can unnest both into a single derived table:

select *
from mytable
where not exists (select *
                  from unnest(a,b) as x(a,b)
                  where x.a like '%xyz%'
                     or x.b like '%xyz%'
                     or x.a like '%abc%'
                     or x.b like '%abc%')


问:
React making axios get, returns error: CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

```<code>useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);
</code>```

In my app.js on node.js express i have these lines:

```<code>var cors = require('cors');
app.use(cors());
</code>```

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)
```

<p>My backend:</p>

<p>...
    var cors = require('cors');
    ...</p>

```app.use(cors());
```

...

How should i edit my request?

答:
To solve the problem, you have to create a proxy server by nodejs and express(or anything else can help in proxying). If you are using the create-react-app, you can follow this tutorial:

Proxying API requests in development

Body:
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);

In my app.js on node.js express i have these lines:

var cors = require('cors');
app.use(cors());

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)

My backend:

...
    var cors = require('cors');
    ...

app.use(cors());

...

How should i edit my request?


问:
How to count in a range with .Find() function in VBA
I have the following Excel Worksheet

With the following .Find() function I found the value that I need and the cell.

```<code>Dim finalResult as Range
Dim finalValue as String
Dim headValue as string

finalValue = "Banana"
headValue = "Food"

Set finalResult = Worksheets("mySheet").Range("A1:A20").Find(finalValue, LookIn:=xlValues, After:=headValue)
</code>```

My question is: Knowing the Start = Food and the End = Banana of the range, how do I count how many cells there are between?

Thank you

答:
Use this code, please. There are more methods to find your cells, but I will use the one you look to prefer:</p>

```<code>Sub testFindRange()
 Dim finalResFood As Range, finalResBanana As Range
 Dim finalValue As String, headValue As String, sh As Worksheet
 Set sh = Worksheets("mySheet")' Having more workbooks open, it would be good to define it using the workbook where it belongs, too.

 finalValue = "Banana"
 headValue = "Food"

 Set finalResBanana = sh.Range("A1:A20").Find(finalValue, LookIn:=xlValues)
 Set finalResFood = sh.Range("A1:A20").Find(headValue, LookIn:=xlValues)
 Debug.Print finalResBanana.row - finalResFood.row
End Sub
</code>```

Body:
I have the following Excel Worksheet

With the following .Find() function I found the value that I need and the cell.

Dim finalResult as Range
Dim finalValue as String
Dim headValue as string

finalValue = "Banana"
headValue = "Food"

Set finalResult = Worksheets("mySheet").Range("A1:A20").Find(finalValue, LookIn:=xlValues, After:=headValue)

My question is: Knowing the Start = Food and the End = Banana of the range, how do I count how many cells there are between?

Thank you

Body:
Use this code, please. There are more methods to find your cells, but I will use the one you look to prefer:

Sub testFindRange()
 Dim finalResFood As Range, finalResBanana As Range
 Dim finalValue As String, headValue As String, sh As Worksheet
 Set sh = Worksheets("mySheet")' Having more workbooks open, it would be good to define it using the workbook where it belongs, too.

 finalValue = "Banana"
 headValue = "Food"

 Set finalResBanana = sh.Range("A1:A20").Find(finalValue, LookIn:=xlValues)
 Set finalResFood = sh.Range("A1:A20").Find(headValue, LookIn:=xlValues)
 Debug.Print finalResBanana.row - finalResFood.row
End Sub


问:
Iterate over a list by setting element as a variable
I would like to create 12 dataframes labelled with month names by using a for loop. So I created a list with the month names list_month. But I am not able to insert the variable i as df_[i] in the for loop.

The operation I am trying to do is to create a new dataframe df_new_month like df_new_feb = df_feb[df_feb['my_feature'] > 20] for each month contained in the list:

Should I follow a different approach?

list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
    print(i, list_month[i])
```

<p>The Error I get is:</p>

```Traceback (most recent call
  last):File"/Users/annalisa/anaconda3/lib/python3.7/site_
  packages/IPython/core/interactiveshell.py", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-50-c09b1f63eb51>", line 3, in <module>
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
NameError: name 'df_' is not defined
```

答:
In my opinion you have to define at first the variable (df_) and then go with your for loop.

For example at least :

df_ = 0
list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    df_[i] = df_[i][df_[i]['my_feature'] > 20]
    print(i, list_month[i])
```

Body:
I would like to create 12 dataframes labelled with month names by using a for loop. So I created a list with the month names list_month. But I am not able to insert the variable i as df_[i] in the for loop.

The operation I am trying to do is to create a new dataframe df_new_month like df_new_feb = df_feb[df_feb['my_feature'] > 20] for each month contained in the list:

Should I follow a different approach?

list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
    print(i, list_month[i])

The Error I get is:

Traceback (most recent call
  last):File"/Users/annalisa/anaconda3/lib/python3.7/site_
  packages/IPython/core/interactiveshell.py", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-50-c09b1f63eb51>", line 3, in <module>
    df_new_[i] = df_[i][df_[i]['my_feature'] > 20]
NameError: name 'df_' is not defined


问:
How to declare a time-based alphanumerical id field with predefined aplphabetic part (Django model)
I am developing an app in Django.

I wanted to insert in my model an auto-incrementing alphanumerical unique ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part.

I tryed to implement this, but it turned out that trying to implement such a field and making it the autofield of the model generates problems in my database.

So I am changing my aim: now I want to implement a time-based alphanumerical unique field with predefined aplphabetic part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value a unique customized alphanumerical value.

Here is what I did, in my models.py:

```<code>def return_timestamped_id():
    prefix = "ITCH"
    import time
    this_time = time.time()
    this_time  = this_time  *10000000
    this_time  = int(this_time)
    timestamp = str(this_time)
    default_value = prefix + timestamp
    return(default_value)

class object_example(models.Model):
    name = models.CharField(max_length=256, blank=True, null=True)
    Id_generated = models.CharField(max_length=256, blank=False, null=False, unique=True, default=return_timestamped_id())
</code>```

The problem is that, as I add objects to this model from the admin section, The
Id_generated is always the same.

I expected that the return_timestamped_id() function was called every time I add a new object. It is clear instead that is called just once and then the same return value is passed to the Id_generated of every new object.

How can I change my code in order to get a different timestamp every time a new object is added?

答:
As you probably saw in the Django docs, you can use either a value or a callable as a default.  If you use a callable (e.g. a function) then it will be called each time a default is needed.

The problem: you were passing a value because you were calling your function default=return_timestamped_id().  The function was being called once, when your module (models.py) was imported into the application.

The solution: pass the function itself default=return_timestamped_id

You can see in the django.models.Fields class the relevant code (comments mine):

```<code>class Field():
    def __init__(self, ..., default=NOT_PROVIDED,...):
        ...
        self.default = default  # save the default as a member variable
        ...

    def get_default(self):
        """Return the default value for this field."""
        return self._get_default()

    @cached_property
    def _get_default(self):
        if self.has_default():
            if callable(self.default):  # if it is callable, return it
                return self.default
            return lambda: self.default # else wrap in a callable
</code>```

Body:
I am developing an app in Django.

I wanted to insert in my model an auto-incrementing alphanumerical unique ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part.

I tryed to implement this, but it turned out that trying to implement such a field and making it the autofield of the model generates problems in my database.

So I am changing my aim: now I want to implement a time-based alphanumerical unique field with predefined aplphabetic part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value a unique customized alphanumerical value.

Here is what I did, in my models.py:

def return_timestamped_id():
    prefix = "ITCH"
    import time
    this_time = time.time()
    this_time  = this_time  *10000000
    this_time  = int(this_time)
    timestamp = str(this_time)
    default_value = prefix + timestamp
    return(default_value)

class object_example(models.Model):
    name = models.CharField(max_length=256, blank=True, null=True)
    Id_generated = models.CharField(max_length=256, blank=False, null=False, unique=True, default=return_timestamped_id())

The problem is that, as I add objects to this model from the admin section, The
Id_generated is always the same.

I expected that the return_timestamped_id() function was called every time I add a new object. It is clear instead that is called just once and then the same return value is passed to the Id_generated of every new object.

How can I change my code in order to get a different timestamp every time a new object is added?

Body:
As you probably saw in the Django docs, you can use either a value or a callable as a default.  If you use a callable (e.g. a function) then it will be called each time a default is needed.

The problem: you were passing a value because you were calling your function default=return_timestamped_id().  The function was being called once, when your module (models.py) was imported into the application.

The solution: pass the function itself default=return_timestamped_id

You can see in the django.models.Fields class the relevant code (comments mine):

class Field():
    def __init__(self, ..., default=NOT_PROVIDED,...):
        ...
        self.default = default  # save the default as a member variable
        ...

    def get_default(self):
        """Return the default value for this field."""
        return self._get_default()

    @cached_property
    def _get_default(self):
        if self.has_default():
            if callable(self.default):  # if it is callable, return it
                return self.default
            return lambda: self.default # else wrap in a callable


问:
Execute javascript from inside update panel on every refresh
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

```<code><asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

答:
here is how can you do this....</p>

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

        Sys.Application.add_init(appl_init);

        function appl_init() {
            var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
            pgRegMgr.add_endRequest(EndHandler);
        }

        function EndHandler() {
        // This will be called whenever your updatepanel update
        // It will be trigger after the update updatepanel
        //add your javascript here
        }
    </script>
</code>```

Body:
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

<asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

Body:
here is how can you do this....

 <script type="text/javascript">

        Sys.Application.add_init(appl_init);

        function appl_init() {
            var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
            pgRegMgr.add_endRequest(EndHandler);
        }

        function EndHandler() {
        // This will be called whenever your updatepanel update
        // It will be trigger after the update updatepanel
        //add your javascript here
        }
    </script>


问:
window.print() is not working in chrome 77 version
I am facing one issue since my chrome browser is updated to version 77.

Initially window.print() is working fine, but once I open a page where it includes embedded PDF using <embed> tag, window.print() stopped working. Using Ctrl+P shortcut it opens the print popup but when I execute window.print() in javascript it doesn't work.

I have executed window.print() command in console, it directly returns undefined.

There might be a some changes in Chrome 77 release as per this thread https://support.google.com/chrome/thread/14107571?hl=en

Does any one have face this issue ?
Please help.

答:
```<code>$(document).ready(function () {

    var URL;

    $('#Print').click(function () {
        $('#embed').remove();
        URL= 'url';

        setTimeout(cPrint, 100);
    });
    function cPrint() {
        window.print();

        $('#div').append('<embed id="embed" src="' + URL + '" />');
    }

});
</code>```


问:
Dictionary of dictionaries in python
Im trying to create a dictionary of dictionaries in python. I have a nested for loop which looks like this

```<code>frequencyLomb = {}
for J in range(1,81,4):
  n_items = take(dataDays.values(),J-1,J+3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    # frequencyLomb[J][K] = freq_grid(temp_time)   want something like this
</code>```

n_items is a 4 element list with indexes 0 to 3 and in every one of these is a two element list with indexes 0 and 1. Now I want to create a dictionary of dictionaries which will save the value of frequencyLomb in way so that the Key name will be the variable J and the items will be added from the inner for loop so the final product will look like this:

```<code>frequencyLomb= {1: {1: 'somevalue1', 2: 'somevalue1', 3: 'somevalue1', 4: 'somevalue1', 5: 'somevalue1'},
      5: {1: 'somevalue1',....}}
</code>```

etc. up to Key number 80

P.S.: The function freq_grid just creates an array of floats and the function take takes the values from dictionary dataDays(dictionary of lists) with keys number J-1 up to values with key J+3

Thanks. Any help is appreciated

答:
You might be looking for defaultdict from collections in the standard library. Creating a defaultdict with dict as default factory will enable you to write to frequencyLomb[J][K] without first creating dict at frequencyLomb[J].

```<code>from collections import defaultdict

frequencyLomb = defaultdict(dict)

for J in range(1, 81, 4):
  n_items = take(dataDays.values(), J - 1, J + 3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    frequencyLomb[J][K] = freq_grid(temp_time)
</code>```

Title: Dictionary of dictionaries in python

Body:
Im trying to create a dictionary of dictionaries in python. I have a nested for loop which looks like this

frequencyLomb = {}
for J in range(1,81,4):
  n_items = take(dataDays.values(),J-1,J+3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    # frequencyLomb[J][K] = freq_grid(temp_time)   want something like this

n_items is a 4 element list with indexes 0 to 3 and in every one of these is a two element list with indexes 0 and 1. Now I want to create a dictionary of dictionaries which will save the value of frequencyLomb in way so that the Key name will be the variable J and the items will be added from the inner for loop so the final product will look like this:

frequencyLomb= {1: {1: 'somevalue1', 2: 'somevalue1', 3: 'somevalue1', 4: 'somevalue1', 5: 'somevalue1'},
      5: {1: 'somevalue1',....}}

etc. up to Key number 80

P.S.: The function freq_grid just creates an array of floats and the function take takes the values from dictionary dataDays(dictionary of lists) with keys number J-1 up to values with key J+3

Thanks. Any help is appreciated

Body:
You might be looking for defaultdict from collections in the standard library. Creating a defaultdict with dict as default factory will enable you to write to frequencyLomb[J][K] without first creating dict at frequencyLomb[J].

from collections import defaultdict

frequencyLomb = defaultdict(dict)

for J in range(1, 81, 4):
  n_items = take(dataDays.values(), J - 1, J + 3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    frequencyLomb[J][K] = freq_grid(temp_time)


问:
How I can merge two audio files - JavaScript?
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.

e.g. (audio1.webm) and (audio2.webm).

```<code>mediaRecorder.stopRecording(function() {
    var blob = mediaRecorder.getBlob();
    var fileName = getFileName('webm');

    var fileObject = new File([blob], fileName, {
        type: 'audio/webm'
    });

    var formData = new FormData();
        formData.append('blob', fileObject);
        formData.append('filename', fileObject.name);

    $.ajax({
        url: '{{ url('/') }}/save-audio',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    });
});
</code>```

Thank you in advance.

UPDATE:

I made it this way instead of recorder.addStreams, and still I can get the recorded.

```<code>var remoteVideos = $('#remoteVideos video');
var el = [];

$.each($('#remoteVideos video'), function(index, val) {
     el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);
</code>```

答:
You can use a similar library: MediaStreamRecorder. Then use MultiStreamRecorder and pass two streams as below,

```<code>recorder = new MultiStreamRecorder([localStream, remoteStream]);
</code>```

You will get localStream from getUserMedia and remoteStream from onaddstream event listener.

You may want to just pass the audio tracks in the array. The rest of the things as it is. FFmpeg and file merging is not necessary.

Body:
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.

e.g. (audio1.webm) and (audio2.webm).

mediaRecorder.stopRecording(function() {
    var blob = mediaRecorder.getBlob();
    var fileName = getFileName('webm');

    var fileObject = new File([blob], fileName, {
        type: 'audio/webm'
    });

    var formData = new FormData();
        formData.append('blob', fileObject);
        formData.append('filename', fileObject.name);

    $.ajax({
        url: '{{ url('/') }}/save-audio',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    });
});

Thank you in advance.

UPDATE:

I made it this way instead of recorder.addStreams, and still I can get the recorded.

var remoteVideos = $('#remoteVideos video');
var el = [];

$.each($('#remoteVideos video'), function(index, val) {
     el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);

Body:
You can use a similar library: MediaStreamRecorder. Then use MultiStreamRecorder and pass two streams as below,

recorder = new MultiStreamRecorder([localStream, remoteStream]);

You will get localStream from getUserMedia and remoteStream from onaddstream event listener.

You may want to just pass the audio tracks in the array. The rest of the things as it is. FFmpeg and file merging is not necessary.


问:
jQuery Center Div toggle in IE6
Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto; How can i work around this. div width is dynamic and not always 200px.

Check jsfiddle http://jsfiddle.net/hZ23J/1/

```<code><button id="center">Left Align</button>
<div></div>

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $(this).text('Left Align')
});
</code>```

答:
This solution works for me in IE6...

```<code>$('#center').click(function () {
    $('div').toggleClass('center');
});
</code>```

class...

```<code>.center { margin: 0px auto; }
</code>```

It's also good practice to keep your JS and CSS separate when possible.

Here is my doctype...

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

Title: jQuery Center Div toggle in IE6

Body:
Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto; How can i work around this. div width is dynamic and not always 200px.

Check jsfiddle http://jsfiddle.net/hZ23J/1/

<button id="center">Left Align</button>

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $(this).text('Left Align')
});

Body:
This solution works for me in IE6...

$('#center').click(function () {
    $('div').toggleClass('center');
});

class...

.center { margin: 0px auto; }

It's also good practice to keep your JS and CSS separate when possible.

Here is my doctype...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


问:
How to export multiple arrays
if I have two arrays how do I export them for example:</p>

```<code>const a=['a','b','c']
const b=['1','2','3']

export default a,b?
</code>```

答:
```<code>export const a=['a','b','c']
export const b=['1','2','3']

//Import page
import { a } from "path/to/a";
import { b } from "path/to/b";
</code>```

export const foo = "This is not default export"

from each file you can have max 1 default export, but as many not default as you want. Just the import syntaxt is different

Title: How to export multiple arrays

Body:
if I have two arrays how do I export them for example:

const a=['a','b','c']
const b=['1','2','3']

export default a,b?

Body:
export const a=['a','b','c']
export const b=['1','2','3']

//Import page
import { a } from "path/to/a";
import { b } from "path/to/b";

export const foo = "This is not default export"

from each file you can have max 1 default export, but as many not default as you want. Just the import syntaxt is different


问:
Lazy load locales for nuxt-i18n
In nuxt-i18n you must specify the locales property with the locales your app will be supporting like this:

```<code>  locales: [
    {
      code: 'en',
      file: 'en-US.js'
    },
    {
      code: 'es',
      file: 'es-ES.js'
    },
    {
      code: 'fr',
      file: 'fr-FR.js'
    }
  ],
</code>```

Could be this fetched from api endpoint and then fill the array?

I've seen something similar in this issue https://github.com/nuxt-community/nuxt-i18n/issues/256#issuecomment-505344965 but I have no idea how to run that code or even it's that possible.

答:
The solution was simple. Nuxt allows you to export an async function as options so I can get the data and next assign it to the i18n object.

https://nuxtjs.org/guide/configuration/#asynchronous-configuration

```<code>export default async () => {
  const data = await getCountries()

  const locales = []

  for (const locale of data) {
    locales.push({
      code: locale,
      file: `${locale}.json`
    })
  }

  return {
      build: {
          ...
      },
      env: {
          ...
      },
      modules: [
          'nuxt-i18n',
          ...
      ],
      i18n: {
          locales,
          strategy: 'prefix',
          detectBrowserLanguage: false,
          lazy: true,
          defaultLocale: 'es',
          langDir: 'translations/'
      },
      ...
  }
}
</code>```

Title: Lazy load locales for nuxt-i18n

Body:
In nuxt-i18n you must specify the locales property with the locales your app will be supporting like this:

  locales: [
    {
      code: 'en',
      file: 'en-US.js'
    },
    {
      code: 'es',
      file: 'es-ES.js'
    },
    {
      code: 'fr',
      file: 'fr-FR.js'
    }
  ],

Could be this fetched from api endpoint and then fill the array?

I've seen something similar in this issue https://github.com/nuxt-community/nuxt-i18n/issues/256#issuecomment-505344965 but I have no idea how to run that code or even it's that possible.

Body:
The solution was simple. Nuxt allows you to export an async function as options so I can get the data and next assign it to the i18n object.

https://nuxtjs.org/guide/configuration/#asynchronous-configuration

export default async () => {
  const data = await getCountries()

  const locales = []

  for (const locale of data) {
    locales.push({
      code: locale,
      file: `${locale}.json`
    })
  }

  return {
      build: {
          ...
      },
      env: {
          ...
      },
      modules: [
          'nuxt-i18n',
          ...
      ],
      i18n: {
          locales,
          strategy: 'prefix',
          detectBrowserLanguage: false,
          lazy: true,
          defaultLocale: 'es',
          langDir: 'translations/'
      },
      ...
  }
}


问:
Execute shell script via Jenkins
I have a very simple shell script build-dev.sh. This is how it looks like:

```<code>#artifact build script
echo "Running application build for DEV environment"

ng build --deploy-url "js/" --base-href "/my-app-ui/" --configuration=dev
mkdir dist/my-app-ui/js
mv ./dist/my-app-ui/*.{js,svg,css} ./dist/my-app-ui/js
</code>```

It builds the Angular application, then creates a folder js and then it moves files with the extensions js, svg and css to this folder.

When I execute this script directly by myself it works perfectly.

The issue is that I want the script to be executed by Jenkins. So I have configured "Execute shell" step in my build. Once the Jenkins job is executed, it fails on the execution of the third line of the script (mv command).

```<code>mv: cannot stat './dist/my-app-ui/*.{js,svg,css}': No such file or directory
Build step 'Execute shell' marked build as failure
</code>```

I think it might be related to the fact that I have .*{js,svg,css} in my script.

Can you please tell me what I am doing wrong?

答:
Well, I am still not sure why it does not work, but the problem is in the usage of brackets - {js,svg,css}.
I have replaced the mv command with three lines:

```<code>mv ./dist/my-app-ui/*.js ./dist/my-app-ui/js
mv ./dist/my-app-ui/*.svg ./dist/my-app-ui/js
mv ./dist/my-app-ui/*.css ./dist/my-app-ui/js
</code>```

This works perfectly. It is still some kind of workaround, but it's doing the exactly same, so it works fine for me.

Title: Execute shell script via Jenkins

Body:
I have a very simple shell script build-dev.sh. This is how it looks like:

#artifact build script
echo "Running application build for DEV environment"

ng build --deploy-url "js/" --base-href "/my-app-ui/" --configuration=dev
mkdir dist/my-app-ui/js
mv ./dist/my-app-ui/*.{js,svg,css} ./dist/my-app-ui/js

It builds the Angular application, then creates a folder js and then it moves files with the extensions js, svg and css to this folder.

When I execute this script directly by myself it works perfectly.

The issue is that I want the script to be executed by Jenkins. So I have configured "Execute shell" step in my build. Once the Jenkins job is executed, it fails on the execution of the third line of the script (mv command).

mv: cannot stat './dist/my-app-ui/*.{js,svg,css}': No such file or directory
Build step 'Execute shell' marked build as failure

I think it might be related to the fact that I have .*{js,svg,css} in my script.

Can you please tell me what I am doing wrong?

Body:
Well, I am still not sure why it does not work, but the problem is in the usage of brackets - {js,svg,css}.
I have replaced the mv command with three lines:

mv ./dist/my-app-ui/*.js ./dist/my-app-ui/js
mv ./dist/my-app-ui/*.svg ./dist/my-app-ui/js
mv ./dist/my-app-ui/*.css ./dist/my-app-ui/js

This works perfectly. It is still some kind of workaround, but it's doing the exactly same, so it works fine for me.


问:
Prevent phone from sending MouseLeftButtonUp event while scrolling
How can I prevent the windows phone 7 from sending a MouseLeftButtonUp-event to my Grid (that I use as Button) while the user is scrolling?

This issue sometimes leads to a navigation to another page just when the user scrolling.

Or should I use a Button-Template for this?

Example code:

```<code><ScrollViewer>
    <StackPanel>
        <Grid x:Name="Button1" MouseLeftButtonUp="Button1_LeftMouseButtonUp">
            <TextBlock Margin="12 15" />
        </Grid>
    </StackPanel>
</ScrollViewer>
</code>```

答:
Instead of LeftMouseButtonUp event try this</p>

```<code>private void Button1_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
    if (!e.IsInertial)
    {
        //Button Click Code
    }
}
</code>```

Body:
How can I prevent the windows phone 7 from sending a MouseLeftButtonUp-event to my Grid (that I use as Button) while the user is scrolling?

This issue sometimes leads to a navigation to another page just when the user scrolling.

Or should I use a Button-Template for this?

Example code:

<ScrollViewer>
    <StackPanel>
        <Grid x:Name="Button1" MouseLeftButtonUp="Button1_LeftMouseButtonUp">
            <TextBlock Margin="12 15" />
        </Grid>
    </StackPanel>
</ScrollViewer>

Body:
Instead of LeftMouseButtonUp event try this

private void Button1_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
    if (!e.IsInertial)
    {
        //Button Click Code
    }
}