问:
Order by custom field value not working for acf date field
I have custom post type event which has custom field event_date. The date format for this field is set to Ymd.

I'm trying to get posts in order of event_date

Here is the code to pull the posts in that order

```<code>$today = date('Ymd');

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
        )
    ),
    'suppress_filters' => true
);
/*
global $wp_filter;
var_dump( $wp_filter['posts_orderby'] );die;
This returns NULL as well
*/

    $query = new WP_Query( $args );
    echo '```';
    var_dump($query->request);die;
```

<p>But the $query->request shows the ORDER BY as post_date rahter than my supplied query.
Here is the dump of request</p>

```string(681) "SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND (
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (11)
            )
) AND (
  wp_postmeta.meta_key = 'event_date'
  AND
  (
    ( mt1.meta_key = 'event_date' AND mt1.meta_value >= '20171113' )
  )
) AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date ASC "
```

<p>can't order by the event_date.
What am i doing wrong??
Even tried by having</p>

```remove_all_filters('posts_orderby');
```

before the wp_query still same result.

FINALLY: Thanks everyone for your kind responses, finnally solved by just changing the order_by to orderby in my query.
Thanks @Prasanna Venkatesh  for letting me check in phpmyadmin. Ran the code in phpmyadmin and fixed it. PS: the sql query was correct except the order_by.

答:
use 'meta_value_num' in your orderby type and</p>

```<code>$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => -1,
    'meta_key'              => 'event_date',
    'orderby'               => 'meta_value_num',
    'order'                 => 'ASC',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
            'type'      => 'NUMERIC'
        )
    ),
    'suppress_filters' => true
);
</code>```

Body:
I have custom post type event which has custom field event_date. The date format for this field is set to Ymd.

I'm trying to get posts in order of event_date

Here is the code to pull the posts in that order

$today = date('Ymd');

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => '-1',
    'order'                 => 'ASC',
    'orderby'              =>'meta_value', // also tried having meta_value_num but that didn't worked as well
    'meta_key'              =>'event_date',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
        )
    ),
    'suppress_filters' => true
);
/*
global $wp_filter;
var_dump( $wp_filter['posts_orderby'] );die;
This returns NULL as well
*/

    $query = new WP_Query( $args );
    echo '
';
    var_dump($query->request);die;

But the $query->request shows the ORDER BY as post_date rahter than my supplied query.
Here is the dump of request

string(681) "SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND (
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (11)
            )
) AND (
  wp_postmeta.meta_key = 'event_date'
  AND
  (
    ( mt1.meta_key = 'event_date' AND mt1.meta_value >= '20171113' )
  )
) AND wp_posts.post_type = 'event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date ASC "

can't order by the event_date.
What am i doing wrong??
Even tried by having

remove_all_filters('posts_orderby');

before the wp_query still same result.

FINALLY: Thanks everyone for your kind responses, finnally solved by just changing the order_by to orderby in my query.
Thanks @Prasanna Venkatesh  for letting me check in phpmyadmin. Ran the code in phpmyadmin and fixed it. PS: the sql query was correct except the order_by.

Body:
use 'meta_value_num' in your orderby type and

$args = array (
    'post_type'             => array( 'event' ),
    'posts_per_page'        => -1,
    'meta_key'              => 'event_date',
    'orderby'               => 'meta_value_num',
    'order'                 => 'ASC',
    'meta_query' => array(
        array(
            'key'       => 'event_date',
            'compare'   => '>=',
            'value'     => $today,
            'type'      => 'NUMERIC'
        )
    ),
    'suppress_filters' => true
);


来源: stackexchange

问:
Where are the class files of jsp files stored in netbeans 8.0
I have two files in my sample web application: 'index.jsp, Jsp1.jsp'. When i run this web application where are the class files of these two jsp files stored in netbeans 8.0?

I searched for the class files in project folder but i couldn't find any.

答:
I know it is very late but it may help someone!!

If you are using glassfish server, find the generated sources under

C:\glassfishv2.1\glassfish\domains\domain1\generated\jsp

Note: I am using glassfish 2.1. In your case you may be using different version.

For tomcat server it is well answered at Where are compiled JSP Java (*__jsp.java) files?

For your reference go through the documentation to enable generate source if you do not see at https://blogs.oracle.com/foo/i-want-to-see-my-jsps-generated-servlet-source

ContentLicense: CC BY-SA 3.0


问:
Disabling/Removing caret from chat window
I have setup richedit control as a chat window and I've no idea how to remove the blinking caret from the control, does anyone know how to do that in edit/richedit control?</p>

答: Use HideCaret().

ContentLicense: CC BY-SA 2.5

Body: Use HideCaret().


问:
Sum the number of firms in one year
Suppose I have a dataframe as follows:

```<code>dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002
</code>```

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

```<code> resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1
</code>```

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

答:
This isn't a complete solution as the results do not include the missing 'exited' years.  Including them is possible, but a lot of extra steps.  Using two libraries, dplyr and tidyr we can walk through the process.

```<code>library(dplyr)
library(tidyr)
dt %>%
  group_by(firm) %>%
  summarise(entered=min(year),exited=max(year),count=1) %>%
  group_by(entered,exited) %>%
  summarise(count=sum(count)) %>%
  mutate(All = sum(count)) %>%
  ungroup() %>%
  spread(exited,count,fill=0)

