javascript – reduce the code

enter code here

function fetchData() {
objData = getCtrlData();
return objData;
}
BindPageChecklistDetails: function BindPageChecklistDetails() {
ChecklistData = ();
$(objData.data).each(function (index, item) {
var objCL = WeldingRecord.GetCheckListDetail();
objCL.Remarks = item.Remarks;
if (item.ResultId != null && item.ResultId != “” && item.ResultId != “-1”) {
objCL.ResultId = item.ResultId;
}
if (item.InspectedBy != null && item.InspectedBy != “” && item.InspectedBy != “-1”) {
objCL.InspectedBy = item.InspectedBy;
objCL.InspectionDate = item.InspectionDate;
}
if (item.FileName != null && item.FileName != “” && item.FileName != “-1”) {
objCL.FileName = item.FileName.name;
}
if (item.MMTCount != null && item.MMTCount != “” && item.MMTCount != “”) {
objCL.MMTCount = item.MMTCount;
}
if (item.MMTHours != null && item.MMTHours != “” && item.MMTHours != “”) {
objCL.MMTHours = item.MMTHours;
}
if (item.MMTMinutes != null && item.MMTMinutes != “” && item.MMTMinutes != “”) {
objCL.MMTMinutes = parseInt(item.MMTMinutes);
}
$(GlobalChecklistDataJSON).each(function (indexs, items) {
$(items.CheckListModel).each(function (index1, item1) {
$(item1.template).each(function (index2, item2) {
$(item2.definition).each(function (index3, item3) {
if (item3.defaultValue == item.CheckListAssociationId) {
objCL.CheckListClassificationId = items.CheckListClassificationId;
return false;
}
});
});
});
});
objCL.CheckListAssociationId = item.CheckListAssociationId;
objCL.Reading = item.Reading;
ChecklistData.push(objCL);
});

if (Temp_intActivityHeaderId != null && Temp_intActivityHeaderId != "0") {
    if (ChecklistData != null && ChecklistData.length > 0) {
        $.each(ChecklistData, function (index, itemdata) {
            $.each(ChecklistUpdateModedata, function (ind, item) {
                if (ChecklistUpdateModedata(ind).RecordStatus == "1" && item.CheckListAssociationId != null && item.CheckListAssociationId == itemdata.CheckListAssociationId) {
                    if (itemdata.Reading != null && itemdata.Reading != "") {
                        WeldingJsonObj.WACheckListDetails(ind).Reading = itemdata.Reading;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).Reading = null;
                    }
                    if (itemdata.Remarks != null && itemdata.Remarks != null) {
                        WeldingJsonObj.WACheckListDetails(ind).Remarks = itemdata.Remarks;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).Remarks = null;
                    }
                    if (itemdata.ResultId != null && itemdata.ResultId != "0") {
                        WeldingJsonObj.WACheckListDetails(ind).ResultId = itemdata.ResultId;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).ResultId = null;
                    }
                    if (itemdata.InspectedBy != null && itemdata.InspectedBy != "0") {
                        WeldingJsonObj.WACheckListDetails(ind).InspectedBy = itemdata.InspectedBy;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).InspectedBy = null;
                    }
                    if (itemdata.InspectionDate != null && itemdata.InspectionDate != "0") {
                        WeldingJsonObj.WACheckListDetails(ind).InspectionDate = itemdata.InspectionDate;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).InspectionDate = null;
                    }
                    if (itemdata.FileName != null && itemdata.FileName != "" && itemdata.FileName != undefined) {
                        WeldingJsonObj.WACheckListDetails(ind).FileName = itemdata.FileName;
                    }
                    if (itemdata.MMTCount != null && itemdata.MMTCount != undefined && itemdata.MMTCount != "" && itemdata.MMTCount(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(ind).MMTCount = itemdata.MMTCount;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).MMTCount = null;
                    }
                    if (itemdata.MMTHours != null && itemdata.MMTHours != undefined && itemdata.MMTHours != "" && itemdata.MMTHours(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(ind).MMTHours = itemdata.MMTHours;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).MMTHours = null;
                    }
                    if (itemdata.MMTMinutes != null && itemdata.MMTMinutes != undefined && itemdata.MMTMinutes != "" && itemdata.MMTMinutes(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(ind).MMTMinutes = itemdata.MMTMinutes;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(ind).MMTMinutes = null;
                    }
                    WeldingJsonObj.WACheckListDetails(ind).CheckListClassificationId = itemdata.CheckListClassificationId;
                    WeldingJsonObj.WACheckListDetails(ind).RecordStatus = "1";
                    WeldingJsonObj.WACheckListDetails(ind).UpdatedDt = getTodayDate();
                    WeldingJsonObj.WACheckListDetails(ind).UpdatedBy = Temp_intUserId;

                }
            });
        });

        var res = ChecklistData.filter(item1 => !ChecklistUpdateModedata.some(item2 => (item2.CheckListAssociationId === item1.CheckListAssociationId)))
        $(res).each(function (key, item) {
            WeldingJsonObj.WACheckListDetails.push(item);
        });

    }
}
else {
    if (ChecklistData != null && ChecklistData.length > 0) {
        $.each(ChecklistData, function (index, itemdata) {
            if (WeldingJsonObj.WACheckListDetails.some(function (el) { return el.CheckListAssociationId === itemdata.CheckListAssociationId })) {
                if (WeldingJsonObj.WACheckListDetails != null && WeldingJsonObj.WACheckListDetails.length > 0) {
                    if (itemdata.Reading != null && itemdata.Reading != "") {
                        WeldingJsonObj.WACheckListDetails(index).Reading = itemdata.Reading;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).Reading = null;
                    }
                    if (itemdata.Remarks != null && itemdata.Remarks != null) {
                        WeldingJsonObj.WACheckListDetails(index).Remarks = itemdata.Remarks;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).Remarks = null;
                    }
                    if (itemdata.ResultId != null && itemdata.ResultId != "0") {
                        WeldingJsonObj.WACheckListDetails(index).ResultId = itemdata.ResultId;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).ResultId = null;
                    }
                    if (itemdata.InspectedBy != null && itemdata.InspectedBy != "0") {
                        WeldingJsonObj.WACheckListDetails(index).InspectedBy = itemdata.InspectedBy;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).InspectedBy = null;
                    }
                    if (itemdata.InspectionDate != null && itemdata.InspectionDate != "0") {
                        WeldingJsonObj.WACheckListDetails(index).InspectionDate = itemdata.InspectionDate;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).InspectionDate = null;
                    }
                    if (itemdata.FileName != null && itemdata.FileName != "" && itemdata.FileName != undefined) {
                        WeldingJsonObj.WACheckListDetails(index).FileName = itemdata.FileName;
                    }
                    if (itemdata.MMTCount != null && itemdata.MMTCount != undefined && itemdata.MMTCount != "" && itemdata.MMTCount(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(index).MMTCount = itemdata.MMTCount;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).MMTCount = null;
                    }
                    if (itemdata.MMTHours != null && itemdata.MMTHours != undefined && itemdata.MMTHours != "" && itemdata.MMTHours(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(index).MMTHours = itemdata.MMTHours;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).MMTHours = null;
                    }
                    if (itemdata.MMTMinutes != null && itemdata.MMTMinutes != undefined && itemdata.MMTMinutes != "" && itemdata.MMTMinutes(0) != " ") {
                        WeldingJsonObj.WACheckListDetails(index).MMTMinutes = itemdata.MMTMinutes;
                    }
                    else {
                        WeldingJsonObj.WACheckListDetails(index).MMTMinutes = null;
                    }
                }
            }
            else {
                WeldingJsonObj.WACheckListDetails.push(itemdata);
            }
        });
    }
}

}
function getchecklistid(id) {
var intchecklistid = “”;
if (ChecklistUpdatedata != null && ChecklistUpdatedata != “”) {
$.each(ChecklistUpdatedata, function (ind, inneritem) {
if (inneritem.CheckListAssociationId === id) {
intchecklistid = inneritem.CheckListDetailId;
}
});
}
if (intchecklistid != null && intchecklistid != “”) {
intchecklistid = intchecklistid;
}
else {
intchecklistid = “0”;
}
return intchecklistid;
}

