问:
Why stored procedure takes more time to execute compared to stored function for same code?
I have created stored-procedure with OUT parameter to handle automate INSERT operations based on values of other tables. I also made stored-function for the same operation. I am facing a problem with execution time for both is heavily different which makes me worried and I don't know why is that.

Following table values in summary:

2016 rows in emp_personal

I am using MariaDB 10.3.14. I am testing with HeidiSQL 10.1.0.5577.
I also tried calling it from Node.JS using MariaDB Node.js Connector. But in both cases, I had almost the same result.

This is Stored Procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_auto_attendance`(
    OUT `result` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE empId,done,isHoliday,isEmpHoliday,isWeekOff,isApprovedLeave,insertedRows INT DEFAULT 0;
DECLARE attendance VARCHAR(20) DEFAULT 'Present';
DECLARE empIds VARCHAR(500) DEFAULT '';

-- declare cursor with all employee Ids who are active
DECLARE empIds_cursor CURSOR FOR
SELECT id from emp_personal where isActive=1;

-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Check if today is holiday
SELECT COUNT(id) INTO isHoliday
FROM apexa_portal.public_holiday_dates
WHERE dateOfHoliday= CURDATE();

OPEN empIds_cursor;
    get_id: LOOP
        SET attendance = 'Present';
        FETCH empIds_cursor INTO empId;

            -- Following check if NOT FOUND handler has called, if yes exit loop else continue. NOTE: If you don't write this, it will be infinite loop.
            IF done = 1 THEN
                LEAVE get_id;
            END IF;

            -- Check if public holiday for employee
            IF isHoliday > 0 THEN
                SELECT COUNT(phtd.isActive) INTO isEmpHoliday FROM public_holiday_template_days as phtd
                LEFT JOIN emp_office_details as eod ON eod.publicHolidayTemplate=phtd.templateId
                LEFT JOIN public_holiday_dates as phd ON phd.pub_holiday_id=phtd.holidayId
                WHERE eod.empID=empId AND phd.dateOfHoliday=CURDATE() AND phtd.isActive=1;
                IF isEmpHoliday > 0 THEN
                    SET attendance = 'Public Holiday';
                END IF;
            END IF;

            -- if not public holiday, Check if week off
            IF attendance <> 'Public Holiday' THEN
                SELECT COUNT(eowd.id) INTO isWeekOff FROM emp_office_working_days as eowd
                WHERE DAY=DAYOFWEEK(CURDATE()) AND eowd.empId=empId AND eowd.isActive=0;
                IF isWeekOff > 0 THEN
                    SET attendance = 'Week Off';
                END IF;
            END IF;

            -- if not week off, Check if approved leave
            IF attendance <> 'Week Off' THEN
                SELECT COUNT(la.id) INTO isApprovedLeave FROM leave_application as la
                WHERE la.fromDate <= CURDATE() AND la.toDate >= CURDATE() AND la.empID=empId AND la.leaveStatus='Approved';
                IF isApprovedLeave > 0 THEN
                    SET attendance = 'Approved Leave';
                END IF;
            END IF;

            -- insert attendance
            INSERT INTO attendance_master(empID,dateOfAttendance,attendance) VALUES(empId,CURDATE(),attendance);
            SET insertedRows = insertedRows + 1;
    END LOOP get_id;
CLOSE empIds_cursor;
SET result = insertedRows;
END
```

<p><strong>This is Stored Function</strong></p>

```CREATE DEFINER=`root`@`localhost` FUNCTION `test_auto_att_func`()
RETURNS int(11)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE empId,done,isHoliday,isEmpHoliday,isWeekOff,isApprovedLeave,insertedRows INT DEFAULT 0;
DECLARE attendance VARCHAR(20) DEFAULT 'Present';
DECLARE empIds VARCHAR(500) DEFAULT '';

-- declare cursor with all employee Ids who are active
DECLARE empIds_cursor CURSOR FOR
SELECT id from emp_personal where isActive=1;

-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Check if today is holiday
SELECT COUNT(id) INTO isHoliday
FROM apexa_portal.public_holiday_dates
WHERE dateOfHoliday= CURDATE();

OPEN empIds_cursor;
    get_id: LOOP
        SET attendance = 'Present';
        FETCH empIds_cursor INTO empId;

            -- Following check if NOT FOUND handler has called, if yes exit loop else continue. NOTE: If you don't write this, it will be infinite loop.
            IF done = 1 THEN
                LEAVE get_id;
            END IF;

            -- Check if public holiday for employee
            IF isHoliday > 0 THEN
                SELECT COUNT(phtd.isActive) INTO isEmpHoliday FROM public_holiday_template_days as phtd
                LEFT JOIN emp_office_details as eod ON eod.publicHolidayTemplate=phtd.templateId
                LEFT JOIN public_holiday_dates as phd ON phd.pub_holiday_id=phtd.holidayId
                WHERE eod.empID=empId AND phd.dateOfHoliday=CURDATE() AND phtd.isActive=1;
                IF isEmpHoliday > 0 THEN
                    SET attendance = 'Public Holiday';
                END IF;
            END IF;

            -- if not public holiday, Check if week off
            IF attendance <> 'Public Holiday' THEN
                SELECT COUNT(eowd.id) INTO isWeekOff FROM emp_office_working_days as eowd
                WHERE DAY=DAYOFWEEK(CURDATE()) AND eowd.empId=empId AND eowd.isActive=0;
                IF isWeekOff > 0 THEN
                    SET attendance = 'Week Off';
                END IF;
            END IF;

            -- if not week off, Check if approved leave
            IF attendance <> 'Week Off' THEN
                SELECT COUNT(la.id) INTO isApprovedLeave FROM leave_application as la
                WHERE la.fromDate <= CURDATE() AND la.toDate >= CURDATE() AND la.empID=empId AND la.leaveStatus='Approved';
                IF isApprovedLeave > 0 THEN
                    SET attendance = 'Approved Leave';
                END IF;
            END IF;

            -- insert attendance
            INSERT INTO attendance_master(empID,dateOfAttendance,attendance) VALUES(empId,CURDATE(),attendance);
            SET insertedRows = insertedRows + 1;
    END LOOP get_id;
CLOSE empIds_cursor;
RETURN insertedRows;

END
```

<p><strong>Time to execute Stored Function</strong></p>

```SELECT `test_auto_att_func`();
/* Affected rows: 0  Found rows: 1  Warnings: 0  Duration for 1 query: 0.328 sec. */
```

<p><strong>Time to execute Stored Procedure</strong></p>

```CALL `sp_auto_attendance`(@res);
SELECT @res;
/* Affected rows: 6,049  Found rows: 1  Warnings: 0  Duration for 2 queries: 00:01:21.6 */
```

Stored Function Output and Stored Procedure Output

Can anyone please explain why this is happening? And if I am doing anything wrong, please let me know how should I correct it?

Thank You.

答:
There should be no difference on performance on similar code when you run the code as a procedure vs as a function.

Most likely explanation (see Affected rows) is that at the the time of the function run, the cursor did not find any active persons whereas in the procedure run did, hence running the loop queries.

Body:
I have created stored-procedure with OUT parameter to handle automate INSERT operations based on values of other tables. I also made stored-function for the same operation. I am facing a problem with execution time for both is heavily different which makes me worried and I don't know why is that.

Following table values in summary:

2016 rows in emp_personal

I am using MariaDB 10.3.14. I am testing with HeidiSQL 10.1.0.5577.
I also tried calling it from Node.JS using MariaDB Node.js Connector. But in both cases, I had almost the same result.