> # A tibble: 2 x 5
>   entered   All `2002` `2004` `2005`
> *   <dbl> <dbl>  <dbl>  <dbl>  <dbl>
> 1    2001     3      2      1      0
> 2    2002     3      1      1      1
</code>```

group_by indicates we want to operate within firm

summarise will calculate values once per group, here we get entered, exited and we produce a counting variable count

Now we group by entered and exited (the order is important), so we're grouping on the cross of both years

We now sum our counting variable by the combination of years.  summarise here drops the right most level of grouping

mutate creates a new variable, All in this case which looks just like the summarise but instead of collapsing rows, it computes it within our group, duplicating for duplicate rows.

ungroup removes residual grouping

spread creates a column for each value in our key, populating it with the specified value column, filling in missing values with 0

Title: Sum the number of firms in one year

Body:
Suppose I have a dataframe as follows:

dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

 resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

Body:
This isn't a complete solution as the results do not include the missing 'exited' years.  Including them is possible, but a lot of extra steps.  Using two libraries, dplyr and tidyr we can walk through the process.

library(dplyr)
library(tidyr)
dt %>%
  group_by(firm) %>%
  summarise(entered=min(year),exited=max(year),count=1) %>%
  group_by(entered,exited) %>%
  summarise(count=sum(count)) %>%
  mutate(All = sum(count)) %>%
  ungroup() %>%
  spread(exited,count,fill=0)

> # A tibble: 2 x 5
>   entered   All `2002` `2004` `2005`
> *   <dbl> <dbl>  <dbl>  <dbl>  <dbl>
> 1    2001     3      2      1      0
> 2    2002     3      1      1      1

group_by indicates we want to operate within firm

summarise will calculate values once per group, here we get entered, exited and we produce a counting variable count

Now we group by entered and exited (the order is important), so we're grouping on the cross of both years

We now sum our counting variable by the combination of years.  summarise here drops the right most level of grouping

mutate creates a new variable, All in this case which looks just like the summarise but instead of collapsing rows, it computes it within our group, duplicating for duplicate rows.

ungroup removes residual grouping

spread creates a column for each value in our key, populating it with the specified value column, filling in missing values with 0


问:
I need to include a triangle as background on a div using css.

Need to add the triangle to the top right corner of a div and make text flow over it. Can we achieve this with plain css without using an image?

答:
You could apply a pseudo element or nest additional divs in your container to get the triangle in the top right position behind the text.

See https://css-tricks.com/examples/ShapesOfCSS/ for examples of css you would need.


问:
Recently add new Drive, Which method below are best to boost Database performance
I was using SQL Server, recently add Hard Disk, I want to use it to boost the Disk I/O for Database process if possible.

A. Merge Two Drive

B. Split mdf(data) and ldf(log) across two drive.

C. Split mdf(data) into 2 ndf(secondary data) across two drive.

what method are the best.

答:
I would go with placing mdf and ldf into seperate drives and also this goes with the best practice of placing log files in its own drive..

I would also check if the disk is good enough for my needs,if not i will go with a good enough disk

There are some good articles which helps in how to configure hard disk and best practices..

http://sqlserveradvisor.blogspot.in/2009/03/sql-server-disk-configuration.html


问:
Can't get this function to display
for starters I'm new to coding so I am sure some of this code will look nasty and probably hard to understand. The program is supposed to have the user enter 5 classes, and 5 test scores for each class, then using functions, I need to find the lowest test score, highest test score, and the average of the scores for each class, all of which I have done in there respective functions. Then display it all using another function, there is my problem. I think it is a simple fix, but I am not sure, all I need to do is call the display function from main, and then have it display, but it just gives me syntax errors every time. Like I said, I think it will be an easy fix, but I am not sure. Any help would be appreciated!</p>

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int minfun(int lowest, int test[5][5])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] < lowest)
            {
                lowest = test[a][i];
            }
        }
    }
    return lowest;
}

int maxfun(int highest, int test[5][5])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] > highest)
            {
                highest = test[a][i];
            }
        }
    }
    return highest;
}

double classavg(double avg, int sum, int test[])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            sum = sum + test[a];
        }
    }
    avg = sum / 5;
    return avg;
}

void display(string classes[], int test[], int lowest, int highest, double avg)
{
    minfun(lowest, test[5]);
    maxfun(highest, test[5]);
    classavg(avg, sum, test[5]);
    for (int a = 0; a < 5; a++)
        {
        for (int i = 0; i < 5; i++)
            {
                cout << "=============================================================" << endl;
                cout << "Displaying stats for " << classes[a] << endl;
                cout << "Lowest test score for " << classes[a] << " is: " << lowest << endl;
                cout << "Highest test score for " << classes[a] << " is: " << highest << endl;
                cout << "The average for " << classes[a] << "is: " << avg << endl;
                cout << "=============================================================" << endl;
            }
        }
    //needs for loop to display stats for each class
}

int main()
{
    const int max_test = 5;
    int lowest = 100;
    int highest = 0;
    int sum = 0;
    double avg = 0;
    string classes[5];
    int test[5][5];

    cout << "Enter the name of your first class: ";
    getline (cin,classes[0]);
    cout << "Enter the name of your second class: ";
    getline (cin, classes[1]);
    cout << "Enter the name of your third class: ";
    getline(cin, classes[2]);
    cout << "Enter the name of your fourth class: ";
    getline(cin, classes[3]);
    cout << "Enter the name of your fifth class: ";
    getline(cin, classes[4]);
    cout << "=============================================================" << endl;
    for (int a = 0; a <= max_test; a++)
    {
        for (int i = 1; i <= max_test; i++)
        {
            cout << "Enter score for test " << i << " in " << classes[a] << " : ";
            cin >> test[a][i];
        }
        cout << "=============================================================" << endl;
    }
    cout << "=============================================================" << endl;
    display(lowest, highest, avg);
    system("pause");
    return 0;
}
</code>```

答:
you have problem passing parameters to a function , i suggest you look that up..
BTW I've made your variables static and fixed up some errors .. and it seems to work
Kudos..</p>

```<code>#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
static string classes[5];
static int test[5][5];
static const int max_test = 5;
static int lowest = 100;
static int highest = 0;
static int sum = 0;
static double avg = 0;

int minfun(int lowest)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] < lowest)
            {
                lowest = test[a][i];
            }
        }
    }
    return lowest;
}

int maxfun(int highest)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] > highest)
            {
                highest = test[a][i];
            }
        }
    }
    return highest;
}

double classavg(double avg)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            sum = sum + test[a][i];
        }
    }
    avg = sum / 5;
    return avg;
}

void display(int lowest, int highest, double avg)
{
    minfun(lowest);
    maxfun(highest);
    classavg(avg);
    for (int a = 0; a < 5; a++)
        {
        for (int i = 0; i < 5; i++)
            {
                cout << "=============================================================" << endl;
                cout << "Displaying stats for " << classes[a] << endl;
                cout << "Lowest test score for " << classes[a] << " is: " << lowest << endl;
                cout << "Highest test score for " << classes[a] << " is: " << highest << endl;
                cout << "The average for " << classes[a] << "is: " << avg << endl;
                cout << "=============================================================" << endl;
            }
        }
    //needs for loop to display stats for each class
}

int main()
{

    cout << "Enter the name of your first class: ";
    getline (cin,classes[0]);
    cout << "Enter the name of your second class: ";
    getline (cin, classes[1]);
    cout << "Enter the name of your third class: ";
    getline(cin, classes[2]);
    cout << "Enter the name of your fourth class: ";
    getline(cin, classes[3]);
    cout << "Enter the name of your fifth class: ";
    getline(cin, classes[4]);
    cout << "=============================================================" << endl;
    for (int a = 0; a <= max_test; a++)
    {
        for (int i = 1; i <= max_test; i++)
        {
            cout << "Enter score for test " << i << " in " << classes[a] << " : ";
            cin >> test[a][i];
        }
        cout << "=============================================================" << endl;
    }
    cout << "=============================================================" << endl;
    display(lowest, highest, avg);
    system("pause");
    return 0;
}
</code>```

Title: Can't get this function to display

Body:
for starters I'm new to coding so I am sure some of this code will look nasty and probably hard to understand. The program is supposed to have the user enter 5 classes, and 5 test scores for each class, then using functions, I need to find the lowest test score, highest test score, and the average of the scores for each class, all of which I have done in there respective functions. Then display it all using another function, there is my problem. I think it is a simple fix, but I am not sure, all I need to do is call the display function from main, and then have it display, but it just gives me syntax errors every time. Like I said, I think it will be an easy fix, but I am not sure. Any help would be appreciated!

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int minfun(int lowest, int test[5][5])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] < lowest)
            {
                lowest = test[a][i];
            }
        }
    }
    return lowest;
}

int maxfun(int highest, int test[5][5])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] > highest)
            {
                highest = test[a][i];
            }
        }
    }
    return highest;
}

double classavg(double avg, int sum, int test[])
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            sum = sum + test[a];
        }
    }
    avg = sum / 5;
    return avg;
}

void display(string classes[], int test[], int lowest, int highest, double avg)
{
    minfun(lowest, test[5]);
    maxfun(highest, test[5]);
    classavg(avg, sum, test[5]);
    for (int a = 0; a < 5; a++)
        {
        for (int i = 0; i < 5; i++)
            {
                cout << "=============================================================" << endl;
                cout << "Displaying stats for " << classes[a] << endl;
                cout << "Lowest test score for " << classes[a] << " is: " << lowest << endl;
                cout << "Highest test score for " << classes[a] << " is: " << highest << endl;
                cout << "The average for " << classes[a] << "is: " << avg << endl;
                cout << "=============================================================" << endl;
            }
        }
    //needs for loop to display stats for each class
}