postgresql – Is it possible to reduce the duplication in this simple query?

I’m new to SQL and so this is probably a stupid question but can I reduce the duplication in this query? My actual query involves more complex expressions. Right now I’m just doing string concatenation from the language I’m using to generate the long query but I think there must be a way to do this with plain SQL?

select
  x + y as a,
  x + z as b,
  (x + y) / (x + z) as c
from
  integers
order by
  z + (x + y) / (x + z) desc
limit
  10;

What I’d like:

select
  x + y as a,
  x + z as b,
  a / b as c
from
  integers
order by
  z + c desc
limit
  10;

-- Fails with: Query Error: error: column "a" does not exist

Sample table:

create table integers as
select x, y, z
from
  generate_series(1, 10) x,
  generate_series(x, 10) y,
  generate_series(y, 10) z;

Fiddle: https://www.db-fiddle.com/f/u3cVh7QsafWNE6ELWhvBc1/0

I’m a beginner in C, the following is a Code snippet that I made, I want to know how can I reduce the amount of line like duplication in my program

I noticed that I have a lot of duplication in my codes, but I really don’t know how to solve duplication that’s why I decided to seek for advice and help from StackOverflow. I also notice that I have been using more than 1 loop in more cases so I wonder can you all check on my following code snippet and tell me how do I reduce the amount of loop usage and remove the duplication.

Code Snippet: https://onlinegdb.com/BJVPOLlmu

My code is a bit long so I decide to put it in an online compiler so that you guys can see it clearly, I’m also a bit sorry for asking this ridiculous question, but I really wanted to know how can I reduce the number of lines and memory usage in my program, I’m pretty bad at this..

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#pragma warning (disable:4996)
#define MAX 20
typedef struct {
    char companyName(41), personInCharge(41), gender, contactNum(13);
    float temperature;
    int infectionLevel;
}Company;

typedef struct {
    int hours, minute;
}Time;

typedef struct {
    int day, month, year;
}Date;

struct SanitizeData {
    char venueID(10);
    Company Details;
    Time Start;
    Time End;
    Date sanitizeDate;
};

// Function Prototype Declaration
int infectionLevelCheck();
void tableHeader();
void tableFooter(int, int);
void sanitizeMenu();
void addRecord();
void searchRecord();
void searchVenueID();
void searchDate();
void searchCompany();
void searchName();
void searchContactNumber();
void searchGender();
void searchTemperature();
void modifyRecord();
void displayRecord();
void deleteRecord();