This is Stored Procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_auto_attendance`(
    OUT `result` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE empId,done,isHoliday,isEmpHoliday,isWeekOff,isApprovedLeave,insertedRows INT DEFAULT 0;
DECLARE attendance VARCHAR(20) DEFAULT 'Present';
DECLARE empIds VARCHAR(500) DEFAULT '';

-- declare cursor with all employee Ids who are active
DECLARE empIds_cursor CURSOR FOR
SELECT id from emp_personal where isActive=1;

-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Check if today is holiday
SELECT COUNT(id) INTO isHoliday
FROM apexa_portal.public_holiday_dates
WHERE dateOfHoliday= CURDATE();

OPEN empIds_cursor;
    get_id: LOOP
        SET attendance = 'Present';
        FETCH empIds_cursor INTO empId;

            -- Following check if NOT FOUND handler has called, if yes exit loop else continue. NOTE: If you don't write this, it will be infinite loop.
            IF done = 1 THEN
                LEAVE get_id;
            END IF;

            -- Check if public holiday for employee
            IF isHoliday > 0 THEN
                SELECT COUNT(phtd.isActive) INTO isEmpHoliday FROM public_holiday_template_days as phtd
                LEFT JOIN emp_office_details as eod ON eod.publicHolidayTemplate=phtd.templateId
                LEFT JOIN public_holiday_dates as phd ON phd.pub_holiday_id=phtd.holidayId
                WHERE eod.empID=empId AND phd.dateOfHoliday=CURDATE() AND phtd.isActive=1;
                IF isEmpHoliday > 0 THEN
                    SET attendance = 'Public Holiday';
                END IF;
            END IF;

            -- if not public holiday, Check if week off
            IF attendance <> 'Public Holiday' THEN
                SELECT COUNT(eowd.id) INTO isWeekOff FROM emp_office_working_days as eowd
                WHERE DAY=DAYOFWEEK(CURDATE()) AND eowd.empId=empId AND eowd.isActive=0;
                IF isWeekOff > 0 THEN
                    SET attendance = 'Week Off';
                END IF;
            END IF;

            -- if not week off, Check if approved leave
            IF attendance <> 'Week Off' THEN
                SELECT COUNT(la.id) INTO isApprovedLeave FROM leave_application as la
                WHERE la.fromDate <= CURDATE() AND la.toDate >= CURDATE() AND la.empID=empId AND la.leaveStatus='Approved';
                IF isApprovedLeave > 0 THEN
                    SET attendance = 'Approved Leave';
                END IF;
            END IF;

            -- insert attendance
            INSERT INTO attendance_master(empID,dateOfAttendance,attendance) VALUES(empId,CURDATE(),attendance);
            SET insertedRows = insertedRows + 1;
    END LOOP get_id;
CLOSE empIds_cursor;
SET result = insertedRows;
END

This is Stored Function

CREATE DEFINER=`root`@`localhost` FUNCTION `test_auto_att_func`()
RETURNS int(11)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE empId,done,isHoliday,isEmpHoliday,isWeekOff,isApprovedLeave,insertedRows INT DEFAULT 0;
DECLARE attendance VARCHAR(20) DEFAULT 'Present';
DECLARE empIds VARCHAR(500) DEFAULT '';

-- declare cursor with all employee Ids who are active
DECLARE empIds_cursor CURSOR FOR
SELECT id from emp_personal where isActive=1;

-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Check if today is holiday
SELECT COUNT(id) INTO isHoliday
FROM apexa_portal.public_holiday_dates
WHERE dateOfHoliday= CURDATE();

OPEN empIds_cursor;
    get_id: LOOP
        SET attendance = 'Present';
        FETCH empIds_cursor INTO empId;

            -- Following check if NOT FOUND handler has called, if yes exit loop else continue. NOTE: If you don't write this, it will be infinite loop.
            IF done = 1 THEN
                LEAVE get_id;
            END IF;

            -- Check if public holiday for employee
            IF isHoliday > 0 THEN
                SELECT COUNT(phtd.isActive) INTO isEmpHoliday FROM public_holiday_template_days as phtd
                LEFT JOIN emp_office_details as eod ON eod.publicHolidayTemplate=phtd.templateId
                LEFT JOIN public_holiday_dates as phd ON phd.pub_holiday_id=phtd.holidayId
                WHERE eod.empID=empId AND phd.dateOfHoliday=CURDATE() AND phtd.isActive=1;
                IF isEmpHoliday > 0 THEN
                    SET attendance = 'Public Holiday';
                END IF;
            END IF;

            -- if not public holiday, Check if week off
            IF attendance <> 'Public Holiday' THEN
                SELECT COUNT(eowd.id) INTO isWeekOff FROM emp_office_working_days as eowd
                WHERE DAY=DAYOFWEEK(CURDATE()) AND eowd.empId=empId AND eowd.isActive=0;
                IF isWeekOff > 0 THEN
                    SET attendance = 'Week Off';
                END IF;
            END IF;

            -- if not week off, Check if approved leave
            IF attendance <> 'Week Off' THEN
                SELECT COUNT(la.id) INTO isApprovedLeave FROM leave_application as la
                WHERE la.fromDate <= CURDATE() AND la.toDate >= CURDATE() AND la.empID=empId AND la.leaveStatus='Approved';
                IF isApprovedLeave > 0 THEN
                    SET attendance = 'Approved Leave';
                END IF;
            END IF;

            -- insert attendance
            INSERT INTO attendance_master(empID,dateOfAttendance,attendance) VALUES(empId,CURDATE(),attendance);
            SET insertedRows = insertedRows + 1;
    END LOOP get_id;
CLOSE empIds_cursor;
RETURN insertedRows;

END

Time to execute Stored Function

SELECT `test_auto_att_func`();
/* Affected rows: 0  Found rows: 1  Warnings: 0  Duration for 1 query: 0.328 sec. */

Time to execute Stored Procedure

CALL `sp_auto_attendance`(@res);
SELECT @res;
/* Affected rows: 6,049  Found rows: 1  Warnings: 0  Duration for 2 queries: 00:01:21.6 */

Stored Function Output and Stored Procedure Output

Can anyone please explain why this is happening? And if I am doing anything wrong, please let me know how should I correct it?

Thank You.


来源: stackexchange

问:
strptime string to datetime object conversion
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

```<code>import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date
</code>```

Output:

```<code>time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

Script using datetime.now - datetime.timedelta:

```<code>import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date
</code>```

Output:

```<code>2019-03-31 21:09:25.183459
</code>```

Expected output:

```<code>time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)
</code>```

答:
Try:-

```<code>import time
import datetime

print(time.strftime("%Y-%m-%d %H:%M:%S %w/%j"))

pre_create_date = (datetime.datetime.today() - datetime.timedelta(60)).strftime("%Y-%m-%d %H:%M:%S %w/%j")

print(pre_create_date)
</code>```

OUTPUT:-

```<code>2019-05-30 12:59:27 4/150
2019-03-31 12:59:27 0/090
</code>```

WORKING:-

The above code first prints out the current Timestamp(the format is the one you asked for). And then outputs the 60 days early Timestamp from current date (today - 60).

Just used strftime() to get our desired attributes off the current date.

EXPLANATION OF CODES USED IN strftime():-

```<code>%Y     Year with century as a decimal number.
%m     Month as a zero-padded decimal number.
%d     Day of the month as a zero-padded decimal.

%H     Hour (24-hour clock) as a zero-padded decimal number.
%M     Minute as a zero-padded decimal number.
%S     Second as a zero-padded decimal number.

%w     Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.
%j     Day of the year as a zero-padded decimal number.
</code>```

NOTE:- After passing the dates via strftime() the output will be of datatype string. If you want the output to be a datetime object then use:-

```<code>datetimeobj_1 = datetime.datetime.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))
</code>```

OUTPUT:-

```<code><class 'datetime.datetime'>
</code>```

If you want the output to be a 'time.struct_time' object then use:-

```<code>datetimeobj_1 = time.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))
</code>```

OUTPUT:-

