问:
table updates empty spaces when user do not enter anything to the textbox
i am doing a project where one may update the name, position, department and tag of the employee.

But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.

my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.

my php code (it now updating) but errors found:

```<code><?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);

if(isset($_POST['submitted']))
    {

    $sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
    $result = mysql_query($sql) or die (mysql_error());
    if(!$result || mysql_num_rows($result) <= 0)
                            {
                                return false;
                            }

    $qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";

    mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
        }
    ?>
</code>```

*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help

```
MisaChan
```

答:
this is what i used to keep it working :) i hope this could be a source for others as well :)</p>

```<code>$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos']  = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep']  = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag']  = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val

$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
    $queryString .="`".$key."`='".$val."',";
}
                            }
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
</code>```

Body:
i am doing a project where one may update the name, position, department and tag of the employee.

But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.

my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.

my php code (it now updating) but errors found:

<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);

if(isset($_POST['submitted']))
    {

    $sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
    $result = mysql_query($sql) or die (mysql_error());
    if(!$result || mysql_num_rows($result) <= 0)
                            {
                                return false;
                            }

    $qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";

    mysql_query($qry) or die (mysql_error());
?><?php
        }
    ?>

*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help

MisaChan

Body:
this is what i used to keep it working :) i hope this could be a source for others as well :)

$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos']  = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep']  = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag']  = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val

$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
    $queryString .="`".$key."`='".$val."',";
}
                            }
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);


来源: stackexchange

问:
Want to delete old entries from SQL Server database
I want to delete all entries from my database that are older than 2 or 3 months. The thing is all of my tables do not contain date column. Is there any way to delete old data from all the tables in my database that has a date column?</p>

答: Add a nullable date column with default of GetDate(). Wait two months and delete everything that has a null in that column or date older than two months</p>

ContentLicense: CC BY-SA 4.0


问:
Cannot access memory error for character array in struct - C
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

```<code>#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;
</code>```

I then use these the following functions to initialize the queue and the nodes.

```<code>int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}
</code>```

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

```<code>int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}
</code>```

I will also include my main function as additional information.

```<code>#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}
</code>```

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

答:
The function initQueue_ch does not make sense.

```<code>int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}
</code>```

The function parameter q is a local variable of the function. Changing the variable within the function does not have effect on the argument supplied to the function.

Moreover there is also no sense to allocate a queue dynamically. The function can look the following way

```<code>void initQueue_ch( Queue_ch *q )
{
    q->count = 0;
    q->front = NULL;
    q->rear  = NULL;
}
</code>```

And in main you could write

```<code>Queue_ch queue;
initQueue_ch( &queue );
</code>```

The same problem exists with the function initQueueNode_ch

```<code>int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}
</code>```

Again the function deals with a copy of the value of the passed argument. Changing the copy does not influence on the original argument.

The function is in whole does not make sense. What you need is a function that allocates a new node.

It can look for example the following way

```<code>QueueNode_ch * createQueueNode_ch( const char *data )
{
    QueueNode_ch *node = malloc( sizeof( QueueNode_ch ) );

    if ( node != NULL )
    {
        node->next = NULL;
        strcpy( node->data, data );
    }

    return node;
}
</code>```

The function enqueue_ch that has the same drawback of passing a pointer to a queue by value can look like

```<code>int enqueue_ch( Queue_ch *q, const char *data )
{
    int success = strlen( data ) < DATA_MAX + 1;

    if ( success )
    {
        QueueNode_ch *node = createQueueNode_ch( data );

        success = node != NULL;

        if ( success )
        {
            if ( q->rear == NULL )
            {
                q->front = q->rear = node;
            }
            else
            {
                q->rear = q->rear->next = node;
            }

            ++q->count;
        }
    }

    return success;
}
</code>```

Here is a demonstrative program.

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

#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;

void initQueue_ch( Queue_ch *q )
{
    q->count = 0;
    q->front = NULL;
    q->rear  = NULL;
}

QueueNode_ch * createQueueNode_ch( const char *data )
{
    QueueNode_ch *node = malloc( sizeof( QueueNode_ch ) );

    if ( node != NULL )
    {
        node->next = NULL;
        strcpy( node->data, data );
    }

    return node;
}

int enqueue_ch( Queue_ch *q, const char *data )
{
    int success = strlen( data ) < DATA_MAX + 1;

    if ( success )
    {
        QueueNode_ch *node = createQueueNode_ch( data );

        success = node != NULL;

        if ( success )
        {
            if ( q->rear == NULL )
            {
                q->front = q->rear = node;
            }
            else
            {
                q->rear = q->rear->next = node;
            }

            ++q->count;
        }
    }

    return success;
}

void deleteQueue_ch( Queue_ch *q )
{
    while ( q->front != NULL )
    {
        QueueNode_ch *node = q->front;
        q->front = q->front->next;
        free( node );
    }

    q->rear = q->front;
    q->count = 0;
}

int main(void)
{
    Queue_ch queue;
    initQueue_ch( &queue );

    enqueue_ch( &queue, "hello" );

    deleteQueue_ch( &queue );

    return 0;
}
</code>```

Body:
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;

I then use these the following functions to initialize the queue and the nodes.

int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}

I will also include my main function as additional information.

#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

Body:
The function initQueue_ch does not make sense.

int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

The function parameter q is a local variable of the function. Changing the variable within the function does not have effect on the argument supplied to the function.

Moreover there is also no sense to allocate a queue dynamically. The function can look the following way

void initQueue_ch( Queue_ch *q )
{
    q->count = 0;
    q->front = NULL;
    q->rear  = NULL;
}

And in main you could write

Queue_ch queue;
initQueue_ch( &queue );

The same problem exists with the function initQueueNode_ch

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}

Again the function deals with a copy of the value of the passed argument. Changing the copy does not influence on the original argument.

The function is in whole does not make sense. What you need is a function that allocates a new node.

It can look for example the following way

QueueNode_ch * createQueueNode_ch( const char *data )
{
    QueueNode_ch *node = malloc( sizeof( QueueNode_ch ) );

    if ( node != NULL )
    {
        node->next = NULL;
        strcpy( node->data, data );
    }

    return node;
}

The function enqueue_ch that has the same drawback of passing a pointer to a queue by value can look like

int enqueue_ch( Queue_ch *q, const char *data )
{
    int success = strlen( data ) < DATA_MAX + 1;

    if ( success )
    {
        QueueNode_ch *node = createQueueNode_ch( data );

        success = node != NULL;

        if ( success )
        {
            if ( q->rear == NULL )
            {
                q->front = q->rear = node;
            }
            else
            {
                q->rear = q->rear->next = node;
            }

            ++q->count;
        }
    }

    return success;
}

Here is a demonstrative program.

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

#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;

void initQueue_ch( Queue_ch *q )
{
    q->count = 0;
    q->front = NULL;
    q->rear  = NULL;
}

QueueNode_ch * createQueueNode_ch( const char *data )
{
    QueueNode_ch *node = malloc( sizeof( QueueNode_ch ) );

    if ( node != NULL )
    {
        node->next = NULL;
        strcpy( node->data, data );
    }

    return node;
}

int enqueue_ch( Queue_ch *q, const char *data )
{
    int success = strlen( data ) < DATA_MAX + 1;

    if ( success )
    {
        QueueNode_ch *node = createQueueNode_ch( data );

        success = node != NULL;

        if ( success )
        {
            if ( q->rear == NULL )
            {
                q->front = q->rear = node;
            }
            else
            {
                q->rear = q->rear->next = node;
            }

            ++q->count;
        }
    }

    return success;
}

void deleteQueue_ch( Queue_ch *q )
{
    while ( q->front != NULL )
    {
        QueueNode_ch *node = q->front;
        q->front = q->front->next;
        free( node );
    }

    q->rear = q->front;
    q->count = 0;
}

int main(void)
{
    Queue_ch queue;
    initQueue_ch( &queue );

    enqueue_ch( &queue, "hello" );

    deleteQueue_ch( &queue );

    return 0;
}


问:
How do I divide integers and not get a 1
Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.</p>

```<code>        Console.Write("Ange dagskassa (kr): ");
        string inlasning = Console.ReadLine();
        int dagskassa = int.Parse(inlasning);

        Console.Write("Ange nuvarande lunchpris (kr): ");
        string inlasning2 = Console.ReadLine();
        int lunchpris = int.Parse(inlasning);

        double antalGaster = dagskassa / lunchpris;

        Console.WriteLine("Antal gäster: " + antalGaster + "st.");