int infectionLevelCheck() {
    char userResponse;
    int infectionLevel;
    int invalidCounter;

    do {
        invalidCounter = 0;
        infectionLevel = 0;
        printf("nnRisk Of Infection Check: n");
        printf("-----------------------n");
        printf("Are you having the 2 or more of the following symptoms listed?n");
        printf("- Fevern");
        printf("- Sore Throatn");
        printf("- Runny Nosen");
        printf("- Diarrhean");
        printf("- Headachen");
        printf("- Body Achen");
        printf("(Y = Yes, N = No): ");
        scanf("%c", &userResponse);
        rewind(stdin);

        if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
            invalidCounter++;
        }
        else if (toupper(userResponse) == 'Y') {
            infectionLevel++;
        }

        printf("nnBesides the Symptoms listed above, are you having the following symptoms: n");
        printf("- Coughn");
        printf("- Difficulty breathingn");
        printf("- Loss of smelln");
        printf("- Loss of tasten");
        printf("(Y = Yes, N = No): ");
        scanf("%c", &userResponse);
        rewind(stdin);

        if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
            invalidCounter++;
        }
        else if (toupper(userResponse) == 'Y') {
            infectionLevel += 4;
        }

        printf("nnHave you travelled to any country outside Malaysianwithin the past 14 days?n");
        printf("(Y = Yes, N = No): ");
        scanf("%c", &userResponse);
        rewind(stdin);

        if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
            invalidCounter++;
        }

        else if (toupper(userResponse) == 'Y') {
            infectionLevel += 2;
        }

        printf("nnHave you had closed contact with anyone who nconfirmed or suspected case of COVID 19 within the 14 days?");
        printf("(Y = Yes, N = No): ");
        scanf("%c", &userResponse);
        rewind(stdin);

        if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
            invalidCounter++;
        }

        else if (toupper(userResponse) == 'Y') {
            infectionLevel += 4;
        }

        if (invalidCounter > 0) {
            printf("n- Error Found: Invalid Response Entered - nn");
        }

    } while (invalidCounter != 0);
    return infectionLevel;
}

void tableHeader() {
    printf("------------------------------------------------------------------------------------------------------------------------n");
    printf("| Venue |   Sanitization   |  Ending  |    Company    |    Person   | Gender |    Contact   | Temperature | Infection  |n");
    printf("|  ID   |       Time       |   Time   |   In-Charge   |  In-Charge  |        |              |             |   Risk     |n");
    printf("|-------|------------------|----------|---------------|-------------|--------|--------------|-------------|------------|n");
}

void tableFooter(int i, int emptyRecord) {
    printf("------------------------------------------------------------------------------------------------------------------------n");
    if (emptyRecord == MAX) {
        printf("No Such Record Foundn");
    }
    else {
        printf("%d Record Foundn", i);
    }
}

void addRecord() {
    struct SanitizeData newData;
    FILE* addPtr;
    char userResponse;
    int validate, invalidCounter, counter = 0, infectionlevel = 0;

    addPtr = fopen("Sanitization Record.dat", "ab");
    if (addPtr == NULL) {
        printf("Unable to open Sanitization Record.datn");
        exit(-1);
    }
    else {

        do {
            system("cls");
            do {
                invalidCounter = 0;
                printf("Add Sanitization Recordn");
                printf("-----------------------n");
                printf("Enter Venue ID: ");
                scanf("%s", &newData.venueID);
                rewind(stdin);

                printf("Enter Sanitized Date in (DD/MM/YYYY Format Eg: 19/02/2021) : ");
                validate = scanf("%d/%d/%d", &newData.sanitizeDate.day, &newData.sanitizeDate.month, &newData.sanitizeDate.year);
                rewind(stdin);

                printf("Enter Sanitized Time in (HH:MM Format Eg: 12:51) - n");
                printf("Starting: ");
                validate = scanf("%d:%d", &newData.Start.hours, &newData.Start.minute);
                rewind(stdin);

                printf("Ending: ");
                validate = scanf("%d:%d", &newData.End.hours, &newData.End.minute);
                rewind(stdin);

                printf("Enter Santizie Handling Company Details: n");
                printf("Company Name: ");
                scanf("%(^n)", &newData.Details.companyName);
                rewind(stdin);

                printf("Person In-Charge Name:  ");
                scanf("%(^n)", &newData.Details.personInCharge);
                rewind(stdin);

                printf("Person In-Charge Gender: ");
                scanf("%c", &newData.Details.gender);
                rewind(stdin);

                printf("Person In-Charge Contact Numer: ");
                scanf("%s", &newData.Details.contactNum);
                rewind(stdin);

                printf("Person In-Charge Temperature: ");
                validate = scanf("%f", &newData.Details.temperature);
                rewind(stdin);

                newData.Details.infectionLevel = infectionLevelCheck();

                if (newData.Details.temperature > 37.8) newData.Details.infectionLevel++;


                if (validate == 0
                    || newData.sanitizeDate.day < 1 || newData.sanitizeDate.day > 31
                    || newData.sanitizeDate.month > 12 || newData.sanitizeDate.month < 1
                    || newData.Start.hours > 24 || newData.Start.hours < 1
                    || newData.Start.minute > 60 || newData.Start.minute < 1
                    || newData.End.hours > 24 || newData.End.hours < 1
                    || newData.End.minute > 60 || newData.End.minute < 1
                    || toupper(newData.Details.gender) != 'M' && toupper(newData.Details.gender) != 'F')
                {
                    if (newData.sanitizeDate.day < 1 || newData.sanitizeDate.day > 31 || newData.sanitizeDate.month > 12 || newData.sanitizeDate.month < 1) {
                        printf("- Error Found: Invalid Month or Days Entered. -n");
                    }
                    if (newData.Start.hours > 24 || newData.Start.hours < 1 || newData.Start.minute > 60 || newData.Start.minute < 1) {
                        printf("- Error Found: Invalid Starting Hours or Minutes Entered. - n");
                    }

                    if (newData.End.hours > 24 || newData.End.hours < 1 || newData.End.minute > 60 || newData.End.minute < 1) {
                        printf("- Error Found: Invalid Ending Hours or Minutes Entered. - n");
                    }

                    if (toupper(newData.Details.gender) != 'M' || toupper(newData.Details.gender) != 'F') {
                        printf("- Error Found: Invalid Gender Entered. -n");
                    }

                    if (validate == 0) {
                        printf("- Error Found: Kindly Enter Valid Input Only. - n");
                    }

                    invalidCounter++;
                    system("pause");
                    system("cls");
                }
                else {
                    fwrite(&newData, sizeof(newData), 1, addPtr);
                    counter++;
                }
            } while (invalidCounter != 0);

            printf("Add Another Record? (N = No): ");
            scanf("%c", &userResponse);
            rewind(stdin);
        } while (toupper(userResponse) != 'N');
        printf("%d Record Added.....n", counter);
        fclose(addPtr);
    }
}