```<code><class 'time.struct_time'>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Python2.7 script with a variable date= "21/05/2019" that works fine.
I need the date variable to be datetime.now - 60 days.

However the output must be like time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=-1)

datetime.datetime.now() with strptime won't work.

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

I expect to be able to use datetime.datetime.today() - datetime.timedelta(days=N) but the output to be a datetime object.

Edit:

It looks like I haven't explained myself very well. Sorry about that.

The script is:

import datetime, time
from datetime import timedelta

N = 60
#pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)
pre_create_date = "28/04/2019"

# Sort out date format
pre_create_date = time.strptime(pre_create_date, "%d/%m/%Y")

print pre_create_date

Output:

time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)

Script using datetime.now - datetime.timedelta:

import datetime, time
from datetime import timedelta

N = 60
pre_create_date = datetime.datetime.today() - datetime.timedelta(days=N)

print pre_create_date

Output:

2019-03-31 21:09:25.183459

Expected output:

time.struct_time(tm_year=2019, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=118, tm_isdst=-1)

Body:
Try:-

import time
import datetime

print(time.strftime("%Y-%m-%d %H:%M:%S %w/%j"))

pre_create_date = (datetime.datetime.today() - datetime.timedelta(60)).strftime("%Y-%m-%d %H:%M:%S %w/%j")

print(pre_create_date)

OUTPUT:-

2019-05-30 12:59:27 4/150
2019-03-31 12:59:27 0/090

WORKING:-

The above code first prints out the current Timestamp(the format is the one you asked for). And then outputs the 60 days early Timestamp from current date (today - 60).

Just used strftime() to get our desired attributes off the current date.

EXPLANATION OF CODES USED IN strftime():-

%Y     Year with century as a decimal number.
%m     Month as a zero-padded decimal number.
%d     Day of the month as a zero-padded decimal.

%H     Hour (24-hour clock) as a zero-padded decimal number.
%M     Minute as a zero-padded decimal number.
%S     Second as a zero-padded decimal number.

%w     Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.
%j     Day of the year as a zero-padded decimal number.

NOTE:- After passing the dates via strftime() the output will be of datatype string. If you want the output to be a datetime object then use:-

datetimeobj_1 = datetime.datetime.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))

OUTPUT:-

<class 'datetime.datetime'>

If you want the output to be a 'time.struct_time' object then use:-

datetimeobj_1 = time.strptime(pre_create_date, "%Y-%m-%d %H:%M:%S %w/%j")
print(type(datetimeobj_1))

OUTPUT:-

<class 'time.struct_time'>


问:
How to stop replacing chars with a replacement character �?
I'm writing a tic-tac-toe game with some additional features.

Sometimes when I try to print the array of chars (which is the board) it replaces some of the characters with a black diamond with a white question mark(�) or an empty square box.

What do I need to do to solve this?

```<code>void print_board(char board[N][N], int n)
{
    printf("\nCurrent board:\n");

    for (int i = 0; i < n; i++)
    {
        printf("|");

        for (int j = 0; j < n; j++)
        {
            printf("%c|", board[i][j]);
        }

        printf("\n");
    }

    printf("\n");
}
</code>```

I expect a normal board with x's and o's but some of these get replaced by � or an empty box.

```<code>void change_board(char board[N][N], int moves_history[TWO][N], int row, int column, int player_index, int turns_num, int board_size)
{
    char player_sign = (player_index == FIRST_PLAYER) ? FIRST_PLAYER_SIGN : SECOND_PLAYER_SIGN;
    board[row][column] = player_sign;
    moves_history[0][turns_num-1] = row;
    moves_history[1][turns_num-1] = column;
    print_board(board, board_size);

    if (did_anyone_win(board,player_index, player_sign,board_size,row,column))
    {
        exit(0);
    }

    player_index = (player_index == FIRST_PLAYER) ? SECOND_PLAYER : FIRST_PLAYER;
    player_turn(board,board_size,turns_num,player_index,moves_history);
}

void Undo(char board[N][N], int moves_history[TWO][N], int undo, int board_size, int turns_num, int player_index)
{
    for (int i = turns_num-TWO; i >= turns_num+undo-1; i--)
    {
        board[moves_history[0][i]][moves_history[1][i]] = EMPTY_CELL;
        moves_history[0][i] = 0;
        moves_history[1][i] = 0;
    }

    print_board(board,board_size);

    player_index = player_index == FIRST_PLAYER ? SECOND_PLAYER : FIRST_PLAYER;
    player_turn(board,board_size,turns_num+undo-1,player_index,moves_history);
}
</code>```

These are the only places where I change the board, I don't think there's any bug here but I put them just for reference.

答: I noticed based on your variable names that you have an NxN matrix for your board. But your move history is an array of size N. Could that be the issue?</p>

Body:
I'm writing a tic-tac-toe game with some additional features.

Sometimes when I try to print the array of chars (which is the board) it replaces some of the characters with a black diamond with a white question mark(�) or an empty square box.

What do I need to do to solve this?

void print_board(char board[N][N], int n)
{
    printf("\nCurrent board:\n");

    for (int i = 0; i < n; i++)
    {
        printf("|");

        for (int j = 0; j < n; j++)
        {
            printf("%c|", board[i][j]);
        }

        printf("\n");
    }

    printf("\n");
}

I expect a normal board with x's and o's but some of these get replaced by � or an empty box.

void change_board(char board[N][N], int moves_history[TWO][N], int row, int column, int player_index, int turns_num, int board_size)
{
    char player_sign = (player_index == FIRST_PLAYER) ? FIRST_PLAYER_SIGN : SECOND_PLAYER_SIGN;
    board[row][column] = player_sign;
    moves_history[0][turns_num-1] = row;
    moves_history[1][turns_num-1] = column;
    print_board(board, board_size);

    if (did_anyone_win(board,player_index, player_sign,board_size,row,column))
    {
        exit(0);
    }

    player_index = (player_index == FIRST_PLAYER) ? SECOND_PLAYER : FIRST_PLAYER;
    player_turn(board,board_size,turns_num,player_index,moves_history);
}

void Undo(char board[N][N], int moves_history[TWO][N], int undo, int board_size, int turns_num, int player_index)
{
    for (int i = turns_num-TWO; i >= turns_num+undo-1; i--)
    {
        board[moves_history[0][i]][moves_history[1][i]] = EMPTY_CELL;
        moves_history[0][i] = 0;
        moves_history[1][i] = 0;
    }

    print_board(board,board_size);

    player_index = player_index == FIRST_PLAYER ? SECOND_PLAYER : FIRST_PLAYER;
    player_turn(board,board_size,turns_num+undo-1,player_index,moves_history);
}

These are the only places where I change the board, I don't think there's any bug here but I put them just for reference.


问:
How do we use the invisible cells in uitableview swift?
I want to change my progress bar one by one in tableview. but when my use invisible cell in code, then it produces nil.

I use the tableview.cellforRowAt(IndexPath) in our code , Please resolve my problem

答:
UITableViewCell is reusable, you cannot update UI of cells that are not displayed (visible), they just do not exist or being reused for another cell.

Reusable means that cell's view (UITableViewCell) will be used for any other cell that might just got in to the tableView bounds, this happens when you delete a row, or when you scroll away and the cell gets out of tableView bounds etc...

So, its not a problem, but by design.

BTW, you are using the correct method tableView.cellForRow(at: IndexPath), it will return a cell only if one is displayed.

You should instead update your data source and keep the progress value, when the cell next time being displayed it will show the value from data source, like so:

```<code>struct CellData {
    var progress: Float
}

var dataSource: [CellData]
</code>```

Now when you need to update the progress of cells, you can just update dataSource, like so

```<code>dataSource[index].progress = value
</code>```

Then you call either call UITableView.realoadData() to refresh the UI of all cells that are visible, or you can update only that particular index, like so:

```<code>if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? CustomCell {
    cell.progressView.setProgress(value, animated: true)
}
</code>```

Body:
UITableViewCell is reusable, you cannot update UI of cells that are not displayed (visible), they just do not exist or being reused for another cell.

Reusable means that cell's view (UITableViewCell) will be used for any other cell that might just got in to the tableView bounds, this happens when you delete a row, or when you scroll away and the cell gets out of tableView bounds etc...

So, its not a problem, but by design.

BTW, you are using the correct method tableView.cellForRow(at: IndexPath), it will return a cell only if one is displayed.

You should instead update your data source and keep the progress value, when the cell next time being displayed it will show the value from data source, like so:

struct CellData {
    var progress: Float
}

var dataSource: [CellData]

Now when you need to update the progress of cells, you can just update dataSource, like so

dataSource[index].progress = value

Then you call either call UITableView.realoadData() to refresh the UI of all cells that are visible, or you can update only that particular index, like so:

if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? CustomCell {
    cell.progressView.setProgress(value, animated: true)
}


问:
Teradara SQL - Operation with max-min dates
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards</p>

```<code>Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1
</code>```

答:
```<code>select user
  ,price as first_price
  ,last_value(price)
   over (paritition by user
         order by date
         rows between unbounded preceding and unbounded following) as last_price
from mytab
qualify
  row_number() -- lowest date only
  over (paritition by user
        order by date) = 1
</code>```

<p>This returns the row with the lowest date and adds the price of the latest date </p>

Body:
suppose I have the following data frame in Reradata SQL.
How can I get the variation between the highest and lowest date, at user level? Regards

Initial table
   user    date   price
    1       1-1       10
    1       2-1       20
    1       3-1       30
    2       1-1       12
    2       2-1       22
    2       3-1       32
    3       1-1       13
    3       2-1       23
    3       3-1       33

 Final table

user   var_price
1       30/10-1
2       32/12-1
3       33/13-1

Body:
select user
  ,price as first_price
  ,last_value(price)
   over (paritition by user
         order by date
         rows between unbounded preceding and unbounded following) as last_price
from mytab
qualify
  row_number() -- lowest date only
  over (paritition by user
        order by date) = 1

This returns the row with the lowest date and adds the price of the latest date


问:
given incrementing ID values and a created date, create a SQL statement to find if any of the dates are out of step with the ID in oracle
Given a table like below:
created is a TIMESTAMP(6), and ID is NUMBER(20,0)

```<code>| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...
</code>```

Determine all the rows where CREATED dates are out of step with the incrementing ID values.

If the values are ordered by ID, is any CREATED < the previous CREATED value.

I have attempted it, and found that my version is cartesioning horribly, and not returning results. I am sure I am missing some efficiencies in the query.

As output I need the ID/CREATED of the rows that are out of step.

答:
it seems you need analytic function lead() for comparison of next level row with current and if it greater than the current then it will come to your output

```<code>with cte as
(
select id,CREATED,lead(CREATED) over(order by id) as NR
from t
) select id,created from cte where CREATED>NR
</code>```

Body:
Given a table like below:
created is a TIMESTAMP(6), and ID is NUMBER(20,0)

| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...

Determine all the rows where CREATED dates are out of step with the incrementing ID values.

If the values are ordered by ID, is any CREATED < the previous CREATED value.

I have attempted it, and found that my version is cartesioning horribly, and not returning results. I am sure I am missing some efficiencies in the query.

As output I need the ID/CREATED of the rows that are out of step.

Body:
it seems you need analytic function lead() for comparison of next level row with current and if it greater than the current then it will come to your output

with cte as
(
select id,CREATED,lead(CREATED) over(order by id) as NR
from t
) select id,created from cte where CREATED>NR


问:
loopback where filter on date's year
I am not sure if database functions are supported thru REST API requests or if I am doing something wrong. I am using mysql db connector.

I have tried using simple where filter with both equality and gte operators.

```<code>{"where":{"YEAR(StartDate)":2018}}