</code>```

答:
The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:

```<code>int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning);  // You're parsing the same input as before
</code>```

To resolve this, convert the second input for the lunch price:

```<code>int dagskassa = int.Parse(inlasning2);  // Parse the *new* input instead
</code>```

Body:
Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.

        Console.Write("Ange dagskassa (kr): ");
        string inlasning = Console.ReadLine();
        int dagskassa = int.Parse(inlasning);

        Console.Write("Ange nuvarande lunchpris (kr): ");
        string inlasning2 = Console.ReadLine();
        int lunchpris = int.Parse(inlasning);

        double antalGaster = dagskassa / lunchpris;

        Console.WriteLine("Antal gäster: " + antalGaster + "st.");

Body:
The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:

int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning);  // You're parsing the same input as before

To resolve this, convert the second input for the lunch price:

int dagskassa = int.Parse(inlasning2);  // Parse the *new* input instead


问:
Snowflake "Max LOB size (16777216) exceeded" error when loading data from Parquet
I am looking to load data from S3 into Snowflake.  My files are in Parquet format, and were created by a spark job.  There are 199 parquet files in my folder in S3, each with about 5500 records.  Each parquet file is snappy compressed and is about 485 kb.

I have successfully created a storage integration and staged my data.  However, when I read my data, I get the following message:

```<code>Max LOB size (16777216) exceeded, actual size of parsed column is 19970365
</code>```

I believe I have followed the General File Sizing Recommendations but I have not been able to figure out a solution to this issue, or even a clear description of this error message.

Here is the basics of my SQL query:

```<code>CREATE OR REPLACE TEMPORARY STAGE my_test_stage
            FILE_FORMAT = (TYPE = PARQUET)
            STORAGE_INTEGRATION = MY_STORAGE_INTEGRATION
            URL = 's3://my-bucket/my-folder';

SELECT $1 FROM @my_test_stage(PATTERN => '.*\\.parquet')
</code>```

I seem to be able to read each parquet file individually by changing the URL parameter in the CREATE STAGE query to the full path of the parquet file.  I really don't want to have to iterate through each file to load them.

答:
The VARIANT data type imposes a 16 MB (compressed) size limit on individual rows.

The resultset is actually a display as a virtual column, so the 16MB limit also applied

Docs Reference:
https://docs.snowflake.com/en/user-guide/data-load-considerations-prepare.html#semi-structured-data-size-limitations

Body:
I am looking to load data from S3 into Snowflake.  My files are in Parquet format, and were created by a spark job.  There are 199 parquet files in my folder in S3, each with about 5500 records.  Each parquet file is snappy compressed and is about 485 kb.

I have successfully created a storage integration and staged my data.  However, when I read my data, I get the following message:

Max LOB size (16777216) exceeded, actual size of parsed column is 19970365

I believe I have followed the General File Sizing Recommendations but I have not been able to figure out a solution to this issue, or even a clear description of this error message.

Here is the basics of my SQL query:

CREATE OR REPLACE TEMPORARY STAGE my_test_stage
            FILE_FORMAT = (TYPE = PARQUET)
            STORAGE_INTEGRATION = MY_STORAGE_INTEGRATION
            URL = 's3://my-bucket/my-folder';

SELECT $1 FROM @my_test_stage(PATTERN => '.*\\.parquet')

I seem to be able to read each parquet file individually by changing the URL parameter in the CREATE STAGE query to the full path of the parquet file.  I really don't want to have to iterate through each file to load them.


问:
how to get the values of one array of objects key based on values of another array of objects?
```<code>   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}
</code>```

the output expected is

```<code>const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}
</code>```

I tried mapping the uids to get and array of values like

```<code>uids = [12, 23]
</code>```

then

```<code>        names = uids.map(key => object[key].name);
</code>```

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this

答:
First of all the structure of data is wrong. It should be an array. Then you could do this:

   data = [
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
];

object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}};

for(let key in object){
  var match = data.filter(i=>i.uid.toString() === key);
  if(match && match.length){
    object[key].amount = match[0].amount;
  }
}
console.log(object)```

Body:
   data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}

the output expected is

const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}

I tried mapping the uids to get and array of values like

uids = [12, 23]

then

        names = uids.map(key => object[key].name);

so that I could use them to map the keys and the names in the other object but couldn't figure it out
I know it is basic javascript but I am new to this


问:
ValueError: Can only compare identically-labeled Series objects: python
I have the following code:

```<code>data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
#time = pd.date_range('2005-01-01','2014-12-12',freq='D').strftime('%Y-%m-%d')
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

#2015 data
breakoutdata = data[(data['Date']  > '2014-12-12')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]
</code>```

However, I keep getting the error: ValueError: Can only compare identically-labeled Series objects

I am confused as to why this is.

The dataframe datamax2015 looks like this:

```<code>Date           ID Element  Data_Value
0    2014-12-13  USW00094889    TMAX          89
1    2014-12-14  USW00094889    TMAX         139
2    2014-12-15  USW00094889    TMAX         128
3    2014-12-16  USW00094889    TMAX         139
4    2014-12-17  USW00094889    TMAX         122
5    2014-12-18  USW00094889    TMAX          22
6    2014-12-19  USW00094889    TMAX          11
7    2014-12-20  USW00094889    TMAX           6
8    2014-12-21  USW00094889    TMAX          33
9    2014-12-22  USW00094889    TMAX          61
10   2014-12-23  USW00094889    TMAX         122
11   2014-12-24  USW00094889    TMAX         139
12   2014-12-25  USW00094889    TMAX         100
13   2014-12-26  USW00094889    TMAX         100
14   2014-12-27  USW00094889    TMAX         111
15   2014-12-28  USW00094889    TMAX         133
16   2014-12-29  USW00094889    TMAX          89
17   2014-12-30  USW00094889    TMAX          33
18   2014-12-31  USW00094889    TMAX         -28
19   2015-01-01  USW00094889    TMAX          11
20   2015-01-02  USW00094889    TMAX          39
21   2015-01-03  USW00014853    TMAX          39
22   2015-01-04  USW00094889    TMAX          44
23   2015-01-05  USW00094889    TMAX          28
24   2015-01-06  USW00094889    TMAX          33
25   2015-01-07  USW00094889    TMAX         -67
26   2015-01-08  USW00094889    TMAX         -82
27   2015-01-09  USW00094889    TMAX         -66
28   2015-01-10  USW00094889    TMAX         -71
29   2015-01-11  USW00094889    TMAX           6
..          ...          ...     ...         ...
354  2015-12-02  USW00094889    TMAX         100
355  2015-12-03  USW00094889    TMAX          94
356  2015-12-04  USW00094889    TMAX          94
357  2015-12-05  USW00094889    TMAX          94
358  2015-12-06  USW00094889    TMAX         100
359  2015-12-07  USW00094889    TMAX         100
360  2015-12-08  USW00094889    TMAX         100
361  2015-12-09  USW00094889    TMAX         122
362  2015-12-10  USW00094889    TMAX         150
363  2015-12-11  USW00094889    TMAX         156
364  2015-12-12  USW00094889    TMAX         200
365  2015-12-13  USW00094889    TMAX         194
366  2015-12-14  USW00094889    TMAX         183
367  2015-12-15  USW00094889    TMAX         161
368  2015-12-16  USW00094889    TMAX         150
369  2015-12-17  USW00094889    TMAX         122
370  2015-12-18  USW00094889    TMAX          33
371  2015-12-19  USW00094889    TMAX          11
372  2015-12-20  USW00094889    TMAX          83
373  2015-12-21  USW00094889    TMAX         122
374  2015-12-22  USW00014853    TMAX         133
375  2015-12-23  USW00014853    TMAX         183
376  2015-12-24  USW00014853    TMAX         172
377  2015-12-25  USW00094889    TMAX         111
378  2015-12-26  USW00094889    TMAX         117
379  2015-12-27  USW00094889    TMAX          83
380  2015-12-28  USW00094889    TMAX          61
381  2015-12-29  USW00094889    TMAX         100
382  2015-12-30  USW00094889    TMAX          67
383  2015-12-31  USW00094889    TMAX          17

[384 rows x 4 columns]
</code>```

The dataframe datamax looks like this:

```<code>     Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]
</code>```

The columns seem to be the same in both dataframes.

I tried resorting the indices in both these dataframes but this did not work.

答:
The problem here is that each dataframe has a different number of rows.

Thus, what I did was created a new column in the dataframe 'datamax' and 'datamin' respectively, with the values from the 'Data_Value' column of the 'datamax2015' dataframe.

I then extracted particular values from this new dataframe by comparing the contents of the columns in this dataframe using the following formulae:

```<code>datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
filteredmax = datamax[datamax['datamax']>datamax['Data_Value']]
filteredmin = datamin[datamin['datamin']<datamin['Data_Value']]
</code>```

This formula then gave me no errors:

```<code>print(filteredmax)
print(filteredmin)

Date           ID Element  Data_Value  datamax
3    2005-01-04  USW00094889    TMAX          39     44.0
5    2005-01-06  USW00094889    TMAX           0     33.0
14   2005-01-15  USW00094889    TMAX         -33     -5.0
15   2005-01-16  USW00094889    TMAX         -33      6.0
16   2005-01-17  USW00094889    TMAX         -50     78.0
17   2005-01-18  USW00094889    TMAX         -33     83.0
18   2005-01-19  USW00094889    TMAX          11     67.0
19   2005-01-20  USW00094889    TMAX          11     39.0
20   2005-01-21  USW00094889    TMAX         -39     22.0
21   2005-01-22  USW00094889    TMAX         -72     -5.0
22   2005-01-23  USW00094889    TMAX         -44     11.0
23   2005-01-24  USW00094889    TMAX          11     44.0
24   2005-01-25  USW00094889    TMAX          28     33.0
27   2005-01-28  USW00094889    TMAX         -11      6.0
28   2005-01-29  USW00094889    TMAX          17     39.0
31   2005-02-01  USW00094889    TMAX          17     39.0
38   2005-02-08  USW00094889    TMAX          67     83.0
39   2005-02-09  USW00094889    TMAX          39     83.0
60   2005-03-02  USW00094889    TMAX         -11     17.0
61   2005-03-03  USW00094889    TMAX          17     44.0
67   2005-03-09  USW00094889    TMAX          -6     94.0
68   2005-03-10  USW00094889    TMAX          61    100.0
69   2005-03-11  USW00094889    TMAX          33    133.0
70   2005-03-12  USW00094889    TMAX          28    128.0
71   2005-03-13  USW00094889    TMAX          39    150.0
72   2005-03-14  USW00094889    TMAX          39    128.0
73   2005-03-15  USW00094889    TMAX          56    139.0
74   2005-03-16  USW00094889    TMAX          78    206.0
75   2005-03-17  USW00094889    TMAX          67    194.0
76   2005-03-18  USW00094889    TMAX          50    117.0
..          ...          ...     ...         ...      ...
333  2005-11-30  USW00094889    TMAX          83    100.0
334  2005-12-01  USW00094889    TMAX          11    111.0
335  2005-12-02  USW00094889    TMAX           0    100.0
336  2005-12-03  USW00094889    TMAX          -6     94.0
337  2005-12-04  USW00094889    TMAX          22     94.0
338  2005-12-05  USW00094889    TMAX          11     94.0
339  2005-12-06  USW00094889    TMAX         -22    100.0
340  2005-12-07  USW00094889    TMAX         -33    100.0
341  2005-12-08  USW00094889    TMAX         -11    100.0
342  2005-12-09  USW00094889    TMAX         -11    122.0
343  2005-12-10  USW00094889    TMAX           0    150.0
344  2005-12-11  USW00014853    TMAX          33    156.0
345  2005-12-12  USW00094889    TMAX          22    200.0
346  2005-12-13  USW00094889    TMAX          -6    194.0
347  2005-12-14  USW00094889    TMAX          11    183.0
348  2005-12-15  USW00094889    TMAX          17    161.0
349  2005-12-16  USW00094889    TMAX          17    150.0
350  2005-12-17  USW00094889    TMAX         -11    122.0
351  2005-12-18  USW00094889    TMAX         -28     33.0
352  2005-12-19  USW00094889    TMAX         -33     11.0
353  2005-12-20  USW00094889    TMAX         -22     83.0
354  2005-12-21  USW00094889    TMAX         -22    122.0
355  2005-12-22  USW00094889    TMAX          28    133.0
356  2005-12-23  USW00094889    TMAX          50    183.0
357  2005-12-24  USW00094889    TMAX          61    172.0
358  2005-12-25  USW00094889    TMAX          61    111.0
359  2005-12-26  USW00094889    TMAX          50    117.0
360  2005-12-27  USW00094889    TMAX          39     83.0
362  2005-12-29  USW00094889    TMAX          56    100.0
363  2005-12-30  USW00094889    TMAX          39     67.0

[171 rows x 5 columns]
           Date           ID Element  Data_Value  datamin
0    2005-01-01  USC00200032    TMIN         -56   -133.0
1    2005-01-02  USC00200032    TMIN         -56   -122.0
2    2005-01-03  USC00200032    TMIN           0    -67.0
3    2005-01-04  USC00200032    TMIN         -39    -88.0
4    2005-01-05  USC00200032    TMIN         -94   -155.0
5    2005-01-06  USC00200032    TMIN        -106   -182.0
6    2005-01-07  USC00200032    TMIN        -111   -182.0
7    2005-01-08  USC00200032    TMIN        -100   -211.0
8    2005-01-09  USC00200032    TMIN         -67   -206.0
9    2005-01-10  USC00200032    TMIN         -56   -206.0
10   2005-01-11  USC00200032    TMIN         -22   -200.0
11   2005-01-12  USC00200032    TMIN         -17   -117.0
12   2005-01-13  USC00200032    TMIN         -83   -216.0
13   2005-01-14  USC00200032    TMIN        -128   -244.0
14   2005-01-15  USC00200032    TMIN        -144   -200.0
15   2005-01-16  USC00200032    TMIN        -150   -167.0
32   2005-02-02  USC00200032    TMIN        -167   -193.0
33   2005-02-03  USC00200032    TMIN        -167   -238.0
34   2005-02-04  USC00200032    TMIN        -156   -211.0
35   2005-02-05  USC00200032    TMIN        -128   -277.0
36   2005-02-06  USC00200032    TMIN         -89   -250.0
37   2005-02-07  USC00200032    TMIN         -56   -122.0
38   2005-02-08  USC00200032    TMIN         -33    -56.0
39   2005-02-09  USC00200032    TMIN         -78   -116.0
40   2005-02-10  USC00200032    TMIN        -111   -171.0
41   2005-02-11  USC00200032    TMIN        -122   -150.0
42   2005-02-12  USC00200032    TMIN         -83   -211.0
43   2005-02-13  USC00200032    TMIN         -56   -266.0
44   2005-02-14  USC00200032    TMIN         -28   -239.0
45   2005-02-15  USC00200032    TMIN         -11   -260.0
..          ...          ...     ...         ...      ...
262  2005-09-20  USC00200032    TMIN          94     39.0
263  2005-09-21  USC00200032    TMIN          78     56.0
264  2005-09-22  USC00200032    TMIN          94     17.0
266  2005-09-24  USC00200032    TMIN         111     56.0
267  2005-09-25  USC00200032    TMIN          94     78.0
275  2005-10-03  USC00200032    TMIN          50     44.0
276  2005-10-04  USC00200032    TMIN         100     61.0
277  2005-10-05  USC00200032    TMIN         100     94.0
282  2005-10-10  USC00200032    TMIN          22      0.0
284  2005-10-12  USC00200032    TMIN          67     28.0
285  2005-10-13  USC00200032    TMIN          83     72.0
286  2005-10-14  USC00200032    TMIN          56    -10.0
287  2005-10-15  USC00200032    TMIN          56    -16.0
288  2005-10-16  USC00200032    TMIN          -6    -10.0
289  2005-10-17  USC00200032    TMIN         -33    -55.0
290  2005-10-18  USC00200032    TMIN         -11    -55.0
291  2005-10-19  USC00200032    TMIN          -6    -61.0
292  2005-10-20  USC00200032    TMIN         -22    -39.0
293  2005-10-21  USC00200032    TMIN           0    -28.0
311  2005-11-08  USC00200032    TMIN         -11    -55.0
312  2005-11-09  USC00200032    TMIN          22    -61.0
313  2005-11-10  USC00200032    TMIN         -39    -44.0
318  2005-11-15  USC00200032    TMIN         -17    -22.0
325  2005-11-22  USC00200032    TMIN         -78   -116.0
331  2005-11-28  USC00200032    TMIN           0    -39.0
332  2005-11-29  USC00200032    TMIN         -39    -93.0
333  2005-11-30  USC00200032    TMIN         -56    -89.0
359  2005-12-26  USC00200032    TMIN         -11    -39.0
361  2005-12-28  USC00200032    TMIN         -28    -39.0
362  2005-12-29  USC00200032    TMIN         -11    -39.0
</code>```

Body:
I have the following code:

data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
#time = pd.date_range('2005-01-01','2014-12-12',freq='D').strftime('%Y-%m-%d')
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