int main()
{
    const int max_test = 5;
    int lowest = 100;
    int highest = 0;
    int sum = 0;
    double avg = 0;
    string classes[5];
    int test[5][5];

    cout << "Enter the name of your first class: ";
    getline (cin,classes[0]);
    cout << "Enter the name of your second class: ";
    getline (cin, classes[1]);
    cout << "Enter the name of your third class: ";
    getline(cin, classes[2]);
    cout << "Enter the name of your fourth class: ";
    getline(cin, classes[3]);
    cout << "Enter the name of your fifth class: ";
    getline(cin, classes[4]);
    cout << "=============================================================" << endl;
    for (int a = 0; a <= max_test; a++)
    {
        for (int i = 1; i <= max_test; i++)
        {
            cout << "Enter score for test " << i << " in " << classes[a] << " : ";
            cin >> test[a][i];
        }
        cout << "=============================================================" << endl;
    }
    cout << "=============================================================" << endl;
    display(lowest, highest, avg);
    system("pause");
    return 0;
}

Body:
you have problem passing parameters to a function , i suggest you look that up..
BTW I've made your variables static and fixed up some errors .. and it seems to work
Kudos..

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
static string classes[5];
static int test[5][5];
static const int max_test = 5;
static int lowest = 100;
static int highest = 0;
static int sum = 0;
static double avg = 0;

int minfun(int lowest)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] < lowest)
            {
                lowest = test[a][i];
            }
        }
    }
    return lowest;
}

int maxfun(int highest)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            if (test[a][i] > highest)
            {
                highest = test[a][i];
            }
        }
    }
    return highest;
}

double classavg(double avg)
{
    for (int a = 0; a < 5; a++)
    {
        for (int i = 0; i < 5; i++)
        {
            sum = sum + test[a][i];
        }
    }
    avg = sum / 5;
    return avg;
}

void display(int lowest, int highest, double avg)
{
    minfun(lowest);
    maxfun(highest);
    classavg(avg);
    for (int a = 0; a < 5; a++)
        {
        for (int i = 0; i < 5; i++)
            {
                cout << "=============================================================" << endl;
                cout << "Displaying stats for " << classes[a] << endl;
                cout << "Lowest test score for " << classes[a] << " is: " << lowest << endl;
                cout << "Highest test score for " << classes[a] << " is: " << highest << endl;
                cout << "The average for " << classes[a] << "is: " << avg << endl;
                cout << "=============================================================" << endl;
            }
        }
    //needs for loop to display stats for each class
}

int main()
{

    cout << "Enter the name of your first class: ";
    getline (cin,classes[0]);
    cout << "Enter the name of your second class: ";
    getline (cin, classes[1]);
    cout << "Enter the name of your third class: ";
    getline(cin, classes[2]);
    cout << "Enter the name of your fourth class: ";
    getline(cin, classes[3]);
    cout << "Enter the name of your fifth class: ";
    getline(cin, classes[4]);
    cout << "=============================================================" << endl;
    for (int a = 0; a <= max_test; a++)
    {
        for (int i = 1; i <= max_test; i++)
        {
            cout << "Enter score for test " << i << " in " << classes[a] << " : ";
            cin >> test[a][i];
        }
        cout << "=============================================================" << endl;
    }
    cout << "=============================================================" << endl;
    display(lowest, highest, avg);
    system("pause");
    return 0;
}


问:
Same Excel formula returns different results in Visual Studio C#
I am translating an Excel formula in my C# application, but it returns different results in Visual Studio. This is the formula (I have hard coded the variables with values in both Excel and Visual Studio for debugging):

```<code>LSBT = (0.085 - (0.0023 * (28 * (((4400 - 3600) / 63) - 12.857))));
</code>```

when using in Excel, it returns:

```<code>0.095213022
</code>```

and in Visual Studio it returns:

```<code>0.14019079999999995
</code>```

Any ideas?

答:
The issue is loss of precision.

In c#, when you write a numeric literal, the compiler assumes you want it represented as an int, and when you use those literals in a formula, loss of precision can result. When you multiple or divide by values that have lost precision, the end result can be WAYYY off.

To avoid the issue, declare all numeric literals as a floating point type. In this example I express them with the suffix M which makes them into decimal variables.

```<code>public class Program
{
    public static void Main()
    {
        var a = (0.085 -( 0.0023*(28*(((4400 - 3600)/63)-12.857))));
        var b = (0.085M -( 0.0023M*(28M*(((4400M - 3600M)/63M)-12.857M))));

        Console.WriteLine(a);
        Console.WriteLine(b);

    }
}
</code>```

Output:

```<code>0.1401908
0.0952130222222222222222222222
</code>```

Code on DotNetFiddle

Body:
I am translating an Excel formula in my C# application, but it returns different results in Visual Studio. This is the formula (I have hard coded the variables with values in both Excel and Visual Studio for debugging):

LSBT = (0.085 - (0.0023 * (28 * (((4400 - 3600) / 63) - 12.857))));

when using in Excel, it returns:

0.095213022

and in Visual Studio it returns:

0.14019079999999995

Any ideas?

Body:
The issue is loss of precision.

In c#, when you write a numeric literal, the compiler assumes you want it represented as an int, and when you use those literals in a formula, loss of precision can result. When you multiple or divide by values that have lost precision, the end result can be WAYYY off.

To avoid the issue, declare all numeric literals as a floating point type. In this example I express them with the suffix M which makes them into decimal variables.

public class Program
{
    public static void Main()
    {
        var a = (0.085 -( 0.0023*(28*(((4400 - 3600)/63)-12.857))));
        var b = (0.085M -( 0.0023M*(28M*(((4400M - 3600M)/63M)-12.857M))));

        Console.WriteLine(a);
        Console.WriteLine(b);

    }
}

Output:

0.1401908
0.0952130222222222222222222222

Code on DotNetFiddle


问:
update property using map versus object.assign
When I use redux I have to care for immutable object, but in pure react, I often update my property in arrays using map

```<code>handleAgeChangedUser = e => {
    const { users, selectedUser } = this.state;

    this.setState(
      {
        users: users.map(o => {
          return o.id === selectedUser.id ? selectedUser : o;
        })
      },
      () => {
        this.ageInput.value = "";
      }
    );
  };
</code>```

Demo https://codesandbox.io/s/z358py2y2p

What's the limitation of this approach and what's other alternative? I remember without es6, I have to use loadash, or worse, back in the day I have to findIndex, then loop manually just to do this simple operation.

答:
While mutuating, you were using the same memory allocation of the state, that is you were using same reference of the state.

Eg: `

```<code>var x = 10;
    x = 20;
</code>```

Here x value is changed to 20 at the same memory space allocated.  You are actually changing the data but not reference here.  Think 'x' as an big object and you are making a change to the deepest key value pair.  Since you were making change at the same reference of the state.  React finds it difficult to understand that whether a change has been made to the state.

Instead if you create an new copy(memory reference) of the state and update the values in it.  It actually refers a different memory location (memory reference) and react easily understands that there is a change in state.

In our case, it works fine.  But while processing bigger data.  We would face issue

Other than these, you can use 'Object.assign()' for objects, for arrays
  you need to take a copy and do your changes on that :-)

`

Body:
When I use redux I have to care for immutable object, but in pure react, I often update my property in arrays using map

handleAgeChangedUser = e => {
    const { users, selectedUser } = this.state;

    this.setState(
      {
        users: users.map(o => {
          return o.id === selectedUser.id ? selectedUser : o;
        })
      },
      () => {
        this.ageInput.value = "";
      }
    );
  };

Demo https://codesandbox.io/s/z358py2y2p

What's the limitation of this approach and what's other alternative? I remember without es6, I have to use loadash, or worse, back in the day I have to findIndex, then loop manually just to do this simple operation.

Body:
While mutuating, you were using the same memory allocation of the state, that is you were using same reference of the state.

Eg: `

var x = 10;
    x = 20;

Here x value is changed to 20 at the same memory space allocated.  You are actually changing the data but not reference here.  Think 'x' as an big object and you are making a change to the deepest key value pair.  Since you were making change at the same reference of the state.  React finds it difficult to understand that whether a change has been made to the state.

Instead if you create an new copy(memory reference) of the state and update the values in it.  It actually refers a different memory location (memory reference) and react easily understands that there is a change in state.

In our case, it works fine.  But while processing bigger data.  We would face issue

Other than these, you can use 'Object.assign()' for objects, for arrays
  you need to take a copy and do your changes on that :-)

`