or

{"where":{"and":[{"YEAR(StartDate)":{"gte":2018}},{"year(StartDate)":{"lte":2020}}]}}
</code>```

I don't get any error and the filter condition is silently ignored returning all records from the table.

答:
You can't call functions from the query, you need to pass the values there. You may want to enable the debugger to see what is going on and what queries are actually triggered. So, assuming that field name in the database is StartDate, you probably want to use something like this:

```<code>{"where":{ "StartDate": {"gte": new Date('2018-01-01T00:00:00.000Z')}} }
</code>```

or, if and statement involved

```<code>{"where":{"and":[{"StartDate":{"gte":new Date('2018-01-01T00:00:00.000Z')}},{"StartDate":{"lte":new Date('2020-01-01T00:00:00.000Z')}}]}}
</code>```

Title: loopback where filter on date's year

Body:
I am not sure if database functions are supported thru REST API requests or if I am doing something wrong. I am using mysql db connector.

I have tried using simple where filter with both equality and gte operators.

{"where":{"YEAR(StartDate)":2018}}

or

{"where":{"and":[{"YEAR(StartDate)":{"gte":2018}},{"year(StartDate)":{"lte":2020}}]}}

I don't get any error and the filter condition is silently ignored returning all records from the table.

Body:
You can't call functions from the query, you need to pass the values there. You may want to enable the debugger to see what is going on and what queries are actually triggered. So, assuming that field name in the database is StartDate, you probably want to use something like this:

{"where":{ "StartDate": {"gte": new Date('2018-01-01T00:00:00.000Z')}} }

or, if and statement involved

{"where":{"and":[{"StartDate":{"gte":new Date('2018-01-01T00:00:00.000Z')}},{"StartDate":{"lte":new Date('2020-01-01T00:00:00.000Z')}}]}}


问:
web component - accept no child elements
How can I define a web component that works like  in that it accepts no child elements?

  <template id="push-message">

    <message>

    </message>
  </template>

  <push-message
     badge="//google.com/favicon.ico"
      icon="//google.com/favicon.ico"
     image="//google.com/favicon.ico">

ok
```
</div>
</div>
</p>

<p><code>DOM</code> should be</p>

```<push-message></push-message>

```

<p>not</p>

```<push-message>

</push-message>
```

and ok should display in the result.

Is there a way to change customElements.define to avoid having to explicitly close <push-message></push-message> and just use <push-message> but have it implicitly self-close?

答:
Self-closing tags as known as void elements.

AFAIK, it is not possible to create custom void elements. In summary, it needs changing browser HTML parsers which is not an easy thing to pull by the web community. Changes are required because of the way the browser implements a tag-soup algorithm.

Thus you will need a closing tag. You can read more about this here:

Specs discussion

Lit-html discussion

On a side note, if you have your own template compiler/parser like vue-compiler and ng-compiler, you can probably instruct it to understand self-closing custom elements at a build time. However, the benefits of achieving this are virtually non-existent.

Body:
How can I define a web component that works like  in that it accepts no child elements?

  <template id="push-message">

    <message>

    </message>
  </template>

  <push-message
     badge="//google.com/favicon.ico"
      icon="//google.com/favicon.ico"
     image="//google.com/favicon.ico">

ok

DOM should be

<push-message></push-message>

not

<push-message>

</push-message>

and ok should display in the result.

Is there a way to change customElements.define to avoid having to explicitly close <push-message></push-message> and just use <push-message> but have it implicitly self-close?


问:
Does not exist in current context error, but it should - ASP.NET c#
Here is the code:

```<code>for (int i = 0; i < Model.Count; i++)
{
    Writer.WriteBeginTag("li");
    if (i % 2 == 1)
    {
            string myVar  = "even ";
    }
    if ((i+1) % 3 == 0)
    {
        myVar += "third";
    }
    Writer.WriteAttribute("class", ""); // I want to use myVar here
    Writer.Write(HtmlTextWriter.TagRightChar);
    Writer.WriteEndTag("li");
}
</code>```

I'm not all that familiar with .NET or C#. I get an error The name "myVar" does not exist in the current context on the second myVar. If I comment this line out, I then have a message The variable "myVar" is assigned but its value is never used. on the first myVar. I don't really understand how or why this would be out of context/scope.

Any ideas?

答:
You are creating the variable myVar in the scope of the first if statement, thus it isn't available in second one. You need to create it beforehand:

```<code>string myVar = "";
if(...)
{
  //use of myVar
}
if(...)
{
 //use of myVar
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the code:

for (int i = 0; i < Model.Count; i++)
{
    Writer.WriteBeginTag("li");
    if (i % 2 == 1)
    {
            string myVar  = "even ";
    }
    if ((i+1) % 3 == 0)
    {
        myVar += "third";
    }
    Writer.WriteAttribute("class", ""); // I want to use myVar here
    Writer.Write(HtmlTextWriter.TagRightChar);
    Writer.WriteEndTag("li");
}

I'm not all that familiar with .NET or C#. I get an error The name "myVar" does not exist in the current context on the second myVar. If I comment this line out, I then have a message The variable "myVar" is assigned but its value is never used. on the first myVar. I don't really understand how or why this would be out of context/scope.

Any ideas?

Body:
You are creating the variable myVar in the scope of the first if statement, thus it isn't available in second one. You need to create it beforehand:

string myVar = "";
if(...)
{
  //use of myVar
}
if(...)
{
 //use of myVar
}


问:
router.post can't pass data
```<code>$.post($gameNetwork._serverURL+'/addfriend',
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
 });

Account.statics.

    friend = function(name,tname,cb) {

        return this.findOneAndUpdate(

        { 'username':  name },

        { $push: {'friendlist': tname}},

        { upsert: true, new: true},

        cb);

    };