#2015 data
breakoutdata = data[(data['Date']  > '2014-12-12')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

However, I keep getting the error: ValueError: Can only compare identically-labeled Series objects

I am confused as to why this is.

The dataframe datamax2015 looks like this:

Date           ID Element  Data_Value
0    2014-12-13  USW00094889    TMAX          89
1    2014-12-14  USW00094889    TMAX         139
2    2014-12-15  USW00094889    TMAX         128
3    2014-12-16  USW00094889    TMAX         139
4    2014-12-17  USW00094889    TMAX         122
5    2014-12-18  USW00094889    TMAX          22
6    2014-12-19  USW00094889    TMAX          11
7    2014-12-20  USW00094889    TMAX           6
8    2014-12-21  USW00094889    TMAX          33
9    2014-12-22  USW00094889    TMAX          61
10   2014-12-23  USW00094889    TMAX         122
11   2014-12-24  USW00094889    TMAX         139
12   2014-12-25  USW00094889    TMAX         100
13   2014-12-26  USW00094889    TMAX         100
14   2014-12-27  USW00094889    TMAX         111
15   2014-12-28  USW00094889    TMAX         133
16   2014-12-29  USW00094889    TMAX          89
17   2014-12-30  USW00094889    TMAX          33
18   2014-12-31  USW00094889    TMAX         -28
19   2015-01-01  USW00094889    TMAX          11
20   2015-01-02  USW00094889    TMAX          39
21   2015-01-03  USW00014853    TMAX          39
22   2015-01-04  USW00094889    TMAX          44
23   2015-01-05  USW00094889    TMAX          28
24   2015-01-06  USW00094889    TMAX          33
25   2015-01-07  USW00094889    TMAX         -67
26   2015-01-08  USW00094889    TMAX         -82
27   2015-01-09  USW00094889    TMAX         -66
28   2015-01-10  USW00094889    TMAX         -71
29   2015-01-11  USW00094889    TMAX           6
..          ...          ...     ...         ...
354  2015-12-02  USW00094889    TMAX         100
355  2015-12-03  USW00094889    TMAX          94
356  2015-12-04  USW00094889    TMAX          94
357  2015-12-05  USW00094889    TMAX          94
358  2015-12-06  USW00094889    TMAX         100
359  2015-12-07  USW00094889    TMAX         100
360  2015-12-08  USW00094889    TMAX         100
361  2015-12-09  USW00094889    TMAX         122
362  2015-12-10  USW00094889    TMAX         150
363  2015-12-11  USW00094889    TMAX         156
364  2015-12-12  USW00094889    TMAX         200
365  2015-12-13  USW00094889    TMAX         194
366  2015-12-14  USW00094889    TMAX         183
367  2015-12-15  USW00094889    TMAX         161
368  2015-12-16  USW00094889    TMAX         150
369  2015-12-17  USW00094889    TMAX         122
370  2015-12-18  USW00094889    TMAX          33
371  2015-12-19  USW00094889    TMAX          11
372  2015-12-20  USW00094889    TMAX          83
373  2015-12-21  USW00094889    TMAX         122
374  2015-12-22  USW00014853    TMAX         133
375  2015-12-23  USW00014853    TMAX         183
376  2015-12-24  USW00014853    TMAX         172
377  2015-12-25  USW00094889    TMAX         111
378  2015-12-26  USW00094889    TMAX         117
379  2015-12-27  USW00094889    TMAX          83
380  2015-12-28  USW00094889    TMAX          61
381  2015-12-29  USW00094889    TMAX         100
382  2015-12-30  USW00094889    TMAX          67
383  2015-12-31  USW00094889    TMAX          17

[384 rows x 4 columns]

The dataframe datamax looks like this:

     Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]

The columns seem to be the same in both dataframes.

I tried resorting the indices in both these dataframes but this did not work.

Body:
The problem here is that each dataframe has a different number of rows.

Thus, what I did was created a new column in the dataframe 'datamax' and 'datamin' respectively, with the values from the 'Data_Value' column of the 'datamax2015' dataframe.

I then extracted particular values from this new dataframe by comparing the contents of the columns in this dataframe using the following formulae:

datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
filteredmax = datamax[datamax['datamax']>datamax['Data_Value']]
filteredmin = datamin[datamin['datamin']<datamin['Data_Value']]

This formula then gave me no errors:

print(filteredmax)
print(filteredmin)

Date           ID Element  Data_Value  datamax
3    2005-01-04  USW00094889    TMAX          39     44.0
5    2005-01-06  USW00094889    TMAX           0     33.0
14   2005-01-15  USW00094889    TMAX         -33     -5.0
15   2005-01-16  USW00094889    TMAX         -33      6.0
16   2005-01-17  USW00094889    TMAX         -50     78.0
17   2005-01-18  USW00094889    TMAX         -33     83.0
18   2005-01-19  USW00094889    TMAX          11     67.0
19   2005-01-20  USW00094889    TMAX          11     39.0
20   2005-01-21  USW00094889    TMAX         -39     22.0
21   2005-01-22  USW00094889    TMAX         -72     -5.0
22   2005-01-23  USW00094889    TMAX         -44     11.0
23   2005-01-24  USW00094889    TMAX          11     44.0
24   2005-01-25  USW00094889    TMAX          28     33.0
27   2005-01-28  USW00094889    TMAX         -11      6.0
28   2005-01-29  USW00094889    TMAX          17     39.0
31   2005-02-01  USW00094889    TMAX          17     39.0
38   2005-02-08  USW00094889    TMAX          67     83.0
39   2005-02-09  USW00094889    TMAX          39     83.0
60   2005-03-02  USW00094889    TMAX         -11     17.0
61   2005-03-03  USW00094889    TMAX          17     44.0
67   2005-03-09  USW00094889    TMAX          -6     94.0
68   2005-03-10  USW00094889    TMAX          61    100.0
69   2005-03-11  USW00094889    TMAX          33    133.0
70   2005-03-12  USW00094889    TMAX          28    128.0
71   2005-03-13  USW00094889    TMAX          39    150.0
72   2005-03-14  USW00094889    TMAX          39    128.0
73   2005-03-15  USW00094889    TMAX          56    139.0
74   2005-03-16  USW00094889    TMAX          78    206.0
75   2005-03-17  USW00094889    TMAX          67    194.0
76   2005-03-18  USW00094889    TMAX          50    117.0
..          ...          ...     ...         ...      ...
333  2005-11-30  USW00094889    TMAX          83    100.0
334  2005-12-01  USW00094889    TMAX          11    111.0
335  2005-12-02  USW00094889    TMAX           0    100.0
336  2005-12-03  USW00094889    TMAX          -6     94.0
337  2005-12-04  USW00094889    TMAX          22     94.0
338  2005-12-05  USW00094889    TMAX          11     94.0
339  2005-12-06  USW00094889    TMAX         -22    100.0
340  2005-12-07  USW00094889    TMAX         -33    100.0
341  2005-12-08  USW00094889    TMAX         -11    100.0
342  2005-12-09  USW00094889    TMAX         -11    122.0
343  2005-12-10  USW00094889    TMAX           0    150.0
344  2005-12-11  USW00014853    TMAX          33    156.0
345  2005-12-12  USW00094889    TMAX          22    200.0
346  2005-12-13  USW00094889    TMAX          -6    194.0
347  2005-12-14  USW00094889    TMAX          11    183.0
348  2005-12-15  USW00094889    TMAX          17    161.0
349  2005-12-16  USW00094889    TMAX          17    150.0
350  2005-12-17  USW00094889    TMAX         -11    122.0
351  2005-12-18  USW00094889    TMAX         -28     33.0
352  2005-12-19  USW00094889    TMAX         -33     11.0
353  2005-12-20  USW00094889    TMAX         -22     83.0
354  2005-12-21  USW00094889    TMAX         -22    122.0
355  2005-12-22  USW00094889    TMAX          28    133.0
356  2005-12-23  USW00094889    TMAX          50    183.0
357  2005-12-24  USW00094889    TMAX          61    172.0
358  2005-12-25  USW00094889    TMAX          61    111.0
359  2005-12-26  USW00094889    TMAX          50    117.0
360  2005-12-27  USW00094889    TMAX          39     83.0
362  2005-12-29  USW00094889    TMAX          56    100.0
363  2005-12-30  USW00094889    TMAX          39     67.0

[171 rows x 5 columns]
           Date           ID Element  Data_Value  datamin
0    2005-01-01  USC00200032    TMIN         -56   -133.0
1    2005-01-02  USC00200032    TMIN         -56   -122.0
2    2005-01-03  USC00200032    TMIN           0    -67.0
3    2005-01-04  USC00200032    TMIN         -39    -88.0
4    2005-01-05  USC00200032    TMIN         -94   -155.0
5    2005-01-06  USC00200032    TMIN        -106   -182.0
6    2005-01-07  USC00200032    TMIN        -111   -182.0
7    2005-01-08  USC00200032    TMIN        -100   -211.0
8    2005-01-09  USC00200032    TMIN         -67   -206.0
9    2005-01-10  USC00200032    TMIN         -56   -206.0
10   2005-01-11  USC00200032    TMIN         -22   -200.0
11   2005-01-12  USC00200032    TMIN         -17   -117.0
12   2005-01-13  USC00200032    TMIN         -83   -216.0
13   2005-01-14  USC00200032    TMIN        -128   -244.0
14   2005-01-15  USC00200032    TMIN        -144   -200.0
15   2005-01-16  USC00200032    TMIN        -150   -167.0
32   2005-02-02  USC00200032    TMIN        -167   -193.0
33   2005-02-03  USC00200032    TMIN        -167   -238.0
34   2005-02-04  USC00200032    TMIN        -156   -211.0
35   2005-02-05  USC00200032    TMIN        -128   -277.0
36   2005-02-06  USC00200032    TMIN         -89   -250.0
37   2005-02-07  USC00200032    TMIN         -56   -122.0
38   2005-02-08  USC00200032    TMIN         -33    -56.0
39   2005-02-09  USC00200032    TMIN         -78   -116.0
40   2005-02-10  USC00200032    TMIN        -111   -171.0
41   2005-02-11  USC00200032    TMIN        -122   -150.0
42   2005-02-12  USC00200032    TMIN         -83   -211.0
43   2005-02-13  USC00200032    TMIN         -56   -266.0
44   2005-02-14  USC00200032    TMIN         -28   -239.0
45   2005-02-15  USC00200032    TMIN         -11   -260.0
..          ...          ...     ...         ...      ...
262  2005-09-20  USC00200032    TMIN          94     39.0
263  2005-09-21  USC00200032    TMIN          78     56.0
264  2005-09-22  USC00200032    TMIN          94     17.0
266  2005-09-24  USC00200032    TMIN         111     56.0
267  2005-09-25  USC00200032    TMIN          94     78.0
275  2005-10-03  USC00200032    TMIN          50     44.0
276  2005-10-04  USC00200032    TMIN         100     61.0
277  2005-10-05  USC00200032    TMIN         100     94.0
282  2005-10-10  USC00200032    TMIN          22      0.0
284  2005-10-12  USC00200032    TMIN          67     28.0
285  2005-10-13  USC00200032    TMIN          83     72.0
286  2005-10-14  USC00200032    TMIN          56    -10.0
287  2005-10-15  USC00200032    TMIN          56    -16.0
288  2005-10-16  USC00200032    TMIN          -6    -10.0
289  2005-10-17  USC00200032    TMIN         -33    -55.0
290  2005-10-18  USC00200032    TMIN         -11    -55.0
291  2005-10-19  USC00200032    TMIN          -6    -61.0
292  2005-10-20  USC00200032    TMIN         -22    -39.0
293  2005-10-21  USC00200032    TMIN           0    -28.0
311  2005-11-08  USC00200032    TMIN         -11    -55.0
312  2005-11-09  USC00200032    TMIN          22    -61.0
313  2005-11-10  USC00200032    TMIN         -39    -44.0
318  2005-11-15  USC00200032    TMIN         -17    -22.0
325  2005-11-22  USC00200032    TMIN         -78   -116.0
331  2005-11-28  USC00200032    TMIN           0    -39.0
332  2005-11-29  USC00200032    TMIN         -39    -93.0
333  2005-11-30  USC00200032    TMIN         -56    -89.0
359  2005-12-26  USC00200032    TMIN         -11    -39.0
361  2005-12-28  USC00200032    TMIN         -28    -39.0
362  2005-12-29  USC00200032    TMIN         -11    -39.0