答:
Use following code, this work perfectly:

```<code> $db = new PDO("mysql:host=$servername;dbname=item", $username, $password);
    $data  = json_decode($jsondata, true);

    $sql = 'INSERT INTO itc (tx_cs, elg) VALUES ';
    $insertQuery = array();
    $insertData = array();
    $n = 0;
    foreach($data['b2b'] as $inner){
        foreach( $inner['inv'][0]['itms'] as $row){
            $insertQuery[] = '(:tx_cs' . $n . ', :elg' . $n . ')';
            $insertData['tx_cs' . $n] = $row['itc']['tx_cs'];
            $insertData['elg' . $n] = $row['itc']['elg'];
            $n++;
        }
    }

    if (!empty($insertQuery)) {
        $sql .= implode(', ', $insertQuery);
        $stmt = $db->prepare($sql);
        $stmt->execute($insertData);
    }
</code>```

With this approach you just run your query one time and have good performance of I/O

Title: This is my JSON data and trying to acces this data and insert to the mysql

Body:
    {
    "gstin":"29AAHCS4690J1ZQ",
    "fp":"072017",
    "b2b":[
      {
         "ctin":"01AAACJ4126D1ZE",
         "cfs":"Y",
         "inv":[
            {
               "itms":[
                  {
                     "num":1,
                     "itc":{
                        "tx_cs":0,
                        "elg":"ip",
                        "tx_i":112.5
                     },
                     "itm_det":{
                        "csamt":0,
                        "rt":18,
                        "txval":625,
                        "iamt":112.5
                     }
                  }
               ],
               "val":738,
               "inv_typ":"R",
               "flag":"N",
               "updby":"S",
               "pos":"29",
               "idt":"31-07-2017",
               "rchrg":"N",
               "cflag":"U",
               "inum":"FL-17000069",

    "chksum":"4d3e41facf5002f418e1ac605d9888d74ee21652e19de6db624fc7106e3c5866"
            }
         ]
      },

{
         "ctin":"29AACFI3027K1ZC",
         "cfs":"Y",
         "inv":[
            {
               "itms":[
                  {
                     "num":1800,
                     "itc":{
                        "elg":"ip",
                        "tx_c":171.59,
                        "tx_s":171.59
                     },
                     "itm_det":{
                        "samt":171.59,
                        "rt":18,
                        "txval":1906.5,
                        "camt":171.59
                     }
                  }
               ],
               "val":2250,
               "inv_typ":"R",
               "flag":"N",
               "updby":"S",
               "pos":"29",
               "idt":"06-07-2017",
               "rchrg":"Y",
               "cflag":"U",
               "inum":"0042",
               "chksum":"aa1187a2bb7d6098c39c4c992bd391ab7fd59e7eeefcea5b91fc9881ba4423d8"
            }
         ]
      }
    ]
    }

The above code is in JSON and I am accessing this in the following way as shown below

<?php
$servername = "localhost";
$username = "root";
$password = "";

$db = new PDO("mysql:host=$servername;dbname=item", $username, $password);
$jsondata = file_get_contents('data.json');
$data  = json_decode($jsondata, true);
$stmt = $db->prepare("insert into itc(tx_cs, elg) values(? , ?)");
var_dump($data);
// echo $data;
foreach($data as $row){
$stmt->bindParam(1, $row['tx_cs']);
$stmt->bindParam(2, $row['elg']);
$stmt->execute();

 }
  ?>

After executing insert statement I am getting just null in mysql any solution for this. If I trying to insert getting illegal string "tx_cs" if there any alternative to access nested JSON data. and also I want to know the how the array indexes Thanks in advance.