</code>```

route

```<code>router.post('/addfriend',  function(req, res) {

//Account.findByName(req.body.username, function(err, account){
    Account.friend(req.body.username,req.body.tusername, function(err, account){
 if (err) {
      return res.status(203).json({
        err: err.msg
      });}
    if (!account) {
      return res.status(203).json({
        err: "Invalid username"
      });}
        var tname = req.body.tusername;

    var profile = {
        tname : tname,
      name: account.username,
      email: account.email,
      id: account._id,
      rank: account.rank
    };  });
</code>```

this code should enter "w" in to the field 'friendlist' in Mongodb,  but I got null instead of w.

how can I get "w" into the field 'friendlist' in Mongodb.
Any help is appreciated
Thanks in advance

答:
You can debug your data of request like this:

```<code>router.post('/addfriend',  function(req, res) {
    console.log(req.body);
    // your logic
}
</code>```

Run your code again, and you can see your data that you expect. If you see tusername = null or undefined, may be the problem in configure of your module that you use, example body-parser, busboy...vv

All comments are welcome!

Title: router.post can't pass data

Body:
$.post($gameNetwork._serverURL+'/addfriend',
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
 });

Account.statics.

    friend = function(name,tname,cb) {

        return this.findOneAndUpdate(

        { 'username':  name },

        { $push: {'friendlist': tname}},

        { upsert: true, new: true},

        cb);

    };

route

router.post('/addfriend',  function(req, res) {

//Account.findByName(req.body.username, function(err, account){
    Account.friend(req.body.username,req.body.tusername, function(err, account){
 if (err) {
      return res.status(203).json({
        err: err.msg
      });}
    if (!account) {
      return res.status(203).json({
        err: "Invalid username"
      });}
        var tname = req.body.tusername;

    var profile = {
        tname : tname,
      name: account.username,
      email: account.email,
      id: account._id,
      rank: account.rank
    };  });

this code should enter "w" in to the field 'friendlist' in Mongodb,  but I got null instead of w.

how can I get "w" into the field 'friendlist' in Mongodb.
Any help is appreciated
Thanks in advance

Body:
You can debug your data of request like this:

router.post('/addfriend',  function(req, res) {
    console.log(req.body);
    // your logic
}

Run your code again, and you can see your data that you expect. If you see tusername = null or undefined, may be the problem in configure of your module that you use, example body-parser, busboy...vv

All comments are welcome!


问:
Convert attributed text to HTML
In my case I have to convert NSHTMLTextDocumentType document to NSMutableAttributedString for which I use below snippet

```<code>[[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding]
                                                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                             NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                        documentAttributes:nil error:nil];
</code>```

When I log my text I get below for attached screenshot

```<code><font color="#ff66b2">dasdasd asd asd asd sa asda </font>
<font color="#00feff">asdasdas  asd </font>
<font color="#0000ff">sa asd asdasdsad</font>
</code>```

Since it's a UITextView I need to give edit support also in iPhone. So how can I convert NSMutableAttributedString into the formate of string logged?

Any help would be greatly appreciated..

答:
Partially agreed answer </p>

```<code>var htmlEncoding: String? {
do {

    let attrubutedString = NSAttributedString(string: self)

    let htmlData = try attrubutedString.data(from:NSMakeRange(0, attrubutedString.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);

    return String.init(data: htmlData, encoding: String.Encoding.utf8)

} catch {

    return nil

}

}
</code>```

Title: Convert attributed text to HTML

Body:
In my case I have to convert NSHTMLTextDocumentType document to NSMutableAttributedString for which I use below snippet

[[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding]
                                                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                             NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                        documentAttributes:nil error:nil];

When I log my text I get below for attached screenshot

dasdasd asd asd asd sa asda
asdasdas  asd
sa asd asdasdsad

Since it's a UITextView I need to give edit support also in iPhone. So how can I convert NSMutableAttributedString into the formate of string logged?

Any help would be greatly appreciated..

Body:
Partially agreed answer

var htmlEncoding: String? {
do {

    let attrubutedString = NSAttributedString(string: self)

    let htmlData = try attrubutedString.data(from:NSMakeRange(0, attrubutedString.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);

    return String.init(data: htmlData, encoding: String.Encoding.utf8)

} catch {

    return nil

}

}


问:
Vuejs and Bootstrap 4 on PlayStation 4 Internet browser
Is there any solution for Vuejs and Bootstrap 4 compatibility with Internet browser on PlayStation 4? When I open my website it just shows our background color and that's it.

So I would like to hear your suggestions. Is there any solution for this? My last solution will be to detect old browsers and show a message that we don't support older browsers.

We use vue 2.5.16 and Bootstrap 4

答:
I would consider using a server side rendering solution to maximise compatibility.
You can find more information about recommended solution for SSR with vue such as Nuxt.js here https://v2.vuejs.org/v2/guide/ssr.html

Depending on the complexity of your site, using SSR to pre-render static sites could be an ideal solution.

I would also recommend adding the snippet you mentioned to inform the user incase there browser is not supported, or better yet forward them to a simpler version that is.


问:
unable to play rtsp throuth vlc plugin on IE11
I created a sample web site through which i will be able to stream videos across my LAN.

I am using VLC (the latest version) .

But i am encountering issue in win10 IE11 ,as vlc plugin is not loading in this . I am using IE11 and my machine is Windows10 64 bit.

and my vlc activex plugin is enabled:
enter image description here

Is there any solution

the following is my code:

```<code><embed
    type="application/x-vlc-plugin"
    pluginspage="http://www.videolan.org"
    wmode="opaque"
    id="vlc"
    width="640"
    height="480"
    target="my_rtsp_url"
/>
</code>```

答:
I have solved this problem.
I installed the wrong version of vlc plugin, my browser is win32, but I used the win64 vlc.</p>

Body:
I created a sample web site through which i will be able to stream videos across my LAN.

I am using VLC (the latest version) .

But i am encountering issue in win10 IE11 ,as vlc plugin is not loading in this . I am using IE11 and my machine is Windows10 64 bit.

and my vlc activex plugin is enabled:
enter image description here

Is there any solution

the following is my code:

<embed
    type="application/x-vlc-plugin"
    pluginspage="http://www.videolan.org"
    wmode="opaque"
    id="vlc"
    width="640"
    height="480"
    target="my_rtsp_url"
/>


问:
Why the NMI function address stored in the NMI Vector address ends with the bit 1 in the ARM cortex?
I have got a STM32-F49ZI nucleo board which is ARM Cortex 4 - 32 bits MCU. I have my own NMI handler i.e. NMI_Handler function, whose address ends with a bit 0. I can see that in the debugger. However, the vector address of NMI Handler stores the same address of NMI_Handler function except that the bit ends with 1. My question why there is a discrepancy. I got to know that this is because ARM cortex M supports only Thumb instructions i.e. 16-bit instructions only. I am unable to understand this reasoning. What's the reason behind it? Why it sets the last bit to 1.

```<code>void NMI_Handler()
{

}
</code>```

Watchdog window shows

```<code>NMI_Handler address - 0x8010 1000
</code>```

However, the address stored in the NMI Vector address is -

```<code>0x8010 1001.
</code>```

答:
ARM architecture of the address is odd then the instruction set is THUMB if even then it is the ARM instruction set.

So it has to be odd

Body:
I have got a STM32-F49ZI nucleo board which is ARM Cortex 4 - 32 bits MCU. I have my own NMI handler i.e. NMI_Handler function, whose address ends with a bit 0. I can see that in the debugger. However, the vector address of NMI Handler stores the same address of NMI_Handler function except that the bit ends with 1. My question why there is a discrepancy. I got to know that this is because ARM cortex M supports only Thumb instructions i.e. 16-bit instructions only. I am unable to understand this reasoning. What's the reason behind it? Why it sets the last bit to 1.

void NMI_Handler()
{

}

Watchdog window shows

NMI_Handler address - 0x8010 1000

However, the address stored in the NMI Vector address is -

0x8010 1001.


问:
How to hide/show a view in the Activity by clicking a button in the Android Cardview?
I am working on a commercial app as an internship. In one of its activity, I have tab view with two fragments. In each fragment, I'm using the card view to hold the views.
The card view has one image view, two text views, and a button and in the bottom of the activity below the tab view, there is a button which has its visibility mode as "GONE".

Now What I want is, Whenever I click on the button in the card view, the button at the bottom of the activity should hide/show for respective clicks.

Cardcaptionadapter.java

```<code>   public CaptionedImagesAdapterMenu.ViewHolder onCreateViewHolder(
            ViewGroup parent, int viewType){
        CardView cv = (CardView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_captioned_image_menu, parent, false);
        return new ViewHolder(cv);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position){
        CardView cardView = holder.cardView;
        ImageView imageView = (ImageView)cardView.findViewById(R.id.info_image);
        Drawable drawable = ContextCompat.getDrawable(cardView.getContext(), imageIds[position]);
        imageView.setImageDrawable(drawable);
        imageView.setContentDescription(captions[position]);
        TextView textView = (TextView)cardView.findViewById(R.id.info_text);
        textView.setText(captions[position]);
        TextView textView1 = cardView.findViewById(R.id.info_menu);
        textView1.setText(desc[position]);
        TextView textView2 = cardView.findViewById(R.id.info_price);
        textView2.setText("₹ " + price[position]);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(position);
                }
            }
        });
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(holder.button.getText().equals("ADD")){
                    holder.button.setText("ADDED");
                    holder.button.setBackgroundColor(Color.parseColor("#00ff00"));
                    SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt("ADDED", 1);
                    editor.apply();
                }
                else {
                    holder.button.setText("ADD");
                    holder.button.setBackgroundColor(Color.parseColor("#ffffff"));
                    SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.clear();
                    editor.apply();
                }
            }
        });
    }
</code>```

MenuActivity.java

```<code> SharedPreferences preferences = getSharedPreferences("ADD",0);
         int addvalue = preferences.getInt("ADDED",0);

         if(addvalue==1){
             orderbutton.setVisibility(View.VISIBLE);
         }
         else{
             orderbutton.setVisibility(View.GONE);
         }
         orderbutton.setOnClickListener(view -> {
             orderbutton.setVisibility(View.GONE);
             paybutton.setVisibility(View.VISIBLE);
         });