void searchVenueID() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    int counter = 0;
    char venueID(10);

    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Venue ID to Search: ");
    scanf("%s", &venueID);

    tableHeader();
    for (int i = 0; i < 20; i++) {
        if (strcmp(venueID, data(i).venueID) == 0) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchDate() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    int counter = 0;
    int day, month, year;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Date to Search (Format: 19/02/2021) : ");
    scanf("%d/%d/%d", &day, &month, &year);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (day == data(i).sanitizeDate.day && month == data(i).sanitizeDate.month && year == data(i).sanitizeDate.year) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchCompany() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    char companyName(41);
    int counter = 0;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Company Name to Search: ");
    scanf("%(^n)", &companyName);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (strcmp(companyName, data(i).Details.companyName) == 0) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchName() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    char personInCharge(41);
    int counter = 0;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Person In-Charge Name to Search: ");
    scanf("%(^n)", &personInCharge);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (strcmp(personInCharge, data(i).Details.personInCharge) == 0) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchContactNumber() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    char contactNum(13);
    int counter = 0;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Contact Number to Search (Format: 010-2012687): ");
    scanf("%s", &contactNum);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (strcmp(contactNum, data(i).Details.contactNum) == 0) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchGender() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    char gender;
    int counter = 0;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Person In-Charge Gender to Search (F = Female, M = Male): ");
    scanf("%c", &gender);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (gender == data(i).Details.gender) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchTemperature() {
    struct SanitizeData data(20);
    FILE* searchPtr;
    int i = 0, emptyRecord = 0;
    float temperature;
    int counter = 0;
    searchPtr = fopen("Sanitization Record.dat", "rb");
    if (searchPtr == NULL) {
        printf("Unable to open Santization Record.datn");
        exit(-1);
    }

    while (fread(&data(i), sizeof(data), 1, searchPtr) != 0) {
        i++;
    }

    printf("Enter Temperature To Search (Eg: 36.6): ");
    scanf("%f", &temperature);

    tableHeader();
    for (i = 0; i < 20; i++) {
        if (temperature == data(i).Details.temperature) {
            counter++;
            printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data(i).venueID, data(i).sanitizeDate.day, data(i).sanitizeDate.month, data(i).sanitizeDate.year,
                data(i).Start.hours, data(i).Start.minute, data(i).End.hours, data(i).End.minute, data(i).Details.companyName,
                data(i).Details.personInCharge);

            switch (toupper(data(i).Details.gender)) {
            case 'F':
                printf("Female ");
                break;
            case 'M':
                printf(" Male  ");
                break;
            }

            printf("| %-12s |    %.2f    | ", data(i).Details.contactNum, data(i).Details.temperature);

            if (data(i).Details.infectionLevel <= 1) {
                printf(" Low Risk  |n");
            }
            else if (data(i).Details.infectionLevel <= 3) {
                printf(" Mid Risk  |n");
            }
            else if (data(i).Details.infectionLevel >= 4) {
                printf(" High Risk |n");
            }
        }
        else {
            emptyRecord++;
        }
    }
    tableFooter(counter, emptyRecord);
    fclose(searchPtr);
}

void searchRecord() {
    int selection, invalidCounter;
    char userResponse;
    do {
        system("cls");
        do {
            invalidCounter = 0;
            printf("Search Record Based On Following Criteria: n");
            printf("1. Venue IDn");
            printf("2. Sanitization Daten");
            printf("3. Company Namen");
            printf("4. Person In-Chargen");
            printf("5. Contact Numbern");
            printf("6. Gendern");
            printf("7. Temperaturen");
            printf("8. Back to Sanitize Menun");
            printf("Enter Your Choice > ");
            scanf("%d", &selection);
            if (selection < 1 || selection > 8) {
                invalidCounter++;
                printf("- Error Found: Enter 1 - 8 ONLY - n");
                system("pause");
                system("cls");
            }
        } while (invalidCounter != 0);
        switch (selection) {
        case 1:
            searchVenueID();
            break;
        case 2:
            searchDate();
            break;
        case 3:
            searchCompany();
            break;
        case 4:
            searchName();
            break;
        case 5:
            searchContactNumber();
            break;
        case 6:
            searchGender();
            break;
        case 7:
            searchTemperature();
        case 8:
            sanitizeMenu();
            break;
        }
        printf("Anymore to Search? (N = No): ");
        scanf("%c", &userResponse);
        rewind(stdin);

    } while (toupper(userResponse) != 'N');
}