问:
onRequestPermissionsResult is not called in fragment android
i am taking runtime permission from user by using below code in fragment .

```<code>if (ContextCompat.checkSelfPermission(getActivity(),
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {

                                ActivityCompat.requestPermissions(mActivity,
                                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                        STORAGE_PERMISSION_CODE);

                            }
</code>```

and overriding

```<code>@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 21: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
</code>```

but override method not called

please give me hint for that i have to override in fragment

答:
I had the same issue,

It is a common mistake and it is very simple to solve.

if you are in an activity we normally use
ActivityCompat.requestPermissions(activity, permissionsNeeded.toTypedArray(),PERMISSION_REQUEST_CODE)

But you shouldn't use the same for a fragment. You can simply use it like requestPermissions(permissionsNeeded.toTypedArray(),PERMISSION_REQUEST_CODE)

If you call the Activity.requestPermission in fragment, the on request callback is get called in the Activity not in the Fragment.

Happy coding

ContentLicense: CC BY-SA 3.0

Body:
i am taking runtime permission from user by using below code in fragment .

if (ContextCompat.checkSelfPermission(getActivity(),
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {

                                ActivityCompat.requestPermissions(mActivity,
                                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                        STORAGE_PERMISSION_CODE);

                            }

and overriding

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 21: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

but override method not called

please give me hint for that i have to override in fragment


问:
Store and show multiple date range value SQL
I'm currently working on a rental car system and and have a few uncertainties about making a reservation for a car. How to display all the dates when a car reserved.

Example.

Car BMV is reserved from 11.20 2015 to 05.12.2015 also 30.11.205 to
  10.12.205 and 10.12.2015 to 25.12.2015

If clint want to make new reservation on this date i will create ALERT "This date is reserved for the car".

All that work with single reservation date but i need multiple.

My cuttent database looks like this:

Bookings:

```<code>    id  customer_id  car_id  booking_date  return_date  time_stamp
------  -----------  ------  ------------  -----------  ----------------
     1            2       5  2015-11-04    2015-11-12   15.06.10 20:10
     2            3       2  2015-11-02    2015-11-13   15.06.10 20:10
     3            1      11  2015-11-05    2015-11-16   15.06.10 20:10
     4            4       8  2015-11-10    2015-12-16   15.06.10 20:10
</code>```

Car:

```<code>   id  car_type_id  branch_id  registration_number  color    date_of_manifacturing  base_price_per_day
------  -----------  ---------  -------------------  -------  ---------------------  --------------------
     1            1          1  BG-123-431           White     2010-11-15                               30
     2            2          1  BG-A32-212           Metalic  2015-11-04                               30
     3            3          2  PA-332-421           Metalic  2008-05-03                               35
     4            4          1  SM-312-542           Black     2014-06-01                               35
     5            5          1  BG-4393-54           Black     2012-05-03                               50
     6            6          1  NS-423-64            White     2010-10-08                               50
</code>```

答:
If you want to select all cars once try group_concat

```<code>select t.*,group_concat(concat('from:', t2.booking_date,' to: ',t2.return_date)) reserved_ranges
from cars t
left join bookings t2 on t2.car_id = t.id
group by t.id;
</code>```

Body:
I'm currently working on a rental car system and and have a few uncertainties about making a reservation for a car. How to display all the dates when a car reserved.

Example.

Car BMV is reserved from 11.20 2015 to 05.12.2015 also 30.11.205 to
  10.12.205 and 10.12.2015 to 25.12.2015

If clint want to make new reservation on this date i will create ALERT "This date is reserved for the car".

All that work with single reservation date but i need multiple.

My cuttent database looks like this:

Bookings:

    id  customer_id  car_id  booking_date  return_date  time_stamp
------  -----------  ------  ------------  -----------  ----------------
     1            2       5  2015-11-04    2015-11-12   15.06.10 20:10
     2            3       2  2015-11-02    2015-11-13   15.06.10 20:10
     3            1      11  2015-11-05    2015-11-16   15.06.10 20:10
     4            4       8  2015-11-10    2015-12-16   15.06.10 20:10

Car:

   id  car_type_id  branch_id  registration_number  color    date_of_manifacturing  base_price_per_day
------  -----------  ---------  -------------------  -------  ---------------------  --------------------
     1            1          1  BG-123-431           White     2010-11-15                               30
     2            2          1  BG-A32-212           Metalic  2015-11-04                               30
     3            3          2  PA-332-421           Metalic  2008-05-03                               35
     4            4          1  SM-312-542           Black     2014-06-01                               35
     5            5          1  BG-4393-54           Black     2012-05-03                               50
     6            6          1  NS-423-64            White     2010-10-08                               50

Body:
If you want to select all cars once try group_concat

select t.*,group_concat(concat('from:', t2.booking_date,' to: ',t2.return_date)) reserved_ranges
from cars t
left join bookings t2 on t2.car_id = t.id
group by t.id;


问:
Why does the output keep returning a 'None' value at the last?
```<code>def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

print(range_test(1,5))
</code>```

Output:

```<code>1
2
3
4
5
None

Process finished with exit code 0
</code>```

答:
You're saying to print the output of range_test, but you aren't returning any value.

To fix this, just remove the print and run range_test(1, 5).

Body:
def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

print(range_test(1,5))

Output:

1
2
3
4
5
None

Process finished with exit code 0


问:
How to disable entire unit test in TestNG?
This is what I can do in JUnit:

```<code>import org.junit.*;
@Ignore
public class FooTest {
  //
}
</code>```

and the entire class will be ignored. How can I do the same in TestNG?

答:
I believe what you want is:

```<code>@Test(enabled=false)
public class FooTest {
  //
}
</code>```

(You can apply the @Test annotation to the class, as well as to methods individually.)

The TestNG documentation has a comprehensive list of the supported annotations, and also describes exclusion/inclusion of tests by group if that's of any interest. Here's a quote from the relevant section:

@Test Marks a class or a method as
  part of the test.

...(snip)...

enabled: Whether methods on this class/method are enabled.

EDIT:
Ignoring a class by applying @Test(enabled=false) is apparently buggy functionality in some versions of TestNG according to this defect that was raised against TestNG.

Body:
This is what I can do in JUnit:

import org.junit.*;
@Ignore
public class FooTest {
  //
}

and the entire class will be ignored. How can I do the same in TestNG?

Body:
I believe what you want is:

@Test(enabled=false)
public class FooTest {
  //
}

(You can apply the @Test annotation to the class, as well as to methods individually.)

The TestNG documentation has a comprehensive list of the supported annotations, and also describes exclusion/inclusion of tests by group if that's of any interest. Here's a quote from the relevant section:

@Test Marks a class or a method as
  part of the test.

...(snip)...

enabled: Whether methods on this class/method are enabled.

EDIT:
Ignoring a class by applying @Test(enabled=false) is apparently buggy functionality in some versions of TestNG according to this defect that was raised against TestNG.


问:
How to handle refresh token on react spa?
I have two servers. One for Hasura GraphQL api which queries the db and provides app data. Another is a node server for authentication. These two servers are not on the same domain.

I have a react spa client. When a user logs in, the node server validates the credentials with the hasura graphql endpoint and provides a jwt token and refresh token to the client. The refresh token is sent via httpOnly cookie as the react client and node server are on the same domain.

Now when the jwt token expires, I want to silently refresh the jwt token using the refresh token which is sent automatically as a cookie to the node server. How would I implement this?

One way that I can think of is, on the client side I decode the jwt and if it's expired I send a request to the refresh token endpoint on the node server and get a new jwt token before sending any request to the hasura graphql server which needs the access token sent as an authorization header. This means I would have to do this check before every graphql request. Is this the optimized way or are there any other way to silently refresh the token given my application architecture?

答:
This blog explains JWT and use cases around it very succinctly, https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/
It covers use cases of silent refresh and how to design auth server.</p>


问:
I want to host a static website on EC2 with nodejs app too
I am trying to host a static website on EC2 but no luck.

here is my config file node

```<code>server {
    listen 80;
    server_name localhost;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:3000";
    }
}
</code>```

I want to host static website too.

How can I do that on EC2

答:
I'm not sure how I can explain it end to end. I hope you got a basic idea of how it works.

From your question, I can understand that you are having some problems with the Nginx configuration.

your Nginx config file should look like this,

```<code>location / {
    # This would be the directory where your frontend code resides
    root /var/www/html/;
    try_files $uri /index.html;
}

location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3000/;
    proxy_set_header Host $http_host;
    proxy_redirect off;
}
</code>```

You can use PM2 for running the nodejs app in your VM.

Here Nginx would be webserver for your frontend application and a proxy to your backend application, all the request is going to hit on your Nginx server.

I hope this is what you are looking for.

Body:
I am trying to host a static website on EC2 but no luck.

here is my config file node

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:3000";
    }
}