</code>```

答: you should add MenuActivity.java code inside public void onBindViewHolder(ViewHolder holder, final int position){ } method also.</p>

Body:
I am working on a commercial app as an internship. In one of its activity, I have tab view with two fragments. In each fragment, I'm using the card view to hold the views.
The card view has one image view, two text views, and a button and in the bottom of the activity below the tab view, there is a button which has its visibility mode as "GONE".

Now What I want is, Whenever I click on the button in the card view, the button at the bottom of the activity should hide/show for respective clicks.

Cardcaptionadapter.java

   public CaptionedImagesAdapterMenu.ViewHolder onCreateViewHolder(
            ViewGroup parent, int viewType){
        CardView cv = (CardView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_captioned_image_menu, parent, false);
        return new ViewHolder(cv);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position){
        CardView cardView = holder.cardView;
        ImageView imageView = (ImageView)cardView.findViewById(R.id.info_image);
        Drawable drawable = ContextCompat.getDrawable(cardView.getContext(), imageIds[position]);
        imageView.setImageDrawable(drawable);
        imageView.setContentDescription(captions[position]);
        TextView textView = (TextView)cardView.findViewById(R.id.info_text);
        textView.setText(captions[position]);
        TextView textView1 = cardView.findViewById(R.id.info_menu);
        textView1.setText(desc[position]);
        TextView textView2 = cardView.findViewById(R.id.info_price);
        textView2.setText("₹ " + price[position]);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(position);
                }
            }
        });
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(holder.button.getText().equals("ADD")){
                    holder.button.setText("ADDED");
                    holder.button.setBackgroundColor(Color.parseColor("#00ff00"));
                    SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt("ADDED", 1);
                    editor.apply();
                }
                else {
                    holder.button.setText("ADD");
                    holder.button.setBackgroundColor(Color.parseColor("#ffffff"));
                    SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.clear();
                    editor.apply();
                }
            }
        });
    }

MenuActivity.java

 SharedPreferences preferences = getSharedPreferences("ADD",0);
         int addvalue = preferences.getInt("ADDED",0);

         if(addvalue==1){
             orderbutton.setVisibility(View.VISIBLE);
         }
         else{
             orderbutton.setVisibility(View.GONE);
         }
         orderbutton.setOnClickListener(view -> {
             orderbutton.setVisibility(View.GONE);
             paybutton.setVisibility(View.VISIBLE);
         });


问:
Plotting with years in python
I have data in my excel file as shown below which I have imported into python and trying to plot the same,

```<code>Year    Andhra Pradesh
1973-74 50.67
1977-78 69.66
1983    115.4
1993-94 288.7
1999-00 453.61
2004-05 603.82
2009-10 1233.76
2011-12 1753.96
</code>```

However, I am getting a blank plot whenever I run the command.

```<code>import pandas as pd
import matplotlib.pyplot as plt
data1= pd.read_excel('C:\\Users\\3004\\Desktop\\Variables.xlsx',2)
plt.plot(data1)
</code>```

I want the years on x axis and the values shown on a histogram or any other plot. However, I receive a blank plot.

答: You can use the DataFrame's own plotting methods: data1.plot()

Title: Plotting with years in python

Body:
I have data in my excel file as shown below which I have imported into python and trying to plot the same,

Year    Andhra Pradesh
1973-74 50.67
1977-78 69.66
1983    115.4
1993-94 288.7
1999-00 453.61
2004-05 603.82
2009-10 1233.76
2011-12 1753.96

However, I am getting a blank plot whenever I run the command.

import pandas as pd
import matplotlib.pyplot as plt
data1= pd.read_excel('C:\\Users\\3004\\Desktop\\Variables.xlsx',2)
plt.plot(data1)

I want the years on x axis and the values shown on a histogram or any other plot. However, I receive a blank plot.


问:
Handling audio file intent in react native
Can somebody help me in receiving audio file intent in react-native,
I want when android user share a call recording file(.amr) with my react-native app i can access that file and store to a remote server (for monitoring quality),

till now am able to make my app available to share audio file with adding below code in AndroidManifest.xml

```<code>    <intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="audio/*" />
</intent-filter>
</code>```

I have searched on Internet for my problem there are some blogs that handling Text/url intent with below code in MainActivity.java

```<code> @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected Bundle getLaunchOptions() {
                Intent intent = MainActivity.this.getIntent();
                Bundle bundle = new Bundle();
                bundle.putString("url", intent.getStringExtra(Intent.EXTRA_TEXT));

                return bundle;
            }
        };
    }
</code>```

its working file with text intent and i am able to get the shared url in my initialProps

```<code>e.g {"url":"https://xxxxxx.com/abc"}
</code>```

but when i am using same above code with audio/.amr file intent i am getting null  e.g {"url":null},

I believe if I got the file name or its full path in my initial props then i can get that file after using react-native-fs

i am new in java and native part of android,
it would be great help if someone can guide me the right way of doing above task.

Thank You

答:
You should use EXTRA_STREAM  for audio. I have been searching for same thing, including to receive other documents too(pdf, doc, audio etc). I didn't find any wrapper that do same for all formats I require to receive. You can create your own through this for audio or whatever type you want https://www.bennettnotes.com/react-native-android-receive-data-from-share-intent/ Hope this helps.</p>

```<code>@Override
    protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
        @Nullable
        @Override
        protected Bundle getLaunchOptions() {
            Intent intent = MainActivity.this.getIntent();
            String type=intent.getType();
            Bundle bundle = new Bundle();
            bundle=null;
            Toast.makeText(getApplicationContext(),
                    type.toString(),
                    Toast.LENGTH_SHORT).show();

           if(type.startsWith("text/"))
               bundle.putString("url", intent.getStringExtra(Intent.EXTRA_TEXT));
           else {
                Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if(uri!=null)
               { bundle.putString("url", uri.getPath());}
           }
            return bundle;
        }
    };
}
</code>```

Body:
Can somebody help me in receiving audio file intent in react-native,
I want when android user share a call recording file(.amr) with my react-native app i can access that file and store to a remote server (for monitoring quality),

till now am able to make my app available to share audio file with adding below code in AndroidManifest.xml

    <intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="audio/*" />
</intent-filter>

I have searched on Internet for my problem there are some blogs that handling Text/url intent with below code in MainActivity.java

 @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected Bundle getLaunchOptions() {
                Intent intent = MainActivity.this.getIntent();
                Bundle bundle = new Bundle();
                bundle.putString("url", intent.getStringExtra(Intent.EXTRA_TEXT));

                return bundle;
            }
        };
    }

its working file with text intent and i am able to get the shared url in my initialProps

e.g {"url":"https://xxxxxx.com/abc"}

but when i am using same above code with audio/.amr file intent i am getting null  e.g {"url":null},

I believe if I got the file name or its full path in my initial props then i can get that file after using react-native-fs

i am new in java and native part of android,
it would be great help if someone can guide me the right way of doing above task.

Thank You

Body:
You should use EXTRA_STREAM  for audio. I have been searching for same thing, including to receive other documents too(pdf, doc, audio etc). I didn't find any wrapper that do same for all formats I require to receive. You can create your own through this for audio or whatever type you want https://www.bennettnotes.com/react-native-android-receive-data-from-share-intent/ Hope this helps.

@Override
    protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
        @Nullable
        @Override
        protected Bundle getLaunchOptions() {
            Intent intent = MainActivity.this.getIntent();
            String type=intent.getType();
            Bundle bundle = new Bundle();
            bundle=null;
            Toast.makeText(getApplicationContext(),
                    type.toString(),
                    Toast.LENGTH_SHORT).show();

           if(type.startsWith("text/"))
               bundle.putString("url", intent.getStringExtra(Intent.EXTRA_TEXT));
           else {
                Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if(uri!=null)
               { bundle.putString("url", uri.getPath());}
           }
            return bundle;
        }
    };
}


问:
QML Slider adjusting rectangle
I have a few questions here, as I'm new to qml. I have a simple interface where I want the slider to adjust the size of the Rectangle (which will eventually be an svg icon). Questions below the image:

When adjusting the slider, it properly changes the blue rectangle size, however how can i make it properly auto-resize the green bounding rectangle to encompass it? It should look something like the image below. Currently the thumbnail exceeds the bounds of the green rect. If it helps the combobox can have a static width of 150.

How can i make the blue rectangle always be vertically center aligned? It appears to always be anchored to the top left.

QML

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        width: parent.width

                        Rectangle {
                            id: icon
                            width: thumbnailsize.value
                            height: thumbnailsize.value
                            color: "steelblue"
                            Layout.alignment: Qt.AlignCenter
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}
</code>```

答:
The first thing is you cannot use the properties "width" and "height" inside a layout, so you need to use "Layout.preferredWidth" and "Layout.preferredHeight".

So you need to make the following changes inside your code:-

```<code>// ...
// ...

    Rectangle {
                id: icon

                Layout.preferredWidth: thumbnailsize.value
                Layout.preferredHeight: thumbnailsize.value
                // #### You can use width and height inside Layouts
    //          width: thumbnailsize.value
    //          height: thumbnailsize.value
                color: "steelblue"
                Layout.alignment: Qt.AlignCenter
              }

// ...
// ..
</code>```