void modifyRecord() {
    struct SanitizeData data;
    struct SanitizeData modify(20);
    FILE* modifyPtr;
    int i = 0, counter = 0, validate, invalidCounter, emptyRecord = 0, modifyCounter = 0;
    char venueID(10), userResponse;
    modifyPtr = fopen("Sanitization Record.dat", "rb");
    if (modifyPtr == NULL) {
        printf("Unable to open Sanitization Record.datn");
        exit(-1);
    }

    while (fread(&data, sizeof(data), 1, modifyPtr) != 0) {
        modify(modifyCounter) = data;
        modifyCounter++;
    }

    modifyPtr = fopen("Sanitization Record.dat", "wb");
    if (modifyPtr == NULL) {
        printf("Unable to open Sanitization Record.datn");
        exit(-1);
    }
    do {
        system("cls");
        printf("Modify Sanitize Recordn");
        printf("----------------------nn");
        printf("Enter Venue ID To Modify: ");
        scanf("%s", &venueID);
        rewind(stdin);
        for (i = 0; i < modifyCounter; i++) {
            if (strcmp(venueID, modify(i).venueID) == 0) {

                printf("Venue ID                       : %sn", modify(i).venueID);
                printf("Sanitization Date              : %02d-%02d-%4dn", modify(i).sanitizeDate.day, modify(i).sanitizeDate.month, modify(i).sanitizeDate.year);
                printf("Starting Time                  : %02d:%02dn", modify(i).Start.hours, modify(i).Start.minute);
                printf("Ending Time                    : %02d:%02dn", modify(i).End.hours, modify(i).End.minute);
                printf("Sanitized Company Name         : %sn", modify(i).Details.companyName);
                printf("Person In-Charge  Name         : %sn", modify(i).Details.personInCharge);
                printf("Person In-Charge Gender        : %cn", modify(i).Details.gender);
                printf("Person In-Charge Contact Number: %sn", modify(i).Details.contactNum);
                printf("Person In-Charge Temperature   : %.2fnn", modify(i).Details.temperature);
                printf("Sure to Modify? (Y = Yes): ");
                scanf("%c", &userResponse);
                if (toupper(userResponse) == 'Y') {
                    counter++;
                    do {
                        invalidCounter = 0;

                        printf("Enter Sanitized Date in (DD/MM/YYYY Format Eg: 19/02/2021) : ");
                        validate = scanf("%d/%d/%d", &modify(i).sanitizeDate.day, &modify(i).sanitizeDate.month, &modify(i).sanitizeDate.year);
                        rewind(stdin);

                        printf("Enter Sanitized Time in (HH:MM Format Eg: 12:51) - n");
                        printf("Starting: ");
                        validate = scanf("%d:%d", &modify(i).Start.hours, &modify(i).Start.minute);
                        rewind(stdin);

                        printf("Ending: ");
                        validate = scanf("%d:%d", &modify(i).End.hours, &modify(i).End.minute);
                        rewind(stdin);

                        printf("Enter Santizie Handling Company Details: n");
                        printf("Company Name: ");
                        scanf("%(^n)", &modify(i).Details.companyName);
                        rewind(stdin);

                        printf("Person In-Charge Name:  ");
                        scanf("%(^n)", &modify(i).Details.personInCharge);
                        rewind(stdin);

                        printf("Person In-Charge Gender: ");
                        scanf("%c", &modify(i).Details.gender);
                        rewind(stdin);

                        printf("Person In-Charge Contact Numer: ");
                        scanf("%s", &modify(i).Details.contactNum);
                        rewind(stdin);

                        printf("Person In-Charge Temperature: ");
                        validate = scanf("%f", &modify(i).Details.temperature);
                        rewind(stdin);

                        modify(i).Details.infectionLevel = infectionLevelCheck();

                        if (modify(i).Details.temperature > 37.8) modify(i).Details.infectionLevel++;


                        if (validate == 0
                            || modify(i).sanitizeDate.day < 1 || modify(i).sanitizeDate.day > 31
                            || modify(i).sanitizeDate.month > 12 || modify(i).sanitizeDate.month < 1
                            || modify(i).Start.hours > 24 || modify(i).Start.hours < 1
                            || modify(i).Start.minute > 60 || modify(i).Start.minute < 1
                            || modify(i).End.hours > 24 || modify(i).End.hours < 1
                            || modify(i).End.minute > 60 || modify(i).End.minute < 1
                            || toupper(modify(i).Details.gender) != 'M' && toupper(modify(i).Details.gender) != 'F')
                        {
                            if (modify(i).sanitizeDate.day < 1 || modify(i).sanitizeDate.day > 31 || modify(i).sanitizeDate.month > 12 || modify(i).sanitizeDate.month < 1) {
                                printf("- Error Found: Invalid Month or Days Entered. -n");
                            }
                            if (modify(i).Start.hours > 24 || modify(i).Start.hours < 1 || modify(i).Start.minute > 60 || modify(i).Start.minute < 1) {
                                printf("- Error Found: Invalid Starting Hours or Minutes Entered. - n");
                            }

                            if (modify(i).End.hours > 24 || modify(i).End.hours < 1 || modify(i).End.minute > 60 || modify(i).End.minute < 1) {
                                printf("- Error Found: Invalid Ending Hours or Minutes Entered. - n");
                            }

                            if (toupper(modify(i).Details.gender) != 'M' || toupper(modify(i).Details.gender) != 'F') {
                                printf("- Error Found: Invalid Gender Entered. -n");
                            }

                            if (validate == 0) {
                                printf("- Error Found: Kindly Enter Valid Input Only. - n");
                            }

                            invalidCounter++;
                            system("pause");
                            system("cls");
                        }

                    } while (invalidCounter != 0);

                }
                else {
                    break;
                }
                fwrite(&modify(i), sizeof(data), 1, modifyPtr);
            }
            else {
                emptyRecord++;
            }
        }
        if (emptyRecord == 20) {
            printf("No Record Foundn");
        }
        printf("Continue Modify Record? (N = No): ");
        scanf("%c", &userResponse);
    } while (userResponse != 'N');
    printf("%d Record Modifiedn", counter);
    fclose(modifyPtr);
}