This is var_dump Result                                                                           array(4) { ["gstin"]=> string(15) "29AAHCS4690J1ZQ" ["fp"]=> string(6) "072017" ["b2b"]=> array(59) { [0]=> array(3) { ["ctin"]=> string(15) "01AAACJ4126D1ZE" ["cfs"]=> string(1) "Y" ["inv"]=> array(1) { [0]=> array(11) { ["itms"]=> array(1) { [0]=> array(3) { ["num"]=> int(1) ["itc"]=> array(3) { ["tx_cs"]=> int(0) ["elg"]=> string(2) "ip" ["tx_i"]=> float(112.5) } ["itm_det"]=> array(4) { ["csamt"]=> int(0) ["rt"]=> int(18) ["txval"]=> int(625) ["iamt"]=> float(112.5) } } } ["val"]=> int(738) ["inv_typ"]=> string(1) "R" ["flag"]=> string(1) "N" ["updby"]=> string(1) "S" ["pos"]=> string(2) "29" ["idt"]=> string(10) "31-07-2017" ["rchrg"]=> string(1) "N" ["cflag"]=> string(1) "U" ["inum"]=> string(11) "FL-17000069" ["chksum"]=> string(64)

Body:
Use following code, this work perfectly:

 $db = new PDO("mysql:host=$servername;dbname=item", $username, $password);
    $data  = json_decode($jsondata, true);

    $sql = 'INSERT INTO itc (tx_cs, elg) VALUES ';
    $insertQuery = array();
    $insertData = array();
    $n = 0;
    foreach($data['b2b'] as $inner){
        foreach( $inner['inv'][0]['itms'] as $row){
            $insertQuery[] = '(:tx_cs' . $n . ', :elg' . $n . ')';
            $insertData['tx_cs' . $n] = $row['itc']['tx_cs'];
            $insertData['elg' . $n] = $row['itc']['elg'];
            $n++;
        }
    }

    if (!empty($insertQuery)) {
        $sql .= implode(', ', $insertQuery);
        $stmt = $db->prepare($sql);
        $stmt->execute($insertData);
    }

With this approach you just run your query one time and have good performance of I/O


问:
User not able to view table entries oracle 12c
I am a newbie to the database and trying to learn roles and privilege in oracle12c. I am logged in as user dba643 and have following codes.

```<code>create table test
(
  obj1 Number,
  obj2 Varchar2(3)
);

Insert into test values('1','A');
Insert into test values('2','B');

create user rtest identified by rtest;

grant connect,resource to rtest;

grant select,insert,update,delete on test to rtest;
</code>```

After logging in as rtest user and issuing the following select statement:

```<code>select * from dba643.test;
</code>```

The user rtest is able to see the two table entries. However, if the user dba643 inserts a new record into the test table, that newly inserted record cannot be viewed by the user rtest. Similarly, the user rtest is able to insert a record into test table, however, the inserted record cannot be viewed by the dba643 user. Is there something basic I am missing in this?

答:
Use "commit". </p>

<p>I am not seeing any commit on your code. Without using commit you can see the entries only on dba643 user. After committing records will be available for all user. </p>

Body:
I am a newbie to the database and trying to learn roles and privilege in oracle12c. I am logged in as user dba643 and have following codes.

create table test
(
  obj1 Number,
  obj2 Varchar2(3)
);

Insert into test values('1','A');
Insert into test values('2','B');

create user rtest identified by rtest;

grant connect,resource to rtest;

grant select,insert,update,delete on test to rtest;

After logging in as rtest user and issuing the following select statement:

select * from dba643.test;

The user rtest is able to see the two table entries. However, if the user dba643 inserts a new record into the test table, that newly inserted record cannot be viewed by the user rtest. Similarly, the user rtest is able to insert a record into test table, however, the inserted record cannot be viewed by the dba643 user. Is there something basic I am missing in this?

Body:
Use "commit".

I am not seeing any commit on your code. Without using commit you can see the entries only on dba643 user. After committing records will be available for all user.


问:
generic code for creating an X*Y 2 dimensional list in python
I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g.

```<code>myList = createList(2,3,"-")
</code>```

would create the resulting list:
[["-", "-", "-"]
 ["-", "-", "-"]]

so far I've created the following function for this but it puts all the initial values on one list:

```<code>def createList(x,y,val):
    myList=[]
    for i in range(x):
        for j in range(y):
            myList.append(val)
    return myList

print(createList(2,3,"-"))
</code>```

which creates the output: ['-', '-', '-', '-', '-', '-']

答:
You could use a list comprehension to do this.
First, create a list of x lists:

```<code>[[] for i in range(x)]
</code>```

You can also create a list of y val:

```<code>[val for j in range(y)]
</code>```

Combining these would give you:

```<code>createList(x,y,val):
    return [["-" for j in range(y)] for i in range(x)]
</code>```

Body:
I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g.

myList = createList(2,3,"-")

would create the resulting list:
[["-", "-", "-"]
 ["-", "-", "-"]]

so far I've created the following function for this but it puts all the initial values on one list:

def createList(x,y,val):
    myList=[]
    for i in range(x):
        for j in range(y):
            myList.append(val)
    return myList

print(createList(2,3,"-"))

which creates the output: ['-', '-', '-', '-', '-', '-']

Body:
You could use a list comprehension to do this.
First, create a list of x lists:

[[] for i in range(x)]

You can also create a list of y val:

[val for j in range(y)]

Combining these would give you:

createList(x,y,val):
    return [["-" for j in range(y)] for i in range(x)]


答:
The problem is due to the extra " in the age column. It needs to be removed before casting the column to Int. Also, you do not need to use a temporary column, dropping the original and then renaming the temporary column to the original name. Simply use withColumn() to overwrite the original.

regexp_replace can solve the extra " problem:

```<code>val df = Seq("\"58","\"44","\"33","\"47").toDF("age")
val df2 = df.withColumn("age", regexp_replace($"age", "\"", "").cast(IntegerType))
</code>```

Which will give the desired result:

```<code>+---+
|age|
+---+
| 58|
| 44|
| 33|
| 47|
+---+
</code>```

Title: Cast from String to Int in DF results in null instead of numbers

Body:
Here's my code for an example:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.IntegerType
val marketingproj5DF2 = marketingproj5DF.withColumn("ageTmp", 'age.cast(IntegerType)).drop("age").withColumnRenamed("ageTmp","age")

Here's what the DF looks like after:

scala> marketingproj5DF2.show(5)

+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
|     age|             job|    marital|    education|    default|    balance|    housing|    loan|    contact|    day|    month|    duration|    campaign|    pdays
|    previous|    poutcome|      y|ageTmp|
+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
|"""age""|         ""job""|""marital""|""education""|""default""|""balance""|""housing""|""loan""|""contact""|""day""|""month""|""duration""|""campaign""|""pdays""
|""previous""|""poutcome""| ""y"""|  null|
|     "58|  ""management""|""married""| ""tertiary""|     ""no""|       2143|    ""yes""|  ""no""|""unknown""|      5|  ""may""|         261|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "44|  ""technician""| ""single""|""secondary""|     ""no""|         29|    ""yes""|  ""no""|""unknown""|      5|  ""may""|         151|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "33|""entrepreneur""|""married""|""secondary""|     ""no""|          2|    ""yes""| ""yes""|""unknown""|      5|  ""may""|          76|           1|       -1
|           0| ""unknown""|""no"""|  null|
|     "47| ""blue-collar""|""married""|  ""unknown""|     ""no""|       1506|    ""yes""|  ""no""|""unknown""|      5|  ""may""|          92|           1|       -1
|           0| ""unknown""|""no"""|  null|
+--------+----------------+-----------+-------------+-----------+-----------+-----------+--------+-----------+-------+---------+------------+------------+---------
+------------+------------+-------+------+
only showing top 5 rows

I'm using Spark 1.6 Scala 2.10.5. The first column is my original "age" column and the data is imported from .csv and I couldn't get all of the data into a DF unless I left it as a string, now that I have the "age" column in, I'm trying to convert/cast the field and query against it.

Body:
The problem is due to the extra " in the age column. It needs to be removed before casting the column to Int. Also, you do not need to use a temporary column, dropping the original and then renaming the temporary column to the original name. Simply use withColumn() to overwrite the original.

regexp_replace can solve the extra " problem:

val df = Seq("\"58","\"44","\"33","\"47").toDF("age")
val df2 = df.withColumn("age", regexp_replace($"age", "\"", "").cast(IntegerType))

Which will give the desired result:

+---+
|age|
+---+
| 58|
| 44|
| 33|
| 47|
+---+


问:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
So for the following code:

```<code>with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
            print('step %d, training accuracy %g' % (i, train_accuracy))
        train_step.run(feed_dict={x: batch[0], y_: batch[1]})

    print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
</code>```

I get this error:

```<code>---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1305                                    feed_dict, fetch_list, target_list,
-> 1306                                    status, run_metadata)
   1307

~/anaconda/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
     87             try:
---> 88                 next(self.gen)
     89             except StopIteration:

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-15-4f0f48e885d9> in <module>()
      4         batch = mnist.train.next_batch(50)
      5         if i % 100 == 0:
----> 6             train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
      7             print('step %d, training accuracy %g' % (i, train_accuracy))
      8         train_step.run(feed_dict={x: batch[0], y_: batch[1]})

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in eval(self, feed_dict, session)
    539
    540     """
--> 541     return _eval_using_default_session(self, feed_dict, self.graph, session)
    542
    543

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
   4083                        "the tensor's graph is different from the session's "
   4084                        "graph.")
-> 4085   return session.run(tensors, feed_dict)
   4086
   4087

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1122     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1123       results = self._do_run(handle, final_targets, final_fetches,
-> 1124                              feed_dict_tensor, options, run_metadata)
   1125     else:
   1126       results = []

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1319     if handle is None:
   1320       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321                            options, run_metadata)
   1322     else:
   1323       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1338         except KeyError:
   1339           pass
-> 1340       raise type(e)(node_def, op, message)
   1341
   1342   def _extend_graph(self):

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'Placeholder_2', defined at:
  File "/Users/mona/anaconda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Users/mona/anaconda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-a02fa3deb1c0>", line 11, in <module>
    y_conv = deepnn(x)
  File "<ipython-input-3-36fb872ab440>", line 59, in deepnn
    keep_prob = tf.placeholder(tf.float32)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1548, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 2094, in _placeholder
    name=name)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

How should I go about troubleshooting and fixing this error?

答:
Assuming Placeholder_2 is the digit label, its shape is <unknown> as mentioned in the error message.

But the shape of this placeholder should be [None, 10], where None represent batch number and 10 is for the number of classes.

Create the placeholder like:

y = tf.placeholder(tf.float32, shape=[None, 10])

and you should be fine.

Body:
So for the following code:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
            print('step %d, training accuracy %g' % (i, train_accuracy))
        train_step.run(feed_dict={x: batch[0], y_: batch[1]})

    print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

I get this error:

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1305                                    feed_dict, fetch_list, target_list,
-> 1306                                    status, run_metadata)
   1307

~/anaconda/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
     87             try:
---> 88                 next(self.gen)
     89             except StopIteration:

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-15-4f0f48e885d9> in <module>()
      4         batch = mnist.train.next_batch(50)
      5         if i % 100 == 0:
----> 6             train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
      7             print('step %d, training accuracy %g' % (i, train_accuracy))
      8         train_step.run(feed_dict={x: batch[0], y_: batch[1]})

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in eval(self, feed_dict, session)
    539
    540     """
--> 541     return _eval_using_default_session(self, feed_dict, self.graph, session)
    542
    543

~/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
   4083                        "the tensor's graph is different from the session's "
   4084                        "graph.")
-> 4085   return session.run(tensors, feed_dict)
   4086
   4087

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1122     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1123       results = self._do_run(handle, final_targets, final_fetches,
-> 1124                              feed_dict_tensor, options, run_metadata)
   1125     else:
   1126       results = []

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1319     if handle is None:
   1320       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321                            options, run_metadata)
   1322     else:
   1323       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)

~/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1338         except KeyError:
   1339           pass
-> 1340       raise type(e)(node_def, op, message)
   1341
   1342   def _extend_graph(self):

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'Placeholder_2', defined at:
  File "/Users/mona/anaconda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Users/mona/anaconda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/mona/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-a02fa3deb1c0>", line 11, in <module>
    y_conv = deepnn(x)
  File "<ipython-input-3-36fb872ab440>", line 59, in deepnn
    keep_prob = tf.placeholder(tf.float32)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1548, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 2094, in _placeholder
    name=name)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float
     [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

How should I go about troubleshooting and fixing this error?


问:
Confirmation of Javascript behavior in a UIWebView
I am trying to execute some Javascript on content within a UIWebView.  Perhaps my knowledge of the Javascript runtime is lacking, but I"m confused about the following example.  See sourcecode and comments for details:

```<code>NSString *html = [NSString stringWithFormat:@"<html><head><script type='text/javascript'>var content='the initial content';function myFunc(){return 'value of content: ' + content;}myFunc();</script></head><body>Hello blank</body></html>"];
// I would expect after this call that the variable content exists, as well as the function myFunc()
[self.webView loadHTMLString:html baseURL:nil];
// However, it appears not to.  The following call returns nothing
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);

// Inserting the Javascript at this point seems to work as expected
result = [self.webView stringByEvaluatingJavaScriptFromString:@"var content='the new content';function myFunc(){return 'value of content: ' + content;}myFunc();"];
NSLog(@"result: %@", result);

// And calling myFunc() at this point is successful
result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);
</code>```

To sum up, I would expect that the Javascript global variable and function I created when i load the html to be available to later javascript calls.  Surprisingly, it appears not to, and all javascript stuff must be added later.  Is this correct?

thanks for any help in advance.

----- update -----
I should add that self.view is a WebView in this case.  Also, I have tried putting the script tag in both the head and body of the HTML doc, with no change in behavior.

答:
mclin's answer is correct in that UIWebView performs the loads in the background.  If all you're loading is plain html and no tags have src="..." type content then you can be reasonably certain that webViewDidFinishLoad (UIWebViewDelegate protocol method) will be called only once and that you can perform your javascript in that delegate method.

However, UIWebView will, after loading the initial HTML start loading any images, javascript, audio, video, etc and webViewDidFinishLoad will be called as each of those subsequent loads complete. I think if you watch the progress bar on Safari on your iPhone, you can kind of see this behavior.  The progress bar goes about half-way after the initial page loads and then marches on a little at a time as the images or what have you are loaded.

I've tried a couple of techniques to run javascript after the page load is complete.  The easier is to have webViewDidFinishLoad perform another selector after a brief delay, and check the loading property of the webView.  You are taking a bit of a risk here in that we bring "timing" and "threads" together, but hey ... if you want easy (ier that is).

```<code>-(void) checkIfLoadDone:(UIWebView *) webView {
  if (webView.loading) { return; }
  // run your javascript here
}

-(void) webViewDidFinishLoad:(UIWebView *) webView {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
  [self performSelector:@selector(checkIfLoadDone:)
             withObject:webView
             afterDelay:0.5];
}

-(void) webViewDidStartLoad:(UIWebView *)webView {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
}

- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  // ooops ... probably should deal with the error, but lets just run checkIfLoadDone
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
  [self performSelector:@selector(checkIfLoadDone:)
             withObject:webView
             afterDelay:0.5];
}
</code>```

A more complex technique is to track the loads individually and maintain a counter.  When the counter returns to 0, you can run your javascript.  In that case you'll want to implement the delegate method for

```<code>- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  if (navigationType != UIWebViewNavigationTypeOther) {
    self.outStandingLoads = 0;
  }
  return YES;
}
</code>```

Now you can have webViewDidStartLoad: increment outStandingLoads and have webViewDidFinishLoad: and webView:didFailLoadWithError: decrement and check outStandingLoads.  I'd use an atomic NSInteger property for outStandingLoads throughout the code to address the potential for there being more than one thread doing the loading.

I think either method will work reasonably well. I chose the latter approach, but only because I needed to address other issues in the webViewDelegate calls.  I decided to extend UIWebView and make it its own delegate where my extension implemented the delegate methods.  I then leverage the NSNotification model to post notifications like "WebPageLoadBegan" and "WebPageLoadComplete" to communicate with my user interface code.  It seemed like an easier model to me when working with two different sets of UI code ... the iPad and iPhone.

I hope this helps.

Body:
I am trying to execute some Javascript on content within a UIWebView.  Perhaps my knowledge of the Javascript runtime is lacking, but I"m confused about the following example.  See sourcecode and comments for details:

NSString *html = [NSString stringWithFormat:@"Hello blank"];
// I would expect after this call that the variable content exists, as well as the function myFunc()
[self.webView loadHTMLString:html baseURL:nil];
// However, it appears not to.  The following call returns nothing
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);

// Inserting the Javascript at this point seems to work as expected
result = [self.webView stringByEvaluatingJavaScriptFromString:@"var content='the new content';function myFunc(){return 'value of content: ' + content;}myFunc();"];
NSLog(@"result: %@", result);

// And calling myFunc() at this point is successful
result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);

To sum up, I would expect that the Javascript global variable and function I created when i load the html to be available to later javascript calls.  Surprisingly, it appears not to, and all javascript stuff must be added later.  Is this correct?

thanks for any help in advance.

----- update -----
I should add that self.view is a WebView in this case.  Also, I have tried putting the script tag in both the head and body of the HTML doc, with no change in behavior.

Body:
mclin's answer is correct in that UIWebView performs the loads in the background.  If all you're loading is plain html and no tags have src="..." type content then you can be reasonably certain that webViewDidFinishLoad (UIWebViewDelegate protocol method) will be called only once and that you can perform your javascript in that delegate method.

However, UIWebView will, after loading the initial HTML start loading any images, javascript, audio, video, etc and webViewDidFinishLoad will be called as each of those subsequent loads complete. I think if you watch the progress bar on Safari on your iPhone, you can kind of see this behavior.  The progress bar goes about half-way after the initial page loads and then marches on a little at a time as the images or what have you are loaded.

I've tried a couple of techniques to run javascript after the page load is complete.  The easier is to have webViewDidFinishLoad perform another selector after a brief delay, and check the loading property of the webView.  You are taking a bit of a risk here in that we bring "timing" and "threads" together, but hey ... if you want easy (ier that is).

-(void) checkIfLoadDone:(UIWebView *) webView {
  if (webView.loading) { return; }
  // run your javascript here
}

-(void) webViewDidFinishLoad:(UIWebView *) webView {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
  [self performSelector:@selector(checkIfLoadDone:)
             withObject:webView
             afterDelay:0.5];
}

-(void) webViewDidStartLoad:(UIWebView *)webView {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
}

- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
  // ooops ... probably should deal with the error, but lets just run checkIfLoadDone
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(checkIfLoadDone:)
                                             object:webView];
  [self performSelector:@selector(checkIfLoadDone:)
             withObject:webView
             afterDelay:0.5];
}

A more complex technique is to track the loads individually and maintain a counter.  When the counter returns to 0, you can run your javascript.  In that case you'll want to implement the delegate method for

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  if (navigationType != UIWebViewNavigationTypeOther) {
    self.outStandingLoads = 0;
  }
  return YES;
}

Now you can have webViewDidStartLoad: increment outStandingLoads and have webViewDidFinishLoad: and webView:didFailLoadWithError: decrement and check outStandingLoads.  I'd use an atomic NSInteger property for outStandingLoads throughout the code to address the potential for there being more than one thread doing the loading.

I think either method will work reasonably well. I chose the latter approach, but only because I needed to address other issues in the webViewDelegate calls.  I decided to extend UIWebView and make it its own delegate where my extension implemented the delegate methods.  I then leverage the NSNotification model to post notifications like "WebPageLoadBegan" and "WebPageLoadComplete" to communicate with my user interface code.  It seemed like an easier model to me when working with two different sets of UI code ... the iPad and iPhone.

I hope this helps.


问:
How to set focus on element on ItemsControl?
I've ItemsControl that its ItemsSource property bind to some dictionary from code behind. The ItemTemplate is consist of only one button. So, for each item in dictionary it creates button.

My question is how can I set focus to one of these buttons (dynamically)?
Should I use ItemContainerGenerator.ContainerFromItem ?
Any other idea?

Thanks in advance!

答:
Yes, use can ItemContainerGenerator.ContainerFromItem to get a container for your data item, then you will need to find you button inside this container and call Focus() on the button.

OR you can use an attached property to bind IsFocused to a property on your data item. See Set focus on textbox in WPF from view model (C#)


问:
How to use Google Map Places API with react?
In my app I've to fetch data from Google Places API and to dispaly markers on the Google Map. Here in this part I've to show the marker and then fetch the location and have to send that to my back end. Can anyone help?</p>

```<code>          <input
            type="text"
            id="pac-input"
            className="controls"
            placeholder="Search Box"
            value={this.state.fields["event_location"] || ''}
            onChange={this.onChange.bind(this, "event_location")} />
          <div id="map"></div>
          <p>Unable to locate? <button className="btn btn-default inline" data-toggle="collapse" data-target="#address_panel">Enter an Address</button></p>
</code>```

答:
You can use the method textSearch() to do what you want. For example:

```<code>var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    query: 'restaurant'
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}
</code>```

Google Places API is really good, so take some time to read it.

If you want to use a package that uses React components, I recommend react-google-maps. You should take a look.

Body:
In my app I've to fetch data from Google Places API and to dispaly markers on the Google Map. Here in this part I've to show the marker and then fetch the location and have to send that to my back end. Can anyone help?

          <input
            type="text"
            id="pac-input"
            className="controls"
            placeholder="Search Box"
            value={this.state.fields["event_location"] || ''}
            onChange={this.onChange.bind(this, "event_location")} />

Unable to locate? <button className="btn btn-default inline" data-toggle="collapse" data-target="#address_panel">Enter an Address</button>

Body:
You can use the method textSearch() to do what you want. For example:

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    query: 'restaurant'
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

Google Places API is really good, so take some time to read it.

If you want to use a package that uses React components, I recommend react-google-maps. You should take a look.


问:
Redirect http to https express.js
I'm trying to reroute http (80) to https (443) in my express app.  I'm using some middle ware to do this. If i go to my https://my-example-domain.com, everything is fine.  But if I go to http://my-example-domain.com it does not redirect and nothing shows up.

I also have setup some iptables on my ubuntu server

```<code>sudo iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 8443 -j ACCEPT
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

function requireHTTPS(req, res, next) {
  if (!req.secure) {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
}

// all environments
app.set('port', process.env.PORT || 8443);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(requireHTTPS);  // redirect to https
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    res.render('index');
})