I want to host static website too.

How can I do that on EC2

Body:
I'm not sure how I can explain it end to end. I hope you got a basic idea of how it works.

From your question, I can understand that you are having some problems with the Nginx configuration.

your Nginx config file should look like this,

location / {
    # This would be the directory where your frontend code resides
    root /var/www/html/;
    try_files $uri /index.html;
}

location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:3000/;
    proxy_set_header Host $http_host;
    proxy_redirect off;
}

You can use PM2 for running the nodejs app in your VM.

Here Nginx would be webserver for your frontend application and a proxy to your backend application, all the request is going to hit on your Nginx server.

I hope this is what you are looking for.


问:
how to make an android APK from android files without using AndroidStudio?
I have those three files:

```<code>  activity_main.xml
  MainActivity.java
  AndroidManifest.xml
</code>```

Those belong to a webview app I found on google...

I want to convert those files into an android apk....

I have no ides at all, just my basic laptop (doesnt support android studio) with internet conection. How can I make that work?

答:
From command line is posible with

```<code> gradlew assembleDebug
</code>```

https://developer.android.com/studio/build/building-cmdline

Body:
I have those three files:

  activity_main.xml
  MainActivity.java
  AndroidManifest.xml

Those belong to a webview app I found on google...

I want to convert those files into an android apk....

I have no ides at all, just my basic laptop (doesnt support android studio) with internet conection. How can I make that work?

Body:
From command line is posible with

 gradlew assembleDebug

https://developer.android.com/studio/build/building-cmdline


问:
How do you round a string in Python?
I am new to Python and a student, my college has chosen the worst book on earth for our course.  I cannot find examples of any concepts, so I apologize in advance as I know these concepts are very basic.  I hope you can help me.

I need to know how to use the round feature in a string.  I find examples but they do not show the string, just simple numbers.

Here is what we are supposed to get as an output:
Enter the gross income: 12345.67
Enter the number of dependents: 1

The income tax is $-130.87  <---- this is what we are supposed to figure out

Here is the coding we are given to alter:

```<code>TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0

# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))

# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
                DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE

# Display the income tax

print("The income tax is $" + str(incomeTax))
</code>```

As I do not have an NUMBER to plug into the formula - I have to figure out how to use "incomeTax" - I have no idea how to do this.  THe book doesnt explain it.  Help?

答:
Im a student as well, with the same dumb book and HW.

I tried the above

str(round(incomeTax,2))

and it didn’t work. Maybe I typed something wrong. After playing around I found this to work

```<code> # Display the income tax

incomeTax = round(incomeTax,2)

print(“The income tax is $” + str(incomeTax))
</code>```

I hope this helps some other poor soul searching the web for an answer!

Title: How do you round a string in Python?

Body:
I am new to Python and a student, my college has chosen the worst book on earth for our course.  I cannot find examples of any concepts, so I apologize in advance as I know these concepts are very basic.  I hope you can help me.

I need to know how to use the round feature in a string.  I find examples but they do not show the string, just simple numbers.

Here is what we are supposed to get as an output:
Enter the gross income: 12345.67
Enter the number of dependents: 1

The income tax is $-130.87  <---- this is what we are supposed to figure out

Here is the coding we are given to alter:

TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0

# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))

# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
                DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE

# Display the income tax

print("The income tax is $" + str(incomeTax))

As I do not have an NUMBER to plug into the formula - I have to figure out how to use "incomeTax" - I have no idea how to do this.  THe book doesnt explain it.  Help?

Body:
Im a student as well, with the same dumb book and HW.

I tried the above

str(round(incomeTax,2))

and it didn’t work. Maybe I typed something wrong. After playing around I found this to work

 # Display the income tax

incomeTax = round(incomeTax,2)

print(“The income tax is $” + str(incomeTax))

I hope this helps some other poor soul searching the web for an answer!


问:
Perl: match against a large array
Say I have $sentence = "The quick brown fox jumps over the lazy dog" and an array @targets = qw(brown red black lazy quick);.

The goal is to find out all words in @targets that contains in the $sentence, in this case, it's this three words: brown lazy quick.

Note: The @targets array could be very large, like there could be 10,000 elements in it. And there could be 10,000 $sentences to deal with.

Is there an efficient and elegant way to do it?

答:
I did a quick comparison between the methods presented in the other answers:

```<code>use feature qw(say);
use strict;
use warnings;
use Algorithm::AhoCorasick::XS;
use Benchmark qw(cmpthese);
use Regexp::Assemble;

{
    my @words = ("barbarous", "blandit", "celery", "gravida", "pencil", "move", "rain",
            "diligent", "letter", "staking", "enjoy", "salty", "abnormal", "volatile",
            "scared", "unsightly", "curabitor", "possible", "morbi", "open", "road");

    my $str = <<'END';
Lorem ipsum dolor sit amet consectetur adipiscing elit Vivamus tempor nulla condimentum ex posuere sed vulputate purus laoreet Etiam ut justo pulvinar lobortis leo in dictum ligula Pellentesque porta et justo a vestibulum Fusce et nulla vitae nisi scelerisque iaculis Donec non mi ligula Donec et ullamcorper eros Duis tincidunt ante dui vel vestibulum risus gravida molestie Nam eleifend placerat enim ultricies eleifend Pellentesque dapibus orci quis nulla faucibus ut rhoncus urna interdum Nam lobortis vitae nunc vel bibendum Nulla sed condimentum justo
Donec mauris felis fermentum eu libero sed cursus fermentum nunc Fusce dolor sapien ultrices nec egestas vel aliquam in mi Duis ullamcorper elit ut ornare tincidunt urna velit ultrices est at molestie urna risus faucibus libero Cras nec quam in orci efficitur tristique venenatis sit amet odio Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Pellentesque pretium metus eu eros vulputate non ornare orci imperdiet Ut pharetra efficitur urna sit amet sodales Donec pharetra eros sit amet dolor ullamcorper aliquet Cras ac ante sit amet erat fermentum consequat eget a turpis Donec a tellus ex Sed suscipit posuere hendrerit Praesent suscipit ante et tortor tempor congue Lorem ipsum dolor sit amet consectetur adipiscing elit Nunc tincidunt erat sit amet venenatis finibus ante massa ornare lacus at euismod tortor neque at velit
Sed ultricies velit ante vel convallis massa accumsan a Curabitur mauris purus tempus eu leo vitae fringilla porttitor augue Pellentesque mattis sed turpis quis viverra Aenean a mauris nec urna sollicitudin bibendum Etiam elementum efficitur lacus nec finibus Morbi ut dolor iaculis porttitor magna quis posuere arcu Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis at luctus sem Suspendisse vel erat porttitor lobortis tortor ac suscipit nulla Cras maximus dapibus odio sit amet aliquet Curabitur iaculis odio at aliquet tincidunt Suspendisse potenti Vivamus maximus est id rhoncus consectetur nisi purus rutrum massa nec ullamcorper risus nisi ut metus
Phasellus lobortis mauris turpis ut sollicitudin felis ultrices vel Ut tristique felis gravida est varius rutrum Sed porttitor pharetra sapien ac gravida urna Curabitur quis dignissim turpis Phasellus turpis sapien scelerisque vitae turpis tincidunt faucibus tempus tortor Proin bibendum elementum libero fermentum rhoncus Ut scelerisque sem eget rutrum scelerisque ex felis scelerisque augue vitae elementum lorem enim sit amet erat Sed congue volutpat mi pellentesque dapibus mi tempor quis Mauris nibh lorem mattis in nibh sed lacinia sagittis urna Etiam posuere odio non nisi placerat fermentum Mauris elit massa fermentum quis hendrerit ut condimentum a risus
Cras ut leo rhoncus laoreet turpis quis consectetur sem Fusce gravida neque et mauris molestie fermentum Proin non vehicula tellus vel volutpat est Nullam quis ornare ligula Nunc sed quam orci Nullam enim dolor cursus interdum fermentum sit amet gravida eu ex Aliquam nec porta mi Ut varius ut dolor vel convallis Curabitur massa purus varius nec diam eget sollicitudin finibus nisi Mauris pharetra in odio in rutrum Vestibulum vel eleifend ex Mauris tellus ex tempor ut dolor luctus facilisis pharetra justo
Cras elementum enim a egestas bibendum sapien ligula convallis tellus in dignissim augue massa vel diam Fusce quis mi diam Phasellus mollis est non ultricies dictum Nullam ullamcorper leo quis lacinia scelerisque libero enim faucibus dui placerat sodales dolor lectus sed ligula Nunc interdum justo vitae faucibus faucibus neque dui cursus nunc ut gravida dui urna sed ipsum Ut luctus lacus nulla id imperdiet elit fermentum sit amet Mauris nulla erat gravida ac enim ut blandit blandit felis Ut feugiat consequat vulputate Mauris erat neque vehicula ac purus ut tristique fringilla nulla
END

    cmpthese(
        -1,
        {
            regexp_assemble => sub { regexp_assemble( $str, \@words ) },
            aho_corasick    => sub { aho_corasick( $str, \@words ) },
            pp_trie         => sub { pp_trie( $str, \@words ) },
            hash_lookup     => sub { hash_lookup( $str, \@words ) },
        }
    );
}

sub hash_lookup {
    my ( $str, $targets ) = @_;

    my %targets = map { $_ => 1 } @$targets;
    my @words = split ' ', $str;
    my @matches;
    foreach my $each_word ( @words ){
        push @matches, $each_word if $targets{$each_word};
    }
    return \@matches;
}

sub pp_trie {
    my ( $str, $targets ) = @_;

    my $filter    = join '|', map {quotemeta} @$targets;
    my $re_filter = qr/\b($filter)\b/;
    my @matches = $str =~ /$re_filter/g;
    return \@matches;
}

sub aho_corasick {
    my ( $str, $targets ) = @_;

    my $matcher = Algorithm::AhoCorasick::XS->new($targets);
    my @matches = $matcher->matches($str);
    return \@matches;
}

sub regexp_assemble {
    my ( $str, $targets ) = @_;
    my $ra = Regexp::Assemble->new;
    $ra->add($_) for @$targets;
    my $regex = $ra->re;
    my @matches = $str =~ /\b($regex)\b/g;
    return \@matches;
}
</code>```