I guess you are even facing the problem when you move the slider to the maximum value, the blue rectangle moves out of its parent which is the lightgreen rectangle.(Below Image)

Slider Max Value Error

So if you make the changes as told above this issue will also be resolved.

Once you make the changes, here is the sample output:-

Minimum Value:-

Minimum Value

Maximum Value:-

Maximum Value

Title: QML Slider adjusting rectangle

Body:
I have a few questions here, as I'm new to qml. I have a simple interface where I want the slider to adjust the size of the Rectangle (which will eventually be an svg icon). Questions below the image:

When adjusting the slider, it properly changes the blue rectangle size, however how can i make it properly auto-resize the green bounding rectangle to encompass it? It should look something like the image below. Currently the thumbnail exceeds the bounds of the green rect. If it helps the combobox can have a static width of 150.

How can i make the blue rectangle always be vertically center aligned? It appears to always be anchored to the top left.

QML

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ColumnLayout {
    anchors.fill: parent

    Flow {
        Layout.fillWidth: true
        spacing: 10

        Repeater {
            model: 5

            Rectangle {
                id: delegateBackground
                width: 200;
                height: contentContainer.height + 10
                border.width: 1
                color: "lightgreen"

                Item {
                    id: contentContainer
                    width: parent.width - 10
                    height: rowContainer.height
                    anchors.centerIn: delegateBackground

                    RowLayout {
                        id: rowContainer
                        width: parent.width

                        Rectangle {
                            id: icon
                            width: thumbnailsize.value
                            height: thumbnailsize.value
                            color: "steelblue"
                            Layout.alignment: Qt.AlignCenter
                        }

                        ComboBox {
                            id: selector
                            Layout.fillWidth: true
                            model: [ "Banana", "Apple", "Coconut" ]
                            Layout.alignment: Qt.AlignCenter
                        }
                    }
                }
            }
        }
    }

    Slider {
        id: thumbnailsize
        from: 16
        value: 48
        to: 64
    }
}

Body:
The first thing is you cannot use the properties "width" and "height" inside a layout, so you need to use "Layout.preferredWidth" and "Layout.preferredHeight".

So you need to make the following changes inside your code:-

// ...
// ...

    Rectangle {
                id: icon

                Layout.preferredWidth: thumbnailsize.value
                Layout.preferredHeight: thumbnailsize.value
                // #### You can use width and height inside Layouts
    //          width: thumbnailsize.value
    //          height: thumbnailsize.value
                color: "steelblue"
                Layout.alignment: Qt.AlignCenter
              }

// ...
// ..

I guess you are even facing the problem when you move the slider to the maximum value, the blue rectangle moves out of its parent which is the lightgreen rectangle.(Below Image)

Slider Max Value Error

So if you make the changes as told above this issue will also be resolved.

Once you make the changes, here is the sample output:-

Minimum Value:-

Minimum Value

Maximum Value:-

Maximum Value


问:
Android XML based UI in Java
I would just like to have an Android XML UI file in Java. I have the XML file and I believe I need a parser that would actually generate the Java UI class file. Any ideas how to go about approaching this ?

EDIT: Well, let me explain this a little better. I am trying to track Google finance data for which I use gdata client library. However its authentication does not work in the Android environment, and so I am switching to Java SE. However, is there any library or something by which I can have the Android UI, without having to write my own parser. Need not necessarily be XML based.

答: You need to write your own parser and instantiate the Swing classes that are synonymous with the controls described in the XML.</p>

Title: Android XML based UI in Java


问:
Laravel vue js mixins not getting function response
I am using laravel 5.8 with vue js. I have created a generalized function for post/get requests. The problem is, i am not getting the mixins function response. Here is my code :

TestComponent.vue

```<code>import GeneralMixin from '../mixins.js';
export default {
    mixins: [ GeneralMixin ],
    methods:{
        login: function (e) {
            let response;
            response = this.testMixin();
            console.log(response);
        }
    }
}
</code>```

mixin.js

```<code>export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {
                return response;
            });
        }
    }
}
</code>```

The console result is undefined

I am not getting response of function testMixin() . Can anyone help please

答:
You need to return the promise, Something like below

In you mixin

```<code>return axios.post(url);
</code>```

And now in component use it like below.

```<code>this.testMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })
</code>```

Body:
I am using laravel 5.8 with vue js. I have created a generalized function for post/get requests. The problem is, i am not getting the mixins function response. Here is my code :

TestComponent.vue

import GeneralMixin from '../mixins.js';
export default {
    mixins: [ GeneralMixin ],
    methods:{
        login: function (e) {
            let response;
            response = this.testMixin();
            console.log(response);
        }
    }
}

mixin.js

export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {
                return response;
            });
        }
    }
}

The console result is undefined

I am not getting response of function testMixin() . Can anyone help please

Body:
You need to return the promise, Something like below

In you mixin

return axios.post(url);

And now in component use it like below.

this.testMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })


问:
Save option form and pass JS variable
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

```<code><form action="saveConfig.php" class="hide-submit" method="post">

<div class="btn-configure step2button">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>
<br>
Total: <input id="total" type="text">
</code>```

JS:

```<code>let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}
</code>```

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.

答:
you will have to create an input element then append that element to the form and then submit the form.</p>

```<code>var inputElement=document.createElement("input");
inputElement.setAttribute("value",total_cost);

var form= document.getElementById("formId");
form.appendChild(inputElement);
</code>```

Title: Save option form and pass JS variable

Body:
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

<form action="saveConfig.php" class="hide-submit" method="post">

Save

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    Item 1 [£1.00]

    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    Item 2 [£12.34]

    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    Item 3 [£9.99]

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>

Total: <input id="total" type="text">

JS:

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.

Body:
you will have to create an input element then append that element to the form and then submit the form.

var inputElement=document.createElement("input");
inputElement.setAttribute("value",total_cost);

var form= document.getElementById("formId");
form.appendChild(inputElement);


问:
mice returns Error in nnet.default: too many weights
I used mice package which have an error：

Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  : too many (1734) weights;

I try to set

```<code>imp<-mice(w,MaxNWts = 2000,seed=1234)
</code>```

but show another error：

Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  :
        formal argument "MaxNWts" matched by multiple actual arguments

what should I do?

答:
I have solved the problem;

imp<-mice(w,seed=1234,nnet.MaxNWts = 2000)

Body:
I used mice package which have an error：

Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  : too many (1734) weights;

I try to set

imp<-mice(w,MaxNWts = 2000,seed=1234)

but show another error：