https.createServer(options, app).listen(8443);
</code>```

So my question is do I just need to add another iptables rule?  Or do I need to configure something in my app?

So based on one answer below, I don't think its a middleware problem, but a port issue.  For example: if i go to http://my-example-domain.com, doesn't work. But if I add port 8443,http://my-example-domain.com:8443, it redirects fine.

答:
You can achieve redirection from http to https</p>

```<code>if(req.headers["x-forwarded-proto"] == "http") {
 res.redirect(301, "https://" + req.host+req.url);
                next();
}
</code>```

Title: Redirect http to https express.js

Body:
I'm trying to reroute http (80) to https (443) in my express app.  I'm using some middle ware to do this. If i go to my https://my-example-domain.com, everything is fine.  But if I go to http://my-example-domain.com it does not redirect and nothing shows up.

I also have setup some iptables on my ubuntu server

sudo iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 8443 -j ACCEPT
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

function requireHTTPS(req, res, next) {
  if (!req.secure) {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
}

// all environments
app.set('port', process.env.PORT || 8443);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(requireHTTPS);  // redirect to https
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    res.render('index');
})

https.createServer(options, app).listen(8443);

So my question is do I just need to add another iptables rule?  Or do I need to configure something in my app?

So based on one answer below, I don't think its a middleware problem, but a port issue.  For example: if i go to http://my-example-domain.com, doesn't work. But if I add port 8443,http://my-example-domain.com:8443, it redirects fine.

Body:
You can achieve redirection from http to https

if(req.headers["x-forwarded-proto"] == "http") {
 res.redirect(301, "https://" + req.host+req.url);
                next();
}


问:
Adding rows based on a few variables
I'm looking for a function that can get inputs like - "project", "locale", "date" and the function will go to the relevant sheet in the spreadsheet based on the "project" value and will show the relevant rows based on the locale and date.

For example -

Spreadsheet X includes 3 sheets - Project 1, project 2 & summary.
In the summary sheet, I have 3 variables - project, locale & date. I also have a button of "show".
Once I'll click on the "show" the function will show me the data according the variables.

答:
Here's a simple example that I think may be close to what you want. It includes a search button and a clear button and expects you to select a cell on the row of the summary table that you desire to see the data of.  After selecting a row on the summary table you click the search button and the data from that project page for that location and date will be display on the side bar.  If you wish to clear the data then press the clear button.

Code.gs:

```<code>function searchForDataSideBar()
{
   var ui=HtmlService.createHtmlOutputFromFile('searchinfordata');
   SpreadsheetApp.getUi().showSidebar(ui);
}