Output:

```<code>                   Rate regexp_assemble   hash_lookup       pp_trie aho_corasick
regexp_assemble  1935/s              --          -86%          -90%         -90%
hash_lookup     14221/s            635%            --          -24%         -28%
pp_trie         18618/s            862%           31%            --          -5%
aho_corasick    19651/s            916%           38%            6%           --
</code>```

So for this setup aho_corasick was the fastest one.

Edit:

If we do the preparation first step in advance, we see that aho_corasick is even faster:

```<code># ... (previous part as before)

    my $regexp_assemble = RegexpAssemble->new();
    my $aho_corasick = AhoCorasick->new();
    my $pp_trie = PPTrie->new();
    my $hash_lookup = HashLookUp->new();
    $regexp_assemble->prepare($str, \@words);
    $aho_corasick->prepare($str, \@words);
    $pp_trie->prepare($str, \@words);
    $hash_lookup->prepare($str, \@words);
    cmpthese(
        -1,
        {
            regexp_assemble => sub { $regexp_assemble->get_matches( $str, \@words ) },
            aho_corasick    => sub { $aho_corasick->get_matches( $str, \@words ) },
            pp_trie         => sub { $pp_trie->get_matches( $str, \@words ) },
            hash_lookup     => sub { $hash_lookup->get_matches( $str, \@words ) },
        }
    );
}

package HashLookUp;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    my %targets = map { $_ => 1 } @$targets;
    my @words = split ' ', $str;
    $self->{targets} = \%targets;
    $self->{words} = \@words;
}

sub get_matches( $self, $str, $targets ) {
    my \%targets = $self->{targets};
    my \@words = $self->{words};
    my @matches;
    foreach my $each_word ( @words ){
        push @matches, $each_word if $targets{$each_word};
    }
    return \@matches;
}

package PPTrie;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);

sub new( $class, %args ) { bless \%args, $class }

sub prepare($self, $str, $targets ) {
    my $filter    = join '|', map {quotemeta} @$targets;
    $self->{re_filter} = qr/\b($filter)\b/;
}

sub get_matches( $self, $str, $targets ) {
    my $re_filter = $self->{re_filter};
    my @matches = $str =~ /$re_filter/g;
    return \@matches;
}

package AhoCorasick;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);
use Algorithm::AhoCorasick::XS;

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    $self->{matcher} = Algorithm::AhoCorasick::XS->new($targets);
}

sub get_matches( $self, $str, $targets ) {
    my $matcher = $self->{matcher};
    my @matches = $matcher->matches($str);
    return \@matches;
}

package RegexpAssemble;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);
use Regexp::Assemble;

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    my $ra = Regexp::Assemble->new;
    $ra->add($_) for @$targets;
    $self->{regex} = $ra->re;
}

sub get_matches($self, $str, $targets ) {
    my $regex = $self->{regex};
    my @matches = $str =~ /\b($regex)\b/g;
    return \@matches;
}
</code>```

The result is now:

```<code>regexp_assemble  16440/s              --          -51%         -69%         -86%
pp_trie          33810/s            106%            --         -37%         -71%
hash_lookup      53592/s            226%           59%           --         -54%
aho_corasick    117029/s            612%          246%         118%           --
</code>```

Title: Perl: match against a large array

Body:
I did a quick comparison between the methods presented in the other answers:

use feature qw(say);
use strict;
use warnings;
use Algorithm::AhoCorasick::XS;
use Benchmark qw(cmpthese);
use Regexp::Assemble;

{
    my @words = ("barbarous", "blandit", "celery", "gravida", "pencil", "move", "rain",
            "diligent", "letter", "staking", "enjoy", "salty", "abnormal", "volatile",
            "scared", "unsightly", "curabitor", "possible", "morbi", "open", "road");

    my $str = <<'END';
Lorem ipsum dolor sit amet consectetur adipiscing elit Vivamus tempor nulla condimentum ex posuere sed vulputate purus laoreet Etiam ut justo pulvinar lobortis leo in dictum ligula Pellentesque porta et justo a vestibulum Fusce et nulla vitae nisi scelerisque iaculis Donec non mi ligula Donec et ullamcorper eros Duis tincidunt ante dui vel vestibulum risus gravida molestie Nam eleifend placerat enim ultricies eleifend Pellentesque dapibus orci quis nulla faucibus ut rhoncus urna interdum Nam lobortis vitae nunc vel bibendum Nulla sed condimentum justo
Donec mauris felis fermentum eu libero sed cursus fermentum nunc Fusce dolor sapien ultrices nec egestas vel aliquam in mi Duis ullamcorper elit ut ornare tincidunt urna velit ultrices est at molestie urna risus faucibus libero Cras nec quam in orci efficitur tristique venenatis sit amet odio Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Pellentesque pretium metus eu eros vulputate non ornare orci imperdiet Ut pharetra efficitur urna sit amet sodales Donec pharetra eros sit amet dolor ullamcorper aliquet Cras ac ante sit amet erat fermentum consequat eget a turpis Donec a tellus ex Sed suscipit posuere hendrerit Praesent suscipit ante et tortor tempor congue Lorem ipsum dolor sit amet consectetur adipiscing elit Nunc tincidunt erat sit amet venenatis finibus ante massa ornare lacus at euismod tortor neque at velit
Sed ultricies velit ante vel convallis massa accumsan a Curabitur mauris purus tempus eu leo vitae fringilla porttitor augue Pellentesque mattis sed turpis quis viverra Aenean a mauris nec urna sollicitudin bibendum Etiam elementum efficitur lacus nec finibus Morbi ut dolor iaculis porttitor magna quis posuere arcu Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis at luctus sem Suspendisse vel erat porttitor lobortis tortor ac suscipit nulla Cras maximus dapibus odio sit amet aliquet Curabitur iaculis odio at aliquet tincidunt Suspendisse potenti Vivamus maximus est id rhoncus consectetur nisi purus rutrum massa nec ullamcorper risus nisi ut metus
Phasellus lobortis mauris turpis ut sollicitudin felis ultrices vel Ut tristique felis gravida est varius rutrum Sed porttitor pharetra sapien ac gravida urna Curabitur quis dignissim turpis Phasellus turpis sapien scelerisque vitae turpis tincidunt faucibus tempus tortor Proin bibendum elementum libero fermentum rhoncus Ut scelerisque sem eget rutrum scelerisque ex felis scelerisque augue vitae elementum lorem enim sit amet erat Sed congue volutpat mi pellentesque dapibus mi tempor quis Mauris nibh lorem mattis in nibh sed lacinia sagittis urna Etiam posuere odio non nisi placerat fermentum Mauris elit massa fermentum quis hendrerit ut condimentum a risus
Cras ut leo rhoncus laoreet turpis quis consectetur sem Fusce gravida neque et mauris molestie fermentum Proin non vehicula tellus vel volutpat est Nullam quis ornare ligula Nunc sed quam orci Nullam enim dolor cursus interdum fermentum sit amet gravida eu ex Aliquam nec porta mi Ut varius ut dolor vel convallis Curabitur massa purus varius nec diam eget sollicitudin finibus nisi Mauris pharetra in odio in rutrum Vestibulum vel eleifend ex Mauris tellus ex tempor ut dolor luctus facilisis pharetra justo
Cras elementum enim a egestas bibendum sapien ligula convallis tellus in dignissim augue massa vel diam Fusce quis mi diam Phasellus mollis est non ultricies dictum Nullam ullamcorper leo quis lacinia scelerisque libero enim faucibus dui placerat sodales dolor lectus sed ligula Nunc interdum justo vitae faucibus faucibus neque dui cursus nunc ut gravida dui urna sed ipsum Ut luctus lacus nulla id imperdiet elit fermentum sit amet Mauris nulla erat gravida ac enim ut blandit blandit felis Ut feugiat consequat vulputate Mauris erat neque vehicula ac purus ut tristique fringilla nulla
END

    cmpthese(
        -1,
        {
            regexp_assemble => sub { regexp_assemble( $str, \@words ) },
            aho_corasick    => sub { aho_corasick( $str, \@words ) },
            pp_trie         => sub { pp_trie( $str, \@words ) },
            hash_lookup     => sub { hash_lookup( $str, \@words ) },
        }
    );
}