void displayRecord() {
    struct SanitizeData data;
    FILE* displayPtr;
    int i = 0;
    displayPtr = fopen("Sanitization Record.dat", "rb");

    if (displayPtr == NULL) {
        printf("Unable to open Sanitization Record.datn");
        exit(-1);
    }

    system("cls");

    printf("Display All Sanitization Recordn");
    printf("-------------------------------n");
    tableHeader();
    while (fread(&data, sizeof(data), 1, displayPtr) != 0) {
        printf("| %-5s | %02d-%02d-%4d %02d:%02d |   %02d:%02d  | %-13s | %-11s | ", data.venueID, data.sanitizeDate.day, data.sanitizeDate.month, data.sanitizeDate.year,
            data.Start.hours, data.Start.minute, data.End.hours, data.End.minute, data.Details.companyName,
            data.Details.personInCharge);

        switch (toupper(data.Details.gender)) {
        case 'F':
            printf("Female ");
            break;
        case 'M':
            printf(" Male  ");
            break;
        }
        printf("| %-12s |    %.2f    | ", data.Details.contactNum, data.Details.temperature);
        if (data.Details.infectionLevel <= 1) {
            printf(" Low Risk  |n");
        }
        else if (data.Details.infectionLevel <= 3) {
            printf(" Mid Risk  |n");
        }
        else if (data.Details.infectionLevel >= 4) {
            printf(" High Risk |n");
        }
        i++;
    }
    printf("------------------------------------------------------------------------------------------------------------------------n");
    printf("%d Record Foundn", i);
    fclose(displayPtr);
}

void deleteRecord() {
    struct SanitizeData data;
    struct SanitizeData delData(20);
    FILE* deletePtr;

    int i = 0, delCount = 0, position, emptyRecord = 0;
    char userResponse;
    char venueID(10);

    deletePtr = fopen("Sanitization Record.dat", "rb");
    if (deletePtr == NULL) {
        printf("Unable to open Sanitization.datn");
        exit(-1);
    }
    else {
        while (fread(&data, sizeof(data), 1, deletePtr) != 0) {
            delData(i) = data;
            i++;
            delCount++;
        }
    }
    fclose(deletePtr);

    deletePtr = fopen("Sanitization Record.dat", "wb");
    if(deletePtr == NULL) {
        printf("Unable to open Sanitization.datn");
        exit(-1);
    }
    else {

        do {
            printf("Delete Record Based On: ");
            printf("1. Venue IDn");
            printf("Enter Venue ID: ");
            scanf("%s", venueID);
            rewind(stdin);

            for (i = 0; i < delCount; i++) {
                if (strcmp(venueID, delData(i).venueID) == 0) {
                    printf("Venue ID                       : %sn", delData(i).venueID);
                    printf("Sanitization Date              : %02d-%02d-%4dn", delData(i).sanitizeDate.day, delData(i).sanitizeDate.month, delData(i).sanitizeDate.year);
                    printf("Starting Time                  : %02d:%02dn", delData(i).Start.hours, delData(i).Start.minute);
                    printf("Ending Time                    : %02d:%02dn", delData(i).End.hours, delData(i).End.minute);
                    printf("Sanitized Company Name         : %sn", delData(i).Details.companyName);
                    printf("Person In-Charge  Name         : %sn", delData(i).Details.personInCharge);
                    printf("Person In-Charge Gender        : %cn", delData(i).Details.gender);
                    printf("Person In-Charge Contact Number: %sn", delData(i).Details.contactNum);
                    printf("Person In-Charge Temperature   : %.2fnn", delData(i).Details.temperature);
                    position = i;
                    printf("Confirm to Delete? (Y = Yes): ");
                    scanf("%c", &userResponse);
                    rewind(stdin);
                    if (toupper(userResponse) == 'Y') {
                        for (i = position; i < delCount; i++) {
                            delData(i) = delData(i + 1);
                        }
                    }
                }
                else {
                    emptyRecord++;
                }
            }

            if (emptyRecord == 20) {
                printf("-Error Found: No Record - n");
            }

            printf("Anymore to Delete? (Y = Yes): ");
            scanf("%c", &userResponse);
            rewind(stdin);

            if (toupper(userResponse) == 'N') {
                for (int i = 0; i < delCount--; i++) {
                    fwrite(&delData(i), sizeof(delData(i)), 1, deletePtr);
                }
            }

        } while (toupper(userResponse) != 'N');
    }
    fclose(deletePtr);
}

void sanitizeMenu() {
    int validate, invalidCounter, selection;
    char userResponse;
    do {
        system("cls");
        do {
            invalidCounter = 0;
            printf("     Sanitization Record Modulen");
            printf("-------------------------------------n");
            printf("            MENUn");
            printf("(1) - Add Sanitization Recordn");
            printf("(2) - Search Sanitization Recordn");
            printf("(3) - Modify Sanitization Recordn");
            printf("(4) - Display Sanitization Recordn");
            printf("(5) - Delete Sanitization Recordn");
            printf("(6) - Record n");
            printf("(7) - Quit This Menun");
            printf("(8) - Exit The Programnn");
            printf("Enter Your Selection: ");
            validate = scanf("%d", &selection);
            rewind(stdin);
            if (selection < 1 || selection > 8 || validate == 0) {
                invalidCounter++;
                printf("- Error Found: Please Enter 1 - 7 Only -n");
                system("pause");
                system("cls");
            }

        } while (invalidCounter != 0);

        switch (selection) {
        case 1:
            addRecord();
            break;
        case 2:
            searchRecord();
            break;
        case 3:
            modifyRecord();
            break;
        case 4:
            displayRecord();
            break;
        case 5:
            deleteRecord();
            break;
        case 6:
            menu();
            break;
        case 7:
            footer();
            exit(0);
        }

        printf("Back to Sanitize Menu? (N = No): ");
        rewind(stdin);
        scanf("%c", &userResponse);
        rewind(stdin);
    } while (toupper(userResponse) != 'N');
}

summation – reduce the number of trigonometry calls in this function

Using trigonometric identities rearrange the following function to have a single trigonometry call:

$$
f(x,y,n)=2^{n-1}(1-cos{frac{xpi}{2^n}})(1-cos{frac{ypi}{2^n}})
$$

I’m looking for help in optimizing it for a computer program I’m working on. Bonus points: run this entire summation with a single trigonometry reference. How can I get the $n$ out of the trigonometry call?
$$
sum_{n=0}^b{f(x,y,n)}
$$

user behavior – Can lack of sponsored content reduce trust in a list/ranking?