function searchForData()
{
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Summary');
  var cell=sh.getActiveCell();
  var row=cell.getRow();
  var cols=sh.getLastColumn();
  var rg=sh.getRange(row, 1, 1, cols);
  var vA=rg.getValues();
  var sh1=ss.getSheetByName(vA[0][0]);
  var rg1=sh1.getDataRange();
  var vA1=rg1.getValues();
  var s='';
  for(var i=1;i<vA1.length;i++)
  {
    var data=vA1[i];
    var a=vA[0][1];
    var b=data[0];
    var c=vA[0][2].valueOf();
    var d=data[1].valueOf();
    if(a==b && c==d)
    {
      s+=Utilities.formatString('Project Name:%s<br />Location:%s<br />Date:%s<br />Data1:%s<br />Data2:%s</br>Data3:%s</br>Data4:%s</br>Data5:%s</br><hr>',vA[0][0],data[0],Utilities.formatDate(new Date(data[1]), Session.getScriptTimeZone(), "E MMM dd,yy"),data[2],data[3],data[4],data[5],data[6])
    }
  }
  return s;
}
</code>```

I used a sidebar to put the buttons on and to display your data.  The name of my file was searchinfordata.html:

```<code><!DOCTYPE html>
<html>
  <head>
   <title>Searching for Data</title>
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   <script>
   function search()
   {
     google.script.run
         .withSuccessHandler(found)
         .searchForData();
   }
   function found(hl)
   {
     document.getElementById('found').innerHTML=hl;
   }
   function clearDiv()
   {
     document.getElementById('found').innerHTML='';
   }
   console.log('MyCode');
   </script>
  </head>
  <body>
    <div id="instr">Please Select a cell on the row in the summary tab that you wish to see the data for.</div>
    <input type="button" value="Search" onClick="search();" />
    <input type="button" value="Clear" onClick="clearDiv();" />
    <div id="found"></div>
  </body>