Error in nnet.default(X, Y, w, mask = mask, size = 0, skip = TRUE, softmax = TRUE,  :
        formal argument "MaxNWts" matched by multiple actual arguments

what should I do?


问:
How to set visibility for include layout in databinding?
I have implemented data binding in my project. I have a particular screen with two nested layouts in include tags. I couldn't change the visibility for include layouts using data binding programmatically.

However, I have achieved it through a boolean, but my question is how to set visibility for that include tag programmatically.

My xml:

<include
  android:id="@+id/reg_email"
  layout="@layout/custom_email"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

<include
  android:id="@+id/reg_phone"
  layout="@layout/custom_phone"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>
```

<p>And in Activity:
when I try to set this - it becomes red meaning it doesn't take it as a view.</p>

<pre class="lang-java prettyprint-override"><code>  dataBinding.regPhone.setVisibility(View.GONE);
  dataBinding.regEmail.setVisibility(View.VISIBLE);
</code>```

答:
add get root to your view

dataBinding.regPhone.getRoot().setVisibility(View.GONE);
dataBinding.regEmail.getRoot().setVisibility(View.VISIBLE);
```

Body:
I have implemented data binding in my project. I have a particular screen with two nested layouts in include tags. I couldn't change the visibility for include layouts using data binding programmatically.

However, I have achieved it through a boolean, but my question is how to set visibility for that include tag programmatically.

My xml:

<include
  android:id="@+id/reg_email"
  layout="@layout/custom_email"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

<include
  android:id="@+id/reg_phone"
  layout="@layout/custom_phone"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

And in Activity:
when I try to set this - it becomes red meaning it doesn't take it as a view.

  dataBinding.regPhone.setVisibility(View.GONE);
  dataBinding.regEmail.setVisibility(View.VISIBLE);


问:
Some network related issues with AJAX
I have an ajax heavy web-application built using PHP, jQuery.

I am looking for solution to below issues.

(1). User is running the application in browser. Internet goes off. The browser makes an ajax request to the server and the request obviously fails due to absence of network. I want a cross-browser way (including Windows/MAC/Linux) to detect this failure and show a notification to the user.

(2). Network is On. The browser makes an ajax request to server and before it receives the response the network goes off. So when the server sends the response the client is offline. Here also I want to show a notification to the user regarding the error. Gmail does this beautifully. I composed a mail, clicked send and the very same moment unplugged the network cable. After about 8-10 seconds it shows a message "Oops... a server error occurred and your email was not sent."

The problem (2) above becomes more complicated on MAC. I checked this case on both MAC and Windows (I checked on windows XP). On windows XP if the network is not there, the request dies after few seconds but on MAC the request does not die for more than 1 hour. Here I can't think of a way to detect that network is gone while receiving response and show this notification to user?

答:
```<code>$(window).ajaxError(function () {
    alert('Oops.  Server error occurred.');
});
</code>```

or

```<code>error: function() { }
</code>```

As a side note, all that's possible to know is if something failed or not.  The browser doesn't know if the machine that's running it has internet access or if the cable gets pulled....  All it knows, and all you need to do, is handle the error cases through either this handler above or jquery's error function param in your AJAX call.

Also, for #2, the gmail error that's being shown is simply that your request wasn't sent successfully.  It has nothing to do with server-side processes.

EDIT: For additional information (such as setting a timeout value that's shorter):

http://api.jquery.com/jQuery.ajaxSetup

Note that the accepted values for ajaxSetup are those listed here:

http://api.jquery.com/jQuery.ajax

Title: Some network related issues with AJAX

Body:
$(window).ajaxError(function () {
    alert('Oops.  Server error occurred.');
});

or

error: function() { }

As a side note, all that's possible to know is if something failed or not.  The browser doesn't know if the machine that's running it has internet access or if the cable gets pulled....  All it knows, and all you need to do, is handle the error cases through either this handler above or jquery's error function param in your AJAX call.

Also, for #2, the gmail error that's being shown is simply that your request wasn't sent successfully.  It has nothing to do with server-side processes.

EDIT: For additional information (such as setting a timeout value that's shorter):

http://api.jquery.com/jQuery.ajaxSetup

Note that the accepted values for ajaxSetup are those listed here:

http://api.jquery.com/jQuery.ajax


问:
Can the "initialData" property be used to write App Script parameters to a Stackdriver message?

Summary

Google suggests that App Script parameters (among other data) can be written to Stackdriver using a JSON object with a "initialData" property.
But it doesn't seem to work.

Issue Example

This Google page contains an example function that illustrates the different ways information can be written to Stackdriver.

An extract from their own code is below:

```<code>var parameters = {
  isValid: true,
  content: 'some string',
  timestamp: new Date()
};
console.log({message: 'Function Input', initialData: parameters});
</code>```

When their App Script function is run it should write these parameter values into the Stackdriver log message.

But after it's run and Stackdriver is examined the message (example below) doesn't contain the parameter anywhere in it:

```<code>{
 insertId:  "s14ubwdkw81"
 jsonPayload: {
  message:  "Function Input"
  serviceContext: {
   service:  "AKfycbwcG7JGj9z-yomue0m_bOVdIVyFgDasdsasdsadngdCkk_l"
  }
 }
 labels: {
  script.googleapis.com/deployment_id:  "AKfycbwcG7JGj9z-yomue0m_bOVdsadsad7x7pHYngdCkk_l"
  script.googleapis.com/process_id:  "EAEA1GOzkIp_aAfasdsadsadsazTnDWNA_ureP83_A8Agfr4IQ9pzSfRzfj1wnw8U_lCUUA4O9afoxyZuCCHYlB5ryBpu0LxfcibIITaoFqdbiVjprxDC5sVIXUAdpnQX3ud0-Xp8t9awJPH484YyeQRsassadZzksNSXYxl4VwcOw"
  script.googleapis.com/project_key:  "MtcDasfdsfsfsfsfsaduYD4VaIEGs0Nwta"
  script.googleapis.com/user_key:  "ANbVsadsadasdadashbqPEennz6PO1tasdsadasdfsddg+PjGhPshrkLV1SGwofeIcgpw0"
 }
 logName:  "projects/project-id-416855555555555555559030426/logs/script.googleapis.com%2Fconsole_logs"
 receiveTimestamp:  "2019-05-22T15:14:53.355673423Z"
 resource: {
  labels: {
   function_name:  "measuringExecutionTime"
   invocation_type:  "editor"
   project_id:  "project-id-416855555555555530426"
  }
  type:  "app_script_function"
 }
 severity:  "DEBUG"
 timestamp:  "2019-05-22T15:14:52.844Z"
}
</code>```

I think this is a Stackdriver or App Script bug, but I wanted to make sure I hadn't made a mistake or missed something.  Any ideas?

Update

Further investigation suggests it probably is a bug, because the same code in a Cloud Function does work as expected, Stackdriver extract below:

```<code>{
 insertId:  "000000-7e143986-76f1-5555-b167-8186214f7739"
 labels: {
  execution_id:  "o8r9555cli0j"
 }
 logName:  "projects/my-project/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp:  "2019-05-16T10:34:26.503211511Z"
 resource: {
  labels: {
   function_name:  "gcf_htp_function_name"
   project_id:  "my-project"
   region:  "us-central1"
  }
  type:  "cloud_function"
 }
 severity:  "INFO"
 textPayload:  "{ message: 'Function Input',
  initialData:
   { isValid: true,
     content: 'some string'}"
 timestamp:  "2019-05-23T10:34:21.084Z"
 trace:  "projects/my-project/traces/a4df23072bfef15269947eaecf3a8f44"
}
</code>```

答:
It was a bug.

Google fixed it.

https://issuetracker.google.com/issues/133278375

Body:
Summary

Google suggests that App Script parameters (among other data) can be written to Stackdriver using a JSON object with a "initialData" property.
But it doesn't seem to work.

Issue Example

This Google page contains an example function that illustrates the different ways information can be written to Stackdriver.

An extract from their own code is below:

var parameters = {
  isValid: true,
  content: 'some string',
  timestamp: new Date()
};
console.log({message: 'Function Input', initialData: parameters});

When their App Script function is run it should write these parameter values into the Stackdriver log message.

But after it's run and Stackdriver is examined the message (example below) doesn't contain the parameter anywhere in it:

{
 insertId:  "s14ubwdkw81"
 jsonPayload: {
  message:  "Function Input"
  serviceContext: {
   service:  "AKfycbwcG7JGj9z-yomue0m_bOVdIVyFgDasdsasdsadngdCkk_l"
  }
 }
 labels: {
  script.googleapis.com/deployment_id:  "AKfycbwcG7JGj9z-yomue0m_bOVdsadsad7x7pHYngdCkk_l"
  script.googleapis.com/process_id:  "EAEA1GOzkIp_aAfasdsadsadsazTnDWNA_ureP83_A8Agfr4IQ9pzSfRzfj1wnw8U_lCUUA4O9afoxyZuCCHYlB5ryBpu0LxfcibIITaoFqdbiVjprxDC5sVIXUAdpnQX3ud0-Xp8t9awJPH484YyeQRsassadZzksNSXYxl4VwcOw"
  script.googleapis.com/project_key:  "MtcDasfdsfsfsfsfsaduYD4VaIEGs0Nwta"
  script.googleapis.com/user_key:  "ANbVsadsadasdadashbqPEennz6PO1tasdsadasdfsddg+PjGhPshrkLV1SGwofeIcgpw0"
 }
 logName:  "projects/project-id-416855555555555555559030426/logs/script.googleapis.com%2Fconsole_logs"
 receiveTimestamp:  "2019-05-22T15:14:53.355673423Z"
 resource: {
  labels: {
   function_name:  "measuringExecutionTime"
   invocation_type:  "editor"
   project_id:  "project-id-416855555555555530426"
  }
  type:  "app_script_function"
 }
 severity:  "DEBUG"
 timestamp:  "2019-05-22T15:14:52.844Z"
}

I think this is a Stackdriver or App Script bug, but I wanted to make sure I hadn't made a mistake or missed something.  Any ideas?

Update

Further investigation suggests it probably is a bug, because the same code in a Cloud Function does work as expected, Stackdriver extract below:

{
 insertId:  "000000-7e143986-76f1-5555-b167-8186214f7739"
 labels: {
  execution_id:  "o8r9555cli0j"
 }
 logName:  "projects/my-project/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
 receiveTimestamp:  "2019-05-16T10:34:26.503211511Z"
 resource: {
  labels: {
   function_name:  "gcf_htp_function_name"
   project_id:  "my-project"
   region:  "us-central1"
  }
  type:  "cloud_function"
 }
 severity:  "INFO"
 textPayload:  "{ message: 'Function Input',
  initialData:
   { isValid: true,
     content: 'some string'}"
 timestamp:  "2019-05-23T10:34:21.084Z"
 trace:  "projects/my-project/traces/a4df23072bfef15269947eaecf3a8f44"
}