sub hash_lookup {
    my ( $str, $targets ) = @_;

    my %targets = map { $_ => 1 } @$targets;
    my @words = split ' ', $str;
    my @matches;
    foreach my $each_word ( @words ){
        push @matches, $each_word if $targets{$each_word};
    }
    return \@matches;
}

sub pp_trie {
    my ( $str, $targets ) = @_;

    my $filter    = join '|', map {quotemeta} @$targets;
    my $re_filter = qr/\b($filter)\b/;
    my @matches = $str =~ /$re_filter/g;
    return \@matches;
}

sub aho_corasick {
    my ( $str, $targets ) = @_;

    my $matcher = Algorithm::AhoCorasick::XS->new($targets);
    my @matches = $matcher->matches($str);
    return \@matches;
}

sub regexp_assemble {
    my ( $str, $targets ) = @_;
    my $ra = Regexp::Assemble->new;
    $ra->add($_) for @$targets;
    my $regex = $ra->re;
    my @matches = $str =~ /\b($regex)\b/g;
    return \@matches;
}

Output:

                   Rate regexp_assemble   hash_lookup       pp_trie aho_corasick
regexp_assemble  1935/s              --          -86%          -90%         -90%
hash_lookup     14221/s            635%            --          -24%         -28%
pp_trie         18618/s            862%           31%            --          -5%
aho_corasick    19651/s            916%           38%            6%           --

So for this setup aho_corasick was the fastest one.

Edit:

If we do the preparation first step in advance, we see that aho_corasick is even faster:

# ... (previous part as before)

    my $regexp_assemble = RegexpAssemble->new();
    my $aho_corasick = AhoCorasick->new();
    my $pp_trie = PPTrie->new();
    my $hash_lookup = HashLookUp->new();
    $regexp_assemble->prepare($str, \@words);
    $aho_corasick->prepare($str, \@words);
    $pp_trie->prepare($str, \@words);
    $hash_lookup->prepare($str, \@words);
    cmpthese(
        -1,
        {
            regexp_assemble => sub { $regexp_assemble->get_matches( $str, \@words ) },
            aho_corasick    => sub { $aho_corasick->get_matches( $str, \@words ) },
            pp_trie         => sub { $pp_trie->get_matches( $str, \@words ) },
            hash_lookup     => sub { $hash_lookup->get_matches( $str, \@words ) },
        }
    );
}

package HashLookUp;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    my %targets = map { $_ => 1 } @$targets;
    my @words = split ' ', $str;
    $self->{targets} = \%targets;
    $self->{words} = \@words;
}

sub get_matches( $self, $str, $targets ) {
    my \%targets = $self->{targets};
    my \@words = $self->{words};
    my @matches;
    foreach my $each_word ( @words ){
        push @matches, $each_word if $targets{$each_word};
    }
    return \@matches;
}

package PPTrie;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);

sub new( $class, %args ) { bless \%args, $class }

sub prepare($self, $str, $targets ) {
    my $filter    = join '|', map {quotemeta} @$targets;
    $self->{re_filter} = qr/\b($filter)\b/;
}

sub get_matches( $self, $str, $targets ) {
    my $re_filter = $self->{re_filter};
    my @matches = $str =~ /$re_filter/g;
    return \@matches;
}

package AhoCorasick;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);
use Algorithm::AhoCorasick::XS;

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    $self->{matcher} = Algorithm::AhoCorasick::XS->new($targets);
}

sub get_matches( $self, $str, $targets ) {
    my $matcher = $self->{matcher};
    my @matches = $matcher->matches($str);
    return \@matches;
}

package RegexpAssemble;
use strict;
use warnings;
use experimental qw(declared_refs refaliasing signatures);
use Regexp::Assemble;

sub new( $class, %args ) { bless \%args, $class }

sub prepare( $self, $str, $targets ) {
    my $ra = Regexp::Assemble->new;
    $ra->add($_) for @$targets;
    $self->{regex} = $ra->re;
}

sub get_matches($self, $str, $targets ) {
    my $regex = $self->{regex};
    my @matches = $str =~ /\b($regex)\b/g;
    return \@matches;
}

The result is now:

regexp_assemble  16440/s              --          -51%         -69%         -86%
pp_trie          33810/s            106%            --         -37%         -71%
hash_lookup      53592/s            226%           59%           --         -54%
aho_corasick    117029/s            612%          246%         118%           --


问:
create a new array from array of arrays
I have this array of arrays:

```<code>let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]
</code>```

And I want to return this single array from it:

```<code>b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]
</code>```

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?

答:
You could use a for loop to iterate through the array, and joining each of the 2nd dimensional arrays. You could use something like this:

for(var i = 0 ; i < array.length ; i++) {
array[i] = array[i][0] + " = " + array[i][1];
}

Title: create a new array from array of arrays

Body:
I have this array of arrays:

let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]

And I want to return this single array from it:

b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?


问:
Storing Application Default Credentials securely in KMS
We have a Java app which uses Google Auth to allow uses in. The app needs to connect to a Google Cloud SQL database which is locked down behind IP restrictions.

We need to use Cloud SQL Socket Factory with Cloud SQL Proxy to get access to the database, this requires Application Default Credentials with an environment variable GOOGLE_APPLICATION_CREDENTIALS pointing at service account credentials JSON file. I'm unsure of how to store this securely, putting that file on the user's PC is obviously not secure.

As per best practices on https://cloud.google.com/docs/authentication/production, it says

You can use an environment variable pointing to credentials outside of the application's source code, such as Cloud Key Management Service.

But this doesn't go on to explain how to do it. How can I store this file securely, in KMS or otherwise, in a way that only authorized Google accounts can access?

答:
First, the Cloud SQL proxy and the Cloud SQL JDBC socket factory are two different implementations of the same thing. The Socket Factory is used from inside your application, while the proxy is an external process. There is no reason to use both at the same time.

Second, how to secure your app depends a lot on how you plan to distribute and run it. If it's a web app, you'll likely create a "service account" that represents the privileges you want your application to have, and then restrict access to the front end of the application using whatever works (firewall, oauth, etc).

If your app is something locally distributed to a users platform, then it's a bit more complicated and much harder to secure. The problem is, anyone with access to your app could potentially access your database or other resources. Since you can't use gcloud, you could either re-implement your own auth layer (like gcloud auth application-default login) that has the user login and generated a temporary credential file that can be used to connect.

Alternatively, you include the credentials with the application itself. You could embed them directly, but if it gets compromised then you have to redistribute the application. What would be potentially safer would be to distribute the credential file(s) separate, and create different ones for each user. This way if one is compromised, you only need to rotate the compromised account.

To my knowledge, there is no way to use KMS to store a service account, as you would still need some way to authenticate with KMS itself.


答:
First you need to install Google's Android Studio. Go to

https://developer.android.com/studio

and then follow the installation instructions. Do not be surprised if this takes some time! Android Studio is BIG when you have installed the necessary SDKs and perhaps an emulator. Android Studio includes a lot of useful help.

Title: how to make an android APK from android files without using AndroidStudio?


问:
I keep getting an error when trying to start my discord bot
<pre class="lang-js prettyprint-override"><code>    PS C:\Users\netin\Desktop\bot> node .
internal/modules/cjs/loader.js:1032
  throw err;
  ^

Error: Cannot find module 'discord.js'
Require stack:
- C:\Users\netin\Desktop\bot\index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1029:15)
    at Function.Module._load (internal/modules/cjs/loader.js:898:27)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at Object.<anonymous> (C:\Users\netin\Desktop\bot\index.js:1:17)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\\Users\\netin\\Desktop\\bot\\index.js' ]
}
</code>```

答:
You did not install discord.js

NPM

```<code>npm i discord.js
</code>```

Yarn

```<code>yarn add discord.js
</code>```

Body:
You did not install discord.js

NPM

npm i discord.js

Yarn

yarn add discord.js