</html>
</code>```

And here's the onOpen() function where you can build your menu or launch your sidebar.

```<code>function onOpen()
{
    SpreadsheetApp.getUi().createMenu('My Tools')
      .addItem('Show Sidebar','searchForDataSideBar')
    .addToUi();

    searchForDataSideBar();//launches your sidebar whenever you open your spreadsheet.
}
</code>```

This is what the Summary Tab looks like:

P1 Tab:

P2 Tab:

P3 Tab:

And Finally the Sidebar:

Title: Adding rows based on a few variables

Body:
Here's a simple example that I think may be close to what you want. It includes a search button and a clear button and expects you to select a cell on the row of the summary table that you desire to see the data of.  After selecting a row on the summary table you click the search button and the data from that project page for that location and date will be display on the side bar.  If you wish to clear the data then press the clear button.

Code.gs:

function searchForDataSideBar()
{
   var ui=HtmlService.createHtmlOutputFromFile('searchinfordata');
   SpreadsheetApp.getUi().showSidebar(ui);
}

function searchForData()
{
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Summary');
  var cell=sh.getActiveCell();
  var row=cell.getRow();
  var cols=sh.getLastColumn();
  var rg=sh.getRange(row, 1, 1, cols);
  var vA=rg.getValues();
  var sh1=ss.getSheetByName(vA[0][0]);
  var rg1=sh1.getDataRange();
  var vA1=rg1.getValues();
  var s='';
  for(var i=1;i<vA1.length;i++)
  {
    var data=vA1[i];
    var a=vA[0][1];
    var b=data[0];
    var c=vA[0][2].valueOf();
    var d=data[1].valueOf();
    if(a==b && c==d)
    {
      s+=Utilities.formatString('Project Name:%s<br />Location:%s<br />Date:%s<br />Data1:%s<br />Data2:%s</br>Data3:%s</br>Data4:%s</br>Data5:%s</br><hr>',vA[0][0],data[0],Utilities.formatDate(new Date(data[1]), Session.getScriptTimeZone(), "E MMM dd,yy"),data[2],data[3],data[4],data[5],data[6])
    }
  }
  return s;
}

I used a sidebar to put the buttons on and to display your data.  The name of my file was searchinfordata.html:

<!DOCTYPE html>
<html>
  <head>
   <title>Searching for Data</title>
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   <script>
   function search()
   {
     google.script.run
         .withSuccessHandler(found)
         .searchForData();
   }
   function found(hl)
   {
     document.getElementById('found').innerHTML=hl;
   }
   function clearDiv()
   {
     document.getElementById('found').innerHTML='';
   }
   console.log('MyCode');
   </script>
  </head>
  <body>
    <div id="instr">Please Select a cell on the row in the summary tab that you wish to see the data for.</div>
    <input type="button" value="Search" onClick="search();" />
    <input type="button" value="Clear" onClick="clearDiv();" />
    <div id="found"></div>
  </body>
</html>

And here's the onOpen() function where you can build your menu or launch your sidebar.

function onOpen()
{
    SpreadsheetApp.getUi().createMenu('My Tools')
      .addItem('Show Sidebar','searchForDataSideBar')
    .addToUi();

    searchForDataSideBar();//launches your sidebar whenever you open your spreadsheet.
}

This is what the Summary Tab looks like:

P1 Tab:

P2 Tab:

P3 Tab:

And Finally the Sidebar:


问:
How to restrict sqlite only to execute SELECT statements, and not INSERT, UPDATE
I have a reports page where you can enter the query manually for a report. How can I block any INSERT, UPDATE or DELETE statements, and only run SELECT?

```<code>using (var connection = new SQLiteConnection(connectionString))
            {
                var da = new SQLiteDataAdapter
                {
                    SelectCommand = new SQLiteCommand(query, connection)
                };
                try
                {
                    da.Fill(table);
                }
</code>```

I could check if the query string contains "INSERT", "UPDATE" or "DELETE", but I don't think it's a good practice.

答: You could use an EXPLAIN statement to break the query down into VM instructions and examine the opcode column of the output.  If the value "OpenWrite" occurs then the query is not read-only.

Body:
I have a reports page where you can enter the query manually for a report. How can I block any INSERT, UPDATE or DELETE statements, and only run SELECT?

using (var connection = new SQLiteConnection(connectionString))
            {
                var da = new SQLiteDataAdapter
                {
                    SelectCommand = new SQLiteCommand(query, connection)
                };
                try
                {
                    da.Fill(table);
                }

I could check if the query string contains "INSERT", "UPDATE" or "DELETE", but I don't think it's a good practice.


问:
Will a Java stack pointing to an array use the same amount of memory?
I have a binary tree of Nodes and want to traverse it. The most common method I'm seeing is a Stack, or a LinkedList. I've also seen other methods that don't add each Node to a Stack/List, and seem to take up almost no memory (they use recursion instead to explore each element).

If I make a List<Node> to track each node in the tree, will I be taking up 2*n the amount of memory? Or, because the objects already exist in the tree, will the List only be a bunch of pointers to Node objects (which exist in the Tree), and therefore don't take up twice the memory?

Test Case:

```<code>Object objs[] = new Object[40];
/*
    Initialize the 40 objects here
*/
List<Object> objTracker = new List<>();
for(int i=0; i<objs.length; i++) {
    objTracker.add(objs[i]);
}
</code>```

Does this now take up 2x the amount of memory, or do all of the objTrackers just redirect/point to the objects stored in objs?

答: You only create a new object when using the new keyword (generally speaking). Since there's no new in objTracker.add(objs[i]);, no new objects are created.

Body:
I have a binary tree of Nodes and want to traverse it. The most common method I'm seeing is a Stack, or a LinkedList. I've also seen other methods that don't add each Node to a Stack/List, and seem to take up almost no memory (they use recursion instead to explore each element).

If I make a List<Node> to track each node in the tree, will I be taking up 2*n the amount of memory? Or, because the objects already exist in the tree, will the List only be a bunch of pointers to Node objects (which exist in the Tree), and therefore don't take up twice the memory?

Test Case:

Object objs[] = new Object[40];
/*
    Initialize the 40 objects here
*/
List<Object> objTracker = new List<>();
for(int i=0; i<objs.length; i++) {
    objTracker.add(objs[i]);
}

Does this now take up 2x the amount of memory, or do all of the objTrackers just redirect/point to the objects stored in objs?


问:
ARKit how to place object on plane surface?
I'm new to ARKit and I imported Unity ARKit Plugin from the Unity Assets Store, I loaded UnityARKitScene to the scene, and replaced the hitcube GameObject with my prefab asset.
I can run the project on my device, but the model which I imported can be placed not only on surfaces but on the 'air' too.

Is there anything that I need to change to make place the model on plane surfaces only?

Thank you.

答:
In UnityARHitTestExample.cs just change the following code

```<code>// prioritize reults types
ARHitTestResultType[] resultTypes = {
    ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
    // if you want to use infinite planes use this:
    //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
    ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
    ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};
</code>```

To this

```<code>// prioritize reults types
ARHitTestResultType[] resultTypes = {
    ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
    // if you want to use infinite planes use this:
    //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
    //ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
    //ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};
</code>```

For more info check https://developer.apple.com/documentation/arkit/arhittestresult.resulttype

Body:
In UnityARHitTestExample.cs just change the following code

// prioritize reults types
ARHitTestResultType[] resultTypes = {
    ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
    // if you want to use infinite planes use this:
    //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
    ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
    ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};

To this

// prioritize reults types
ARHitTestResultType[] resultTypes = {
    ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
    // if you want to use infinite planes use this:
    //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
    //ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
    //ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};

For more info check https://developer.apple.com/documentation/arkit/arhittestresult.resulttype