We’ve been doing some research on a website of ours. On this website we help the user pick the cheapest product for what they are searching for (example: TV / Smartwatch etc).

In the heatmaps we see that if there is no sponsored content, most of the users click the second option. While if we do show sponsored content, most of the users select the first non-sponsored option. The sponsored content is, in all cases, clearly marked paid content.

enter image description here

While doing user interviews (for general research) we noticed that a lot of users say they do not trust ‘websites that compare stuff’ because they do not know if the content is sponsored or not.

In the user interviews after a usertest the user says they picked the second option in the non sponsored list because it looked the best for them. Users that had sponsored content also picked the second one and gave the somewhat the same reply.

However in the sponsored list the 3rd option would be the same option as the 2nd in the non sponsored list.

So my question is as followed, would showing sponsored content increase the trust of the list because it is clearly marked? And when there is no sponsored content, would the user pick the second because they maybe assume the first is sponsored content?

Note: The usertests were qualitative and not quantitative

python – Reduce computing time of planning method (grid)

Has anyone an idea how to change the planning(self, sx, sy, gx, gy)-method to save computing time? I’m new to NumPy and don’t know how to use it effectively yet, but I heard it could also be a good solution.

import math
import matplotlib.pyplot as plt

show_animation = True

class AStarPlanner:

    def __init__(self, ox, oy, resolution, rr):
        """
        Initialize grid map for a star planning

        ox: x position list of Obstacles (m)
        oy: y position list of Obstacles (m)
        resolution: grid resolution (m)
        rr: robot radius(m)
        """

        self.resolution = resolution
        self.rr = rr
        self.min_x, self.min_y = 0, 0
        self.max_x, self.max_y = 0, 0
        self.obstacle_map = None
        self.x_width, self.y_width = 0, 0
        self.motion = self.get_motion_model()
        self.calc_obstacle_map(ox, oy)

    class Node:
        def __init__(self, x, y, cost, parent_index):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost
            self.parent_index = parent_index

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.parent_index)

    def planning(self, sx, sy, gx, gy):
        """
        A star path search

        input:
            s_x: start x position (m)
            s_y: start y position (m)
            gx: goal x position (m)
            gy: goal y position (m)

        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        start_node = self.Node(self.calc_xy_index(sx, self.min_x),
                               self.calc_xy_index(sy, self.min_y), 0.0, -1)
        goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
                              self.calc_xy_index(gy, self.min_y), 0.0, -1)

        open_set, closed_set = dict(), dict()
        open_set(self.calc_grid_index(start_node)) = start_node

        while 1:
            if len(open_set) == 0:
                print("Open set is empty..")
                break

            c_id = min(
                open_set,
                key=lambda o: open_set(o).cost + self.calc_heuristic(goal_node,
                                                                     open_set(
                                                                         o)))
            current = open_set(c_id)

            if current.x == goal_node.x and current.y == goal_node.y:
                print("Found goal")
                goal_node.parent_index = current.parent_index
                goal_node.cost = current.cost
                break

            # Remove the item from the open set
            del open_set(c_id)

            # Add it to the closed set
            closed_set(c_id) = current

            # expand_grid search grid based on motion model
            for i, _ in enumerate(self.motion):
                node = self.Node(current.x + self.motion(i)(0),
                                 current.y + self.motion(i)(1),
                                 current.cost + self.motion(i)(2), c_id)
                n_id = self.calc_grid_index(node)

                # If the node is not safe, do nothing
                if not self.verify_node(node):
                    continue

                if n_id in closed_set:
                    continue

                if n_id not in open_set:
                    open_set(n_id) = node  # discovered a new node
                else:
                    if open_set(n_id).cost > node.cost:
                        # This path is the best until now. record it
                        open_set(n_id) = node

        rx, ry = self.calc_final_path(goal_node, closed_set)

        return rx, ry

    def calc_final_path(self, goal_node, closed_set):
        # generate final course
        rx, ry = (self.calc_grid_position(goal_node.x, self.min_x)), (
            self.calc_grid_position(goal_node.y, self.min_y))
        parent_index = goal_node.parent_index
        while parent_index != -1:
            n = closed_set(parent_index)
            rx.append(self.calc_grid_position(n.x, self.min_x))
            ry.append(self.calc_grid_position(n.y, self.min_y))
            parent_index = n.parent_index

        return rx, ry

    @staticmethod
    def calc_heuristic(n1, n2):
        w = 1.0  # weight of heuristic
        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
        return d

    def calc_grid_position(self, index, min_position):
        """
        calc grid position

        :param index:
        :param min_position:
        :return:
        """
        pos = index * self.resolution + min_position
        return int(pos)

    def decalc_grid_position(self, pos, min_position):
        index = (pos - min_position) / self.resolution
        
        return int(index)    
    
    def calc_xy_index(self, position, min_pos):
        return round((position - min_pos) / self.resolution)

    def calc_grid_index(self, node):
        return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)

    def verify_node(self, node):
        px = self.calc_grid_position(node.x, self.min_x)
        py = self.calc_grid_position(node.y, self.min_y)

        if px < self.min_x:
            return False
        elif py < self.min_y:
            return False
        elif px >= self.max_x:
            return False
        elif py >= self.max_y:
            return False

        # collision check
        if self.obstacle_map(node.x)(node.y):
            return False

        return True

    def compute_robot_radius(self):
        """ Compute and store table of offsets of cells within a robot's radius.
        """
        self.robot_radius = ()
        for x in range(int(-self.rr), int(self.rr) + 1):
            for y in range(int(-self.rr), int(self.rr) + 1):
                if math.hypot(x, y) < self.rr:
                    self.robot_radius.append((x, y))

    def calc_obstacle_map(self, ox, oy):

        self.min_x = round(min(ox))
        self.min_y = round(min(oy))
        self.max_x = round(max(ox))
        self.max_y = round(max(oy))
        print("min_x:", self.min_x)
        print("min_y:", self.min_y)
        print("max_x:", self.max_x)
        print("max_y:", self.max_y)

        self.x_width = round((self.max_x - self.min_x) / self.resolution)
        self.y_width = round((self.max_y - self.min_y) / self.resolution)
        print("x_width:", self.x_width)
        print("y_width:", self.y_width)

        self.compute_robot_radius()

        self.obstacle_map = ((False for _ in range(len(oy))) for _ in range(len(ox)))

        obstacles = zip(ox, oy)
        for ox, oy in obstacles:
            ox = self.decalc_grid_position(ox, self.min_x)
            oy = self.decalc_grid_position(oy, self.min_y)
            for dx, dy in self.robot_radius:
                self.obstacle_map(int(ox + dx))(int(oy + dy)) = True


    @staticmethod
    def get_motion_model():
        # dx, dy, cost
        motion = ((1, 0, 1),
                  (0, 1, 1),
                  (-1, 0, 1),
                  (0, -1, 1),
                  (-1, -1, math.sqrt(2)),
                  (-1, 1, math.sqrt(2)),
                  (1, -1, math.sqrt(2)),
                  (1, 1, math.sqrt(2)))

        return motion


def main():
    print(__file__ + " start!!")

    # start and goal position
    sx = 10.0  # (m)
    sy = 10.0  # (m)
    gx = 55.0  # (m)
    gy = -5.0  # (m)
    grid_size = 2.0  # (m)
    robot_radius = 2.0  # (m)

    # set obstacle positions
    ox, oy = (), ()
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "xb")
        plt.grid(True)
        plt.axis("equal")

    a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
    rx, ry = a_star.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.pause(0.001)
        plt.show()


if __name__ == '__main__':
    main()

dnd 5e – House Rule – Upcasting Enlarge / Reduce to extend duration

The party is deep into my 5e-updated classic Greyhawk Giants series.

The hill giants and their orc and goblin minions have attacked the Sterish city of Headwater and have taken about a quarter of the city. The party is about to embark on a mission to go behind enemy lines, kidnap and assassinate a stone giant who is critical to the hill giants’ city / siege offensive as being their only trained engineer. While the party’s patron recognizes that the stone giant needs to die, she also recognizes that at present the Stone Giant Thane has not joined the giant alliance and wants to keep it that way. Thus, she is requesting that they carry the body of the slain giant honorably back to his Thane in an effort to preserve a fragile peace between the humans and the stone giants. I would like the party to be able to accept this mission, without it becoming either a logistical challenge involving wagons and draft animals, or without loaning them a portable hole.

Instead, I would like to provide them with a version of the Enlarge / Reduce spell which is in all aspects identical to the original except that it can be upcast to extend the duration.

I figure the giant is 17 feet high and 1000 pounds; after reduce it would be 8.5 feet and a manageable 125 pounds.

For this version of Enlarge / Reduce I am proposing that:

When cast at 3rd level against living creatures, it lasts 10 minutes

When cast at 3rd level against objects, it lasts 1 hour

When cast at 4th level against living creatures, it lasts 1 hour (similar to polymorph)

When cast at 4th level against objects, it lasts 8 hours

When cast at 5th level against living creatures, it lasts 8 hours (much less than geas)

When cast at 5th level against objects, it lasts 24 hours

The party Wizard is currently 8th level and getting close to 9th. Requiring her to use both her fourth level slots and maintain concentration for the duration of travel every day in order to move swiftly and stealthily into the mountains with the body is just the right level of challenge for the group.

My only concern is that allowing this version of the spell to the party wizard permanently will have some unforeseen interaction with some other spell, ability, or item that I will later regret. This question, for example, asks about upcasting enlarge to permit two changes in creature size, and answers identify the interaction with levitation and grappling being problematic. I am interested in a similar troubleshooting review.

amazon rds – How to reduce size of my RDS mySql database of 5000 GB to 2000 GB, with all the triggers and functions intact?

I have a RDS MySql database of provisioned storage 5000 GiB. Out of 5000 GiB I am using only 1400 GiB and want to reduce size of provisioned storgae to 2000 GiB. All the tables are innoDb.

I want to keep my triggers, indexes, keys and functions intact.

What will be the simplest and most fail proof approach to achieve this ?

dnd 5e – Are there any poisons which reduce ability scores?

None in the official rules.

The only source books other than DMG that include poisons are in Xanathar’s Guide to Everything (poisoned needle trap and poisoned tempest), and the Players Handbook (Basic Poison Vial, and Poisoner’s Kit).

It should be easy enough to homebrew, however.

The Shadow’s Strength Drain is a melee weapon attack, with no save. The Intellect Devourer’s Devour Intellect is a saving throw, followed by a roll contested by the players intelligence, and completely reduces there intelligence to zero on a failure. I don’t think either of these are good templates to follow for a poison.
Some questions to ask:

  1. How readily available is this poison? Can it be purchased at the capital city magic shop only? or can it be picked up in any local adventuring store? How likely are the players opponents to have these poisons?
  2. Is the poison something your players can create themselves, same as a magic item? In that case, what “rarity” would you consider the poison in terms of how long it will take the play to create the item? does it require some special ingredient, such as “condensed Shadow” or “Intellect Devourer claws?”
  3. Is the poison stacking? Say you reduce by 1d6 on a successful hit, can you deal another 1d6 if applied again? in this case, what happens if the ability score is reduced to zero?
  4. How is the poison applied? Remember the list from the DMG includes poisons applied by ingestion, inhalation, injury, or contact, what would work best for this?
  5. How long does the poison last, and how is it cured?

With these questions in mind, you shouldn’t have too much difficulty creating something your players can work with or against.